• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

worktile / slate-angular / eb354b3b-ecec-4650-9fe3-f777f328d104

07 Jan 2026 06:50AM UTC coverage: 36.491% (-0.2%) from 36.662%
eb354b3b-ecec-4650-9fe3-f777f328d104

Pull #331

circleci

Xwatson
Merge branch 'master' into xws/#WIK-19723
Pull Request #331: fix(virtual-scroll): #WIK-19723 clear the collapsed and hidden selection

394 of 1283 branches covered (30.71%)

Branch coverage included in aggregate %.

0 of 10 new or added lines in 1 file covered. (0.0%)

254 existing lines in 1 file now uncovered.

1093 of 2792 relevant lines covered (39.15%)

24.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

22.23
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    HostBinding,
6
    Renderer2,
7
    ElementRef,
8
    ChangeDetectionStrategy,
9
    OnDestroy,
10
    ChangeDetectorRef,
11
    NgZone,
12
    Injector,
13
    forwardRef,
14
    OnChanges,
15
    SimpleChanges,
16
    AfterViewChecked,
17
    DoCheck,
18
    inject,
19
    ViewContainerRef
20
} from '@angular/core';
21
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node, Selection } from 'slate';
22
import { direction } from 'direction';
23
import scrollIntoView from 'scroll-into-view-if-needed';
24
import { AngularEditor } from '../../plugins/angular-editor';
25
import {
26
    DOMElement,
27
    isDOMNode,
28
    DOMStaticRange,
29
    DOMRange,
30
    isDOMElement,
31
    isPlainTextOnlyPaste,
32
    DOMSelection,
33
    getDefaultView,
34
    EDITOR_TO_WINDOW,
35
    EDITOR_TO_ELEMENT,
36
    NODE_TO_ELEMENT,
37
    ELEMENT_TO_NODE,
38
    IS_FOCUSED,
39
    IS_READ_ONLY
40
} from 'slate-dom';
41
import { Subject } from 'rxjs';
42
import {
43
    IS_FIREFOX,
44
    IS_SAFARI,
45
    IS_CHROME,
46
    HAS_BEFORE_INPUT_SUPPORT,
47
    IS_ANDROID,
48
    SLATE_DEBUG_KEY,
49
    SLATE_DEBUG_KEY_SCROLL_TOP
50
} from '../../utils/environment';
51
import Hotkeys from '../../utils/hotkeys';
52
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
53
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
54
import { SlateErrorCode } from '../../types/error';
55
import { NG_VALUE_ACCESSOR } from '@angular/forms';
56
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
57
import { ViewType } from '../../types/view';
58
import { HistoryEditor } from 'slate-history';
59
import {
60
    buildHeightsAndAccumulatedHeights,
61
    EDITOR_TO_BUSINESS_TOP,
62
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
63
    ELEMENT_KEY_TO_HEIGHTS,
64
    getBusinessTop,
65
    getRealHeightByElement,
66
    IS_ENABLED_VIRTUAL_SCROLL,
67
    isDebug,
68
    isDebugScrollTop,
69
    isDecoratorRangeListEqual,
70
    measureHeightByIndics
71
} from '../../utils';
72
import { SlatePlaceholder } from '../../types/feature';
73
import { restoreDom } from '../../utils/restore-dom';
74
import { ListRender } from '../../view/render/list-render';
75
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
76
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
77
import { isKeyHotkey } from 'is-hotkey';
78
import { calculateVirtualTopHeight, debugLog, EDITOR_TO_ROOT_NODE_WIDTH } from '../../utils/virtual-scroll';
79

80
// not correctly clipboardData on beforeinput
81
const forceOnDOMPaste = IS_SAFARI;
1✔
82

83
@Component({
84
    selector: 'slate-editable',
85
    host: {
86
        class: 'slate-editable-container',
87
        '[attr.contenteditable]': 'readonly ? undefined : true',
88
        '[attr.role]': `readonly ? undefined : 'textbox'`,
89
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
90
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
91
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
92
    },
93
    template: '',
94
    changeDetection: ChangeDetectionStrategy.OnPush,
95
    providers: [
96
        {
97
            provide: NG_VALUE_ACCESSOR,
98
            useExisting: forwardRef(() => SlateEditable),
23✔
99
            multi: true
100
        }
101
    ],
102
    imports: []
103
})
104
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
105
    viewContext: SlateViewContext;
106
    context: SlateChildrenContext;
107

108
    private destroy$ = new Subject();
23✔
109

110
    isComposing = false;
23✔
111
    isDraggingInternally = false;
23✔
112
    isUpdatingSelection = false;
23✔
113
    latestElement = null as DOMElement | null;
23✔
114

115
    protected manualListeners: (() => void)[] = [];
23✔
116

117
    private initialized: boolean;
118

119
    private onTouchedCallback: () => void = () => {};
23✔
120

121
    private onChangeCallback: (_: any) => void = () => {};
23✔
122

123
    @Input() editor: AngularEditor;
124

125
    @Input() renderElement: (element: Element) => ViewType | null;
126

127
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
128

129
    @Input() renderText: (text: SlateText) => ViewType | null;
130

131
    @Input() decorate: (entry: NodeEntry) => Range[] = () => [];
228✔
132

133
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
134

135
    @Input() scrollSelectionIntoView: (editor: AngularEditor, domRange: DOMRange) => void = defaultScrollSelectionIntoView;
23✔
136

137
    @Input() isStrictDecorate: boolean = true;
23✔
138

139
    @Input() trackBy: (node: Element) => any = () => null;
206✔
140

141
    @Input() readonly = false;
23✔
142

143
    @Input() placeholder: string;
144

145
    @Input()
146
    set virtualScroll(config: SlateVirtualScrollConfig) {
147
        this.virtualScrollConfig = config;
×
148
        if (isDebugScrollTop) {
×
149
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
150
        }
151
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
152
        if (this.isEnabledVirtualScroll()) {
×
153
            this.tryUpdateVirtualViewport();
×
154
        }
155
    }
156

157
    //#region input event handler
158
    @Input() beforeInput: (event: Event) => void;
159
    @Input() blur: (event: Event) => void;
160
    @Input() click: (event: MouseEvent) => void;
161
    @Input() compositionEnd: (event: CompositionEvent) => void;
162
    @Input() compositionUpdate: (event: CompositionEvent) => void;
163
    @Input() compositionStart: (event: CompositionEvent) => void;
164
    @Input() copy: (event: ClipboardEvent) => void;
165
    @Input() cut: (event: ClipboardEvent) => void;
166
    @Input() dragOver: (event: DragEvent) => void;
167
    @Input() dragStart: (event: DragEvent) => void;
168
    @Input() dragEnd: (event: DragEvent) => void;
169
    @Input() drop: (event: DragEvent) => void;
170
    @Input() focus: (event: Event) => void;
171
    @Input() keydown: (event: KeyboardEvent) => void;
172
    @Input() paste: (event: ClipboardEvent) => void;
173
    //#endregion
174

175
    //#region DOM attr
176
    @Input() spellCheck = false;
23✔
177
    @Input() autoCorrect = false;
23✔
178
    @Input() autoCapitalize = false;
23✔
179

180
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
181
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
182
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
183

184
    get hasBeforeInputSupport() {
185
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
186
    }
187
    //#endregion
188

189
    viewContainerRef = inject(ViewContainerRef);
23✔
190

191
    getOutletParent = () => {
23✔
192
        return this.elementRef.nativeElement;
43✔
193
    };
194

195
    getOutletElement = () => {
23✔
196
        if (this.virtualScrollInitialized) {
23!
197
            return this.virtualCenterOutlet;
×
198
        } else {
199
            return null;
23✔
200
        }
201
    };
202

203
    listRender: ListRender;
204

205
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
206
        enabled: false,
207
        scrollTop: 0,
208
        viewportHeight: 0,
209
        viewportBoundingTop: 0,
210
        scrollContainer: null
