-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrich-markdown-editor.new.tsx
More file actions
466 lines (428 loc) · 14.6 KB
/
rich-markdown-editor.new.tsx
File metadata and controls
466 lines (428 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import { MARKDOWN_HELP_URL } from 'front-end/config';
import { makeStartLoading, makeStopLoading } from 'front-end/lib';
import * as FormField from 'front-end/lib/components/form-field';
import { Immutable, UpdateReturnValue, View, ViewElement } from 'front-end/lib/framework';
import FileLink from 'front-end/lib/views/file-link';
import Icon, { AvailableIcons } from 'front-end/lib/views/icon';
import Link, { externalDest } from 'front-end/lib/views/link';
import React from 'react';
import { Spinner } from 'reactstrap';
import { SUPPORTED_IMAGE_EXTENSIONS } from 'shared/lib/resources/file';
import { adt, ADT } from 'shared/lib/types';
import { Validation } from 'shared/lib/validation';
export type Value = string;
export type UploadImage = (file: File) => Promise<Validation<{ name: string; url: string }>>;
type Snapshot = [string, number, number]; // [value, selectionStart, selectionEnd]
type StackEntry = ADT<'single', Snapshot> | ADT<'batch', Snapshot>;
type Stack = StackEntry[];
function emptyStack(): Stack {
return [];
}
function isStackEmpty(stack: Stack): boolean {
return !stack.length;
}
interface ChildState extends FormField.ChildStateBase<Value> {
currentStackEntry: StackEntry | null; // When in the middle of undoing/redoing to ensure continuity in UX.
undo: Stack;
redo: Stack;
loading: number;
selectionStart: number;
selectionEnd: number;
uploadImage: UploadImage;
}
export interface ChildParams extends FormField.ChildParamsBase<Value> {
uploadImage: UploadImage;
}
type InnerChildMsg
= ADT<'onChangeTextArea', Snapshot>
| ADT<'onChangeSelection', [number, number]> // [selectionStart, selectionEnd]
| ADT<'controlUndo'>
| ADT<'controlRedo'>
| ADT<'controlH1'>
| ADT<'controlH2'>
| ADT<'controlH3'>
| ADT<'controlBold'>
| ADT<'controlItalics'>
| ADT<'controlOrderedList'>
| ADT<'controlUnorderedList'>
| ADT<'controlImage', File>
| ADT<'focus'>;
type ExtraChildProps = {};
type ChildComponent = FormField.ChildComponent<Value, ChildParams, ChildState, InnerChildMsg, ExtraChildProps>;
export type State = FormField.State<Value, ChildState>;
export type Params = FormField.Params<Value, ChildParams>;
export type Msg = FormField.Msg<InnerChildMsg>;
const childInit: ChildComponent['init'] = async params => ({
...params,
currentStackEntry: null,
undo: emptyStack(),
redo: emptyStack(),
loading: 0,
selectionStart: 0,
selectionEnd: 0
});
const startLoading = makeStartLoading<ChildState>('loading');
const stopLoading = makeStopLoading<ChildState>('loading');
interface InsertParams {
separateLine?: boolean;
text(selectedText: string): string;
}
function insert(state: Immutable<ChildState>, params: InsertParams): UpdateReturnValue<ChildState, FormField.ChildMsg<InnerChildMsg>> {
const { text, separateLine = false } = params;
const selectedText = state.value.substring(state.selectionStart, state.selectionEnd);
const body = text(selectedText);
let prefix = state.value.substring(0, state.selectionStart);
if (prefix !== '' && separateLine) {
prefix = prefix.replace(/\n?\n?$/, '\n\n');
}
let suffix = state.value.substring(state.selectionEnd);
if (suffix !== '' && separateLine) {
suffix = suffix.replace(/^\n?\n?/, '\n\n');
}
state = pushStack(state, 'undo', getStackEntry(state));
state = resetRedoStack(state);
state = setSnapshot(state, [
`${prefix}${body}${suffix}`,
prefix.length,
prefix.length + body.length
]);
return [
state,
async (state, dispatch) => {
dispatch(adt('@validate'));
dispatch(adt('focus'));
return null;
}
];
}
function getSnapshot(state: Immutable<ChildState>): Snapshot {
return [
state.value,
state.selectionStart,
state.selectionEnd
];
}
function setSnapshot(state: Immutable<ChildState>, snapshot: Snapshot): Immutable<ChildState> {
return state
.set('value', snapshot[0])
.set('selectionStart', snapshot[1])
.set('selectionEnd', snapshot[2]);
}
function getStackEntry(state: Immutable<ChildState>): StackEntry {
return state.currentStackEntry || adt('single', getSnapshot(state));
}
function setStackEntry(state: Immutable<ChildState>, entry: StackEntry): Immutable<ChildState> {
return setSnapshot(state, entry.value)
.set('currentStackEntry', entry);
}
function resetRedoStack(state: Immutable<ChildState>): Immutable<ChildState> {
return state
.set('redo', emptyStack())
.set('currentStackEntry', null);
}
const MAX_STACK_ENTRIES = 50;
const STACK_BATCH_SIZE = 5;
function pushStack(state: Immutable<ChildState>, k: 'undo' | 'redo', entry: StackEntry): Immutable<ChildState> {
return state.update(k, stack => {
const addAsNewest = () => [entry, ...stack.slice(0, MAX_STACK_ENTRIES - 1)];
// If stack is smaller than batch size, or are adding a batch, simply add the entry.
if (stack.length < STACK_BATCH_SIZE || entry.tag === 'batch') {
return addAsNewest();
}
// If newest entries are batches, simply add the entry.
for (let i = 0; i < STACK_BATCH_SIZE; i++) {
if (stack[i].tag === 'batch') {
return addAsNewest();
}
}
// Otherwise, the newest (single) entries need to be batched.
return [
entry,
adt('batch', stack[STACK_BATCH_SIZE - 1].value), // convert single entry to batch
...stack.slice(STACK_BATCH_SIZE, MAX_STACK_ENTRIES - 2)
];
});
}
function popStack(state: Immutable<ChildState>, k: 'undo' | 'redo'): [StackEntry | undefined, Immutable<ChildState>] {
const stack = state.get(k);
if (!stack.length) { return [undefined, state]; }
const [entry, ...rest] = stack;
return [
entry,
state.set(k, rest)
];
}
const childUpdate: ChildComponent['update'] = ({ state, msg }) => {
switch (msg.tag) {
case 'onChangeTextArea':
state = pushStack(state, 'undo', getStackEntry(state));
state = resetRedoStack(state);
return [setSnapshot(state, msg.value)];
case 'onChangeSelection':
return [state
.set('selectionStart', msg.value[0])
.set('selectionEnd', msg.value[1])
];
case 'controlUndo': {
let entry;
[entry, state] = popStack(state, 'undo');
if (!entry) { return [state]; }
state = pushStack(state, 'redo', getStackEntry(state));
state = setStackEntry(state, entry);
return [state];
}
case 'controlRedo': {
let entry;
[entry, state] = popStack(state, 'redo');
if (!entry) { return [state]; }
state = pushStack(state, 'undo', getStackEntry(state));
state = setStackEntry(state, entry);
return [state];
}
case 'controlH1':
return insert(state, {
text: selectedText => `# ${selectedText}`,
separateLine: true
});
case 'controlH2':
return insert(state, {
text: selectedText => `## ${selectedText}`,
separateLine: true
});
case 'controlH3':
return insert(state, {
text: selectedText => `### ${selectedText}`,
separateLine: true
});
case 'controlBold':
return insert(state, {
text: selectedText => `**${selectedText}**`
});
case 'controlItalics':
return insert(state, {
text: selectedText => `*${selectedText}*`
});
case 'controlOrderedList':
return insert(state, {
text: selectedText => `1. ${selectedText}`,
separateLine: true
});
case 'controlUnorderedList':
return insert(state, {
text: selectedText => `- ${selectedText}`,
separateLine: true
});
case 'controlImage':
return [
startLoading(state),
async (state, dispatch) => {
state = stopLoading(state);
const uploadResult = await state.uploadImage(msg.value);
if (uploadResult.tag === 'invalid') { return state; }
const result = insert(state, {
text: () => ``
});
state = result[0];
if (result[1]) {
await result[1](state, dispatch);
}
return state;
}
];
case 'focus':
return [
state,
async () => {
const el = document.getElementById(state.id);
if (el) { el.focus(); }
return null;
}
];
default:
return [state];
}
};
interface ControlIconProps {
name: AvailableIcons;
disabled: boolean;
children?: ViewElement;
width?: number;
height?: number;
className?: string;
onClick?(): void;
}
const ControlIcon: View<ControlIconProps> = ({ name, disabled, onClick, children, width = 1.25, height = 1.25, className = '' }) => {
return (
<Link color={disabled ? 'secondary' : 'dark'} className={`${className} d-flex justify-content-center align-items-center position-relative`} disabled={disabled} onClick={onClick} style={{ lineHeight: 0, pointerEvents: disabled ? 'none' : undefined }}>
<Icon name={name} width={width} height={height} />
{children ? children : ''}
</Link>
);
};
const ControlSeparator: View<{}> = () => {
return (<div className='mr-3 border-left h-100'></div>);
};
const Controls: ChildComponent['view'] = ({ state, dispatch, disabled = false }) => {
const isLoading = state.loading > 0;
const isDisabled = disabled || isLoading;
const onSelectFile = (file: File) => {
if (isDisabled) { return; }
dispatch(adt('controlImage', file));
};
return (
<div className='bg-light flex-grow-0 flex-shrink-0 d-flex flex-nowrap align-items-center px-3 py-2 form-control border-0'>
<ControlIcon
name='undo'
width={0.9}
height={0.9}
disabled={isDisabled || isStackEmpty(state.undo)}
className='mr-2'
onClick={() => dispatch(adt('controlUndo'))} />
<ControlIcon
name='redo'
width={0.9}
height={0.9}
disabled={isDisabled || isStackEmpty(state.redo)}
className='mr-3'
onClick={() => dispatch(adt('controlRedo'))} />
<ControlSeparator />
<ControlIcon
name='h1'
disabled={isDisabled}
className='mr-2'
onClick={() => dispatch(adt('controlH1'))} />
<ControlIcon
name='h2'
disabled={isDisabled}
className='mr-2'
onClick={() => dispatch(adt('controlH2'))} />
<ControlIcon
name='h3'
disabled={isDisabled}
className='mr-3'
onClick={() => dispatch(adt('controlH3'))} />
<ControlSeparator />
<ControlIcon
name='bold'
disabled={isDisabled}
width={0.9}
height={0.9}
className='mr-2'
onClick={() => dispatch(adt('controlBold'))} />
<ControlIcon
name='italics'
width={0.9}
height={0.9}
disabled={isDisabled}
className='mr-3'
onClick={() => dispatch(adt('controlItalics'))} />
<ControlSeparator />
<ControlIcon
name='unordered-list'
width={1}
height={1}
disabled={isDisabled}
className='mr-2'
onClick={() => dispatch(adt('controlUnorderedList'))} />
<ControlIcon
name='ordered-list'
width={1}
height={1}
disabled={isDisabled}
className='mr-3'
onClick={() => dispatch(adt('controlOrderedList'))} />
<ControlSeparator />
<FileLink
className='p-0'
disabled={isDisabled}
style={{
pointerEvents: isDisabled ? 'none' : undefined
}}
onChange={onSelectFile}
accept={SUPPORTED_IMAGE_EXTENSIONS}
color='secondary'>
<Icon name='image' width={1.1} height={1.1} />
</FileLink>
<div className='ml-auto d-flex align-items-center'>
<Spinner
size='sm'
color='secondary'
className={`o-50 ${isLoading ? '' : 'd-none'}`} />
<Link newTab dest={externalDest(MARKDOWN_HELP_URL)} color='primary' className='d-flex justify-content-center align-items-center ml-2' style={{ lineHeight: 0 }}>
<Icon name='markdown' width={1.25} height={1.25} />
</Link>
</div>
</div>
);
};
const ChildView: ChildComponent['view'] = props => {
const { state, dispatch, placeholder, className = '', validityClassName, disabled = false } = props;
const isLoading = state.loading > 0;
const isDisabled = disabled || isLoading;
const onChangeSelection = (target: EventTarget & HTMLTextAreaElement) => {
if (isDisabled) { return; }
const start = target.selectionStart;
const end = target.selectionEnd;
if (start !== state.selectionStart || end !== state.selectionEnd) {
dispatch(adt('onChangeSelection', [start, end]));
}
};
return (
<div className={`form-control ${className} ${validityClassName} p-0 d-flex flex-column flex-nowrap align-items-stretch`}>
<Controls {...props} />
<textarea
id={state.id}
value={state.value}
placeholder={placeholder}
disabled={isDisabled}
className={`${validityClassName} form-control flex-grow-1 border-left-0 border-right-0 border-bottom-0`}
style={{
borderTopLeftRadius: 0,
borderTopRightRadius: 0
}}
ref={ref => {
const start = state.selectionStart;
const end = state.selectionEnd;
if (ref) {
if (ref.selectionStart !== start) { ref.selectionStart = start; }
if (ref.selectionEnd !== end) { ref.selectionEnd = end; }
}
}}
onChange={e => {
const value = e.currentTarget.value;
dispatch(adt('onChangeTextArea', [
value,
e.currentTarget.selectionStart,
e.currentTarget.selectionEnd
]));
// Let the parent form field component know that the value has been updated.
props.onChange(value);
}}
onKeyDown={e => {
const isModifier = e.ctrlKey || e.metaKey;
const isUndo = isModifier && !e.shiftKey && e.keyCode === 90; //Ctrl-Z or Cmd-Z
const isRedo = isModifier && ((e.shiftKey && e.keyCode === 90) || e.keyCode === 89); //Ctrl-Shift-Z, Cmd-Shift-Z, Ctrl-Y or Cmd-Y
const run = (msg: InnerChildMsg) => {
e.preventDefault();
dispatch(msg);
};
if (isUndo) {
run(adt('controlUndo'));
} else if (isRedo) {
run(adt('controlRedo'));
}
}}
onSelect={e => onChangeSelection(e.currentTarget)}>
</textarea>
</div>
);
};
export const component = FormField.makeComponent<Value, ChildParams, ChildState, InnerChildMsg, ExtraChildProps>({
init: childInit,
update: childUpdate,
view: ChildView
});
export const init = component.init;
export const update = component.update;
export const view = component.view;
export default component;