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

worktile / slate-angular / 51d30601-335a-499c-a487-8c5898f72e71

16 Dec 2025 10:40AM UTC coverage: 37.009% (-0.5%) from 37.461%
51d30601-335a-499c-a487-8c5898f72e71

Pull #325

circleci

Xwatson
fix: optimize params anchorkey to anchorElement
Pull Request #325: feat(virtual-scroll): #WIK-19623 support scrolling to specified node key

380 of 1234 branches covered (30.79%)

Branch coverage included in aggregate %.

1 of 38 new or added lines in 1 file covered. (2.63%)

393 existing lines in 1 file now uncovered.

1070 of 2684 relevant lines covered (39.87%)

24.25 hits per line

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

22.01
/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 lastAnchorElement?: Element;
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 { anchorElement, scrollTo } = this.virtualToAnchorConfig || {};
×
NEW
UNCOV
713
        if (!anchorElement || !scrollTo) {
×
NEW
UNCOV
714
            return;
×
715
        }
NEW
UNCOV
716
        if (anchorElement === this.lastAnchorElement) {
×
NEW
UNCOV
717
            return;
×
718
        }
NEW
719
        const children = this.editor.children;
×
NEW
720
        if (!children.length) {
×
NEW
721
            return;
×
722
        }
NEW
723
        const anchorIndex = children.findIndex(item => item === anchorElement);
×
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.lastAnchorElement = anchorElement;
×
NEW
UNCOV
738
        if (isDebug) {
×
NEW
739
            this.debugLog(
×
740
                'log',
741
                'anchorScroll element:',
742
                anchorElement,
743
                'targetScrollTop:',
744
                targetScrollTop,
745
                'businessHeight:',
746
                this.businessHeight
747
            );
748
        }
NEW
749
        scrollTo(targetScrollTop);
×
NEW
750
        this.lastAnchorElement = null;
×
751
    }
752

753
    private buildHeightsAndAccumulatedHeights() {
NEW
UNCOV
754
        const children = (this.editor.children || []) as Element[];
×
NEW
UNCOV
755
        const heights = new Array(children.length);
×
NEW
UNCOV
756
        const accumulatedHeights = new Array(children.length + 1);
×
NEW
UNCOV
757
        accumulatedHeights[0] = 0;
×
NEW
UNCOV
758
        for (let i = 0; i < children.length; i++) {
×
NEW
UNCOV
759
            const height = this.getBlockHeight(i);
×
NEW
UNCOV
760
            heights[i] = height;
×
NEW
UNCOV
761
            accumulatedHeights[i + 1] = accumulatedHeights[i] + height;
×
762
        }
NEW
763
        return { heights, accumulatedHeights };
×
764
    }
765

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

804
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
UNCOV
805
            const currentHeight = heights[i];
×
UNCOV
806
            const nextOffset = accumulatedOffset + currentHeight;
×
807
            // 可视区域有交集,加入渲染
UNCOV
808
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
809
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
810
                visible.push(children[i]);
×
811
                visibleIndexes.push(i);
×
812
            }
UNCOV
813
            accumulatedOffset = nextOffset;
×
814
        }
815

UNCOV
816
        if (visibleStartIndex === -1 && elementLength) {
×
817
            visibleStartIndex = elementLength - 1;
×
818
            visible.push(children[visibleStartIndex]);
×
819
            visibleIndexes.push(visibleStartIndex);
×
820
        }
821

822
        const visibleEndIndex =
UNCOV
823
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
UNCOV
824
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
UNCOV
825
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
826

827
        return {
×
828
            inViewportChildren: visible.length ? visible : children,
×
829
            visibleIndexes: new Set(visibleIndexes),
830
            top,
831
            bottom,
832
            heights
833
        };
834
    }
835

836
    private applyVirtualView(virtualView: VirtualViewResult) {
837
        this.inViewportChildren = virtualView.inViewportChildren;
×
UNCOV
838
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
UNCOV
839
        this.inViewportIndics = virtualView.visibleIndexes;
×
840
    }