211
    };
212

213
    private inViewportChildren: Element[] = [];
23✔
214
    private inViewportIndics: number[] = [];
23✔
215
    private keyHeightMap = new Map<string, number>();
23✔
216
    private tryUpdateVirtualViewportAnimId: number;
217
    private tryMeasureInViewportChildrenHeightsAnimId: number;
218
    private editorResizeObserver?: ResizeObserver;
219

220
    constructor(
221
        public elementRef: ElementRef,
23✔
222
        public renderer2: Renderer2,
23✔
223
        public cdr: ChangeDetectorRef,
23✔
224
        private ngZone: NgZone,
23✔
225
        private injector: Injector
23✔
226
    ) {}
227

228
    ngOnInit() {
229
        this.editor.injector = this.injector;
23✔
230
        this.editor.children = [];
23✔
231
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
232
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
233
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
234
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
235
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
236
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
237
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
238
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
239
            this.ngZone.run(() => {
13✔
240
                this.onChange();
13✔
241
            });
242
        });
243
        this.ngZone.runOutsideAngular(() => {
23✔
244
            this.initialize();
23✔
245
        });
246
        this.initializeViewContext();
23✔
247
        this.initializeContext();
23✔
248

249
        // add browser class
250
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
251
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
252
        this.initializeVirtualScroll();
23✔
253
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
254
    }
255

256
    ngOnChanges(simpleChanges: SimpleChanges) {
257
        if (!this.initialized) {
30✔
258
            return;
23✔
259
        }
260
        const decorateChange = simpleChanges['decorate'];
7✔
261
        if (decorateChange) {
7✔
262
            this.forceRender();
2✔
263
        }
264
        const placeholderChange = simpleChanges['placeholder'];
7✔
265
        if (placeholderChange) {
7✔
266
            this.render();
1✔
267
        }
268
        const readonlyChange = simpleChanges['readonly'];
7✔
269
        if (readonlyChange) {
7!
270
            IS_READ_ONLY.set(this.editor, this.readonly);
×
271
            this.render();
×
272
            this.toSlateSelection();
×
273
        }
274
    }
275

276
    registerOnChange(fn: any) {
277
        this.onChangeCallback = fn;
23✔
278
    }
279
    registerOnTouched(fn: any) {
280
        this.onTouchedCallback = fn;
23✔
281
    }
282

283
    writeValue(value: Element[]) {
284
        if (value && value.length) {
49✔
285
            this.editor.children = value;
26✔
286
            this.initializeContext();
26✔
287
            if (this.isEnabledVirtualScroll()) {
26!
288
                const virtualView = this.calculateVirtualViewport();
×
289
                this.applyVirtualView(virtualView);
×
290
                const childrenForRender = virtualView.inViewportChildren;
×
291
                if (isDebug) {
×
292
                    debugLog('log', 'writeValue calculate: ', virtualView.inViewportIndics, 'initialized: ', this.listRender.initialized);
×
293
                }
294
                if (!this.listRender.initialized) {
×
295
                    this.listRender.initialize(childrenForRender, this.editor, this.context, 0, virtualView.inViewportIndics);
×
296
                } else {
297
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
298
                    this.listRender.update(
×
299
                        childrenWithPreRendering,
300
                        this.editor,
301
                        this.context,
302
                        preRenderingCount,
303
                        childrenWithPreRenderingIndics
304
                    );
305
                }
306
            } else {
307
                if (!this.listRender.initialized) {
26✔
308
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
309
                } else {
310
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
311
                }
312
            }
313
            this.cdr.markForCheck();
26✔
314
        }
315
    }
316

317
    initialize() {
318
        this.initialized = true;
23✔
319
        const window = AngularEditor.getWindow(this.editor);
23✔
320
        this.addEventListener(
23✔
321
            'selectionchange',
322
            event => {
323
                this.toSlateSelection();
2✔
324
            },
325
            window.document
326
        );
327
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
328
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
329
        }
330
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
331
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
332
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
333
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
334
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
335
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
336
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
337
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
338
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
339
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
340
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
341
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
342
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
343
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
344
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
345
            this.addEventListener(event.name, () => {});
115✔
346
        });
347
    }
348

