/
caret.ts
587 lines (496 loc) · 17.5 KB
/
caret.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/**
* @class Caret
* @classdesc Contains methods for working Caret
*
* Uses Range methods to manipulate with caret
*
* @module Caret
*
* @version 2.0.0
*/
import Selection from '../selection';
import Module from '../__module';
import Block from '../block';
import $ from '../dom';
import * as _ from '../utils';
/**
* @typedef {Caret} Caret
*/
export default class Caret extends Module {
/**
* Allowed caret positions in input
*
* @static
* @returns {{START: string, END: string, DEFAULT: string}}
*/
public get positions(): {START: string; END: string; DEFAULT: string} {
return {
START: 'start',
END: 'end',
DEFAULT: 'default',
};
}
/**
* Elements styles that can be useful for Caret Module
*/
private static get CSS(): {shadowCaret: string} {
return {
shadowCaret: 'cdx-shadow-caret',
};
}
/**
* Get's deepest first node and checks if offset is zero
*
* @returns {boolean}
*/
public get isAtStart(): boolean {
const selection = Selection.get();
const firstNode = $.getDeepestNode(this.Editor.BlockManager.currentBlock.currentInput);
let focusNode = selection.focusNode;
/** In case lastNode is native input */
if ($.isNativeInput(firstNode)) {
return (firstNode as HTMLInputElement).selectionEnd === 0;
}
/** Case when selection have been cleared programmatically, for example after CBS */
if (!selection.anchorNode) {
return false;
}
/**
* Workaround case when caret in the text like " |Hello!"
* selection.anchorOffset is 1, but real caret visible position is 0
*
* @type {number}
*/
let firstLetterPosition = focusNode.textContent.search(/\S/);
if (firstLetterPosition === -1) { // empty text
firstLetterPosition = 0;
}
/**
* If caret was set by external code, it might be set to text node wrapper.
* <div>|hello</div> <---- Selection references to <div> instead of text node
*
* In this case, anchor node has ELEMENT_NODE node type.
* Anchor offset shows amount of children between start of the element and caret position.
*
* So we use child with focusOffset index as new anchorNode.
*/
let focusOffset = selection.focusOffset;
if (focusNode.nodeType !== Node.TEXT_NODE && focusNode.childNodes.length) {
if (focusNode.childNodes[focusOffset]) {
focusNode = focusNode.childNodes[focusOffset];
focusOffset = 0;
} else {
focusNode = focusNode.childNodes[focusOffset - 1];
focusOffset = focusNode.textContent.length;
}
}
/**
* In case of
* <div contenteditable>
* <p><b></b></p> <-- first (and deepest) node is <b></b>
* |adaddad <-- focus node
* </div>
*/
if ($.isLineBreakTag(firstNode as HTMLElement) || $.isEmpty(firstNode)) {
const leftSiblings = this.getHigherLevelSiblings(focusNode as HTMLElement, 'left');
const nothingAtLeft = leftSiblings.every((node) => {
/**
* Workaround case when block starts with several <br>'s (created by SHIFT+ENTER)
*
* @see https://github.com/codex-team/editor.js/issues/726
* We need to allow to delete such linebreaks, so in this case caret IS NOT AT START
*/
const regularLineBreak = $.isLineBreakTag(node);
/**
* Workaround SHIFT+ENTER in Safari, that creates <div><br></div> instead of <br>
*/
const lineBreakInSafari = node.children.length === 1 && $.isLineBreakTag(node.children[0] as HTMLElement);
const isLineBreak = regularLineBreak || lineBreakInSafari;
return $.isEmpty(node) && !isLineBreak;
});
if (nothingAtLeft && focusOffset === firstLetterPosition) {
return true;
}
}
/**
* We use <= comparison for case:
* "| Hello" <--- selection.anchorOffset is 0, but firstLetterPosition is 1
*/
return firstNode === null || (focusNode === firstNode && focusOffset <= firstLetterPosition);
}
/**
* Get's deepest last node and checks if offset is last node text length
*
* @returns {boolean}
*/
public get isAtEnd(): boolean {
const selection = Selection.get();
let focusNode = selection.focusNode;
const lastNode = $.getDeepestNode(this.Editor.BlockManager.currentBlock.currentInput, true);
/** In case lastNode is native input */
if ($.isNativeInput(lastNode)) {
return (lastNode as HTMLInputElement).selectionEnd === (lastNode as HTMLInputElement).value.length;
}
/** Case when selection have been cleared programmatically, for example after CBS */
if (!selection.focusNode) {
return false;
}
/**
* If caret was set by external code, it might be set to text node wrapper.
* <div>hello|</div> <---- Selection references to <div> instead of text node
*
* In this case, anchor node has ELEMENT_NODE node type.
* Anchor offset shows amount of children between start of the element and caret position.
*
* So we use child with anchofocusOffset - 1 as new focusNode.
*/
let focusOffset = selection.focusOffset;
if (focusNode.nodeType !== Node.TEXT_NODE && focusNode.childNodes.length) {
if (focusNode.childNodes[focusOffset - 1]) {
focusNode = focusNode.childNodes[focusOffset - 1];
focusOffset = focusNode.textContent.length;
} else {
focusNode = focusNode.childNodes[0];
focusOffset = 0;
}
}
/**
* In case of
* <div contenteditable>
* adaddad| <-- anchor node
* <p><b></b></p> <-- first (and deepest) node is <b></b>
* </div>
*/
if ($.isLineBreakTag(lastNode as HTMLElement) || $.isEmpty(lastNode)) {
const rightSiblings = this.getHigherLevelSiblings(focusNode as HTMLElement, 'right');
const nothingAtRight = rightSiblings.every((node, i) => {
/**
* If last right sibling is BR isEmpty returns false, but there actually nothing at right
*/
const isLastBR = i === rightSiblings.length - 1 && $.isLineBreakTag(node as HTMLElement);
return isLastBR || ($.isEmpty(node) && !$.isLineBreakTag(node));
});
if (nothingAtRight && focusOffset === focusNode.textContent.length) {
return true;
}
}
/**
* Workaround case:
* hello | <--- anchorOffset will be 5, but textContent.length will be 6.
* Why not regular .trim():
* in case of ' hello |' trim() will also remove space at the beginning, so length will be lower than anchorOffset
*/
const rightTrimmedText = lastNode.textContent.replace(/\s+$/, '');
/**
* We use >= comparison for case:
* "Hello |" <--- selection.anchorOffset is 7, but rightTrimmedText is 6
*/
return focusNode === lastNode && focusOffset >= rightTrimmedText.length;
}
/**
* Method gets Block instance and puts caret to the text node with offset
* There two ways that method applies caret position:
* - first found text node: sets at the beginning, but you can pass an offset
* - last found text node: sets at the end of the node. Also, you can customize the behaviour
*
* @param {Block} block - Block class
* @param {string} position - position where to set caret.
* If default - leave default behaviour and apply offset if it's passed
* @param {number} offset - caret offset regarding to the text node
*/
public setToBlock(block: Block, position: string = this.positions.DEFAULT, offset = 0): void {
const { BlockManager } = this.Editor;
let element;
switch (position) {
case this.positions.START:
element = block.firstInput;
break;
case this.positions.END:
element = block.lastInput;
break;
default:
element = block.currentInput;
}
if (!element) {
return;
}
const nodeToSet = $.getDeepestNode(element, position === this.positions.END);
const contentLength = $.getContentLength(nodeToSet);
switch (true) {
case position === this.positions.START:
offset = 0;
break;
case position === this.positions.END:
case offset > contentLength:
offset = contentLength;
break;
}
/**
* @todo try to fix via Promises or use querySelectorAll to not to use timeout
*/
_.delay(() => {
this.set(nodeToSet as HTMLElement, offset);
}, 20)();
BlockManager.setCurrentBlockByChildNode(block.holder);
BlockManager.currentBlock.currentInput = element;
}
/**
* Set caret to the current input of current Block.
*
* @param {HTMLElement} input - input where caret should be set
* @param {string} position - position of the caret.
* If default - leave default behaviour and apply offset if it's passed
* @param {number} offset - caret offset regarding to the text node
*/
public setToInput(input: HTMLElement, position: string = this.positions.DEFAULT, offset = 0): void {
const { currentBlock } = this.Editor.BlockManager;
const nodeToSet = $.getDeepestNode(input);
switch (position) {
case this.positions.START:
this.set(nodeToSet as HTMLElement, 0);
break;
case this.positions.END:
this.set(nodeToSet as HTMLElement, $.getContentLength(nodeToSet));
break;
default:
if (offset) {
this.set(nodeToSet as HTMLElement, offset);
}
}
currentBlock.currentInput = input;
}
/**
* Creates Document Range and sets caret to the element with offset
*
* @param {HTMLElement} element - target node.
* @param {number} offset - offset
*/
public set(element: HTMLElement, offset = 0): void {
const range = document.createRange(),
selection = Selection.get();
/** if found deepest node is native input */
if ($.isNativeInput(element)) {
if (!$.canSetCaret(element)) {
return;
}
element.focus();
(element as HTMLInputElement).selectionStart = (element as HTMLInputElement).selectionEnd = offset;
return;
}
range.setStart(element, offset);
range.setEnd(element, offset);
selection.removeAllRanges();
selection.addRange(range);
/** If new cursor position is not visible, scroll to it */
const { top, bottom } = element.nodeType === Node.ELEMENT_NODE
? element.getBoundingClientRect()
: range.getBoundingClientRect();
const { innerHeight } = window;
if (top < 0) {
window.scrollBy(0, top);
}
if (bottom > innerHeight) {
window.scrollBy(0, bottom - innerHeight);
}
}
/**
* Set Caret to the last Block
* If last block is not empty, append another empty block
*/
public setToTheLastBlock(): void {
const lastBlock = this.Editor.BlockManager.lastBlock;
if (!lastBlock) {
return;
}
/**
* If last block is empty and it is an initialBlock, set to that.
* Otherwise, append new empty block and set to that
*/
if (this.Editor.Tools.isInitial(lastBlock.tool) && lastBlock.isEmpty) {
this.setToBlock(lastBlock);
} else {
const newBlock = this.Editor.BlockManager.insertAtEnd();
this.setToBlock(newBlock);
}
}
/**
* Extract content fragment of current Block from Caret position to the end of the Block
*/
public extractFragmentFromCaretPosition(): void|DocumentFragment {
const selection = Selection.get();
if (selection.rangeCount) {
const selectRange = selection.getRangeAt(0);
const currentBlockInput = this.Editor.BlockManager.currentBlock.currentInput;
selectRange.deleteContents();
if (currentBlockInput) {
const range = selectRange.cloneRange();
range.selectNodeContents(currentBlockInput);
range.setStart(selectRange.endContainer, selectRange.endOffset);
return range.extractContents();
}
}
}
/**
* Set's caret to the next Block or Tool`s input
* Before moving caret, we should check if caret position is at the end of Plugins node
* Using {@link Dom#getDeepestNode} to get a last node and match with current selection
*
* @param {boolean} force - force navigation even if caret is not at the end
*
* @returns {boolean}
*/
public navigateNext(force = false): boolean {
const { BlockManager, Tools } = this.Editor;
const { currentBlock, nextContentfulBlock } = BlockManager;
const { nextInput } = currentBlock;
let nextBlock = nextContentfulBlock;
if (!nextBlock && !nextInput) {
/**
* If there is no nextBlock and currentBlock is initial, do not navigate
*/
if (Tools.isInitial(currentBlock.tool)) {
return false;
}
/**
* If there is no nextBlock, but currentBlock is not initial,
* insert new initial block at the end and navigate to it
*/
nextBlock = BlockManager.insertAtEnd();
}
if (force || this.isAtEnd) {
/** If next Tool`s input exists, focus on it. Otherwise set caret to the next Block */
if (!nextInput) {
this.setToBlock(nextBlock, this.positions.START);
} else {
this.setToInput(nextInput, this.positions.START);
}
return true;
}
return false;
}
/**
* Set's caret to the previous Tool`s input or Block
* Before moving caret, we should check if caret position is start of the Plugins node
* Using {@link Dom#getDeepestNode} to get a last node and match with current selection
*
* @param {boolean} force - force navigation even if caret is not at the start
*
* @returns {boolean}
*/
public navigatePrevious(force = false): boolean {
const { currentBlock, previousContentfulBlock } = this.Editor.BlockManager;
if (!currentBlock) {
return false;
}
const { previousInput } = currentBlock;
if (!previousContentfulBlock && !previousInput) {
return false;
}
if (force || this.isAtStart) {
/** If previous Tool`s input exists, focus on it. Otherwise set caret to the previous Block */
if (!previousInput) {
this.setToBlock(previousContentfulBlock, this.positions.END);
} else {
this.setToInput(previousInput, this.positions.END);
}
return true;
}
return false;
}
/**
* Inserts shadow element after passed element where caret can be placed
*
* @param {Element} element - element after which shadow caret should be inserted
*/
public createShadow(element: Element): void {
const shadowCaret = document.createElement('span');
shadowCaret.classList.add(Caret.CSS.shadowCaret);
element.insertAdjacentElement('beforeend', shadowCaret);
}
/**
* Restores caret position
*
* @param {HTMLElement} element - element where caret should be restored
*/
public restoreCaret(element: HTMLElement): void {
const shadowCaret = element.querySelector(`.${Caret.CSS.shadowCaret}`);
if (!shadowCaret) {
return;
}
/**
* After we set the caret to the required place
* we need to clear shadow caret
*
* - make new range
* - select shadowed span
* - use extractContent to remove it from DOM
*/
const sel = new Selection();
sel.expandToTag(shadowCaret as HTMLElement);
setTimeout(() => {
const newRange = document.createRange();
newRange.selectNode(shadowCaret);
newRange.extractContents();
}, 50);
}
/**
* Inserts passed content at caret position
*
* @param {string} content - content to insert
*/
public insertContentAtCaretPosition(content: string): void {
const fragment = document.createDocumentFragment();
const wrapper = document.createElement('div');
const selection = Selection.get();
const range = Selection.range;
wrapper.innerHTML = content;
Array.from(wrapper.childNodes).forEach((child: Node) => fragment.appendChild(child));
const lastChild = fragment.lastChild;
range.deleteContents();
range.insertNode(fragment);
/** Cross-browser caret insertion */
const newRange = document.createRange();
newRange.setStart(lastChild, lastChild.textContent.length);
selection.removeAllRanges();
selection.addRange(newRange);
}
/**
* Get all first-level (first child of [contenteditabel]) siblings from passed node
* Then you can check it for emptiness
*
* @example
* <div contenteditable>
* <p></p> |
* <p></p> | left first-level siblings
* <p></p> |
* <blockquote><a><b>adaddad</b><a><blockquote> <-- passed node for example <b>
* <p></p> |
* <p></p> | right first-level siblings
* <p></p> |
* </div>
*
* @param {HTMLElement} from - element from which siblings should be searched
* @param {'left' | 'right'} direction - direction of search
*
* @returns {HTMLElement[]}
*/
private getHigherLevelSiblings(from: HTMLElement, direction?: 'left' | 'right'): HTMLElement[] {
let current = from;
const siblings = [];
/**
* Find passed node's firs-level parent (in example - blockquote)
*/
while (current.parentNode && (current.parentNode as HTMLElement).contentEditable !== 'true') {
current = current.parentNode as HTMLElement;
}
const sibling = direction === 'left' ? 'previousSibling' : 'nextSibling';
/**
* Find all left/right siblings
*/
while (current[sibling]) {
current = current[sibling] as HTMLElement;
siblings.push(current);
}
return siblings;
}
}