841

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

949
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
UNCOV
950
        const node = this.editor.children[index] as Element;
×
UNCOV
951
        const isVisible = this.editor.isVisible(node);
×
UNCOV
952
        if (!isVisible) {
×
UNCOV
953
            return 0;
×
954
        }
UNCOV
955
        if (!node) {
×
956
            return defaultHeight;
×
957
        }
UNCOV
958
        const key = AngularEditor.findKey(this.editor, node);
×
UNCOV
959
        const height = this.keyHeightMap.get(key.id);
×
UNCOV
960
        if (typeof height === 'number') {
×
UNCOV
961
            return height;
×
962
        }
UNCOV
963
        if (this.keyHeightMap.has(key.id)) {
×
UNCOV
964
            console.error('getBlockHeight: invalid height value', key.id, height);
×
965
        }
UNCOV
966
        return defaultHeight;
×
967
    }
968

969
    private scheduleMeasureVisibleHeights() {
UNCOV
970
        if (!this.isEnabledVirtualScroll()) {
×
UNCOV
971
            return;
×
972
        }
UNCOV
973
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
UNCOV
974
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
UNCOV
975
            this.measureVisibleHeights();
×
976
        });
977
    }
978

979
    private measureVisibleHeights() {
UNCOV
980
        const children = (this.editor.children || []) as Element[];
×
UNCOV
981
        this.inViewportIndics.forEach(index => {
×
982
            const node = children[index];
×
UNCOV
983
            if (!node) {
×
UNCOV
984
                return;
×
985
            }
UNCOV
986
            const key = AngularEditor.findKey(this.editor, node);
×
987
            // 跳过已测过的块,除非强制测量
UNCOV
988
            if (this.keyHeightMap.has(key.id)) {
×
989
                return;
×
990
            }
UNCOV
991
            const view = ELEMENT_TO_COMPONENT.get(node);
×
UNCOV
992
            if (!view) {
×
UNCOV
993
                return;
×
994
            }
UNCOV
995
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
UNCOV
996
            if (ret instanceof Promise) {
×
UNCOV
997
                ret.then(height => {
×
998
                    this.keyHeightMap.set(key.id, height);
×
999
                });
1000
            } else {
UNCOV
1001
                this.keyHeightMap.set(key.id, ret);
×
1002
            }
1003
        });
1004
    }
1005

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

1044
    //#region event proxy
1045
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1046
        this.manualListeners.push(
483✔
1047
            this.renderer2.listen(target, eventName, (event: Event) => {
1048
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1049
                if (beforeInputEvent) {
5!
1050
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1051
                }
1052
                listener(event);
5✔
1053
            })
1054
        );
1055
    }
1056