349
    calculateVirtualScrollSelection(selection: Selection) {
350
        if (selection) {
×
NEW
351
            if (this.isSelectionHidden(selection)) {
×
NEW
352
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
NEW
353
                return null;
×
354
            }
UNCOV
355
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
UNCOV
356
            const indics = this.inViewportIndics;
×
UNCOV
357
            if (indics.length > 0) {
×
358
                const currentVisibleRange: Range = {
×
359
                    anchor: Editor.start(this.editor, [indics[0]]),
360
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
361
                };
UNCOV
362
                const [start, end] = Range.edges(selection);
×
363
                let forwardSelection = { anchor: start, focus: end };
×
UNCOV
364
                if (!isBlockCardCursor) {
×
365
                    forwardSelection = { anchor: start, focus: end };
×
366
                } else {
367
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
368
                }
369
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
370
                if (intersectedSelection && isBlockCardCursor) {
×
371
                    return selection;
×
372
                }
UNCOV
373
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
UNCOV
374
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
UNCOV
375
                    if (isDebug) {
×
UNCOV
376
                        debugLog(
×
377
                            'log',
378
                            `selection is not in visible range, selection: ${JSON.stringify(
379
                                selection
380
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
381
                        );
382
                    }
UNCOV
383
                    return intersectedSelection;
×
384
                }
385
                return selection;
×
386
            }
387
        }
388
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
389
        return selection;
×
390
    }
391

392
    private isSelectionHidden(selection?: Selection | null) {
NEW
393
        if (!this.isEnabledVirtualScroll() || !selection) {
×
NEW
394
            return false;
×
395
        }
NEW
UNCOV
396
        const anchorIndex = selection.anchor.path[0];
×
NEW
UNCOV
397
        const focusIndex = selection.focus.path[0];
×
NEW
UNCOV
398
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
×
NEW
399
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
×
NEW
400
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
×
401
    }
402

403
    toNativeSelection(autoScroll = true) {
15✔
404
        try {
15✔
405
            let { selection } = this.editor;
15✔
406
            if (this.isEnabledVirtualScroll()) {
15!
UNCOV
407
                selection = this.calculateVirtualScrollSelection(selection);
×
408
            }
409
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
410
            const { activeElement } = root;
15✔
411
            const domSelection = (root as Document).getSelection();
15✔
412

413
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
414
                return;
14✔
415
            }
416

417
            const hasDomSelection = domSelection.type !== 'None';
1✔
418

419
            // If the DOM selection is properly unset, we're done.
420
            if (!selection && !hasDomSelection) {
1!
UNCOV
421
                return;
×
422
            }
423

424
            // If the DOM selection is already correct, we're done.
425
            // verify that the dom selection is in the editor
426
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
427
            let hasDomSelectionInEditor = false;
1✔
428
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
429
                hasDomSelectionInEditor = true;
1✔
430
            }
431

432
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
433
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
434
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
435
                    exactMatch: false,
436
                    suppressThrow: true
437
                });
438
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
UNCOV
439
                    return;
×
440
                }
441
            }
442

443
            // prevent updating native selection when active element is void element
444
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
UNCOV
445
                return;
×
446
            }
447

448
            // when <Editable/> is being controlled through external value
449
            // then its children might just change - DOM responds to it on its own
450
            // but Slate's value is not being updated through any operation
451
            // and thus it doesn't transform selection on its own
452
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
UNCOV
453
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
UNCOV
454
                return;
×
455
            }
456

457
            // Otherwise the DOM selection is out of sync, so update it.
458
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
459
            this.isUpdatingSelection = true;
1✔
460

461
            const newDomRange = selection && AngularEditor.toDOMRange(this.editor, selection);
1✔
462

463
            if (newDomRange) {
1!
464
                // COMPAT: Since the DOM range has no concept of backwards/forwards
465
                // we need to check and do the right thing here.
466
                if (Range.isBackward(selection)) {
1!
467
                    // eslint-disable-next-line max-len
UNCOV
468
                    domSelection.setBaseAndExtent(
×
469
                        newDomRange.endContainer,
470
                        newDomRange.endOffset,
471
                        newDomRange.startContainer,
472
                        newDomRange.startOffset
473
                    );
474
                } else {
475
                    // eslint-disable-next-line max-len
476
                    domSelection.setBaseAndExtent(
1✔
477
                        newDomRange.startContainer,
478
                        newDomRange.startOffset,
479
                        newDomRange.endContainer,
480
                        newDomRange.endOffset
481
                    );
482
                }
483
            } else {
UNCOV
484
                domSelection.removeAllRanges();
×
485
            }
486

487
            setTimeout(() => {
1✔
488
                if (
1!
489
                    this.isEnabledVirtualScroll() &&
1!
490
                    !selection &&
491
                    this.editor.selection &&
492
                    autoScroll &&
493
                    this.virtualScrollConfig.scrollContainer &&
494
                    !this.isSelectionHidden(this.editor.selection)
495
                ) {
UNCOV
496
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
UNCOV
497
                    this.isUpdatingSelection = false;
×
UNCOV
498
                    return;
×
499
                } else {
500
                    // handle scrolling in setTimeout because of
501
                    // dom should not have updated immediately after listRender's updating
502
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
503
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
504
                    // to focus the contenteditable element too. (2016/11/16)
505
                    if (newDomRange && IS_FIREFOX) {
1!
506
                        el.focus();
×
507
                    }
508
                }
509
                this.isUpdatingSelection = false;
1✔
510
            });
511
        } catch (error) {
UNCOV
512
            this.editor.onError({
×
513
                code: SlateErrorCode.ToNativeSelectionError,
514
                nativeError: error
515
            });
UNCOV
516
            this.isUpdatingSelection = false;
×
517
        }
518
    }
519

520
    onChange() {
521
        this.forceRender();
13✔
522
        this.onChangeCallback(this.editor.children);
13✔
523
    }
524

525
    ngAfterViewChecked() {}
526

527
    ngDoCheck() {}
528

529
    forceRender() {
530
        this.updateContext();
15✔
531
        if (this.isEnabledVirtualScroll()) {
15!
UNCOV
532
            this.updateListRenderAndRemeasureHeights();
×
533
        } else {
534
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
535
        }
536
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
537
        // when the DOMElement where the selection is located is removed
538
        // the compositionupdate and compositionend events will no longer be fired
539
        // so isComposing needs to be corrected
540
        // need exec after this.cdr.detectChanges() to render HTML
541
        // need exec before this.toNativeSelection() to correct native selection
542
        if (this.isComposing) {
15!
543
            // Composition input text be not rendered when user composition input with selection is expanded
544
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
545
            // this time condition is true and isComposing is assigned false
546
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
547
            setTimeout(() => {
×
548
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
UNCOV
549
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
550
                let textContent = '';
×
551
                // skip decorate text
UNCOV
552
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
553
                    let text = stringDOMNode.textContent;
×
554
                    const zeroChar = '\uFEFF';
×
555
                    // remove zero with char
556
                    if (text.startsWith(zeroChar)) {
×
UNCOV
557
                        text = text.slice(1);
×
558
                    }
559
                    if (text.endsWith(zeroChar)) {
×
UNCOV
560
                        text = text.slice(0, text.length - 1);
×
561
                    }
UNCOV
562
                    textContent += text;
×
563
                });
564
                if (Node.string(textNode).endsWith(textContent)) {
×
565
                    this.isComposing = false;
×
566
                }
567
            }, 0);
568
        }
569
        this.toNativeSelection();
15✔
570
    }
571

572
    render() {
573
        const changed = this.updateContext();
2✔
574
        if (changed) {
2✔
575
            if (this.isEnabledVirtualScroll()) {
2!
UNCOV
576
                this.updateListRenderAndRemeasureHeights();
×
577
            } else {
578
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
579
            }
580
        }
581
    }
582

583
    updateListRenderAndRemeasureHeights() {
584
        const virtualView = this.calculateVirtualViewport();
×
585
        const oldInViewportChildren = this.inViewportChildren;
×
586
        this.applyVirtualView(virtualView);
×
587
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
UNCOV
588
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
589
        // 新增或者修改的才需要重算,计算出这个结果
590
        const remeasureIndics = [];
×
591
        this.inViewportChildren.forEach((child, index) => {
×
592
            if (oldInViewportChildren.indexOf(child) === -1) {
×
UNCOV
593
                remeasureIndics.push(this.inViewportIndics[index]);
×
594
            }
595
        });
596
        if (isDebug && remeasureIndics.length > 0) {
×
UNCOV
597
            console.log('remeasure height by indics: ', remeasureIndics);
×
598
        }
599
    }
600

601
    updateContext() {
602
        const decorations = this.generateDecorations();
17✔
603
        if (
17✔
604
            this.context.selection !== this.editor.selection ||
46✔
605
            this.context.decorate !== this.decorate ||
606
            this.context.readonly !== this.readonly ||
607
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
608
        ) {
609
            this.context = {
10✔
610
                parent: this.editor,
611
                selection: this.editor.selection,
612
                decorations: decorations,
613
                decorate: this.decorate,
614
                readonly: this.readonly
615
            };
616
            return true;
10✔
617
        }
618
        return false;
7✔
619
    }
620

621
    initializeContext() {
622
        this.context = {
49✔
623
            parent: this.editor,
624
            selection: this.editor.selection,
625
            decorations: this.generateDecorations(),
626
            decorate: this.decorate,
627
            readonly: this.readonly
628
        };
629
    }
630

631
    initializeViewContext() {
632
        this.viewContext = {
23✔
633
            editor: this.editor,
634
            renderElement: this.renderElement,
635
            renderLeaf: this.renderLeaf,
636
            renderText: this.renderText,
637
            trackBy: this.trackBy,
638
            isStrictDecorate: this.isStrictDecorate
639
        };
640
    }
641

642
    composePlaceholderDecorate(editor: Editor) {
643
        if (this.placeholderDecorate) {
64!
UNCOV
644
            return this.placeholderDecorate(editor) || [];
×
645
        }
646

647
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
648
            const start = Editor.start(editor, []);
3✔
649
            return [
3✔
650
                {
651
                    placeholder: this.placeholder,
652
                    anchor: start,
653
                    focus: start
654
                }
655
            ];
656
        } else {
657
            return [];
61✔
658
        }
659
    }
660

661
    generateDecorations() {
662
        const decorations = this.decorate([this.editor, []]);
66✔
663
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
664
        decorations.push(...placeholderDecorations);
66✔
665
        return decorations;
66✔
666
    }
667

668
    private isEnabledVirtualScroll() {
669
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
670
    }
671

672
    virtualScrollInitialized = false;
23✔
673

674
    virtualTopHeightElement: HTMLElement;
675

676
    virtualBottomHeightElement: HTMLElement;
677

678
    virtualCenterOutlet: HTMLElement;
679

680
    initializeVirtualScroll() {
681
        if (this.virtualScrollInitialized) {
23!
UNCOV
682
            return;
×
683
        }
684
        if (this.isEnabledVirtualScroll()) {
23!
685
            this.virtualScrollInitialized = true;
×
686
            this.virtualTopHeightElement = document.createElement('div');
×
687
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
688
            this.virtualTopHeightElement.contentEditable = 'false';
×
689
            this.virtualBottomHeightElement = document.createElement('div');
×
690
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
691
            this.virtualBottomHeightElement.contentEditable = 'false';
×
692
            this.virtualCenterOutlet = document.createElement('div');
×
693
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
694
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
695
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
696
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
697
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
698
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
699
            this.editorResizeObserver = new ResizeObserver(entries => {
×
700
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
701
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
702
                    this.keyHeightMap.clear();
×
703
                    const remeasureIndics = this.inViewportIndics;
×
704
                    measureHeightByIndics(this.editor, remeasureIndics, true);
×
705
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
706
                    if (isDebug) {
×
UNCOV
707
                        debugLog(
×
708
                            'log',
709
                            'editorResizeObserverRectWidth: ',
710
                            editorResizeObserverRectWidth,
711
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
712
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
713
                        );
714
                    }
715
                }
716
            });
UNCOV
717
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
718
        }
719
    }
720

721
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
722
        if (!this.virtualScrollInitialized) {
×
UNCOV
723
            return;
×
724
        }
725
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
726
        if (bottomHeight !== undefined) {
×
UNCOV
727
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
728
        }
729
    }
730

731
    getActualVirtualTopHeight() {
732
        if (!this.virtualScrollInitialized) {
×
UNCOV
733
            return 0;
×
734
        }
UNCOV
735
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
736
    }
737

738
    handlePreRendering() {
739
        let preRenderingCount = 0;
×
740
        const childrenWithPreRendering = [...this.inViewportChildren];
×
741
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
742
        const firstIndex = this.inViewportIndics[0];
×
743
        for (let index = firstIndex - 1; index >= 0; index--) {
×
744
            const element = this.editor.children[index] as Element;
×
745
            if (this.editor.isVisible(element)) {
×
746
                childrenWithPreRendering.unshift(element);
×
747
                childrenWithPreRenderingIndics.unshift(index);
×
748
                preRenderingCount = 1;
×
UNCOV
749
                break;
×
750
            }
751
        }
752
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
753
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
754
            const element = this.editor.children[index] as Element;
×
755
            if (this.editor.isVisible(element)) {
×
756
                childrenWithPreRendering.push(element);
×
757
                childrenWithPreRenderingIndics.push(index);
×
UNCOV
758
                break;
×
759
            }
760
        }
UNCOV
761
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
762
    }
763

764
    private tryUpdateVirtualViewport() {
765
        if (isDebug) {
×
UNCOV
766
            debugLog('log', 'tryUpdateVirtualViewport');
×
767
        }
768
        if (this.inViewportIndics.length > 0) {
×
769
            const topHeight = this.getActualVirtualTopHeight();
×
770
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0]);
×
771
            if (topHeight !== refreshVirtualTopHeight) {
×
772
                if (isDebug) {
×
UNCOV
773
                    debugLog(
×
774
                        'log',
775
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
776
                        topHeight - refreshVirtualTopHeight
777
                    );
778
                }
779
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
UNCOV
780
                return;
×
781
            }
782
        }
783
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
784
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
785
            if (isDebug) {
×
UNCOV
786
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
787
            }
788
            let virtualView = this.calculateVirtualViewport();
×
789
            let diff = this.diffVirtualViewport(virtualView);
×
790
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
791
                const remeasureIndics = diff.changedIndexesOfTop;
×
792
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
793
                if (changed) {
×
794
                    virtualView = this.calculateVirtualViewport();
×
UNCOV
795
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
796
                }
797
            }
798
            if (diff.isDifferent) {
×
799
                this.applyVirtualView(virtualView);
×
800
                if (this.listRender.initialized) {
×
801
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
UNCOV
802
                    this.listRender.update(
×
803
                        childrenWithPreRendering,
804
                        this.editor,
805
                        this.context,
806
                        preRenderingCount,
807
                        childrenWithPreRenderingIndics
808
                    );
809
                    if (diff.needAddOnTop) {
×
810
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
811
                        if (isDebug) {
×
UNCOV
812
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
813
                        }
814
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
815
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
816
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
817
                        if (changed) {
×
818
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
819
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
820
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
821
                            this.setVirtualSpaceHeight(newTopHeight);
×
822
                            if (isDebug) {
×
UNCOV
823
                                debugLog(
×
824
                                    'log',
825
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
826
                                );
827
                            }
828
                        }
829
                    }
830
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
UNCOV
831
                        this.toNativeSelection(false);
×
832
                    }
833
                }
834
            }
835
            if (isDebug) {
×
UNCOV
836
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
837
            }
838
        });
839
    }
840

841
    private calculateVirtualViewport() {
842
        const children = (this.editor.children || []) as Element[];
×
843
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
UNCOV
844
            return {
×
845
                inViewportChildren: children,
846
                inViewportIndics: [],
847
                top: 0,
848
                bottom: 0,
849
                heights: []
850
            };
851
        }
852
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
853
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
854
        if (!viewportHeight) {
×
UNCOV
855
            return {
×
856
                inViewportChildren: [],
857
                inViewportIndics: [],
858
                top: 0,
859
                bottom: 0,
860
                heights: []
861
            };
862
        }
863
        const elementLength = children.length;
×
864
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
865
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
866
            setTimeout(() => {
×
UNCOV
867
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
868
                const businessTop =
UNCOV
869
                    Math.ceil(virtualTopBoundingTop) +
×
870
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
871
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
872
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
873
                if (isDebug) {
×
UNCOV
874
                    debugLog('log', 'businessTop', businessTop);
×
875
                }
876
            }, 100);
877
        }
878
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
879
        const { heights, accumulatedHeights, visibles } = buildHeightsAndAccumulatedHeights(this.editor);
×
880
        const totalHeight = accumulatedHeights[elementLength];
×
881
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
882
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
883
        const viewBottom = limitedScrollTop + viewportHeight;
×
884
        let accumulatedOffset = 0;
×
885
        let inViewportStartIndex = -1;
×
886
        const visible: Element[] = [];
×
UNCOV
887
        const inViewportIndics: number[] = [];
×
888

889
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
890
            const currentHeight = heights[i];
×
891
            const nextOffset = accumulatedOffset + currentHeight;
×
892
            if (!visibles[i]) {
×
893
                accumulatedOffset = nextOffset;
×
UNCOV
894
                continue;
×
895
            }
896
            // 可视区域有交集,加入渲染
897
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
898
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
899
                visible.push(children[i]);
×
UNCOV
900
                inViewportIndics.push(i);
×
901
            }
UNCOV
902
            accumulatedOffset = nextOffset;
×
903
        }
904

905
        const inViewportEndIndex =
906
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
907
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
908
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
UNCOV
909
        return {
×
910
            inViewportChildren: visible.length ? visible : children,
×
911
            inViewportIndics,
912
            top,
913
            bottom,
914
            heights,
915
            accumulatedHeights
916
        };
917
    }
918

919
    private applyVirtualView(virtualView: VirtualViewResult) {
920
        this.inViewportChildren = virtualView.inViewportChildren;
×
921
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
UNCOV
922
        this.inViewportIndics = virtualView.inViewportIndics;
×
923
    }
924

925
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
926
        if (!this.inViewportChildren.length) {
×
927
            if (isDebug) {
×
UNCOV
928
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
929
            }
UNCOV
930
            return {
×
931
                isDifferent: true,
932
                changedIndexesOfTop: [],
933
                changedIndexesOfBottom: []
934
            };
935
        }
936
        const oldIndexesInViewport = [...this.inViewportIndics];
×
937
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
938
        const firstNewIndex = newIndexesInViewport[0];
×
939
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
940
        const firstOldIndex = oldIndexesInViewport[0];
×
UNCOV
941
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
942
        const isSameViewport =
943
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
944
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
945
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
UNCOV
946
            return {
×
947
                isDifferent: !isSameViewport,
948
                changedIndexesOfTop: [],
949
                changedIndexesOfBottom: []
950
            };
951
        }
952
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
953
            const changedIndexesOfTop = [];
×
954
            const changedIndexesOfBottom = [];
×
955
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
956
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
957
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
958
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
UNCOV
959
            if (needRemoveOnTop || needAddOnBottom) {
×
960
                // 向下
961
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
962
                    const element = oldIndexesInViewport[index];
×
963
                    if (!newIndexesInViewport.includes(element)) {
×
UNCOV
964
                        changedIndexesOfTop.push(element);
×
965
                    } else {
UNCOV
966
                        break;
×
967
                    }
968
                }
969
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
970
                    const element = newIndexesInViewport[index];
×
971
                    if (!oldIndexesInViewport.includes(element)) {
×
UNCOV
972
                        changedIndexesOfBottom.push(element);
×
973
                    } else {
UNCOV
974
                        break;
×
975
                    }
976
                }
UNCOV
977
            } else if (needAddOnTop || needRemoveOnBottom) {
×
978
                // 向上
979
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
980
                    const element = newIndexesInViewport[index];
×
981
                    if (!oldIndexesInViewport.includes(element)) {
×
UNCOV
982
                        changedIndexesOfTop.push(element);
×
983
                    } else {
UNCOV
984
                        break;
×
985
                    }
986
                }
987
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
988
                    const element = oldIndexesInViewport[index];
×
989
                    if (!newIndexesInViewport.includes(element)) {
×
UNCOV
990
                        changedIndexesOfBottom.push(element);
×
991
                    } else {
UNCOV
992
                        break;
×
993
                    }
994
                }
995
            }
996
            if (isDebug) {
×
997
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
998
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
999
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
UNCOV
1000
                debugLog(
×
1001
                    'log',
1002
                    'changedIndexesOfTop:',
1003
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
1004
                    changedIndexesOfTop,
UNCOV
1005
                    changedIndexesOfTop.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
1006
                );
UNCOV
1007
                debugLog(
×
1008
                    'log',
1009
                    'changedIndexesOfBottom:',
1010
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
1011
                    changedIndexesOfBottom,
UNCOV
1012
                    changedIndexesOfBottom.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
1013
                );
1014
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
UNCOV
1015
                const needBottom = virtualView.heights
×
1016
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
1017
                    .reduce((acc, height) => acc + height, 0);
×
UNCOV
1018
                debugLog(
×
1019
                    'log',
1020
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
1021
                    'newTopHeight:',
1022
                    needTop,
1023
                    'prevTopHeight:',
1024
                    parseFloat(this.virtualTopHeightElement.style.height)
1025
                );
UNCOV
1026
                debugLog(
×
1027
                    'log',
1028
                    'newBottomHeight:',
1029
                    needBottom,
1030
                    'prevBottomHeight:',
1031
                    parseFloat(this.virtualBottomHeightElement.style.height)
1032
                );
UNCOV
1033
                debugLog('warn', '=========== Dividing line ===========');
×
1034
            }
UNCOV
1035
            return {
×
1036
                isDifferent: true,
1037
                needRemoveOnTop,
1038
                needAddOnTop,
1039
                needRemoveOnBottom,
1040
                needAddOnBottom,
1041
                changedIndexesOfTop,
1042
                changedIndexesOfBottom
1043
            };
1044
        }
UNCOV
1045
        return {
×
1046
            isDifferent: false,
1047
            changedIndexesOfTop: [],
1048
            changedIndexesOfBottom: []
1049
        };
1050
    }
1051

1052
    //#region event proxy
1053
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1054
        this.manualListeners.push(
483✔
1055
            this.renderer2.listen(target, eventName, (event: Event) => {
1056
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1057
                if (beforeInputEvent) {
5!
UNCOV
1058
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1059
                }
1060
                listener(event);
5✔
1061
            })
1062
        );
1063
    }
1064

1065
    private toSlateSelection() {
1066
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1067
            try {
1✔
1068
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1069
                const { activeElement } = root;
1✔
1070
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1071
                const domSelection = (root as Document).getSelection();
1✔
1072

1073
                if (activeElement === el) {
1!
1074
                    this.latestElement = activeElement;
1✔
1075
                    IS_FOCUSED.set(this.editor, true);
1✔
1076
                } else {
UNCOV
1077
                    IS_FOCUSED.delete(this.editor);
×
1078
                }
1079

1080
                if (!domSelection) {
1!
UNCOV
1081
                    return Transforms.deselect(this.editor);
×
1082
                }
1083

1084
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1085
                const hasDomSelectionInEditor =
1086
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1087
                if (!hasDomSelectionInEditor) {
1!
1088
                    Transforms.deselect(this.editor);
×
UNCOV
1089
                    return;
×
1090
                }
1091

1092
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1093
                // for example, double-click the last cell of the table to select a non-editable DOM
1094
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1095
                if (range) {
1✔
1096
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
UNCOV
1097
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1098
                            // force adjust DOMSelection
UNCOV
1099
                            this.toNativeSelection(false);
×
1100
                        }
1101
                    } else {
1102
                        Transforms.select(this.editor, range);
1✔
1103
                    }
1104
                }
1105
            } catch (error) {
UNCOV
1106
                this.editor.onError({
×
1107
                    code: SlateErrorCode.ToSlateSelectionError,
1108
                    nativeError: error
1109
                });
1110
            }
1111
        }
1112
    }
1113

1114
    private onDOMBeforeInput(
1115
        event: Event & {
1116
            inputType: string;
1117
            isComposing: boolean;
1118
            data: string | null;
1119
            dataTransfer: DataTransfer | null;
1120
            getTargetRanges(): DOMStaticRange[];
1121
        }
1122
    ) {
1123
        const editor = this.editor;
×
1124
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1125
        const { activeElement } = root;
×
1126
        const { selection } = editor;
×
1127
        const { inputType: type } = event;
×
1128
        const data = event.dataTransfer || event.data || undefined;
×
1129
        if (IS_ANDROID) {
×
1130
            let targetRange: Range | null = null;
×
1131
            let [nativeTargetRange] = event.getTargetRanges();
×
1132
            if (nativeTargetRange) {
×
UNCOV
1133
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1134
            }
1135
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1136
            // have to manually get the selection here to ensure it's up-to-date.
1137
            const window = AngularEditor.getWindow(editor);
×
1138
            const domSelection = window.getSelection();
×
1139
            if (!targetRange && domSelection) {
×
UNCOV
1140
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1141
            }
1142
            targetRange = targetRange ?? editor.selection;
×
1143
            if (type === 'insertCompositionText') {
×
1144
                if (data && data.toString().includes('\n')) {
×
1145
                    restoreDom(editor, () => {
×
UNCOV
1146
                        Editor.insertBreak(editor);
×
1147
                    });
1148
                } else {
1149
                    if (targetRange) {
×
1150
                        if (data) {
×
1151
                            restoreDom(editor, () => {
×
UNCOV
1152
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1153
                            });
1154
                        } else {
1155
                            restoreDom(editor, () => {
×
UNCOV
1156
                                Transforms.delete(editor, { at: targetRange });
×
1157
                            });
1158
                        }
1159
                    }
1160
                }
UNCOV
1161
                return;
×
1162
            }
UNCOV
1163
            if (type === 'deleteContentBackward') {
×
1164
                // gboard can not prevent default action, so must use restoreDom,
1165
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1166
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1167
                if (!Range.isCollapsed(targetRange)) {
×
1168
                    restoreDom(editor, () => {
×
UNCOV
1169
                        Transforms.delete(editor, { at: targetRange });
×
1170
                    });
UNCOV
1171
                    return;
×
1172
                }
1173
            }
1174
            if (type === 'insertText') {
×
1175
                restoreDom(editor, () => {
×
1176
                    if (typeof data === 'string') {
×
UNCOV
1177
                        Editor.insertText(editor, data);
×
1178
                    }
1179
                });
UNCOV
1180
                return;
×
1181
            }
1182
        }
UNCOV
1183
        if (
×
1184
            !this.readonly &&
×
1185
            AngularEditor.hasEditableTarget(editor, event.target) &&
1186
            !isTargetInsideVoid(editor, activeElement) &&
1187
            !this.isDOMEventHandled(event, this.beforeInput)
1188
        ) {
1189
            try {
×
UNCOV
1190
                event.preventDefault();
×
1191

1192
                // COMPAT: If the selection is expanded, even if the command seems like
1193
                // a delete forward/backward command it should delete the selection.
1194
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1195
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1196
                    Editor.deleteFragment(editor, { direction });
×
UNCOV
1197
                    return;
×
1198
                }
1199

UNCOV
1200
                switch (type) {
×
1201
                    case 'deleteByComposition':
1202
                    case 'deleteByCut':
1203
                    case 'deleteByDrag': {
1204
                        Editor.deleteFragment(editor);
×
UNCOV
1205
                        break;
×
1206
                    }
1207

1208
                    case 'deleteContent':
1209
                    case 'deleteContentForward': {
1210
                        Editor.deleteForward(editor);
×
UNCOV
1211
                        break;
×
1212
                    }
1213

1214
                    case 'deleteContentBackward': {
1215
                        Editor.deleteBackward(editor);
×
UNCOV
1216
                        break;
×
1217
                    }
1218

1219
                    case 'deleteEntireSoftLine': {
1220
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1221
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1222
                        break;
×
1223
                    }
1224

1225
                    case 'deleteHardLineBackward': {
1226
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
1227
                        break;
×
1228
                    }
1229

1230
                    case 'deleteSoftLineBackward': {
1231
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1232
                        break;
×
1233
                    }
1234

1235
                    case 'deleteHardLineForward': {
1236
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
1237
                        break;
×
1238
                    }
1239

1240
                    case 'deleteSoftLineForward': {
1241
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1242
                        break;
×
1243
                    }
1244

1245
                    case 'deleteWordBackward': {
1246
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1247
                        break;
×
1248
                    }
1249

1250
                    case 'deleteWordForward': {
1251
                        Editor.deleteForward(editor, { unit: 'word' });
×
UNCOV
1252
                        break;
×
1253
                    }
1254

1255
                    case 'insertLineBreak':
1256
                    case 'insertParagraph': {
1257
                        Editor.insertBreak(editor);
×
UNCOV
1258
                        break;
×
1259
                    }
1260

1261
                    case 'insertFromComposition': {
1262
                        // COMPAT: in safari, `compositionend` event is dispatched after
1263
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1264
                        // https://www.w3.org/TR/input-events-2/
1265
                        // so the following code is the right logic
1266
                        // because DOM selection in sync will be exec before `compositionend` event
1267
                        // isComposing is true will prevent DOM selection being update correctly.
1268
                        this.isComposing = false;
×
UNCOV
1269
                        preventInsertFromComposition(event, this.editor);
×
1270
                    }
1271
                    case 'insertFromDrop':
1272
                    case 'insertFromPaste':
1273
                    case 'insertFromYank':
1274
                    case 'insertReplacementText':
1275
                    case 'insertText': {
1276
                        // use a weak comparison instead of 'instanceof' to allow
1277
                        // programmatic access of paste events coming from external windows
1278
                        // like cypress where cy.window does not work realibly
1279
                        if (data?.constructor.name === 'DataTransfer') {
×
1280
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1281
                        } else if (typeof data === 'string') {
×
UNCOV
1282
                            Editor.insertText(editor, data);
×
1283
                        }
UNCOV
1284
                        break;
×
1285
                    }
1286
                }
1287
            } catch (error) {
UNCOV
1288
                this.editor.onError({
×
1289
                    code: SlateErrorCode.OnDOMBeforeInputError,
1290
                    nativeError: error
1291
                });
1292
            }
1293
        }
1294
    }
1295

1296
    private onDOMBlur(event: FocusEvent) {
UNCOV
1297
        if (
×
1298
            this.readonly ||
×
1299
            this.isUpdatingSelection ||
1300
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1301
            this.isDOMEventHandled(event, this.blur)
1302
        ) {
UNCOV
1303
            return;
×
1304
        }
1305

UNCOV
1306
        const window = AngularEditor.getWindow(this.editor);
×
1307

1308
        // COMPAT: If the current `activeElement` is still the previous
1309
        // one, this is due to the window being blurred when the tab
1310
        // itself becomes unfocused, so we want to abort early to allow to
1311
        // editor to stay focused when the tab becomes focused again.
1312
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1313
        if (this.latestElement === root.activeElement) {
×
UNCOV
1314
            return;
×
1315
        }
1316

1317
        const { relatedTarget } = event;
×
UNCOV
1318
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1319

1320
        // COMPAT: The event should be ignored if the focus is returning
1321
        // to the editor from an embedded editable element (eg. an <input>
1322
        // element inside a void node).
1323
        if (relatedTarget === el) {
×
UNCOV
1324
            return;
×
1325
        }
1326

1327
        // COMPAT: The event should be ignored if the focus is moving from
1328
        // the editor to inside a void node's spacer element.
1329
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
UNCOV
1330
            return;
×
1331
        }
1332

1333
        // COMPAT: The event should be ignored if the focus is moving to a
1334
        // non- editable section of an element that isn't a void node (eg.
1335
        // a list item of the check list example).
1336
        if (relatedTarget != null && isDOMNode(relatedTarget) && AngularEditor.hasDOMNode(this.editor, relatedTarget)) {
×
UNCOV
1337
            const node = AngularEditor.toSlateNode(this.editor, relatedTarget);
×
1338

1339
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
UNCOV
1340
                return;
×
1341
            }
1342
        }
1343

UNCOV
1344
        IS_FOCUSED.delete(this.editor);
×
1345
    }
1346

1347
    private onDOMClick(event: MouseEvent) {
UNCOV
1348
        if (
×
1349
            !this.readonly &&
×
1350
            AngularEditor.hasTarget(this.editor, event.target) &&
1351
            !this.isDOMEventHandled(event, this.click) &&
1352
            isDOMNode(event.target)
1353
        ) {
1354
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1355
            const path = AngularEditor.findPath(this.editor, node);
×
1356
            const start = Editor.start(this.editor, path);
×
UNCOV
1357
            const end = Editor.end(this.editor, path);
×
1358

1359
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
1360
            const endVoid = Editor.void(this.editor, { at: end });
×
1361

1362
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1363
                let blockPath = path;
×
1364
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1365
                    const block = Editor.above(this.editor, {
×
UNCOV
1366
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1367
                        at: path
1368
                    });
1369

UNCOV
1370
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1371
                }
1372

1373
                const range = Editor.range(this.editor, blockPath);
×
1374
                Transforms.select(this.editor, range);
×
UNCOV
1375
                return;
×
1376
            }
1377

UNCOV
1378
            if (
×
1379
                startVoid &&
×
1380
                endVoid &&
1381
                Path.equals(startVoid[1], endVoid[1]) &&
1382
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1383
            ) {
1384
                const range = Editor.range(this.editor, start);
×
UNCOV
1385
                Transforms.select(this.editor, range);
×
1386
            }
1387
        }
1388
    }
1389

1390
    private onDOMCompositionStart(event: CompositionEvent) {
1391
        const { selection } = this.editor;
1✔
1392
        if (selection) {
1!
1393
            // solve the problem of cross node Chinese input
1394
            if (Range.isExpanded(selection)) {
×
1395
                Editor.deleteFragment(this.editor);
×
UNCOV
1396
                this.forceRender();
×
1397
            }
1398
        }
1399
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1400
            this.isComposing = true;
1✔
1401
        }
1402
        this.render();
1✔
1403
    }
1404

1405
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1406
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1407
    }
1408

1409
    private onDOMCompositionEnd(event: CompositionEvent) {
1410
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1411
            Transforms.delete(this.editor);
×
1412
        }
UNCOV
1413
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1414
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1415
            // aren't correct and never fire the "insertFromComposition"
1416
            // type that we need. So instead, insert whenever a composition
1417
            // ends since it will already have been committed to the DOM.
1418
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1419
                preventInsertFromComposition(event, this.editor);
×
UNCOV
1420
                Editor.insertText(this.editor, event.data);
×
1421
            }
1422

1423
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1424
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1425
            this.isComposing = false;
×
1426
        }
UNCOV
1427
        this.render();
×
1428
    }
1429

1430
    private onDOMCopy(event: ClipboardEvent) {
1431
        const window = AngularEditor.getWindow(this.editor);
×
1432
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1433
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1434
            event.preventDefault();
×
UNCOV
1435
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1436
        }
1437
    }
1438

1439
    private onDOMCut(event: ClipboardEvent) {
1440
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1441
            event.preventDefault();
×
1442
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
UNCOV
1443
            const { selection } = this.editor;
×
1444

1445
            if (selection) {
×
UNCOV
1446
                AngularEditor.deleteCutData(this.editor);
×
1447
            }
1448
        }
1449
    }
1450

1451
    private onDOMDragOver(event: DragEvent) {
UNCOV
1452
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1453
            // Only when the target is void, call `preventDefault` to signal
1454
            // that drops are allowed. Editable content is droppable by
1455
            // default, and calling `preventDefault` hides the cursor.
UNCOV
1456
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1457

1458
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1459
                event.preventDefault();
×
1460
            }
1461
        }
1462
    }
1463

1464
    private onDOMDragStart(event: DragEvent) {
1465
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1466
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1467
            const path = AngularEditor.findPath(this.editor, node);
×
1468
            const voidMatch =
UNCOV
1469
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1470

1471
            // If starting a drag on a void node, make sure it is selected
1472
            // so that it shows up in the selection's fragment.
1473
            if (voidMatch) {
×
1474
                const range = Editor.range(this.editor, path);
×
UNCOV
1475
                Transforms.select(this.editor, range);
×
1476
            }
1477

UNCOV
1478
            this.isDraggingInternally = true;
×
1479

UNCOV
1480
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1481
        }
1482
    }
1483

1484
    private onDOMDrop(event: DragEvent) {
1485
        const editor = this.editor;
×
1486
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
UNCOV
1487
            event.preventDefault();
×
1488
            // Keep a reference to the dragged range before updating selection
UNCOV
1489
            const draggedRange = editor.selection;
×
1490

1491
            // Find the range where the drop happened
1492
            const range = AngularEditor.findEventRange(editor, event);
×
UNCOV
1493
            const data = event.dataTransfer;
×
1494

UNCOV
1495
            Transforms.select(editor, range);
×
1496

1497
            if (this.isDraggingInternally) {
×
1498
                if (draggedRange) {
×
UNCOV
1499
                    Transforms.delete(editor, {
×
1500
                        at: draggedRange
1501
                    });
1502
                }
1503

UNCOV
1504
                this.isDraggingInternally = false;
×
1505
            }
1506

UNCOV
1507
            AngularEditor.insertData(editor, data);
×
1508

1509
            // When dragging from another source into the editor, it's possible
1510
            // that the current editor does not have focus.
1511
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1512
                AngularEditor.focus(editor);
×
1513
            }
1514
        }
1515
    }
1516

1517
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1518
        if (
×
1519
            !this.readonly &&
×
1520
            this.isDraggingInternally &&
1521
            AngularEditor.hasTarget(this.editor, event.target) &&
1522
            !this.isDOMEventHandled(event, this.dragEnd)
1523
        ) {
UNCOV
1524
            this.isDraggingInternally = false;
×
1525
        }
1526
    }
1527

1528
    private onDOMFocus(event: Event) {
1529
        if (
2✔
1530
            !this.readonly &&
8✔
1531
            !this.isUpdatingSelection &&
1532
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1533
            !this.isDOMEventHandled(event, this.focus)
1534
        ) {
1535
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1536
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1537
            this.latestElement = root.activeElement;
2✔
1538

1539
            // COMPAT: If the editor has nested editable elements, the focus
1540
            // can go to them. In Firefox, this must be prevented because it
1541
            // results in issues with keyboard navigation. (2017/03/30)
1542
            if (IS_FIREFOX && event.target !== el) {
2!
1543
                el.focus();
×
UNCOV
1544
                return;
×
1545
            }
1546

1547
            IS_FOCUSED.set(this.editor, true);
2✔
1548
        }
1549
    }
1550

1551
    private onDOMKeydown(event: KeyboardEvent) {
1552
        const editor = this.editor;
×
1553
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1554
        const { activeElement } = root;
×
UNCOV
1555
        if (
×
1556
            !this.readonly &&
×
1557
            AngularEditor.hasEditableTarget(editor, event.target) &&
1558
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1559
            !this.isComposing &&
1560
            !this.isDOMEventHandled(event, this.keydown)
1561
        ) {
1562
            const nativeEvent = event;
×
UNCOV
1563
            const { selection } = editor;
×
1564

1565
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
UNCOV
1566
            const isRTL = direction(Node.string(element)) === 'rtl';
×
1567

UNCOV
1568
            try {
×
1569
                // COMPAT: Since we prevent the default behavior on
1570
                // `beforeinput` events, the browser doesn't think there's ever
1571
                // any history stack to undo or redo, so we have to manage these
1572
                // hotkeys ourselves. (2019/11/06)
1573
                if (Hotkeys.isRedo(nativeEvent)) {
×
UNCOV
1574
                    event.preventDefault();
×
1575

1576
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1577
                        editor.redo();
×
1578
                    }
1579

UNCOV
1580
                    return;
×
1581
                }
1582

1583
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1584
                    event.preventDefault();
×
1585

1586
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1587
                        editor.undo();
×
1588
                    }
1589

UNCOV
1590
                    return;
×
1591
                }
1592

1593
                // COMPAT: Certain browsers don't handle the selection updates
1594
                // properly. In Chrome, the selection isn't properly extended.
1595
                // And in Firefox, the selection isn't properly collapsed.
1596
                // (2017/10/17)
1597
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1598
                    event.preventDefault();
×
1599
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
UNCOV
1600
                    return;
×
1601
                }
1602

1603
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1604
                    event.preventDefault();
×
1605
                    Transforms.move(editor, { unit: 'line' });
×
UNCOV
1606
                    return;
×
1607
                }
1608

1609
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1610
                    event.preventDefault();
×
UNCOV
1611
                    Transforms.move(editor, {
×
1612
                        unit: 'line',
1613
                        edge: 'focus',
1614
                        reverse: true
1615
                    });
UNCOV
1616
                    return;
×
1617
                }
1618

1619
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1620
                    event.preventDefault();
×
1621
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
UNCOV
1622
                    return;
×
1623
                }
1624

1625
                // COMPAT: If a void node is selected, or a zero-width text node
1626
                // adjacent to an inline is selected, we need to handle these
1627
                // hotkeys manually because browsers won't be able to skip over
1628
                // the void node with the zero-width space not being an empty
1629
                // string.
1630
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
UNCOV
1631
                    event.preventDefault();
×
1632

1633
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1634
                        Transforms.move(editor, { reverse: !isRTL });
×
1635
                    } else {
UNCOV
1636
                        Transforms.collapse(editor, { edge: 'start' });
×
1637
                    }
1638

UNCOV
1639
                    return;
×
1640
                }
1641

1642
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1643
                    event.preventDefault();
×
1644
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1645
                        Transforms.move(editor, { reverse: isRTL });
×
1646
                    } else {
UNCOV
1647
                        Transforms.collapse(editor, { edge: 'end' });
×
1648
                    }
1649

UNCOV
1650
                    return;
×
1651
                }
1652

1653
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1654
                    event.preventDefault();
×
1655

1656
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1657
                        Transforms.collapse(editor, { edge: 'focus' });
×
1658
                    }
1659

1660
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1661
                    return;
×
1662
                }
1663

1664
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1665
                    event.preventDefault();
×
1666

1667
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1668
                        Transforms.collapse(editor, { edge: 'focus' });
×
1669
                    }
1670

1671
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
UNCOV
1672
                    return;
×
1673
                }
1674

1675
                if (isKeyHotkey('mod+a', event)) {
×
1676
                    this.editor.selectAll();
×
1677
                    event.preventDefault();
×
UNCOV
1678
                    return;
×
1679
                }
1680

1681
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1682
                // fall back to guessing at the input intention for hotkeys.
1683
                // COMPAT: In iOS, some of these hotkeys are handled in the
UNCOV
1684
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1685
                    // We don't have a core behavior for these, but they change the
1686
                    // DOM if we don't prevent them, so we have to.
1687
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1688
                        event.preventDefault();
×
UNCOV
1689
                        return;
×
1690
                    }
1691

1692
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1693
                        event.preventDefault();
×
1694
                        Editor.insertBreak(editor);
×
UNCOV
1695
                        return;
×
1696
                    }
1697

1698
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1699
                        event.preventDefault();
×
1700

1701
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1702
                            Editor.deleteFragment(editor, {
×
1703
                                direction: 'backward'
1704
                            });
1705
                        } else {
UNCOV
1706
                            Editor.deleteBackward(editor);
×
1707
                        }
1708

UNCOV
1709
                        return;
×
1710
                    }
1711

1712
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1713
                        event.preventDefault();
×
1714

1715
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1716
                            Editor.deleteFragment(editor, {
×
1717
                                direction: 'forward'
1718
                            });
1719
                        } else {
UNCOV
1720
                            Editor.deleteForward(editor);
×
1721
                        }
1722

UNCOV
1723
                        return;
×
1724
                    }
1725

1726
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1727
                        event.preventDefault();
×
1728

1729
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1730
                            Editor.deleteFragment(editor, {
×
1731
                                direction: 'backward'
1732
                            });
1733
                        } else {
UNCOV
1734
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1735
                        }
1736

UNCOV
1737
                        return;
×
1738
                    }
1739

1740
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1741
                        event.preventDefault();
×
1742

1743
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1744
                            Editor.deleteFragment(editor, {
×
1745
                                direction: 'forward'
1746
                            });
1747
                        } else {
UNCOV
1748
                            Editor.deleteForward(editor, { unit: 'line' });
×
1749
                        }
1750

UNCOV
1751
                        return;
×
1752
                    }
1753

1754
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1755
                        event.preventDefault();
×
1756

1757
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1758
                            Editor.deleteFragment(editor, {
×
1759
                                direction: 'backward'
1760
                            });
1761
                        } else {
UNCOV
1762
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1763
                        }
1764

UNCOV
1765
                        return;
×
1766
                    }
1767

1768
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1769
                        event.preventDefault();
×
1770

1771
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1772
                            Editor.deleteFragment(editor, {
×
1773
                                direction: 'forward'
1774
                            });
1775
                        } else {
UNCOV
1776
                            Editor.deleteForward(editor, { unit: 'word' });
×
1777
                        }
1778

UNCOV
1779
                        return;
×
1780
                    }
1781
                } else {
UNCOV
1782
                    if (IS_CHROME || IS_SAFARI) {
×
1783
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1784
                        // an event when deleting backwards in a selected void inline node
UNCOV
1785
                        if (
×
1786
                            selection &&
×
1787
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1788
                            Range.isCollapsed(selection)
1789
                        ) {
1790
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
UNCOV
1791
                            if (
×
1792
                                Element.isElement(currentNode) &&
×
1793
                                Editor.isVoid(editor, currentNode) &&
1794
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1795
                            ) {
1796
                                event.preventDefault();
×
UNCOV
1797
                                Editor.deleteBackward(editor, {
×
1798
                                    unit: 'block'
1799
                                });
UNCOV
1800
                                return;
×
1801
                            }
1802
                        }
1803
                    }
1804
                }
1805
            } catch (error) {
UNCOV
1806
                this.editor.onError({
×
1807
                    code: SlateErrorCode.OnDOMKeydownError,
1808
                    nativeError: error
1809
                });
1810
            }
1811
        }
1812
    }
1813

1814
    private onDOMPaste(event: ClipboardEvent) {
1815
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1816
        // fall back to React's `onPaste` here instead.
1817
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1818
        // when "paste without formatting" option is used.
1819
        // This unfortunately needs to be handled with paste events instead.
UNCOV
1820
        if (
×
1821
            !this.isDOMEventHandled(event, this.paste) &&
×
1822
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1823
            !this.readonly &&
1824
            AngularEditor.hasEditableTarget(this.editor, event.target)
1825
        ) {
1826
            event.preventDefault();
×
UNCOV
1827
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1828
        }
1829
    }
1830

1831
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1832
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1833
        // fall back to React's leaky polyfill instead just for it. It
1834
        // only works for the `insertText` input type.
UNCOV
1835
        if (
×
1836
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1837
            !this.readonly &&
1838
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1839
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1840
        ) {
1841
            event.nativeEvent.preventDefault();
×
1842
            try {
×
1843
                const text = event.data;
×
1844
                if (!Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1845
                    Editor.deleteFragment(this.editor);
×
1846
                }
1847
                // just handle Non-IME input
1848
                if (!this.isComposing) {
×
UNCOV
1849
                    Editor.insertText(this.editor, text);
×
1850
                }
1851
            } catch (error) {
UNCOV
1852
                this.editor.onError({
×
1853
                    code: SlateErrorCode.ToNativeSelectionError,
1854
                    nativeError: error
1855
                });
1856
            }
1857
        }
1858
    }
1859

1860
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1861
        if (!handler) {
3✔
1862
            return false;
3✔
1863
        }
1864
        handler(event);
×
UNCOV
1865
        return event.defaultPrevented;
×
1866
    }
1867
    //#endregion
1868

1869
    ngOnDestroy() {
1870
        this.editorResizeObserver?.disconnect();
23✔
1871
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1872
        this.manualListeners.forEach(manualListener => {
23✔
1873
            manualListener();
483✔
1874
        });
1875
        this.destroy$.complete();
23✔
1876
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1877
    }
1878
}
1879

1880
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1881
    // This was affecting the selection of multiple blocks and dragging behavior,
1882
    // so enabled only if the selection has been collapsed.
1883
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
UNCOV
1884
        const leafEl = domRange.startContainer.parentElement!;
×
1885

1886
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1887
        // When this happens, do not scroll like most editors do.
1888
        const domRect = domRange.getBoundingClientRect();
×
UNCOV
1889
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1890

1891
        if (isZeroDimensionRect) {
×
1892
            const leafRect = leafEl.getBoundingClientRect();
×
UNCOV
1893
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1894

1895
            if (leafHasDimensions) {
×
UNCOV
1896
                return;
×
1897
            }
1898
        }
1899

1900
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1901
        scrollIntoView(leafEl, {
×
1902
            scrollMode: 'if-needed'
1903
        });
UNCOV
1904
        delete leafEl.getBoundingClientRect;
×
1905
    }
1906
};
1907

1908
/**
1909
 * Check if the target is inside void and in the editor.
1910
 */
1911

1912
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1913
    let slateNode: Node | null = null;
1✔
1914
    try {
1✔
1915
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1916
    } catch (error) {}
1917
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1918
};
1919

1920
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1921
    return (
2✔
1922
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1923
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1924
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1925
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1926
    );
1927
};
1928

1929
/**
1930
 * remove default insert from composition
1931
 * @param text
1932
 */
1933
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1934
    const types = ['compositionend', 'insertFromComposition'];
×
1935
    if (!types.includes(event.type)) {
×
UNCOV
1936
        return;
×
1937
    }
1938
    const insertText = (event as CompositionEvent).data;
×
1939
    const window = AngularEditor.getWindow(editor);
×
UNCOV
1940
    const domSelection = window.getSelection();
×
1941
    // ensure text node insert composition input text
1942
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1943
        const textNode = domSelection.anchorNode;
×
UNCOV
1944
        textNode.splitText(textNode.length - insertText.length).remove();
×
1945
    }
1946
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc