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

worktile / slate-angular / aa11590a-51e0-4205-a92b-9598dff92e86

16 Dec 2025 07:10AM UTC coverage: 36.924% (-0.5%) from 37.461%
aa11590a-51e0-4205-a92b-9598dff92e86

Pull #325

circleci

Xwatson
chore: add changeset
Pull Request #325: feat(virtual-scroll): #WIK-19623 support scrolling to specified node key

380 of 1237 branches covered (30.72%)

Branch coverage included in aggregate %.

1 of 44 new or added lines in 1 file covered. (2.27%)

397 existing lines in 1 file now uncovered.

1070 of 2690 relevant lines covered (39.78%)

24.21 hits per line

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

21.87
/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
    VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT,
49
    SLATE_DEBUG_KEY
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
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
61
    ELEMENT_TO_COMPONENT,
62
    IS_ENABLED_VIRTUAL_SCROLL,
63
    isDecoratorRangeListEqual
64
} from '../../utils';
65
import { SlatePlaceholder } from '../../types/feature';
66
import { restoreDom } from '../../utils/restore-dom';
67
import { ListRender } from '../../view/render/list-render';
68
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
69
import { BaseElementComponent } from '../../view/base';
70
import { BaseElementFlavour } from '../../view/flavour/element';
71
import { SlateVirtualScrollConfig, SlateVirtualScrollToAnchorConfig, VirtualViewResult } from '../../types';
72
import { isKeyHotkey } from 'is-hotkey';
73
import { VirtualScrollDebugOverlay } from './debug';
74

75
export const JUST_NOW_UPDATED_VIRTUAL_VIEW = new WeakMap<AngularEditor, boolean>();
1✔
76

77
export const ELEMENT_KEY_TO_HEIGHTS = new WeakMap<AngularEditor, Map<string, number>>();
1✔
78

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

82
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
83

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

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

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

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

118
    private initialized: boolean;
119

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

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

124
    @Input() editor: AngularEditor;
125

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

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

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

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

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

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

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

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

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

144
    @Input() placeholder: string;
145

146
    @Input()
147
    set virtualScroll(config: SlateVirtualScrollConfig) {
UNCOV
148
        this.virtualScrollConfig = config;
×
UNCOV
149
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
UNCOV
150
        if (this.isEnabledVirtualScroll()) {
×
UNCOV
151
            this.tryUpdateVirtualViewport();
×
152
        }
153
    }
154

155
    @Input()
156
    set virtualScrollToAnchor(config: SlateVirtualScrollToAnchorConfig) {
NEW
UNCOV
157
        this.virtualToAnchorConfig = config;
×
NEW
UNCOV
158
        if (this.isEnabledVirtualScroll()) {
×
NEW
UNCOV
159
            this.tryAnchorScroll();
×
160
        }
161
    }
162

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

181
    //#region DOM attr
182
    @Input() spellCheck = false;
23✔
183
    @Input() autoCorrect = false;
23✔
184
    @Input() autoCapitalize = false;
23✔
185

186
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
187
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
188
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
189

190
    get hasBeforeInputSupport() {
191
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
192
    }
193
    //#endregion
194

195
    viewContainerRef = inject(ViewContainerRef);
23✔
196

197
    getOutletParent = () => {
23✔
198
        return this.elementRef.nativeElement;
43✔
199
    };
200

201
    getOutletElement = () => {
23✔
202
        if (this.virtualScrollInitialized) {
23!
UNCOV
203
            return this.virtualCenterOutlet;
×
204
        } else {
205
            return null;
23✔
206
        }
207
    };
208

209
    listRender: ListRender;
210

211
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
212
        enabled: false,
213
        scrollTop: 0,
214
        viewportHeight: 0
215
    };
216

217
    private inViewportChildren: Element[] = [];
23✔
218
    private inViewportIndics = new Set<number>();
23✔
219
    private keyHeightMap = new Map<string, number>();
23✔
220
    private refreshVirtualViewAnimId: number;
221
    private measureVisibleHeightsAnimId: number;
222
    private editorResizeObserver?: ResizeObserver;
223
    private virtualToAnchorConfig: SlateVirtualScrollToAnchorConfig | null = null;
23✔
224
    private lastAnchorKey?: string;
225

226
    constructor(
227
        public elementRef: ElementRef,
23✔
228
        public renderer2: Renderer2,
23✔
229
        public cdr: ChangeDetectorRef,
23✔
230
        private ngZone: NgZone,
23✔
231
        private injector: Injector
23✔
232
    ) {}
233

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

255
        // add browser class
256
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
257
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
258
        this.initializeVirtualScroll();
23✔
259
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
260
    }
261

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

282
    registerOnChange(fn: any) {
283
        this.onChangeCallback = fn;
23✔
284
    }
285
    registerOnTouched(fn: any) {
286
        this.onTouchedCallback = fn;
23✔
287
    }
288

289
    writeValue(value: Element[]) {
290
        if (value && value.length) {
49✔
291
            this.editor.children = value;
26✔
292
            this.initializeContext();
26✔
293
            if (this.isEnabledVirtualScroll()) {
26!
UNCOV
294
                const virtualView = this.calculateVirtualViewport();
×
UNCOV
295
                this.applyVirtualView(virtualView);
×
UNCOV
296
                const childrenForRender = virtualView.inViewportChildren;
×
UNCOV
297
                if (!this.listRender.initialized) {
×
UNCOV
298
                    this.listRender.initialize(childrenForRender, this.editor, this.context);
×
299
                } else {
UNCOV
300
                    this.listRender.update(childrenForRender, this.editor, this.context);
×
301
                }
UNCOV
302
                this.scheduleMeasureVisibleHeights();
×
303
            } else {
304
                if (!this.listRender.initialized) {
26✔
305
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
306
                } else {
307
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
308
                }
309
            }
310
            this.cdr.markForCheck();
26✔
311
        }
312
    }
313

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