1057
    private toSlateSelection() {
1058
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1059
            try {
1✔
1060
                if (isDebug) {
1!
UNCOV
1061
                    console.log('toSlateSelection');
×
1062
                }
1063
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1064
                const { activeElement } = root;
1✔
1065
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1066
                const domSelection = (root as Document).getSelection();
1✔
1067

1068
                if (activeElement === el) {
1!
1069
                    this.latestElement = activeElement;
1✔
1070
                    IS_FOCUSED.set(this.editor, true);
1✔
1071
                } else {
1072
                    IS_FOCUSED.delete(this.editor);
×
1073
                }
1074

1075
                if (!domSelection) {
1!
1076
                    return Transforms.deselect(this.editor);
×
1077
                }
1078

1079
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1080
                const hasDomSelectionInEditor =
1081
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1082
                if (!hasDomSelectionInEditor) {
1!
UNCOV
1083
                    Transforms.deselect(this.editor);
×
1084
                    return;
×
1085
                }
1086

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

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

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

UNCOV
1195
                switch (type) {
×
1196
                    case 'deleteByComposition':
1197
                    case 'deleteByCut':
1198
                    case 'deleteByDrag': {
UNCOV
1199
                        Editor.deleteFragment(editor);
×
UNCOV
1200
                        break;
×
1201
                    }
1202

1203
                    case 'deleteContent':
1204
                    case 'deleteContentForward': {
UNCOV
1205
                        Editor.deleteForward(editor);
×
UNCOV
1206
                        break;
×
1207
                    }
1208

1209
                    case 'deleteContentBackward': {
UNCOV
1210
                        Editor.deleteBackward(editor);
×
UNCOV
1211
                        break;
×
1212
                    }
1213

1214
                    case 'deleteEntireSoftLine': {
1215
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1216
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1217
                        break;
×
1218
                    }
1219

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

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

1230
                    case 'deleteHardLineForward': {
1231
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
1232
                        break;
×
1233
                    }
1234

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

1240
                    case 'deleteWordBackward': {
1241
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1242
                        break;
×
1243
                    }
1244

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

1250
                    case 'insertLineBreak':
1251
                    case 'insertParagraph': {
UNCOV
1252
                        Editor.insertBreak(editor);
×
UNCOV
1253
                        break;
×
1254
                    }
1255

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

1291
    private onDOMBlur(event: FocusEvent) {
UNCOV
1292
        if (
×
1293
            this.readonly ||
×
1294
            this.isUpdatingSelection ||
1295
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1296
            this.isDOMEventHandled(event, this.blur)
1297
        ) {
UNCOV
1298
            return;
×
1299
        }
1300

UNCOV
1301
        const window = AngularEditor.getWindow(this.editor);
×
1302

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

1312
        const { relatedTarget } = event;
×
UNCOV
1313
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1314

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

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

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

1334
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1335
                return;
×
1336
            }
1337
        }
1338

UNCOV
1339
        IS_FOCUSED.delete(this.editor);
×
1340
    }
1341

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

UNCOV
1354
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
1355
            const endVoid = Editor.void(this.editor, { at: end });
×
1356

1357
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
UNCOV
1358
                let blockPath = path;
×
1359
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1360
                    const block = Editor.above(this.editor, {
×
UNCOV
1361
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1362
                        at: path
1363
                    });
1364

UNCOV
1365
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1366
                }
1367

1368
                const range = Editor.range(this.editor, blockPath);
×
UNCOV
1369
                Transforms.select(this.editor, range);
×
1370
                return;
×
1371
            }
1372

UNCOV
1373
            if (
×
1374
                startVoid &&
×
1375
                endVoid &&
1376
                Path.equals(startVoid[1], endVoid[1]) &&
1377
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1378
            ) {
1379
                const range = Editor.range(this.editor, start);
×
UNCOV
1380
                Transforms.select(this.editor, range);
×
1381
            }
1382
        }
1383
    }
1384

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

1400
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1401
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1402
    }
1403

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

1418
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1419
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1420
            this.isComposing = false;
×
1421
        }
UNCOV
1422
        this.render();
×
1423
    }
1424

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

1434
    private onDOMCut(event: ClipboardEvent) {
UNCOV
1435
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
UNCOV
1436
            event.preventDefault();
×
UNCOV
1437
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
UNCOV
1438
            const { selection } = this.editor;
×
1439

UNCOV
1440
            if (selection) {
×
UNCOV
1441
                AngularEditor.deleteCutData(this.editor);
×
1442
            }
1443
        }
1444
    }
1445

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

1453
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1454
                event.preventDefault();
×
1455
            }
1456
        }
1457
    }
1458

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

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

UNCOV
1473
            this.isDraggingInternally = true;
×
1474

1475
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1476
        }
1477
    }
1478

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

1486
            // Find the range where the drop happened
1487
            const range = AngularEditor.findEventRange(editor, event);
×
1488
            const data = event.dataTransfer;
×
1489

UNCOV
1490
            Transforms.select(editor, range);
×
1491

UNCOV
1492
            if (this.isDraggingInternally) {
×
UNCOV
1493
                if (draggedRange) {
×
UNCOV
1494
                    Transforms.delete(editor, {
×
1495
                        at: draggedRange
1496
                    });
1497
                }
1498

1499
                this.isDraggingInternally = false;
×
1500
            }
