-
Notifications
You must be signed in to change notification settings - Fork 13
/
useEditable.ts
423 lines (364 loc) · 13 KB
/
useEditable.ts
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
import {
RefObject,
useCallback,
useState,
useRef,
useLayoutEffect,
} from 'react';
interface Position {
position: number;
content: string;
line: number;
}
type History = [Position, string];
type ChangeHandler = (text: string, position: Position) => void;
type UpdateAction = (content: string) => void;
const observerSettings = {
characterData: true,
characterDataOldValue: true,
childList: true,
subtree: true,
};
const isUndoRedoKey = (event: KeyboardEvent): boolean =>
(event.metaKey || event.ctrlKey) && event.code === 'KeyZ';
const toString = (element: HTMLElement): string => {
const queue: Node[] = [element.firstChild!];
let content = '';
let node: Node;
while ((node = queue.pop()!)) {
if (node.nodeType === Node.TEXT_NODE) {
content += node.textContent;
} else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
content += '\n';
}
if (node.nextSibling) queue.push(node.nextSibling);
if (node.firstChild) queue.push(node.firstChild);
}
// contenteditable Quirk: Without plaintext-only a pre/pre-wrap element must always
// end with at least one newline character
if (content[content.length - 1] !== '\n') content += '\n';
return content;
};
const getPosition = (element: HTMLElement): Position => {
const selection = window.getSelection()!;
const queue: Node[] = [element.firstChild!];
// Without plaintext-only mode we may get a node and an offset of one of its children
// if the selection happens to land in-between nodes
let { focusNode, focusOffset } = selection;
if (focusNode && focusNode.nodeType !== Node.TEXT_NODE) {
if (focusOffset <= focusNode.childNodes.length - 1)
focusNode = focusNode.childNodes[focusOffset];
focusOffset = 0;
}
let position = 0;
let line = 0;
let content = '';
let node: Node | void;
while ((node = queue.pop()!)) {
if (node.nodeType === Node.TEXT_NODE) {
let textContent = node.textContent!;
if (node === focusNode) {
textContent = textContent.slice(0, focusOffset);
}
position += textContent.length;
content += textContent;
const newlineRe = /\n/g;
let match: RegExpExecArray | null;
while ((match = newlineRe.exec(textContent))) {
content = textContent.slice(match.index + 1);
line++;
}
if (node === focusNode) break;
} else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
content = '';
line++;
position++;
}
if (node.nextSibling && node !== focusNode) queue.push(node.nextSibling);
if (node.firstChild) queue.push(node.firstChild);
}
return {
position,
content,
line,
};
};
const setPosition = (element: HTMLElement, position: number): void => {
const selection = window.getSelection()!;
const range = document.createRange();
const queue: Node[] = [element.firstChild!];
let current = 0;
let node: Node;
while ((node = queue.pop()!)) {
if (node.nodeType === Node.TEXT_NODE) {
const length = node.textContent!.length;
if (current + length >= position) {
const offset = position - current;
if (offset === length) {
range.setStartAfter(node);
} else {
range.setStart(node, offset);
}
break;
}
current += node.textContent!.length;
} else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
if (current + 1 >= position) {
range.setStartAfter(node);
break;
}
current++;
}
if (node.nextSibling) queue.push(node.nextSibling);
if (node.firstChild) queue.push(node.firstChild);
}
selection.empty();
selection.addRange(range);
};
const insert = (text: string) => {
const selection = window.getSelection()!;
let range = window.getSelection()!.getRangeAt(0)!;
const node = document.createTextNode(text);
selection.getRangeAt(0).deleteContents();
range.insertNode(node);
range = document.createRange();
range.setStartAfter(node);
selection.empty();
selection.addRange(range);
};
interface Options {
disabled?: boolean;
indentation?: number;
}
export const useEditable = (
elementRef: RefObject<HTMLElement>,
onChange: ChangeHandler,
opts?: Options
): UpdateAction => {
if (!opts) opts = {};
const unblock = useState([])[1];
const onChangeRef = useRef(onChange);
const positionRef = useRef(-1);
const historyRef = useRef<History[]>([]);
const historyAtRef = useRef(-1);
const queueRef = useRef<MutationRecord[]>([]);
const addMutationsToQueue = (list: MutationRecord[]) => {
for (let i = 0; i < list.length; i++) queueRef.current.push(list[i]);
};
const disconnectedRef = useRef(false);
const observerRef = useRef(new MutationObserver(addMutationsToQueue));
onChangeRef.current = onChange;
const update = useCallback((content: string) => {
const { current: element } = elementRef;
if (element) {
const position = getPosition(element);
const prevContent = toString(element);
positionRef.current =
position.position + (content.length - prevContent.length);
onChangeRef.current(content, position);
}
}, []);
// Only for SSR / server-side logic
if (typeof navigator !== 'object') return update;
useLayoutEffect(() => {
if (!elementRef.current || opts!.disabled) return;
disconnectedRef.current = false;
observerRef.current.observe(elementRef.current, observerSettings);
if (positionRef.current >= 0) {
setPosition(elementRef.current, positionRef.current);
}
return () => {
observerRef.current.disconnect();
};
});
useLayoutEffect(() => {
if (!elementRef.current || opts!.disabled) {
historyRef.current.length = 0;
historyAtRef.current = -1;
return;
}
const element = elementRef.current!;
if (positionRef.current > -1) {
element.focus();
setPosition(element, positionRef.current);
}
const prevWhiteSpace = element.style.whiteSpace;
const prevContentEditable = element.contentEditable;
let hasPlaintextSupport = true;
try {
// Firefox and IE11 do not support plaintext-only mode
element.contentEditable = 'plaintext-only';
} catch (_error) {
element.contentEditable = 'true';
hasPlaintextSupport = false;
}
if (prevWhiteSpace !== 'pre') element.style.whiteSpace = 'pre-wrap';
if (opts!.indentation) {
element.style.tabSize = (element.style as any).MozTabSize =
'' + opts!.indentation;
}
const indentRe = new RegExp(
`^(?:${' '.repeat(opts!.indentation || 0)}|\\t)`
);
let _trackStateTimestamp: number;
const trackState = (ignoreTimestamp?: boolean) => {
if (!elementRef.current || positionRef.current === -1) return;
const { current: history } = historyRef;
const content = toString(element);
const position = getPosition(element);
const timestamp = new Date().valueOf();
// Prevent recording new state in list if last one has been new enough
const lastEntry = history[historyAtRef.current];
if (
(!ignoreTimestamp && timestamp - _trackStateTimestamp < 500) ||
(lastEntry && lastEntry[1] === content)
) {
_trackStateTimestamp = timestamp;
return;
}
const at = ++historyAtRef.current;
history[at] = [position, content];
history.splice(at + 1);
if (at > 500) {
historyAtRef.current--;
history.shift();
}
};
const disconnect = () => {
observerRef.current.disconnect();
disconnectedRef.current = true;
};
const flushChanges = () => {
addMutationsToQueue(observerRef.current.takeRecords());
if (queueRef.current.length > 0) {
disconnect();
const content = toString(element);
const position = getPosition(element);
positionRef.current = position.position;
let mutation: MutationRecord | void;
let i = 0;
while ((mutation = queueRef.current.pop())) {
if (mutation.oldValue !== null)
mutation.target.textContent = mutation.oldValue;
for (i = mutation.removedNodes.length - 1; i >= 0; i--)
mutation.target.insertBefore(
mutation.removedNodes[i],
mutation.nextSibling
);
for (i = mutation.addedNodes.length - 1; i >= 0; i--)
if (mutation.addedNodes[i].parentNode)
mutation.target.removeChild(mutation.addedNodes[i]);
}
onChangeRef.current(content, position);
}
};
const onKeyDown = (event: HTMLElementEventMap['keydown']) => {
if (event.defaultPrevented || event.target !== element) {
return;
} else if (disconnectedRef.current) {
// React Quirk: It's expected that we may lose events while disconnected, which is why
// we'd like to block some inputs if they're unusually fast. However, this always
// coincides with React not executing the update immediately and then getting stuck,
// which can be prevented by issuing a dummy state change.
event.preventDefault();
return unblock([]);
}
if (isUndoRedoKey(event)) {
event.preventDefault();
let history: History;
if (!event.shiftKey) {
const at = --historyAtRef.current;
history = historyRef.current[at];
if (!history) historyAtRef.current = 0;
} else {
const at = ++historyAtRef.current;
history = historyRef.current[at];
if (!history) historyAtRef.current = historyRef.current.length - 1;
}
if (history) {
disconnect();
positionRef.current = history[0].position;
onChangeRef.current(history[1], history[0]);
}
return;
} else {
trackState();
}
if (event.key === 'Enter') {
event.preventDefault();
// Firefox / IE11 Quirk: Since plaintext-only is unsupported we must
// ensure that only newline characters are inserted
const position = getPosition(element);
// We also get the current line and preserve indentation for the next
// line that's created
const match = /\S/g.exec(position.content);
const index = match ? match.index : position.content.length;
const text = '\n' + position.content.slice(0, index);
insert(text);
} else if (!hasPlaintextSupport && event.key === 'Backspace') {
event.preventDefault();
const range = window.getSelection()!.getRangeAt(0)!;
if (
range.startContainer !== range.endContainer ||
range.startOffset !== range.endOffset
) {
range.deleteContents();
} else {
// Firefox Quirk: Backspacing won't preserve the correct position
// so it's easier to reimplement it and skip rendering for normal backspacing
disconnect();
const position = getPosition(element);
const index = Math.max(0, position.position - 1);
const content = toString(element);
update(content.slice(0, index) + content.slice(index + 1));
}
} else if (opts!.indentation && event.key === 'Tab') {
event.preventDefault();
const position = getPosition(element);
const start = position.position - position.content.length;
const content = toString(element);
const newContent = event.shiftKey
? content.slice(0, start) +
position.content.replace(indentRe, '') +
content.slice(start + position.content.length)
: content.slice(0, start) + '\t' + content.slice(start);
update(newContent);
}
};
const onKeyUp = (event: HTMLElementEventMap['keyup']) => {
if (event.defaultPrevented || event.isComposing) return;
if (!isUndoRedoKey(event)) trackState();
flushChanges();
// Chrome Quirk: The contenteditable may lose focus after the first edit or so
element.focus();
};
const onFocus = () => {
positionRef.current = getPosition(element).position;
};
const onBlur = () => {
positionRef.current = -1;
};
const onPaste = (event: HTMLElementEventMap['paste']) => {
event.preventDefault();
trackState(true);
insert(event.clipboardData!.getData('text/plain'));
trackState(true);
flushChanges();
};
window.addEventListener('keydown', onKeyDown);
element.addEventListener('focus', onFocus);
element.addEventListener('blur', onBlur);
element.addEventListener('paste', onPaste);
element.addEventListener('keyup', onKeyUp);
return () => {
window.removeEventListener('keydown', onKeyDown);
element.removeEventListener('focus', onFocus);
element.removeEventListener('blur', onBlur);
element.removeEventListener('paste', onPaste);
element.removeEventListener('keyup', onKeyUp);
element.style.whiteSpace = prevWhiteSpace;
element.contentEditable = prevContentEditable;
};
}, [elementRef.current!, opts!.disabled, opts!.indentation]);
return update;
};