346
    calculateVirtualScrollSelection(selection: Selection) {
UNCOV
347
        if (selection) {
×
UNCOV
348
            const indics = Array.from(this.inViewportIndics.values());
×
UNCOV
349
            if (indics.length > 0) {
×
UNCOV
350
                const currentVisibleRange: Range = {
×
351
                    anchor: Editor.start(this.editor, [indics[0]]),
352
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
353
                };
UNCOV
354
                const [start, end] = Range.edges(selection);
×
UNCOV
355
                const forwardSelection = { anchor: start, focus: end };
×
356
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
357
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
UNCOV
358
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
UNCOV
359
                    if (isDebug) {
×
UNCOV
360
                        this.debugLog(
×
361
                            'log',
362
                            `selection is not in visible range, selection: ${JSON.stringify(
363
                                selection
364
                            )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
365
                        );
366
                    }
UNCOV
367
                    return intersectedSelection;
×
368
                }
UNCOV
369
                return selection;
×
370
            }
371
        }
UNCOV
372
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
UNCOV
373
        return selection;
×
374
    }
375

376
    toNativeSelection() {
377
        try {
15✔
378
            let { selection } = this.editor;
15✔
379
            if (this.isEnabledVirtualScroll()) {
15!
UNCOV
380
                selection = this.calculateVirtualScrollSelection(selection);
×
381
            }
382
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
383
            const { activeElement } = root;
15✔
384
            const domSelection = (root as Document).getSelection();
15✔
385

386
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
387
                return;
14✔
388
            }
389

390
            const hasDomSelection = domSelection.type !== 'None';
1✔
391

392
            // If the DOM selection is properly unset, we're done.
393
            if (!selection && !hasDomSelection) {
1!
UNCOV
394
                return;
×
395
            }
396

397
            // If the DOM selection is already correct, we're done.
398
            // verify that the dom selection is in the editor
399
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
400
            let hasDomSelectionInEditor = false;
1✔
401
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
402
                hasDomSelectionInEditor = true;
1✔
403
            }
404

405
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
406
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
407
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
408
                    exactMatch: false,
409
                    suppressThrow: true
410
                });
411
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
UNCOV
412
                    return;
×
413
                }
414
            }
415

416
            // prevent updating native selection when active element is void element
417
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
UNCOV
418
                return;
×
419
            }
420

421
            // when <Editable/> is being controlled through external value
422
            // then its children might just change - DOM responds to it on its own
423
            // but Slate's value is not being updated through any operation
424
            // and thus it doesn't transform selection on its own
425
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
UNCOV
426
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
UNCOV
427
                return;
×
428
            }
429

430
            // Otherwise the DOM selection is out of sync, so update it.
431
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
432
            this.isUpdatingSelection = true;
1✔
433

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

436
            if (newDomRange) {
1!
437
                // COMPAT: Since the DOM range has no concept of backwards/forwards
438
                // we need to check and do the right thing here.
439
                if (Range.isBackward(selection)) {
1!
440
                    // eslint-disable-next-line max-len
441
                    domSelection.setBaseAndExtent(
×
442
                        newDomRange.endContainer,
443
                        newDomRange.endOffset,
444
                        newDomRange.startContainer,
445
                        newDomRange.startOffset
446
                    );
447
                } else {
448
                    // eslint-disable-next-line max-len
449
                    domSelection.setBaseAndExtent(
1✔
450
                        newDomRange.startContainer,
451
                        newDomRange.startOffset,
452
                        newDomRange.endContainer,
453
                        newDomRange.endOffset
454
                    );
455
                }
456
            } else {
457
                domSelection.removeAllRanges();
×
458
            }
459

460
            setTimeout(() => {
1✔
461
                // handle scrolling in setTimeout because of
462
                // dom should not have updated immediately after listRender's updating
463
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
464
                // COMPAT: In Firefox, it's not enough to create a range, you also need
465
                // to focus the contenteditable element too. (2016/11/16)
466
                if (newDomRange && IS_FIREFOX) {
1!
UNCOV
467
                    el.focus();
×
468
                }
469

470
                this.isUpdatingSelection = false;
1✔
471
            });
472
        } catch (error) {
UNCOV
473
            this.editor.onError({
×
474
                code: SlateErrorCode.ToNativeSelectionError,
475
                nativeError: error
476
            });
477
            this.isUpdatingSelection = false;
×
478
        }
479
    }
480

481
    onChange() {
482
        this.forceRender();
13✔
483
        this.onChangeCallback(this.editor.children);
13✔
484
    }
485

486
    ngAfterViewChecked() {}
487

488
    ngDoCheck() {}
489

490
    forceRender() {
491
        this.updateContext();
15✔
492
        if (this.isEnabledVirtualScroll()) {
15!
UNCOV
493
            const virtualView = this.calculateVirtualViewport();
×
UNCOV
494
            this.applyVirtualView(virtualView);
×
UNCOV
495
            this.listRender.update(this.inViewportChildren, this.editor, this.context);
×
496
            const visibleIndexes = Array.from(this.inViewportIndics);
×
497
            this.remeasureHeightByIndics(visibleIndexes);
×
498
        } else {
499
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
500
        }
501
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
502
        // when the DOMElement where the selection is located is removed
503
        // the compositionupdate and compositionend events will no longer be fired
504
        // so isComposing needs to be corrected
505
        // need exec after this.cdr.detectChanges() to render HTML
506
        // need exec before this.toNativeSelection() to correct native selection
507
        if (this.isComposing) {
15!
508
            // Composition input text be not rendered when user composition input with selection is expanded
509
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
510
            // this time condition is true and isComposing is assigned false
511
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
UNCOV
512
            setTimeout(() => {
×
513
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
514
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
UNCOV
515
                let textContent = '';
×
516
                // skip decorate text
UNCOV
517
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
UNCOV
518
                    let text = stringDOMNode.textContent;
×
UNCOV
519
                    const zeroChar = '\uFEFF';
×
520
                    // remove zero with char
UNCOV
521
                    if (text.startsWith(zeroChar)) {
×
UNCOV
522
                        text = text.slice(1);
×
523
                    }
UNCOV
524
                    if (text.endsWith(zeroChar)) {
×
525
                        text = text.slice(0, text.length - 1);
×
526
                    }
527
                    textContent += text;
×
528
                });
UNCOV
529
                if (Node.string(textNode).endsWith(textContent)) {
×
UNCOV
530
                    this.isComposing = false;
×
531
                }
532
            }, 0);
533
        }
534
        this.toNativeSelection();
15✔
535
    }
536

537
    render() {
538
        const changed = this.updateContext();
2✔
539
        if (changed) {
2✔
540
            if (this.isEnabledVirtualScroll()) {
2!
UNCOV
541
                const virtualView = this.calculateVirtualViewport();
×
UNCOV
542
                this.applyVirtualView(virtualView);
×
UNCOV
543
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
UNCOV
544
                this.scheduleMeasureVisibleHeights();
×
545
            } else {
546
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
547
            }
548
        }
549
    }
550

551
    updateContext() {
552
        const decorations = this.generateDecorations();
17✔
553
        if (
17✔
554
            this.context.selection !== this.editor.selection ||
46✔
555
            this.context.decorate !== this.decorate ||
556
            this.context.readonly !== this.readonly ||
557
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
558
        ) {
559
            this.context = {
10✔
560
                parent: this.editor,
561
                selection: this.editor.selection,
562
                decorations: decorations,
563
                decorate: this.decorate,
564
                readonly: this.readonly
565
            };
566
            return true;
10✔
567
        }
568
        return false;
7✔
569
    }
570

571
    initializeContext() {
572
        this.context = {
49✔
573
            parent: this.editor,
574
            selection: this.editor.selection,
575
            decorations: this.generateDecorations(),
576
            decorate: this.decorate,
577
            readonly: this.readonly
578
        };
579
    }
580

581
    initializeViewContext() {
582
        this.viewContext = {
23✔
583
            editor: this.editor,
584
            renderElement: this.renderElement,
585
            renderLeaf: this.renderLeaf,
586
            renderText: this.renderText,
587
            trackBy: this.trackBy,
588
            isStrictDecorate: this.isStrictDecorate
589
        };
590
    }
591

592
    composePlaceholderDecorate(editor: Editor) {
593
        if (this.placeholderDecorate) {
64!
UNCOV
594
            return this.placeholderDecorate(editor) || [];
×
595
        }
596

597
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
598
            const start = Editor.start(editor, []);
3✔
599
            return [
3✔
600
                {
601
                    placeholder: this.placeholder,
602
                    anchor: start,
603
                    focus: start
604
                }
605
            ];
606
        } else {
607
            return [];
61✔
608
        }
609
    }
610

611
    generateDecorations() {
612
        const decorations = this.decorate([this.editor, []]);
66✔
613
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
614
        decorations.push(...placeholderDecorations);
66✔
615
        return decorations;
66✔
616
    }
617

618
    private isEnabledVirtualScroll() {
619
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
81✔
620
    }
621

622
    // the height from scroll container top to editor top height element
623
    private businessHeight: number = 0;
23✔
624

625
    virtualScrollInitialized = false;
23✔
626

627
    virtualTopHeightElement: HTMLElement;
628

629
    virtualBottomHeightElement: HTMLElement;
630

631
    virtualCenterOutlet: HTMLElement;
632

633
    initializeVirtualScroll() {
634
        if (this.virtualScrollInitialized) {
23!
635
            return;
×
636
        }
637
        if (this.isEnabledVirtualScroll()) {
23!
638
            this.virtualScrollInitialized = true;
×
639
            this.virtualTopHeightElement = document.createElement('div');
×
UNCOV
640
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
UNCOV
641
            this.virtualTopHeightElement.contentEditable = 'false';
×
642
            this.virtualBottomHeightElement = document.createElement('div');
×
643
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
644
            this.virtualBottomHeightElement.contentEditable = 'false';
×
645
            this.virtualCenterOutlet = document.createElement('div');
×
UNCOV
646
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
UNCOV
647
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
UNCOV
648
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
UNCOV
649
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
UNCOV
650
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
651
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
652
            this.editorResizeObserver = new ResizeObserver(entries => {
×
UNCOV
653
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
654
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
655
                    this.remeasureHeightByIndics(Array.from(this.inViewportIndics));
×
656
                }
657
            });
UNCOV
658
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
659
            if (isDebug) {
×
660
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
UNCOV
661
                VirtualScrollDebugOverlay.getInstance(doc);
×
662
            }
663
        }
664
    }
665

666
    setVirtualSpaceHeight(topHeight: number, bottomHeight: number) {
667
        if (!this.virtualScrollInitialized) {
×
668
            return;
×
669
        }
UNCOV
670
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
671
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
672
    }
673

674
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
675
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
676
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
677
    }
678

679
    private tryUpdateVirtualViewport() {
UNCOV
680
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
681
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
682
            let virtualView = this.calculateVirtualViewport();
×
683
            let diff = this.diffVirtualViewport(virtualView);
×
684
            if (!diff.isDiff) {
×
685
                return;
×
686
            }
UNCOV
687
            if (diff.isMissingTop) {
×
688
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
UNCOV
689
                if (result) {
×
UNCOV
690
                    virtualView = this.calculateVirtualViewport();
×
UNCOV
691
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
UNCOV
692
                    if (!diff.isDiff) {
×
693
                        return;
×
694
                    }
695
                }
696
            }
UNCOV
697
            this.applyVirtualView(virtualView);
×
UNCOV
698
            if (this.listRender.initialized) {
×
UNCOV
699
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
UNCOV
700
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
UNCOV
701
                    this.toNativeSelection();
×
702
                }
703
            }
704
            this.scheduleMeasureVisibleHeights();
×
705
        });
706
    }
707

708
    private tryAnchorScroll() {
NEW
709
        if (!this.isEnabledVirtualScroll()) {
×
NEW
710
            return;
×
711
        }
NEW
UNCOV
712
        const { anchorKey, scrollTo } = this.virtualToAnchorConfig || {};
×
NEW
UNCOV
713
        if (!anchorKey || !scrollTo) {
×
NEW
UNCOV
714
            return;
×
715
        }
NEW
UNCOV
716
        if (anchorKey === this.lastAnchorKey) {
×
NEW
UNCOV
717
            return;
×
718
        }
NEW
719
        const children = (this.editor.children || []) as Element[];
×
NEW
720
        if (!children.length) {
×
NEW
721
            return;
×
722
        }
NEW
723
        const anchorIndex = this.getElementIndexByKeyId(anchorKey);
×
NEW
724
        if (anchorIndex < 0) {
×
NEW
725
            return;
×
726
        }
727

NEW
728
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
NEW
729
        if (!viewportHeight) {
×
NEW
UNCOV
730
            return;
×
731
        }
NEW
732
        const { accumulatedHeights } = this.buildHeightsAndAccumulatedHeights();
×
733

NEW
734
        const itemTop = accumulatedHeights[anchorIndex] ?? 0;
×
NEW
735
        const targetScrollTop = itemTop + this.businessHeight;
×
736

NEW
737
        this.lastAnchorKey = anchorKey;
×
NEW
UNCOV
738
        if (isDebug) {
×
NEW
739
            this.debugLog(
×
740
                'log',
741
                'anchorScroll key:',
742
                anchorKey,
743
                'targetScrollTop:',
744
                targetScrollTop,
745
                'businessHeight:',
746
                this.businessHeight
747
            );
748
        }
NEW
749
        scrollTo(targetScrollTop);
×
NEW
750
        this.lastAnchorKey = '';
×
751
    }
752

753
    private getElementIndexByKeyId(keyId: string): number {
NEW
UNCOV
754
        const children = this.editor.children;
×
NEW
UNCOV
755
        for (let i = 0; i < children.length; i++) {
×
NEW
UNCOV
756
            const key = AngularEditor.findKey(this.editor, children[i]);
×
NEW
UNCOV
757
            if (key?.id === keyId) {
×
NEW
UNCOV
758
                return i;
×
759
            }
760
        }
NEW
UNCOV
761
        return -1;
×
762
    }
763

764
    private buildHeightsAndAccumulatedHeights() {
NEW
765
        const children = (this.editor.children || []) as Element[];
×
NEW
UNCOV
766
        const heights = new Array(children.length);
×
NEW
UNCOV
767
        const accumulatedHeights = new Array(children.length + 1);
×
NEW
UNCOV
768
        accumulatedHeights[0] = 0;
×
NEW
769
        for (let i = 0; i < children.length; i++) {
×
NEW
770
            const height = this.getBlockHeight(i);
×
NEW
UNCOV
771
            heights[i] = height;
×
NEW
UNCOV
772
            accumulatedHeights[i + 1] = accumulatedHeights[i] + height;
×
773
        }
NEW
UNCOV
774
        return { heights, accumulatedHeights };
×
775
    }
776

777
    private calculateVirtualViewport() {
778
        const children = (this.editor.children || []) as Element[];
×
779
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
780
            return {
×
781
                inViewportChildren: children,
782
                visibleIndexes: new Set<number>(),
783
                top: 0,
784
                bottom: 0,
785
                heights: []
786
            };
787
        }
788
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
789
        if (isDebug) {
×
UNCOV
790
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
791
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
792
        }
793
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
794
        if (!viewportHeight) {
×
UNCOV
795
            return {
×
796
                inViewportChildren: [],
797
                visibleIndexes: new Set<number>(),
798
                top: 0,
799
                bottom: 0,
800
                heights: []
801
            };
802
        }
UNCOV
803
        const elementLength = children.length;
×
804
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
NEW
UNCOV
805
        const { heights, accumulatedHeights } = this.buildHeightsAndAccumulatedHeights();
×
UNCOV
806
        const totalHeight = accumulatedHeights[elementLength];
×
807
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
UNCOV
808
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
809
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
810
        let accumulatedOffset = 0;
×
811
        let visibleStartIndex = -1;
×
812
        const visible: Element[] = [];
×
UNCOV
813
        const visibleIndexes: number[] = [];
×
814

UNCOV
815
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
UNCOV
816
            const currentHeight = heights[i];
×
817
            const nextOffset = accumulatedOffset + currentHeight;
×
818
            // 可视区域有交集,加入渲染
819
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
820
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
UNCOV
821
                visible.push(children[i]);
×
822
                visibleIndexes.push(i);
×
823
            }
UNCOV
824
            accumulatedOffset = nextOffset;
×
825
        }
826

827
        if (visibleStartIndex === -1 && elementLength) {
×
828
            visibleStartIndex = elementLength - 1;
×
829
            visible.push(children[visibleStartIndex]);
×
830
            visibleIndexes.push(visibleStartIndex);
×
831
        }
832

833
        const visibleEndIndex =
UNCOV
834
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
835
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
UNCOV
836
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
837

UNCOV
838
        return {
×
839
            inViewportChildren: visible.length ? visible : children,
×
840
            visibleIndexes: new Set(visibleIndexes),
841
            top,
842
            bottom,
843
            heights
844
        };
845
    }
846

847
    private applyVirtualView(virtualView: VirtualViewResult) {
848
        this.inViewportChildren = virtualView.inViewportChildren;
×
849
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
UNCOV
850
        this.inViewportIndics = virtualView.visibleIndexes;
×
851
    }
852

853
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
UNCOV
854
        if (!this.inViewportChildren.length) {
×
UNCOV
855
            return {
×
856
                isDiff: true,
857
                diffTopRenderedIndexes: [],
858
                diffBottomRenderedIndexes: []
859
            };
860
        }
UNCOV
861
        const oldVisibleIndexes = [...this.inViewportIndics];
×
UNCOV
862
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
UNCOV
863
        const firstNewIndex = newVisibleIndexes[0];
×
UNCOV
864
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
UNCOV
865
        const firstOldIndex = oldVisibleIndexes[0];
×
UNCOV
866
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
UNCOV
867
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
868
            const diffTopRenderedIndexes = [];
×
UNCOV
869
            const diffBottomRenderedIndexes = [];
×
UNCOV
870
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
UNCOV
871
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
UNCOV
872
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
UNCOV
873
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
UNCOV
874
            if (isMissingTop || isAddedBottom) {
×
875
                // 向下
876
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
877
                    const element = oldVisibleIndexes[index];
×
878
                    if (!newVisibleIndexes.includes(element)) {
×
879
                        diffTopRenderedIndexes.push(element);
×
880
                    } else {
881
                        break;
×
882
                    }
883
                }
884
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
885
                    const element = newVisibleIndexes[index];
×
886
                    if (!oldVisibleIndexes.includes(element)) {
×
887
                        diffBottomRenderedIndexes.push(element);
×
888
                    } else {
889
                        break;
×
890
                    }
891
                }
892
            } else if (isAddedTop || isMissingBottom) {
×
893
                // 向上
894
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
895
                    const element = newVisibleIndexes[index];
×
UNCOV
896
                    if (!oldVisibleIndexes.includes(element)) {
×
897
                        diffTopRenderedIndexes.push(element);
×
898
                    } else {
899
                        break;
×
900
                    }
901
                }
902
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
903
                    const element = oldVisibleIndexes[index];
×
904
                    if (!newVisibleIndexes.includes(element)) {
×
UNCOV
905
                        diffBottomRenderedIndexes.push(element);
×
906
                    } else {
907
                        break;
×
908
                    }
909
                }
910
            }
UNCOV
911
            if (isDebug) {
×
UNCOV
912
                this.debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
913
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
914
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
915
                this.debugLog(
×
916
                    'log',
917
                    'diffTopRenderedIndexes:',
918
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
919
                    diffTopRenderedIndexes,
920
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
921
                );
922
                this.debugLog(
×
923
                    'log',
924
                    'diffBottomRenderedIndexes:',
925
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
926
                    diffBottomRenderedIndexes,
927
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
928
                );
929
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
930
                const needBottom = virtualView.heights
×
931
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
932
                    .reduce((acc, height) => acc + height, 0);
×
933
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
UNCOV
934
                this.debugLog(
×
935
                    'log',
936
                    'newBottomHeight:',
937
                    needBottom,
938
                    'prevBottomHeight:',
939
                    parseFloat(this.virtualBottomHeightElement.style.height)
940
                );
941
                this.debugLog('warn', '=========== Dividing line ===========');
×
942
            }
UNCOV
943
            return {
×
944
                isDiff: true,
945
                isMissingTop,
946
                isAddedTop,
947
                isMissingBottom,
948
                isAddedBottom,
949
                diffTopRenderedIndexes,
950
                diffBottomRenderedIndexes
951
            };
952
        }
UNCOV
953
        return {
×
954
            isDiff: false,
955
            diffTopRenderedIndexes: [],
956
            diffBottomRenderedIndexes: []
957
        };
958
    }
959

960
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
UNCOV
961
        const node = this.editor.children[index] as Element;
×
UNCOV
962
        const isVisible = this.editor.isVisible(node);
×
UNCOV
963
        if (!isVisible) {
×
UNCOV
964
            return 0;
×
965
        }
UNCOV
966
        if (!node) {
×
967
            return defaultHeight;
×
968
        }
UNCOV
969
        const key = AngularEditor.findKey(this.editor, node);
×
UNCOV
970
        const height = this.keyHeightMap.get(key.id);
×
UNCOV
971
        if (typeof height === 'number') {
×
UNCOV
972
            return height;
×
973
        }
UNCOV
974
        if (this.keyHeightMap.has(key.id)) {
×
UNCOV
975
            console.error('getBlockHeight: invalid height value', key.id, height);
×
976
        }
UNCOV
977
        return defaultHeight;
×
978
    }
979

980
    private scheduleMeasureVisibleHeights() {
UNCOV
981
        if (!this.isEnabledVirtualScroll()) {
×
982
            return;
×
983
        }
UNCOV
984
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
UNCOV
985
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
UNCOV
986
            this.measureVisibleHeights();
×
987
        });
988
    }
989

990
    private measureVisibleHeights() {
UNCOV
991
        const children = (this.editor.children || []) as Element[];
×
UNCOV
992
        this.inViewportIndics.forEach(index => {
×
UNCOV
993
            const node = children[index];
×
UNCOV
994
            if (!node) {
×
UNCOV
995
                return;
×
996
            }
UNCOV
997
            const key = AngularEditor.findKey(this.editor, node);
×
998
            // 跳过已测过的块,除非强制测量
UNCOV
999
            if (this.keyHeightMap.has(key.id)) {
×
1000
                return;
×
1001
            }
UNCOV
1002
            const view = ELEMENT_TO_COMPONENT.get(node);
×
UNCOV
1003
            if (!view) {
×
UNCOV
1004
                return;
×
1005
            }
UNCOV
1006
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
1007
            if (ret instanceof Promise) {
×
UNCOV
1008
                ret.then(height => {
×
UNCOV
1009
                    this.keyHeightMap.set(key.id, height);
×
1010
                });
1011
            } else {
UNCOV
1012
                this.keyHeightMap.set(key.id, ret);
×
1013
            }
1014
        });
1015
    }
1016

1017
    private remeasureHeightByIndics(indics: number[]): boolean {
UNCOV
1018
        const children = (this.editor.children || []) as Element[];
×
UNCOV
1019
        let isHeightChanged = false;
×
UNCOV
1020
        indics.forEach(index => {
×
UNCOV
1021
            const node = children[index];
×
UNCOV
1022
            if (!node) {
×
UNCOV
1023
                return;
×
1024
            }
1025
            const key = AngularEditor.findKey(this.editor, node);
×
1026
            const view = ELEMENT_TO_COMPONENT.get(node);
×
1027
            if (!view) {
×
1028
                return;
×
1029
            }
1030
            const prevHeight = this.keyHeightMap.get(key.id);
×
1031
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
1032
            if (ret instanceof Promise) {
×
1033
                ret.then(height => {
×
1034
                    if (height !== prevHeight) {
×
UNCOV
1035
                        this.keyHeightMap.set(key.id, height);
×
UNCOV
1036
                        isHeightChanged = true;
×
UNCOV
1037
                        if (isDebug) {
×
1038
                            this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
1039
                        }
1040
                    }
1041
                });
1042
            } else {
1043
                if (ret !== prevHeight) {
×
1044
                    this.keyHeightMap.set(key.id, ret);
×
1045
                    isHeightChanged = true;
×
1046
                    if (isDebug) {
×
1047
                        this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
1048
                    }
1049
                }
1050
            }
1051
        });
1052
        return isHeightChanged;
×
1053
    }
1054

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

1068
    private toSlateSelection() {
1069
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1070
            try {
1✔
1071
                if (isDebug) {
1!
1072
                    console.log('toSlateSelection');
×
1073
                }
1074
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1075
                const { activeElement } = root;
1✔
1076
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1077
                const domSelection = (root as Document).getSelection();
1✔
1078

1079
                if (activeElement === el) {
1!
1080
                    this.latestElement = activeElement;
1✔
1081
                    IS_FOCUSED.set(this.editor, true);
1✔
1082
                } else {
UNCOV
1083
                    IS_FOCUSED.delete(this.editor);
×
1084
                }
1085

1086
                if (!domSelection) {
1!
UNCOV
1087
                    return Transforms.deselect(this.editor);
×
1088
                }
1089

1090
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1091
                const hasDomSelectionInEditor =
1092
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1093
                if (!hasDomSelectionInEditor) {
1!
UNCOV
1094
                    Transforms.deselect(this.editor);
×
1095
                    return;
×
1096
                }
1097

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

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

1198
                // COMPAT: If the selection is expanded, even if the command seems like
1199
                // a delete forward/backward command it should delete the selection.
UNCOV
1200
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
UNCOV
1201
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
UNCOV
1202
                    Editor.deleteFragment(editor, { direction });
×
UNCOV
1203
                    return;
×
1204
                }
1205

UNCOV
1206
                switch (type) {
×
1207
                    case 'deleteByComposition':
1208
                    case 'deleteByCut':
1209
                    case 'deleteByDrag': {
UNCOV
1210
                        Editor.deleteFragment(editor);
×
UNCOV
1211
                        break;
×
1212
                    }
1213

1214
                    case 'deleteContent':
1215
                    case 'deleteContentForward': {
UNCOV
1216
                        Editor.deleteForward(editor);
×
UNCOV
1217
                        break;
×
1218
                    }
1219

1220
                    case 'deleteContentBackward': {
UNCOV
1221
                        Editor.deleteBackward(editor);
×
UNCOV
1222
                        break;
×
1223
                    }
1224

1225
                    case 'deleteEntireSoftLine': {
UNCOV
1226
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1227
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1228
                        break;
×
1229
                    }
1230

1231
                    case 'deleteHardLineBackward': {
UNCOV
1232
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
1233
                        break;
×
1234
                    }
1235

1236
                    case 'deleteSoftLineBackward': {
1237
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1238
                        break;
×
1239
                    }
1240

1241
                    case 'deleteHardLineForward': {
UNCOV
1242
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
1243
                        break;
×
1244
                    }
1245

1246
                    case 'deleteSoftLineForward': {
UNCOV
1247
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1248
                        break;
×
1249
                    }
1250

1251
                    case 'deleteWordBackward': {
UNCOV
1252
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1253
                        break;
×
1254
                    }
1255

1256
                    case 'deleteWordForward': {
1257
                        Editor.deleteForward(editor, { unit: 'word' });
×
1258
                        break;
×
1259
                    }
1260

1261
                    case 'insertLineBreak':
1262
                    case 'insertParagraph': {
1263
                        Editor.insertBreak(editor);
×
1264
                        break;
×
1265
                    }
1266

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

1302
    private onDOMBlur(event: FocusEvent) {
UNCOV
1303
        if (
×
1304
            this.readonly ||
×
1305
            this.isUpdatingSelection ||
1306
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1307
            this.isDOMEventHandled(event, this.blur)
1308
        ) {
UNCOV
1309
            return;
×
1310
        }
1311

1312
        const window = AngularEditor.getWindow(this.editor);
×
1313

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

UNCOV
1323
        const { relatedTarget } = event;
×
UNCOV
1324
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1325

1326
        // COMPAT: The event should be ignored if the focus is returning
1327
        // to the editor from an embedded editable element (eg. an <input>
1328
        // element inside a void node).
UNCOV
1329
        if (relatedTarget === el) {
×
UNCOV
1330
            return;
×
1331
        }
1332

1333
        // COMPAT: The event should be ignored if the focus is moving from
1334
        // the editor to inside a void node's spacer element.
1335
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1336
            return;
×
1337
        }
1338

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

UNCOV
1345
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1346
                return;
×
1347
            }
1348
        }
1349

UNCOV
1350
        IS_FOCUSED.delete(this.editor);
×
1351
    }
1352

1353
    private onDOMClick(event: MouseEvent) {
UNCOV
1354
        if (
×
1355
            !this.readonly &&
×
1356
            AngularEditor.hasTarget(this.editor, event.target) &&
1357
            !this.isDOMEventHandled(event, this.click) &&
1358
            isDOMNode(event.target)
1359
        ) {
1360
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1361
            const path = AngularEditor.findPath(this.editor, node);
×
UNCOV
1362
            const start = Editor.start(this.editor, path);
×
UNCOV
1363
            const end = Editor.end(this.editor, path);
×
1364

UNCOV
1365
            const startVoid = Editor.void(this.editor, { at: start });
×
1366
            const endVoid = Editor.void(this.editor, { at: end });
×
1367

1368
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
UNCOV
1369
                let blockPath = path;
×
1370
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
UNCOV
1371
                    const block = Editor.above(this.editor, {
×
UNCOV
1372
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1373
                        at: path
1374
                    });
1375

1376
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1377
                }
1378

1379
                const range = Editor.range(this.editor, blockPath);
×
UNCOV
1380
                Transforms.select(this.editor, range);
×
1381
                return;
×
1382
            }
1383

UNCOV
1384
            if (
×
1385
                startVoid &&
×
1386
                endVoid &&
1387
                Path.equals(startVoid[1], endVoid[1]) &&
1388
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1389
            ) {
1390
                const range = Editor.range(this.editor, start);
×
UNCOV
1391
                Transforms.select(this.editor, range);
×
1392
            }
1393
        }
1394
    }
1395

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

1411
    private onDOMCompositionUpdate(event: CompositionEvent) {
1412
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1413
    }
1414

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

1429
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1430
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1431
            this.isComposing = false;
×
1432
        }
UNCOV
1433
        this.render();
×
1434
    }
1435

1436
    private onDOMCopy(event: ClipboardEvent) {
UNCOV
1437
        const window = AngularEditor.getWindow(this.editor);
×
UNCOV
1438
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
UNCOV
1439
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
UNCOV
1440
            event.preventDefault();
×
UNCOV
1441
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1442
        }
1443
    }
1444

1445
    private onDOMCut(event: ClipboardEvent) {
UNCOV
1446
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
UNCOV
1447
            event.preventDefault();
×
UNCOV
1448
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
UNCOV
1449
            const { selection } = this.editor;
×
1450

UNCOV
1451
            if (selection) {
×
UNCOV
1452
                AngularEditor.deleteCutData(this.editor);
×
1453
            }
1454
        }
1455
    }
1456

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

1464
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1465
                event.preventDefault();
×
1466
            }
1467
        }
1468
    }
1469

1470
    private onDOMDragStart(event: DragEvent) {
UNCOV
1471
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
UNCOV
1472
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1473
            const path = AngularEditor.findPath(this.editor, node);
×
1474
            const voidMatch =
1475
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1476

1477
            // If starting a drag on a void node, make sure it is selected
1478
            // so that it shows up in the selection's fragment.
UNCOV
1479
            if (voidMatch) {
×
UNCOV
1480
                const range = Editor.range(this.editor, path);
×
1481
                Transforms.select(this.editor, range);
×
1482
            }
1483

1484
            this.isDraggingInternally = true;
×
1485

UNCOV
1486
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1487
        }
1488
    }
1489

1490
    private onDOMDrop(event: DragEvent) {
1491
        const editor = this.editor;
×
UNCOV
1492
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
UNCOV
1493
            event.preventDefault();
×
1494
            // Keep a reference to the dragged range before updating selection
UNCOV
1495
            const draggedRange = editor.selection;
×
1496

1497
            // Find the range where the drop happened
1498
            const range = AngularEditor.findEventRange(editor, event);
×
1499
            const data = event.dataTransfer;
×
1500

1501
            Transforms.select(editor, range);
×
1502

UNCOV
1503
            if (this.isDraggingInternally) {
×
1504
                if (draggedRange) {
×
1505
                    Transforms.delete(editor, {
×
1506
                        at: draggedRange
1507
                    });
1508
                }
1509

1510
                this.isDraggingInternally = false;
×
1511
            }
1512

UNCOV
1513
            AngularEditor.insertData(editor, data);
×
1514

1515
            // When dragging from another source into the editor, it's possible
1516
            // that the current editor does not have focus.
1517
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1518
                AngularEditor.focus(editor);
×
1519
            }
1520
        }
1521
    }
1522

1523
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1524
        if (
×
1525
            !this.readonly &&
×
1526
            this.isDraggingInternally &&
1527
            AngularEditor.hasTarget(this.editor, event.target) &&
1528
            !this.isDOMEventHandled(event, this.dragEnd)
1529
        ) {
UNCOV
1530
            this.isDraggingInternally = false;
×
1531
        }
1532
    }
1533

1534
    private onDOMFocus(event: Event) {
1535
        if (
2✔
1536
            !this.readonly &&
8✔
1537
            !this.isUpdatingSelection &&
1538
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1539
            !this.isDOMEventHandled(event, this.focus)
1540
        ) {
1541
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1542
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1543
            this.latestElement = root.activeElement;
2✔
1544

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

1553
            IS_FOCUSED.set(this.editor, true);
2✔
1554
        }
1555
    }
1556

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

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

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

UNCOV
1582
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1583
                        editor.redo();
×
1584
                    }
1585

UNCOV
1586
                    return;
×
1587
                }
1588

1589
                if (Hotkeys.isUndo(nativeEvent)) {
×
1590
                    event.preventDefault();
×
1591

UNCOV
1592
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1593
                        editor.undo();
×
1594
                    }
1595

1596
                    return;
×
1597
                }
1598

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

UNCOV
1609
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1610
                    event.preventDefault();
×
UNCOV
1611
                    Transforms.move(editor, { unit: 'line' });
×
UNCOV
1612
                    return;
×
1613
                }
1614

UNCOV
1615
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1616
                    event.preventDefault();
×
1617
                    Transforms.move(editor, {
×
1618
                        unit: 'line',
1619
                        edge: 'focus',
1620
                        reverse: true
1621
                    });
UNCOV
1622
                    return;
×
1623
                }
1624

UNCOV
1625
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
UNCOV
1626
                    event.preventDefault();
×
1627
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1628
                    return;
×
1629
                }
1630

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

UNCOV
1639
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1640
                        Transforms.move(editor, { reverse: !isRTL });
×
1641
                    } else {
1642
                        Transforms.collapse(editor, { edge: 'start' });
×
1643
                    }
1644

1645
                    return;
×
1646
                }
1647

UNCOV
1648
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1649
                    event.preventDefault();
×
UNCOV
1650
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1651
                        Transforms.move(editor, { reverse: isRTL });
×
1652
                    } else {
UNCOV
1653
                        Transforms.collapse(editor, { edge: 'end' });
×
1654
                    }
1655

1656
                    return;
×
1657
                }
1658

1659
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1660
                    event.preventDefault();
×
1661

UNCOV
1662
                    if (selection && Range.isExpanded(selection)) {
×
1663
                        Transforms.collapse(editor, { edge: 'focus' });
×
1664
                    }
1665

1666
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1667
                    return;
×
1668
                }
1669

1670
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1671
                    event.preventDefault();
×
1672

1673
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1674
                        Transforms.collapse(editor, { edge: 'focus' });
×
1675
                    }
1676

1677
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
UNCOV
1678
                    return;
×
1679
                }
1680

UNCOV
1681
                if (isKeyHotkey('mod+a', event)) {
×
UNCOV
1682
                    this.editor.selectAll();
×
1683
                    event.preventDefault();
×
UNCOV
1684
                    return;
×
1685
                }
1686

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

1698
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
UNCOV
1699
                        event.preventDefault();
×
UNCOV
1700
                        Editor.insertBreak(editor);
×
1701
                        return;
×
1702
                    }
1703

UNCOV
1704
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1705
                        event.preventDefault();
×
1706

1707
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1708
                            Editor.deleteFragment(editor, {
×
1709
                                direction: 'backward'
1710
                            });
1711
                        } else {
UNCOV
1712
                            Editor.deleteBackward(editor);
×
1713
                        }
1714

UNCOV
1715
                        return;
×
1716
                    }
1717

UNCOV
1718
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1719
                        event.preventDefault();
×
1720

1721
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1722
                            Editor.deleteFragment(editor, {
×
1723
                                direction: 'forward'
1724
                            });
1725
                        } else {
UNCOV
1726
                            Editor.deleteForward(editor);
×
1727
                        }
1728

UNCOV
1729
                        return;
×
1730
                    }
1731

UNCOV
1732
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1733
                        event.preventDefault();
×
1734

UNCOV
1735
                        if (selection && Range.isExpanded(selection)) {
×
1736
                            Editor.deleteFragment(editor, {
×
1737
                                direction: 'backward'
1738
                            });
1739
                        } else {
UNCOV
1740
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1741
                        }
1742

1743
                        return;
×
1744
                    }
1745

1746
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1747
                        event.preventDefault();
×
1748

1749
                        if (selection && Range.isExpanded(selection)) {
×
1750
                            Editor.deleteFragment(editor, {
×
1751
                                direction: 'forward'
1752
                            });
1753
                        } else {
UNCOV
1754
                            Editor.deleteForward(editor, { unit: 'line' });
×
1755
                        }
1756

UNCOV
1757
                        return;
×
1758
                    }
1759

UNCOV
1760
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1761
                        event.preventDefault();
×
1762

UNCOV
1763
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1764
                            Editor.deleteFragment(editor, {
×
1765
                                direction: 'backward'
1766
                            });
1767
                        } else {
UNCOV
1768
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1769
                        }
1770

UNCOV
1771
                        return;
×
1772
                    }
1773

UNCOV
1774
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1775
                        event.preventDefault();
×
1776

UNCOV
1777
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1778
                            Editor.deleteFragment(editor, {
×
1779
                                direction: 'forward'
1780
                            });
1781
                        } else {
UNCOV
1782
                            Editor.deleteForward(editor, { unit: 'word' });
×
1783
                        }
1784

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

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

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

1866
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1867
        if (!handler) {
3✔
1868
            return false;
3✔
1869
        }
UNCOV
1870
        handler(event);
×
UNCOV
1871
        return event.defaultPrevented;
×
1872
    }
1873
    //#endregion
1874

1875
    ngOnDestroy() {
1876
        this.editorResizeObserver?.disconnect();
23✔
1877
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1878
        this.manualListeners.forEach(manualListener => {
23✔
1879
            manualListener();
483✔
1880
        });
1881
        this.destroy$.complete();
23✔
1882
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1883
    }
1884
}
1885

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

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

UNCOV
1897
        if (isZeroDimensionRect) {
×
UNCOV
1898
            const leafRect = leafEl.getBoundingClientRect();
×
UNCOV
1899
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1900

UNCOV
1901
            if (leafHasDimensions) {
×
UNCOV
1902
                return;
×
1903
            }
1904
        }
1905

UNCOV
1906
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1907
        scrollIntoView(leafEl, {
×
1908
            scrollMode: 'if-needed'
1909
        });
UNCOV
1910
        delete leafEl.getBoundingClientRect;
×
1911
    }
1912
};
1913

1914
/**
1915
 * Check if the target is inside void and in the editor.
1916
 */
1917

1918
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1919
    let slateNode: Node | null = null;
1✔
1920
    try {
1✔
1921
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1922
    } catch (error) {}
1923
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1924
};
1925

1926
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1927
    return (
2✔
1928
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1929
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1930
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1931
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1932
    );
1933
};
1934

1935
/**
1936
 * remove default insert from composition
1937
 * @param text
1938
 */
1939
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
UNCOV
1940
    const types = ['compositionend', 'insertFromComposition'];
×
UNCOV
1941
    if (!types.includes(event.type)) {
×
UNCOV
1942
        return;
×
1943
    }
UNCOV
1944
    const insertText = (event as CompositionEvent).data;
×
UNCOV
1945
    const window = AngularEditor.getWindow(editor);
×
UNCOV
1946
    const domSelection = window.getSelection();
×
1947
    // ensure text node insert composition input text
UNCOV
1948
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
UNCOV
1949
        const textNode = domSelection.anchorNode;
×
UNCOV
1950
        textNode.splitText(textNode.length - insertText.length).remove();
×
1951
    }
1952
};
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