1501

UNCOV
1502
            AngularEditor.insertData(editor, data);
×
1503

1504
            // When dragging from another source into the editor, it's possible
1505
            // that the current editor does not have focus.
1506
            if (!AngularEditor.isFocused(editor)) {
×
1507
                AngularEditor.focus(editor);
×
1508
            }
1509
        }
1510
    }
1511

1512
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1513
        if (
×
1514
            !this.readonly &&
×
1515
            this.isDraggingInternally &&
1516
            AngularEditor.hasTarget(this.editor, event.target) &&
1517
            !this.isDOMEventHandled(event, this.dragEnd)
1518
        ) {
UNCOV
1519
            this.isDraggingInternally = false;
×
1520
        }
1521
    }
1522

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

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

1542
            IS_FOCUSED.set(this.editor, true);
2✔
1543
        }
1544
    }
1545

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

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

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

UNCOV
1571
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1572
                        editor.redo();
×
1573
                    }
1574

UNCOV
1575
                    return;
×
1576
                }
1577

1578
                if (Hotkeys.isUndo(nativeEvent)) {
×
1579
                    event.preventDefault();
×
1580

UNCOV
1581
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1582
                        editor.undo();
×
1583
                    }
1584

1585
                    return;
×
1586
                }
1587

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

UNCOV
1598
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1599
                    event.preventDefault();
×
1600
                    Transforms.move(editor, { unit: 'line' });
×
UNCOV
1601
                    return;
×
1602
                }
1603

UNCOV
1604
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
UNCOV
1605
                    event.preventDefault();
×
UNCOV
1606
                    Transforms.move(editor, {
×
1607
                        unit: 'line',
1608
                        edge: 'focus',
1609
                        reverse: true
1610
                    });
UNCOV
1611
                    return;
×
1612
                }
1613

1614
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
UNCOV
1615
                    event.preventDefault();
×
1616
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1617
                    return;
×
1618
                }
1619

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

1628
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1629
                        Transforms.move(editor, { reverse: !isRTL });
×
1630
                    } else {
1631
                        Transforms.collapse(editor, { edge: 'start' });
×
1632
                    }
1633

UNCOV
1634
                    return;
×
1635
                }
1636

UNCOV
1637
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1638
                    event.preventDefault();
×
UNCOV
1639
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1640
                        Transforms.move(editor, { reverse: isRTL });
×
1641
                    } else {
1642
                        Transforms.collapse(editor, { edge: 'end' });
×
1643
                    }
1644

1645
                    return;
×
1646
                }
1647

UNCOV
1648
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1649
                    event.preventDefault();
×
1650

UNCOV
1651
                    if (selection && Range.isExpanded(selection)) {
×
1652
                        Transforms.collapse(editor, { edge: 'focus' });
×
1653
                    }
1654

1655
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1656
                    return;
×
1657
                }
1658

1659
                if (Hotkeys.isMoveWordForward(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 (isKeyHotkey('mod+a', event)) {
×
UNCOV
1671
                    this.editor.selectAll();
×
1672
                    event.preventDefault();
×
1673
                    return;
×
1674
                }
1675

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

UNCOV
1687
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
UNCOV
1688
                        event.preventDefault();
×
UNCOV
1689
                        Editor.insertBreak(editor);
×
UNCOV
1690
                        return;
×
1691
                    }
1692

UNCOV
1693
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1694
                        event.preventDefault();
×
1695

UNCOV
1696
                        if (selection && Range.isExpanded(selection)) {
×
1697
                            Editor.deleteFragment(editor, {
×
1698
                                direction: 'backward'
1699
                            });
1700
                        } else {
1701
                            Editor.deleteBackward(editor);
×
1702
                        }
1703

UNCOV
1704
                        return;
×
1705
                    }
1706

1707
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1708
                        event.preventDefault();
×
1709

UNCOV
1710
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1711
                            Editor.deleteFragment(editor, {
×
1712
                                direction: 'forward'
1713
                            });
1714
                        } else {
UNCOV
1715
                            Editor.deleteForward(editor);
×
1716
                        }
1717

UNCOV
1718
                        return;
×
1719
                    }
1720

1721
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1722
                        event.preventDefault();
×
1723

UNCOV
1724
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1725
                            Editor.deleteFragment(editor, {
×
1726
                                direction: 'backward'
1727
                            });
1728
                        } else {
UNCOV
1729
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1730
                        }
1731

UNCOV
1732
                        return;
×
1733
                    }
1734

UNCOV
1735
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1736
                        event.preventDefault();
×
1737

UNCOV
1738
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1739
                            Editor.deleteFragment(editor, {
×
1740
                                direction: 'forward'
1741
                            });
1742
                        } else {
1743
                            Editor.deleteForward(editor, { unit: 'line' });
×
1744
                        }
1745

1746
                        return;
×
1747
                    }
1748

1749
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1750
                        event.preventDefault();
×
1751

UNCOV
1752
                        if (selection && Range.isExpanded(selection)) {
×
1753
                            Editor.deleteFragment(editor, {
×
1754
                                direction: 'backward'
1755
                            });
1756
                        } else {
UNCOV
1757
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1758
                        }
1759

UNCOV
1760
                        return;
×
1761
                    }
1762

UNCOV
1763
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1764
                        event.preventDefault();
×
1765

1766
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1767
                            Editor.deleteFragment(editor, {
×
1768
                                direction: 'forward'
1769
                            });
1770
                        } else {
UNCOV
1771
                            Editor.deleteForward(editor, { unit: 'word' });
×
1772
                        }
1773

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

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

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

1855
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1856
        if (!handler) {
3✔
1857
            return false;
3✔
1858
        }
UNCOV
1859
        handler(event);
×
UNCOV
1860
        return event.defaultPrevented;
×
1861
    }
1862
    //#endregion
1863

1864
    ngOnDestroy() {
1865
        this.editorResizeObserver?.disconnect();
22✔
1866
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1867
        this.manualListeners.forEach(manualListener => {
22✔
1868
            manualListener();
462✔
1869
        });
1870
        this.destroy$.complete();
22✔
1871
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1872
    }
1873
}
1874

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

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

UNCOV
1886
        if (isZeroDimensionRect) {
×
UNCOV
1887
            const leafRect = leafEl.getBoundingClientRect();
×
UNCOV
1888
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1889

UNCOV
1890
            if (leafHasDimensions) {
×
UNCOV
1891
                return;
×
1892
            }
1893
        }
1894

UNCOV
1895
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1896
        scrollIntoView(leafEl, {
×
1897
            scrollMode: 'if-needed'
1898
        });
UNCOV
1899
        delete leafEl.getBoundingClientRect;
×
1900
    }
1901
};
1902

1903
/**
1904
 * Check if the target is inside void and in the editor.
1905
 */
1906

1907
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1908
    let slateNode: Node | null = null;
1✔
1909
    try {
1✔
1910
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1911
    } catch (error) {}
1912
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1913
};
1914

1915
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1916
    return (
2✔
1917
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1918
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1919
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1920
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1921
    );
1922
};
1923

1924
/**
1925
 * remove default insert from composition
1926
 * @param text
1927
 */
1928
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
UNCOV
1929
    const types = ['compositionend', 'insertFromComposition'];
×
UNCOV
1930
    if (!types.includes(event.type)) {
×
UNCOV
1931
        return;
×
1932
    }
UNCOV
1933
    const insertText = (event as CompositionEvent).data;
×
UNCOV
1934
    const window = AngularEditor.getWindow(editor);
×
UNCOV
1935
    const domSelection = window.getSelection();
×
1936
    // ensure text node insert composition input text
UNCOV
1937
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
UNCOV
1938
        const textNode = domSelection.anchorNode;
×
UNCOV
1939
        textNode.splitText(textNode.length - insertText.length).remove();
×
1940
    }
1941
};
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