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

worktile / slate-angular / cff60f55-2113-4e78-8887-270dd7ccce48

15 Dec 2025 07:45AM UTC coverage: 37.588% (-0.9%) from 38.476%
cff60f55-2113-4e78-8887-270dd7ccce48

push

circleci

web-flow
refactor(virtual-scroll): prevent executing virtual scroll logic when the editor is not enabled virtual scroll #WIK-19625

381 of 1212 branches covered (31.44%)

Branch coverage included in aggregate %.

10 of 28 new or added lines in 1 file covered. (35.71%)

15 existing lines in 1 file now uncovered.

1065 of 2635 relevant lines covered (40.42%)

24.61 hits per line

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

22.92
/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 } 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_BUFFER_COUNT,
49
    VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT,
50
    SLATE_DEBUG_KEY
51
} from '../../utils/environment';
52
import Hotkeys from '../../utils/hotkeys';
53
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
54
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
55
import { SlateErrorCode } from '../../types/error';
56
import { NG_VALUE_ACCESSOR } from '@angular/forms';
57
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
58
import { ViewType } from '../../types/view';
59
import { HistoryEditor } from 'slate-history';
60
import { ELEMENT_TO_COMPONENT, isDecoratorRangeListEqual } from '../../utils';
61
import { SlatePlaceholder } from '../../types/feature';
62
import { restoreDom } from '../../utils/restore-dom';
63
import { ListRender } from '../../view/render/list-render';
64
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
65
import { BaseElementComponent } from '../../view/base';
66
import { BaseElementFlavour } from '../../view/flavour/element';
67
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
68
import { isKeyHotkey } from 'is-hotkey';
69
import { VirtualScrollDebugOverlay } from './debug';
70

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

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

75
// not correctly clipboardData on beforeinput
76
const forceOnDOMPaste = IS_SAFARI;
1✔
77

78
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
79

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

105
    private destroy$ = new Subject();
23✔
106

107
    isComposing = false;
23✔
108
    isDraggingInternally = false;
23✔
109
    isUpdatingSelection = false;
23✔
110
    latestElement = null as DOMElement | null;
23✔
111

112
    protected manualListeners: (() => void)[] = [];
23✔
113

114
    private initialized: boolean;
115

116
    private onTouchedCallback: () => void = () => {};
23✔
117

118
    private onChangeCallback: (_: any) => void = () => {};
23✔
119

120
    @Input() editor: AngularEditor;
121

122
    @Input() renderElement: (element: Element) => ViewType | null;
123

124
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
125

126
    @Input() renderText: (text: SlateText) => ViewType | null;
127

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

130
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
131

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

134
    @Input() isStrictDecorate: boolean = true;
23✔
135

136
    @Input() trackBy: (node: Element) => any = () => null;
206✔
137

138
    @Input() readonly = false;
23✔
139

140
    @Input() placeholder: string;
141

142
    @Input()
143
    set virtualScroll(config: SlateVirtualScrollConfig) {
144
        this.virtualScrollConfig = config;
×
NEW
145
        if (this.isEnabledVirtualScroll()) {
×
NEW
146
            this.tryUpdateVirtualViewport();
×
147
        }
148
    }
149

150
    //#region input event handler
151
    @Input() beforeInput: (event: Event) => void;
152
    @Input() blur: (event: Event) => void;
153
    @Input() click: (event: MouseEvent) => void;
154
    @Input() compositionEnd: (event: CompositionEvent) => void;
155
    @Input() compositionUpdate: (event: CompositionEvent) => void;
156
    @Input() compositionStart: (event: CompositionEvent) => void;
157
    @Input() copy: (event: ClipboardEvent) => void;
158
    @Input() cut: (event: ClipboardEvent) => void;
159
    @Input() dragOver: (event: DragEvent) => void;
160
    @Input() dragStart: (event: DragEvent) => void;
161
    @Input() dragEnd: (event: DragEvent) => void;
162
    @Input() drop: (event: DragEvent) => void;
163
    @Input() focus: (event: Event) => void;
164
    @Input() keydown: (event: KeyboardEvent) => void;
165
    @Input() paste: (event: ClipboardEvent) => void;
166
    //#endregion
167

168
    //#region DOM attr
169
    @Input() spellCheck = false;
23✔
170
    @Input() autoCorrect = false;
23✔
171
    @Input() autoCapitalize = false;
23✔
172

173
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
174
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
175
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
176

177
    get hasBeforeInputSupport() {
178
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
179
    }
180
    //#endregion
181

182
    viewContainerRef = inject(ViewContainerRef);
23✔
183

184
    getOutletParent = () => {
23✔
185
        return this.elementRef.nativeElement;
43✔
186
    };
187

188
    getOutletElement = () => {
23✔
189
        if (this.virtualScrollInitialized) {
23!
190
            return this.virtualCenterOutlet;
×
191
        } else {
192
            return null;
23✔
193
        }
194
    };
195

196
    listRender: ListRender;
197

198
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
199
        enabled: false,
200
        scrollTop: 0,
201
        viewportHeight: 0
202
    };
203

204
    private inViewportChildren: Element[] = [];
23✔
205
    private inViewportIndics = new Set<number>();
23✔
206
    private keyHeightMap = new Map<string, number>();
23✔
207
    private refreshVirtualViewAnimId: number;
208
    private measureVisibleHeightsAnimId: number;
209
    private editorResizeObserver?: ResizeObserver;
210

211
    constructor(
212
        public elementRef: ElementRef,
23✔
213
        public renderer2: Renderer2,
23✔
214
        public cdr: ChangeDetectorRef,
23✔
215
        private ngZone: NgZone,
23✔
216
        private injector: Injector
23✔
217
    ) {}
218

219
    ngOnInit() {
220
        this.editor.injector = this.injector;
23✔
221
        this.editor.children = [];
23✔
222
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
223
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
224
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
225
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
226
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
227
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
228
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
229
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
230
            this.ngZone.run(() => {
13✔
231
                this.onChange();
13✔
232
            });
233
        });
234
        this.ngZone.runOutsideAngular(() => {
23✔
235
            this.initialize();
23✔
236
        });
237
        this.initializeViewContext();
23✔
238
        this.initializeContext();
23✔
239

240
        // add browser class
241
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
242
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
243
        this.initializeVirtualScroll();
23✔
244
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
245
    }
246

247
    ngOnChanges(simpleChanges: SimpleChanges) {
248
        if (!this.initialized) {
30✔
249
            return;
23✔
250
        }
251
        const decorateChange = simpleChanges['decorate'];
7✔
252
        if (decorateChange) {
7✔
253
            this.forceRender();
2✔
254
        }
255
        const placeholderChange = simpleChanges['placeholder'];
7✔
256
        if (placeholderChange) {
7✔
257
            this.render();
1✔
258
        }
259
        const readonlyChange = simpleChanges['readonly'];
7✔
260
        if (readonlyChange) {
7!
261
            IS_READ_ONLY.set(this.editor, this.readonly);
×
262
            this.render();
×
263
            this.toSlateSelection();
×
264
        }
265
    }
266

267
    registerOnChange(fn: any) {
268
        this.onChangeCallback = fn;
23✔
269
    }
270
    registerOnTouched(fn: any) {
271
        this.onTouchedCallback = fn;
23✔
272
    }
273

274
    writeValue(value: Element[]) {
275
        if (value && value.length) {
49✔
276
            this.editor.children = value;
26✔
277
            this.initializeContext();
26✔
278
            if (this.isEnabledVirtualScroll()) {
26!
NEW
279
                const virtualView = this.calculateVirtualViewport();
×
NEW
280
                this.applyVirtualView(virtualView);
×
NEW
281
                const childrenForRender = virtualView.inViewportChildren;
×
NEW
282
                if (!this.listRender.initialized) {
×
NEW
283
                    this.listRender.initialize(childrenForRender, this.editor, this.context);
×
284
                } else {
NEW
285
                    this.listRender.update(childrenForRender, this.editor, this.context);
×
286
                }
NEW
287
                this.scheduleMeasureVisibleHeights();
×
288
            } else {
289
                if (!this.listRender.initialized) {
26✔
290
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
291
                } else {
292
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
293
                }
294
            }
295
            this.cdr.markForCheck();
26✔
296
        }
297
    }
298

299
    initialize() {
300
        this.initialized = true;
23✔
301
        const window = AngularEditor.getWindow(this.editor);
23✔
302
        this.addEventListener(
23✔
303
            'selectionchange',
304
            event => {
305
                this.toSlateSelection();
2✔
306
            },
307
            window.document
308
        );
309
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
310
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
311
        }
312
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
313
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
314
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
315
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
316
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
317
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
318
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
319
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
320
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
321
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
322
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
323
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
324
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
325
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
326
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
327
            this.addEventListener(event.name, () => {});
115✔
328
        });
329
    }
330

331
    toNativeSelection() {
332
        try {
15✔
333
            let { selection } = this.editor;
15✔
334
            if (this.isEnabledVirtualScroll() && selection) {
15!
335
                const indics = Array.from(this.inViewportIndics.values());
×
336
                if (indics.length > 0) {
×
337
                    const currentVisibleRange: Range = {
×
338
                        anchor: Editor.start(this.editor, [indics[0]]),
339
                        focus: Editor.end(this.editor, [indics[indics.length - 1]])
340
                    };
341
                    const [start, end] = Range.edges(selection);
×
342
                    const forwardSelection = { anchor: start, focus: end };
×
343
                    const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
344
                    if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
345
                        selection = intersectedSelection;
×
346
                        if (isDebug) {
×
347
                            this.debugLog(
×
348
                                'log',
349
                                `selection is not in visible range, selection: ${JSON.stringify(
350
                                    selection
351
                                )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
352
                            );
353
                        }
354
                    }
355
                }
356
            }
357
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
358
            const { activeElement } = root;
15✔
359
            const domSelection = (root as Document).getSelection();
15✔
360

361
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
362
                return;
14✔
363
            }
364

365
            const hasDomSelection = domSelection.type !== 'None';
1✔
366

367
            // If the DOM selection is properly unset, we're done.
368
            if (!selection && !hasDomSelection) {
1!
369
                return;
×
370
            }
371

372
            // If the DOM selection is already correct, we're done.
373
            // verify that the dom selection is in the editor
374
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
375
            let hasDomSelectionInEditor = false;
1✔
376
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
377
                hasDomSelectionInEditor = true;
1✔
378
            }
379

380
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
381
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
382
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
383
                    exactMatch: false,
384
                    suppressThrow: true
385
                });
386
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
387
                    return;
×
388
                }
389
            }
390

391
            // prevent updating native selection when active element is void element
392
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
393
                return;
×
394
            }
395

396
            // when <Editable/> is being controlled through external value
397
            // then its children might just change - DOM responds to it on its own
398
            // but Slate's value is not being updated through any operation
399
            // and thus it doesn't transform selection on its own
400
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
401
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
402
                return;
×
403
            }
404

405
            // Otherwise the DOM selection is out of sync, so update it.
406
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
407
            this.isUpdatingSelection = true;
1✔
408

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

411
            if (newDomRange) {
1!
412
                // COMPAT: Since the DOM range has no concept of backwards/forwards
413
                // we need to check and do the right thing here.
414
                if (Range.isBackward(selection)) {
1!
415
                    // eslint-disable-next-line max-len
416
                    domSelection.setBaseAndExtent(
×
417
                        newDomRange.endContainer,
418
                        newDomRange.endOffset,
419
                        newDomRange.startContainer,
420
                        newDomRange.startOffset
421
                    );
422
                } else {
423
                    // eslint-disable-next-line max-len
424
                    domSelection.setBaseAndExtent(
1✔
425
                        newDomRange.startContainer,
426
                        newDomRange.startOffset,
427
                        newDomRange.endContainer,
428
                        newDomRange.endOffset
429
                    );
430
                }
431
            } else {
432
                domSelection.removeAllRanges();
×
433
            }
434

435
            setTimeout(() => {
1✔
436
                // handle scrolling in setTimeout because of
437
                // dom should not have updated immediately after listRender's updating
438
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
439
                // COMPAT: In Firefox, it's not enough to create a range, you also need
440
                // to focus the contenteditable element too. (2016/11/16)
441
                if (newDomRange && IS_FIREFOX) {
1!
442
                    el.focus();
×
443
                }
444

445
                this.isUpdatingSelection = false;
1✔
446
            });
447
        } catch (error) {
448
            this.editor.onError({
×
449
                code: SlateErrorCode.ToNativeSelectionError,
450
                nativeError: error
451
            });
452
            this.isUpdatingSelection = false;
×
453
        }
454
    }
455

456
    onChange() {
457
        this.forceRender();
13✔
458
        this.onChangeCallback(this.editor.children);
13✔
459
    }
460

461
    ngAfterViewChecked() {}
462

463
    ngDoCheck() {}
464

465
    forceRender() {
466
        this.updateContext();
15✔
467
        if (this.isEnabledVirtualScroll()) {
15!
NEW
468
            const virtualView = this.calculateVirtualViewport();
×
NEW
469
            this.applyVirtualView(virtualView);
×
NEW
470
            this.listRender.update(this.inViewportChildren, this.editor, this.context);
×
NEW
471
            const visibleIndexes = Array.from(this.inViewportIndics);
×
NEW
472
            this.remeasureHeightByIndics(visibleIndexes);
×
473
        } else {
474
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
475
        }
476
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
477
        // when the DOMElement where the selection is located is removed
478
        // the compositionupdate and compositionend events will no longer be fired
479
        // so isComposing needs to be corrected
480
        // need exec after this.cdr.detectChanges() to render HTML
481
        // need exec before this.toNativeSelection() to correct native selection
482
        if (this.isComposing) {
15!
483
            // Composition input text be not rendered when user composition input with selection is expanded
484
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
485
            // this time condition is true and isComposing is assigned false
486
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
487
            setTimeout(() => {
×
488
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
489
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
490
                let textContent = '';
×
491
                // skip decorate text
492
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
493
                    let text = stringDOMNode.textContent;
×
494
                    const zeroChar = '\uFEFF';
×
495
                    // remove zero with char
496
                    if (text.startsWith(zeroChar)) {
×
497
                        text = text.slice(1);
×
498
                    }
499
                    if (text.endsWith(zeroChar)) {
×
500
                        text = text.slice(0, text.length - 1);
×
501
                    }
502
                    textContent += text;
×
503
                });
504
                if (Node.string(textNode).endsWith(textContent)) {
×
505
                    this.isComposing = false;
×
506
                }
507
            }, 0);
508
        }
509
        this.toNativeSelection();
15✔
510
    }
511

512
    render() {
513
        const changed = this.updateContext();
2✔
514
        if (changed) {
2✔
515
            if (this.isEnabledVirtualScroll()) {
2!
NEW
516
                const virtualView = this.calculateVirtualViewport();
×
NEW
517
                this.applyVirtualView(virtualView);
×
NEW
518
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
NEW
519
                this.scheduleMeasureVisibleHeights();
×
520
            } else {
521
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
522
            }
523
        }
524
    }
525

526
    updateContext() {
527
        const decorations = this.generateDecorations();
17✔
528
        if (
17✔
529
            this.context.selection !== this.editor.selection ||
46✔
530
            this.context.decorate !== this.decorate ||
531
            this.context.readonly !== this.readonly ||
532
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
533
        ) {
534
            this.context = {
10✔
535
                parent: this.editor,
536
                selection: this.editor.selection,
537
                decorations: decorations,
538
                decorate: this.decorate,
539
                readonly: this.readonly
540
            };
541
            return true;
10✔
542
        }
543
        return false;
7✔
544
    }
545

546
    initializeContext() {
547
        this.context = {
49✔
548
            parent: this.editor,
549
            selection: this.editor.selection,
550
            decorations: this.generateDecorations(),
551
            decorate: this.decorate,
552
            readonly: this.readonly
553
        };
554
    }
555

556
    initializeViewContext() {
557
        this.viewContext = {
23✔
558
            editor: this.editor,
559
            renderElement: this.renderElement,
560
            renderLeaf: this.renderLeaf,
561
            renderText: this.renderText,
562
            trackBy: this.trackBy,
563
            isStrictDecorate: this.isStrictDecorate
564
        };
565
    }
566

567
    composePlaceholderDecorate(editor: Editor) {
568
        if (this.placeholderDecorate) {
64!
569
            return this.placeholderDecorate(editor) || [];
×
570
        }
571

572
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
573
            const start = Editor.start(editor, []);
3✔
574
            return [
3✔
575
                {
576
                    placeholder: this.placeholder,
577
                    anchor: start,
578
                    focus: start
579
                }
580
            ];
581
        } else {
582
            return [];
61✔
583
        }
584
    }
585

586
    generateDecorations() {
587
        const decorations = this.decorate([this.editor, []]);
66✔
588
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
589
        decorations.push(...placeholderDecorations);
66✔
590
        return decorations;
66✔
591
    }
592

593
    private isEnabledVirtualScroll() {
594
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
81✔
595
    }
596

597
    // the height from scroll container top to editor top height element
598
    private businessHeight: number = 0;
23✔
599

600
    virtualScrollInitialized = false;
23✔
601

602
    virtualTopHeightElement: HTMLElement;
603

604
    virtualBottomHeightElement: HTMLElement;
605

606
    virtualCenterOutlet: HTMLElement;
607

608
    initializeVirtualScroll() {
609
        if (this.virtualScrollInitialized) {
23!
610
            return;
×
611
        }
612
        if (this.isEnabledVirtualScroll()) {
23!
613
            this.virtualScrollInitialized = true;
×
614
            this.virtualTopHeightElement = document.createElement('div');
×
615
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
616
            this.virtualTopHeightElement.contentEditable = 'false';
×
617
            this.virtualBottomHeightElement = document.createElement('div');
×
618
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
619
            this.virtualBottomHeightElement.contentEditable = 'false';
×
620
            this.virtualCenterOutlet = document.createElement('div');
×
621
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
622
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
623
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
624
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
625
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
UNCOV
626
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
627
            this.editorResizeObserver = new ResizeObserver(entries => {
×
628
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
629
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
630
                    this.remeasureHeightByIndics(Array.from(this.inViewportIndics));
×
631
                }
632
            });
633
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
634
            if (isDebug) {
×
635
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
636
                VirtualScrollDebugOverlay.getInstance(doc);
×
637
            }
638
        }
639
    }
640

641
    setVirtualSpaceHeight(topHeight: number, bottomHeight: number) {
UNCOV
642
        if (!this.virtualScrollInitialized) {
×
UNCOV
643
            return;
×
644
        }
645
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
646
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
647
    }
648

649
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
650
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
651
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
652
    }
653

654
    private tryUpdateVirtualViewport() {
655
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
656
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
657
            let virtualView = this.calculateVirtualViewport();
×
658
            let diff = this.diffVirtualViewport(virtualView);
×
659
            if (!diff.isDiff) {
×
660
                return;
×
661
            }
662
            if (diff.isMissingTop) {
×
663
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
664
                if (result) {
×
665
                    virtualView = this.calculateVirtualViewport();
×
666
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
667
                    if (!diff.isDiff) {
×
668
                        return;
×
669
                    }
670
                }
671
            }
672
            this.applyVirtualView(virtualView);
×
673
            if (this.listRender.initialized) {
×
674
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
675
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
676
                    this.toNativeSelection();
×
677
                }
678
            }
679
            this.scheduleMeasureVisibleHeights();
×
680
        });
681
    }
682

683
    private calculateVirtualViewport() {
UNCOV
684
        const children = (this.editor.children || []) as Element[];
×
UNCOV
685
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
UNCOV
686
            return {
×
687
                inViewportChildren: children,
688
                visibleIndexes: new Set<number>(),
689
                top: 0,
690
                bottom: 0,
691
                heights: []
692
            };
693
        }
694
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
695
        if (isDebug) {
×
696
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
697
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
698
        }
699
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
700
        if (!viewportHeight) {
×
701
            return {
×
702
                inViewportChildren: [],
703
                visibleIndexes: new Set<number>(),
704
                top: 0,
705
                bottom: 0,
706
                heights: []
707
            };
708
        }
709
        const elementLength = children.length;
×
710
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
711
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
712
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
713
        const totalHeight = accumulatedHeights[elementLength];
×
714
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
715
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
716
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
717
        let accumulatedOffset = 0;
×
718
        let visibleStartIndex = -1;
×
719
        const visible: Element[] = [];
×
720
        const visibleIndexes: number[] = [];
×
721

722
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
723
            const currentHeight = heights[i];
×
724
            const nextOffset = accumulatedOffset + currentHeight;
×
725
            // 可视区域有交集,加入渲染
726
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
727
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
728
                visible.push(children[i]);
×
729
                visibleIndexes.push(i);
×
730
            }
731
            accumulatedOffset = nextOffset;
×
732
        }
733

734
        if (visibleStartIndex === -1 && elementLength) {
×
735
            visibleStartIndex = elementLength - 1;
×
736
            visible.push(children[visibleStartIndex]);
×
737
            visibleIndexes.push(visibleStartIndex);
×
738
        }
739

740
        const visibleEndIndex =
741
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
742
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
743
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
744

745
        return {
×
746
            inViewportChildren: visible.length ? visible : children,
×
747
            visibleIndexes: new Set(visibleIndexes),
748
            top,
749
            bottom,
750
            heights
751
        };
752
    }
753

754
    private applyVirtualView(virtualView: VirtualViewResult) {
UNCOV
755
        this.inViewportChildren = virtualView.inViewportChildren;
×
UNCOV
756
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
UNCOV
757
        this.inViewportIndics = virtualView.visibleIndexes;
×
758
    }
759

760
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
761
        if (!this.inViewportChildren.length) {
×
762
            return {
×
763
                isDiff: true,
764
                diffTopRenderedIndexes: [],
765
                diffBottomRenderedIndexes: []
766
            };
767
        }
768
        const oldVisibleIndexes = [...this.inViewportIndics];
×
769
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
770
        const firstNewIndex = newVisibleIndexes[0];
×
771
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
772
        const firstOldIndex = oldVisibleIndexes[0];
×
773
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
774
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
775
            const diffTopRenderedIndexes = [];
×
776
            const diffBottomRenderedIndexes = [];
×
777
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
778
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
779
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
780
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
781
            if (isMissingTop || isAddedBottom) {
×
782
                // 向下
783
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
784
                    const element = oldVisibleIndexes[index];
×
785
                    if (!newVisibleIndexes.includes(element)) {
×
786
                        diffTopRenderedIndexes.push(element);
×
787
                    } else {
788
                        break;
×
789
                    }
790
                }
791
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
792
                    const element = newVisibleIndexes[index];
×
793
                    if (!oldVisibleIndexes.includes(element)) {
×
794
                        diffBottomRenderedIndexes.push(element);
×
795
                    } else {
796
                        break;
×
797
                    }
798
                }
799
            } else if (isAddedTop || isMissingBottom) {
×
800
                // 向上
801
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
802
                    const element = newVisibleIndexes[index];
×
803
                    if (!oldVisibleIndexes.includes(element)) {
×
804
                        diffTopRenderedIndexes.push(element);
×
805
                    } else {
806
                        break;
×
807
                    }
808
                }
809
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
810
                    const element = oldVisibleIndexes[index];
×
811
                    if (!newVisibleIndexes.includes(element)) {
×
812
                        diffBottomRenderedIndexes.push(element);
×
813
                    } else {
814
                        break;
×
815
                    }
816
                }
817
            }
818
            if (isDebug) {
×
819
                this.debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
820
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
821
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
822
                this.debugLog(
×
823
                    'log',
824
                    'diffTopRenderedIndexes:',
825
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
826
                    diffTopRenderedIndexes,
827
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
828
                );
829
                this.debugLog(
×
830
                    'log',
831
                    'diffBottomRenderedIndexes:',
832
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
833
                    diffBottomRenderedIndexes,
834
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
835
                );
836
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
837
                const needBottom = virtualView.heights
×
838
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
839
                    .reduce((acc, height) => acc + height, 0);
×
840
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
841
                this.debugLog(
×
842
                    'log',
843
                    'newBottomHeight:',
844
                    needBottom,
845
                    'prevBottomHeight:',
846
                    parseFloat(this.virtualBottomHeightElement.style.height)
847
                );
848
                this.debugLog('warn', '=========== Dividing line ===========');
×
849
            }
850
            return {
×
851
                isDiff: true,
852
                isMissingTop,
853
                isAddedTop,
854
                isMissingBottom,
855
                isAddedBottom,
856
                diffTopRenderedIndexes,
857
                diffBottomRenderedIndexes
858
            };
859
        }
860
        return {
×
861
            isDiff: false,
862
            diffTopRenderedIndexes: [],
863
            diffBottomRenderedIndexes: []
864
        };
865
    }
866

867
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
868
        const node = this.editor.children[index] as Element;
×
869
        const isVisible = this.editor.isVisible(node);
×
870
        if (!isVisible) {
×
871
            return 0;
×
872
        }
873
        if (!node) {
×
874
            return defaultHeight;
×
875
        }
876
        const key = AngularEditor.findKey(this.editor, node);
×
877
        const height = this.keyHeightMap.get(key.id);
×
878
        if (typeof height === 'number') {
×
879
            return height;
×
880
        }
881
        if (this.keyHeightMap.has(key.id)) {
×
882
            console.error('getBlockHeight: invalid height value', key.id, height);
×
883
        }
884
        return defaultHeight;
×
885
    }
886

887
    private buildAccumulatedHeight(heights: number[]) {
888
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
889
        for (let i = 0; i < heights.length; i++) {
×
890
            // 存储前 i 个的累计高度
891
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
892
        }
893
        return accumulatedHeights;
×
894
    }
895

896
    private scheduleMeasureVisibleHeights() {
UNCOV
897
        if (!this.isEnabledVirtualScroll()) {
×
UNCOV
898
            return;
×
899
        }
900
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
901
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
902
            this.measureVisibleHeights();
×
903
        });
904
    }
905

906
    private measureVisibleHeights() {
907
        const children = (this.editor.children || []) as Element[];
×
908
        this.inViewportIndics.forEach(index => {
×
909
            const node = children[index];
×
910
            if (!node) {
×
911
                return;
×
912
            }
913
            const key = AngularEditor.findKey(this.editor, node);
×
914
            // 跳过已测过的块,除非强制测量
915
            if (this.keyHeightMap.has(key.id)) {
×
916
                return;
×
917
            }
918
            const view = ELEMENT_TO_COMPONENT.get(node);
×
919
            if (!view) {
×
920
                return;
×
921
            }
922
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
923
            if (ret instanceof Promise) {
×
924
                ret.then(height => {
×
925
                    this.keyHeightMap.set(key.id, height);
×
926
                });
927
            } else {
928
                this.keyHeightMap.set(key.id, ret);
×
929
            }
930
        });
931
    }
932

933
    private remeasureHeightByIndics(indics: number[]): boolean {
UNCOV
934
        const children = (this.editor.children || []) as Element[];
×
UNCOV
935
        let isHeightChanged = false;
×
UNCOV
936
        indics.forEach(index => {
×
937
            const node = children[index];
×
938
            if (!node) {
×
939
                return;
×
940
            }
941
            const key = AngularEditor.findKey(this.editor, node);
×
942
            const view = ELEMENT_TO_COMPONENT.get(node);
×
943
            if (!view) {
×
944
                return;
×
945
            }
946
            const prevHeight = this.keyHeightMap.get(key.id);
×
947
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
948
            if (ret instanceof Promise) {
×
949
                ret.then(height => {
×
950
                    if (height !== prevHeight) {
×
951
                        this.keyHeightMap.set(key.id, height);
×
952
                        isHeightChanged = true;
×
953
                        if (isDebug) {
×
954
                            this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
955
                        }
956
                    }
957
                });
958
            } else {
959
                if (ret !== prevHeight) {
×
960
                    this.keyHeightMap.set(key.id, ret);
×
961
                    isHeightChanged = true;
×
962
                    if (isDebug) {
×
963
                        this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
964
                    }
965
                }
966
            }
967
        });
UNCOV
968
        return isHeightChanged;
×
969
    }
970

971
    //#region event proxy
972
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
973
        this.manualListeners.push(
483✔
974
            this.renderer2.listen(target, eventName, (event: Event) => {
975
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
976
                if (beforeInputEvent) {
5!
977
                    this.onFallbackBeforeInput(beforeInputEvent);
×
978
                }
979
                listener(event);
5✔
980
            })
981
        );
982
    }
983

984
    private toSlateSelection() {
985
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
986
            try {
1✔
987
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
988
                const { activeElement } = root;
1✔
989
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
990
                const domSelection = (root as Document).getSelection();
1✔
991

992
                if (activeElement === el) {
1!
993
                    this.latestElement = activeElement;
1✔
994
                    IS_FOCUSED.set(this.editor, true);
1✔
995
                } else {
996
                    IS_FOCUSED.delete(this.editor);
×
997
                }
998

999
                if (!domSelection) {
1!
1000
                    return Transforms.deselect(this.editor);
×
1001
                }
1002

1003
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1004
                const hasDomSelectionInEditor =
1005
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1006
                if (!hasDomSelectionInEditor) {
1!
1007
                    Transforms.deselect(this.editor);
×
1008
                    return;
×
1009
                }
1010

1011
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1012
                // for example, double-click the last cell of the table to select a non-editable DOM
1013
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1014
                if (range) {
1✔
1015
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1016
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1017
                            // force adjust DOMSelection
1018
                            this.toNativeSelection();
×
1019
                        }
1020
                    } else {
1021
                        Transforms.select(this.editor, range);
1✔
1022
                    }
1023
                }
1024
            } catch (error) {
1025
                this.editor.onError({
×
1026
                    code: SlateErrorCode.ToSlateSelectionError,
1027
                    nativeError: error
1028
                });
1029
            }
1030
        }
1031
    }
1032

1033
    private onDOMBeforeInput(
1034
        event: Event & {
1035
            inputType: string;
1036
            isComposing: boolean;
1037
            data: string | null;
1038
            dataTransfer: DataTransfer | null;
1039
            getTargetRanges(): DOMStaticRange[];
1040
        }
1041
    ) {
1042
        const editor = this.editor;
×
1043
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1044
        const { activeElement } = root;
×
1045
        const { selection } = editor;
×
1046
        const { inputType: type } = event;
×
1047
        const data = event.dataTransfer || event.data || undefined;
×
1048
        if (IS_ANDROID) {
×
1049
            let targetRange: Range | null = null;
×
1050
            let [nativeTargetRange] = event.getTargetRanges();
×
1051
            if (nativeTargetRange) {
×
1052
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1053
            }
1054
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1055
            // have to manually get the selection here to ensure it's up-to-date.
1056
            const window = AngularEditor.getWindow(editor);
×
1057
            const domSelection = window.getSelection();
×
1058
            if (!targetRange && domSelection) {
×
1059
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1060
            }
1061
            targetRange = targetRange ?? editor.selection;
×
1062
            if (type === 'insertCompositionText') {
×
1063
                if (data && data.toString().includes('\n')) {
×
1064
                    restoreDom(editor, () => {
×
1065
                        Editor.insertBreak(editor);
×
1066
                    });
1067
                } else {
1068
                    if (targetRange) {
×
1069
                        if (data) {
×
1070
                            restoreDom(editor, () => {
×
1071
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1072
                            });
1073
                        } else {
1074
                            restoreDom(editor, () => {
×
1075
                                Transforms.delete(editor, { at: targetRange });
×
1076
                            });
1077
                        }
1078
                    }
1079
                }
1080
                return;
×
1081
            }
1082
            if (type === 'deleteContentBackward') {
×
1083
                // gboard can not prevent default action, so must use restoreDom,
1084
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1085
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1086
                if (!Range.isCollapsed(targetRange)) {
×
1087
                    restoreDom(editor, () => {
×
1088
                        Transforms.delete(editor, { at: targetRange });
×
1089
                    });
1090
                    return;
×
1091
                }
1092
            }
1093
            if (type === 'insertText') {
×
1094
                restoreDom(editor, () => {
×
1095
                    if (typeof data === 'string') {
×
1096
                        Editor.insertText(editor, data);
×
1097
                    }
1098
                });
1099
                return;
×
1100
            }
1101
        }
1102
        if (
×
1103
            !this.readonly &&
×
1104
            AngularEditor.hasEditableTarget(editor, event.target) &&
1105
            !isTargetInsideVoid(editor, activeElement) &&
1106
            !this.isDOMEventHandled(event, this.beforeInput)
1107
        ) {
1108
            try {
×
1109
                event.preventDefault();
×
1110

1111
                // COMPAT: If the selection is expanded, even if the command seems like
1112
                // a delete forward/backward command it should delete the selection.
1113
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1114
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1115
                    Editor.deleteFragment(editor, { direction });
×
1116
                    return;
×
1117
                }
1118

1119
                switch (type) {
×
1120
                    case 'deleteByComposition':
1121
                    case 'deleteByCut':
1122
                    case 'deleteByDrag': {
1123
                        Editor.deleteFragment(editor);
×
1124
                        break;
×
1125
                    }
1126

1127
                    case 'deleteContent':
1128
                    case 'deleteContentForward': {
1129
                        Editor.deleteForward(editor);
×
1130
                        break;
×
1131
                    }
1132

1133
                    case 'deleteContentBackward': {
1134
                        Editor.deleteBackward(editor);
×
1135
                        break;
×
1136
                    }
1137

1138
                    case 'deleteEntireSoftLine': {
1139
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1140
                        Editor.deleteForward(editor, { unit: 'line' });
×
1141
                        break;
×
1142
                    }
1143

1144
                    case 'deleteHardLineBackward': {
1145
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1146
                        break;
×
1147
                    }
1148

1149
                    case 'deleteSoftLineBackward': {
1150
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1151
                        break;
×
1152
                    }
1153

1154
                    case 'deleteHardLineForward': {
1155
                        Editor.deleteForward(editor, { unit: 'block' });
×
1156
                        break;
×
1157
                    }
1158

1159
                    case 'deleteSoftLineForward': {
1160
                        Editor.deleteForward(editor, { unit: 'line' });
×
1161
                        break;
×
1162
                    }
1163

1164
                    case 'deleteWordBackward': {
1165
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1166
                        break;
×
1167
                    }
1168

1169
                    case 'deleteWordForward': {
1170
                        Editor.deleteForward(editor, { unit: 'word' });
×
1171
                        break;
×
1172
                    }
1173

1174
                    case 'insertLineBreak':
1175
                    case 'insertParagraph': {
1176
                        Editor.insertBreak(editor);
×
1177
                        break;
×
1178
                    }
1179

1180
                    case 'insertFromComposition': {
1181
                        // COMPAT: in safari, `compositionend` event is dispatched after
1182
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1183
                        // https://www.w3.org/TR/input-events-2/
1184
                        // so the following code is the right logic
1185
                        // because DOM selection in sync will be exec before `compositionend` event
1186
                        // isComposing is true will prevent DOM selection being update correctly.
1187
                        this.isComposing = false;
×
1188
                        preventInsertFromComposition(event, this.editor);
×
1189
                    }
1190
                    case 'insertFromDrop':
1191
                    case 'insertFromPaste':
1192
                    case 'insertFromYank':
1193
                    case 'insertReplacementText':
1194
                    case 'insertText': {
1195
                        // use a weak comparison instead of 'instanceof' to allow
1196
                        // programmatic access of paste events coming from external windows
1197
                        // like cypress where cy.window does not work realibly
1198
                        if (data?.constructor.name === 'DataTransfer') {
×
1199
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1200
                        } else if (typeof data === 'string') {
×
1201
                            Editor.insertText(editor, data);
×
1202
                        }
1203
                        break;
×
1204
                    }
1205
                }
1206
            } catch (error) {
1207
                this.editor.onError({
×
1208
                    code: SlateErrorCode.OnDOMBeforeInputError,
1209
                    nativeError: error
1210
                });
1211
            }
1212
        }
1213
    }
1214

1215
    private onDOMBlur(event: FocusEvent) {
1216
        if (
×
1217
            this.readonly ||
×
1218
            this.isUpdatingSelection ||
1219
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1220
            this.isDOMEventHandled(event, this.blur)
1221
        ) {
1222
            return;
×
1223
        }
1224

1225
        const window = AngularEditor.getWindow(this.editor);
×
1226

1227
        // COMPAT: If the current `activeElement` is still the previous
1228
        // one, this is due to the window being blurred when the tab
1229
        // itself becomes unfocused, so we want to abort early to allow to
1230
        // editor to stay focused when the tab becomes focused again.
1231
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1232
        if (this.latestElement === root.activeElement) {
×
1233
            return;
×
1234
        }
1235

1236
        const { relatedTarget } = event;
×
1237
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1238

1239
        // COMPAT: The event should be ignored if the focus is returning
1240
        // to the editor from an embedded editable element (eg. an <input>
1241
        // element inside a void node).
1242
        if (relatedTarget === el) {
×
1243
            return;
×
1244
        }
1245

1246
        // COMPAT: The event should be ignored if the focus is moving from
1247
        // the editor to inside a void node's spacer element.
1248
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1249
            return;
×
1250
        }
1251

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

1258
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1259
                return;
×
1260
            }
1261
        }
1262

1263
        IS_FOCUSED.delete(this.editor);
×
1264
    }
1265

1266
    private onDOMClick(event: MouseEvent) {
1267
        if (
×
1268
            !this.readonly &&
×
1269
            AngularEditor.hasTarget(this.editor, event.target) &&
1270
            !this.isDOMEventHandled(event, this.click) &&
1271
            isDOMNode(event.target)
1272
        ) {
1273
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1274
            const path = AngularEditor.findPath(this.editor, node);
×
1275
            const start = Editor.start(this.editor, path);
×
1276
            const end = Editor.end(this.editor, path);
×
1277

1278
            const startVoid = Editor.void(this.editor, { at: start });
×
1279
            const endVoid = Editor.void(this.editor, { at: end });
×
1280

1281
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1282
                let blockPath = path;
×
1283
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1284
                    const block = Editor.above(this.editor, {
×
1285
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1286
                        at: path
1287
                    });
1288

1289
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1290
                }
1291

1292
                const range = Editor.range(this.editor, blockPath);
×
1293
                Transforms.select(this.editor, range);
×
1294
                return;
×
1295
            }
1296

1297
            if (
×
1298
                startVoid &&
×
1299
                endVoid &&
1300
                Path.equals(startVoid[1], endVoid[1]) &&
1301
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1302
            ) {
1303
                const range = Editor.range(this.editor, start);
×
1304
                Transforms.select(this.editor, range);
×
1305
            }
1306
        }
1307
    }
1308

1309
    private onDOMCompositionStart(event: CompositionEvent) {
1310
        const { selection } = this.editor;
1✔
1311
        if (selection) {
1!
1312
            // solve the problem of cross node Chinese input
1313
            if (Range.isExpanded(selection)) {
×
1314
                Editor.deleteFragment(this.editor);
×
1315
                this.forceRender();
×
1316
            }
1317
        }
1318
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1319
            this.isComposing = true;
1✔
1320
        }
1321
        this.render();
1✔
1322
    }
1323

1324
    private onDOMCompositionUpdate(event: CompositionEvent) {
1325
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1326
    }
1327

1328
    private onDOMCompositionEnd(event: CompositionEvent) {
1329
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1330
            Transforms.delete(this.editor);
×
1331
        }
1332
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1333
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1334
            // aren't correct and never fire the "insertFromComposition"
1335
            // type that we need. So instead, insert whenever a composition
1336
            // ends since it will already have been committed to the DOM.
1337
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1338
                preventInsertFromComposition(event, this.editor);
×
1339
                Editor.insertText(this.editor, event.data);
×
1340
            }
1341

1342
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1343
            // so we need avoid repeat isnertText by isComposing === true,
1344
            this.isComposing = false;
×
1345
        }
1346
        this.render();
×
1347
    }
1348

1349
    private onDOMCopy(event: ClipboardEvent) {
1350
        const window = AngularEditor.getWindow(this.editor);
×
1351
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1352
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1353
            event.preventDefault();
×
1354
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1355
        }
1356
    }
1357

1358
    private onDOMCut(event: ClipboardEvent) {
1359
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1360
            event.preventDefault();
×
1361
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1362
            const { selection } = this.editor;
×
1363

1364
            if (selection) {
×
1365
                AngularEditor.deleteCutData(this.editor);
×
1366
            }
1367
        }
1368
    }
1369

1370
    private onDOMDragOver(event: DragEvent) {
1371
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1372
            // Only when the target is void, call `preventDefault` to signal
1373
            // that drops are allowed. Editable content is droppable by
1374
            // default, and calling `preventDefault` hides the cursor.
1375
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1376

1377
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1378
                event.preventDefault();
×
1379
            }
1380
        }
1381
    }
1382

1383
    private onDOMDragStart(event: DragEvent) {
1384
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1385
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1386
            const path = AngularEditor.findPath(this.editor, node);
×
1387
            const voidMatch =
1388
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1389

1390
            // If starting a drag on a void node, make sure it is selected
1391
            // so that it shows up in the selection's fragment.
1392
            if (voidMatch) {
×
1393
                const range = Editor.range(this.editor, path);
×
1394
                Transforms.select(this.editor, range);
×
1395
            }
1396

1397
            this.isDraggingInternally = true;
×
1398

1399
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1400
        }
1401
    }
1402

1403
    private onDOMDrop(event: DragEvent) {
1404
        const editor = this.editor;
×
1405
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1406
            event.preventDefault();
×
1407
            // Keep a reference to the dragged range before updating selection
1408
            const draggedRange = editor.selection;
×
1409

1410
            // Find the range where the drop happened
1411
            const range = AngularEditor.findEventRange(editor, event);
×
1412
            const data = event.dataTransfer;
×
1413

1414
            Transforms.select(editor, range);
×
1415

1416
            if (this.isDraggingInternally) {
×
1417
                if (draggedRange) {
×
1418
                    Transforms.delete(editor, {
×
1419
                        at: draggedRange
1420
                    });
1421
                }
1422

1423
                this.isDraggingInternally = false;
×
1424
            }
1425

1426
            AngularEditor.insertData(editor, data);
×
1427

1428
            // When dragging from another source into the editor, it's possible
1429
            // that the current editor does not have focus.
1430
            if (!AngularEditor.isFocused(editor)) {
×
1431
                AngularEditor.focus(editor);
×
1432
            }
1433
        }
1434
    }
1435

1436
    private onDOMDragEnd(event: DragEvent) {
1437
        if (
×
1438
            !this.readonly &&
×
1439
            this.isDraggingInternally &&
1440
            AngularEditor.hasTarget(this.editor, event.target) &&
1441
            !this.isDOMEventHandled(event, this.dragEnd)
1442
        ) {
1443
            this.isDraggingInternally = false;
×
1444
        }
1445
    }
1446

1447
    private onDOMFocus(event: Event) {
1448
        if (
2✔
1449
            !this.readonly &&
8✔
1450
            !this.isUpdatingSelection &&
1451
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1452
            !this.isDOMEventHandled(event, this.focus)
1453
        ) {
1454
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1455
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1456
            this.latestElement = root.activeElement;
2✔
1457

1458
            // COMPAT: If the editor has nested editable elements, the focus
1459
            // can go to them. In Firefox, this must be prevented because it
1460
            // results in issues with keyboard navigation. (2017/03/30)
1461
            if (IS_FIREFOX && event.target !== el) {
2!
1462
                el.focus();
×
1463
                return;
×
1464
            }
1465

1466
            IS_FOCUSED.set(this.editor, true);
2✔
1467
        }
1468
    }
1469

1470
    private onDOMKeydown(event: KeyboardEvent) {
1471
        const editor = this.editor;
×
1472
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1473
        const { activeElement } = root;
×
1474
        if (
×
1475
            !this.readonly &&
×
1476
            AngularEditor.hasEditableTarget(editor, event.target) &&
1477
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1478
            !this.isComposing &&
1479
            !this.isDOMEventHandled(event, this.keydown)
1480
        ) {
1481
            const nativeEvent = event;
×
1482
            const { selection } = editor;
×
1483

1484
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
1485
            const isRTL = direction(Node.string(element)) === 'rtl';
×
1486

1487
            try {
×
1488
                // COMPAT: Since we prevent the default behavior on
1489
                // `beforeinput` events, the browser doesn't think there's ever
1490
                // any history stack to undo or redo, so we have to manage these
1491
                // hotkeys ourselves. (2019/11/06)
1492
                if (Hotkeys.isRedo(nativeEvent)) {
×
1493
                    event.preventDefault();
×
1494

1495
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1496
                        editor.redo();
×
1497
                    }
1498

1499
                    return;
×
1500
                }
1501

1502
                if (Hotkeys.isUndo(nativeEvent)) {
×
1503
                    event.preventDefault();
×
1504

1505
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1506
                        editor.undo();
×
1507
                    }
1508

1509
                    return;
×
1510
                }
1511

1512
                // COMPAT: Certain browsers don't handle the selection updates
1513
                // properly. In Chrome, the selection isn't properly extended.
1514
                // And in Firefox, the selection isn't properly collapsed.
1515
                // (2017/10/17)
1516
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1517
                    event.preventDefault();
×
1518
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1519
                    return;
×
1520
                }
1521

1522
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1523
                    event.preventDefault();
×
1524
                    Transforms.move(editor, { unit: 'line' });
×
1525
                    return;
×
1526
                }
1527

1528
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1529
                    event.preventDefault();
×
1530
                    Transforms.move(editor, {
×
1531
                        unit: 'line',
1532
                        edge: 'focus',
1533
                        reverse: true
1534
                    });
1535
                    return;
×
1536
                }
1537

1538
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1539
                    event.preventDefault();
×
1540
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1541
                    return;
×
1542
                }
1543

1544
                // COMPAT: If a void node is selected, or a zero-width text node
1545
                // adjacent to an inline is selected, we need to handle these
1546
                // hotkeys manually because browsers won't be able to skip over
1547
                // the void node with the zero-width space not being an empty
1548
                // string.
1549
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1550
                    event.preventDefault();
×
1551

1552
                    if (selection && Range.isCollapsed(selection)) {
×
1553
                        Transforms.move(editor, { reverse: !isRTL });
×
1554
                    } else {
1555
                        Transforms.collapse(editor, { edge: 'start' });
×
1556
                    }
1557

1558
                    return;
×
1559
                }
1560

1561
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1562
                    event.preventDefault();
×
1563
                    if (selection && Range.isCollapsed(selection)) {
×
1564
                        Transforms.move(editor, { reverse: isRTL });
×
1565
                    } else {
1566
                        Transforms.collapse(editor, { edge: 'end' });
×
1567
                    }
1568

1569
                    return;
×
1570
                }
1571

1572
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1573
                    event.preventDefault();
×
1574

1575
                    if (selection && Range.isExpanded(selection)) {
×
1576
                        Transforms.collapse(editor, { edge: 'focus' });
×
1577
                    }
1578

1579
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1580
                    return;
×
1581
                }
1582

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

1586
                    if (selection && Range.isExpanded(selection)) {
×
1587
                        Transforms.collapse(editor, { edge: 'focus' });
×
1588
                    }
1589

1590
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1591
                    return;
×
1592
                }
1593

1594
                if (isKeyHotkey('mod+a', event)) {
×
1595
                    this.editor.selectAll();
×
1596
                    event.preventDefault();
×
1597
                    return;
×
1598
                }
1599

1600
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1601
                // fall back to guessing at the input intention for hotkeys.
1602
                // COMPAT: In iOS, some of these hotkeys are handled in the
1603
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1604
                    // We don't have a core behavior for these, but they change the
1605
                    // DOM if we don't prevent them, so we have to.
1606
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1607
                        event.preventDefault();
×
1608
                        return;
×
1609
                    }
1610

1611
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1612
                        event.preventDefault();
×
1613
                        Editor.insertBreak(editor);
×
1614
                        return;
×
1615
                    }
1616

1617
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1618
                        event.preventDefault();
×
1619

1620
                        if (selection && Range.isExpanded(selection)) {
×
1621
                            Editor.deleteFragment(editor, {
×
1622
                                direction: 'backward'
1623
                            });
1624
                        } else {
1625
                            Editor.deleteBackward(editor);
×
1626
                        }
1627

1628
                        return;
×
1629
                    }
1630

1631
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1632
                        event.preventDefault();
×
1633

1634
                        if (selection && Range.isExpanded(selection)) {
×
1635
                            Editor.deleteFragment(editor, {
×
1636
                                direction: 'forward'
1637
                            });
1638
                        } else {
1639
                            Editor.deleteForward(editor);
×
1640
                        }
1641

1642
                        return;
×
1643
                    }
1644

1645
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1646
                        event.preventDefault();
×
1647

1648
                        if (selection && Range.isExpanded(selection)) {
×
1649
                            Editor.deleteFragment(editor, {
×
1650
                                direction: 'backward'
1651
                            });
1652
                        } else {
1653
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1654
                        }
1655

1656
                        return;
×
1657
                    }
1658

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

1662
                        if (selection && Range.isExpanded(selection)) {
×
1663
                            Editor.deleteFragment(editor, {
×
1664
                                direction: 'forward'
1665
                            });
1666
                        } else {
1667
                            Editor.deleteForward(editor, { unit: 'line' });
×
1668
                        }
1669

1670
                        return;
×
1671
                    }
1672

1673
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1674
                        event.preventDefault();
×
1675

1676
                        if (selection && Range.isExpanded(selection)) {
×
1677
                            Editor.deleteFragment(editor, {
×
1678
                                direction: 'backward'
1679
                            });
1680
                        } else {
1681
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1682
                        }
1683

1684
                        return;
×
1685
                    }
1686

1687
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1688
                        event.preventDefault();
×
1689

1690
                        if (selection && Range.isExpanded(selection)) {
×
1691
                            Editor.deleteFragment(editor, {
×
1692
                                direction: 'forward'
1693
                            });
1694
                        } else {
1695
                            Editor.deleteForward(editor, { unit: 'word' });
×
1696
                        }
1697

1698
                        return;
×
1699
                    }
1700
                } else {
1701
                    if (IS_CHROME || IS_SAFARI) {
×
1702
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1703
                        // an event when deleting backwards in a selected void inline node
1704
                        if (
×
1705
                            selection &&
×
1706
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1707
                            Range.isCollapsed(selection)
1708
                        ) {
1709
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1710
                            if (
×
1711
                                Element.isElement(currentNode) &&
×
1712
                                Editor.isVoid(editor, currentNode) &&
1713
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1714
                            ) {
1715
                                event.preventDefault();
×
1716
                                Editor.deleteBackward(editor, {
×
1717
                                    unit: 'block'
1718
                                });
1719
                                return;
×
1720
                            }
1721
                        }
1722
                    }
1723
                }
1724
            } catch (error) {
1725
                this.editor.onError({
×
1726
                    code: SlateErrorCode.OnDOMKeydownError,
1727
                    nativeError: error
1728
                });
1729
            }
1730
        }
1731
    }
1732

1733
    private onDOMPaste(event: ClipboardEvent) {
1734
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1735
        // fall back to React's `onPaste` here instead.
1736
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1737
        // when "paste without formatting" option is used.
1738
        // This unfortunately needs to be handled with paste events instead.
1739
        if (
×
1740
            !this.isDOMEventHandled(event, this.paste) &&
×
1741
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1742
            !this.readonly &&
1743
            AngularEditor.hasEditableTarget(this.editor, event.target)
1744
        ) {
1745
            event.preventDefault();
×
1746
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1747
        }
1748
    }
1749

1750
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1751
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1752
        // fall back to React's leaky polyfill instead just for it. It
1753
        // only works for the `insertText` input type.
1754
        if (
×
1755
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1756
            !this.readonly &&
1757
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1758
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1759
        ) {
1760
            event.nativeEvent.preventDefault();
×
1761
            try {
×
1762
                const text = event.data;
×
1763
                if (!Range.isCollapsed(this.editor.selection)) {
×
1764
                    Editor.deleteFragment(this.editor);
×
1765
                }
1766
                // just handle Non-IME input
1767
                if (!this.isComposing) {
×
1768
                    Editor.insertText(this.editor, text);
×
1769
                }
1770
            } catch (error) {
1771
                this.editor.onError({
×
1772
                    code: SlateErrorCode.ToNativeSelectionError,
1773
                    nativeError: error
1774
                });
1775
            }
1776
        }
1777
    }
1778

1779
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1780
        if (!handler) {
3✔
1781
            return false;
3✔
1782
        }
1783
        handler(event);
×
1784
        return event.defaultPrevented;
×
1785
    }
1786
    //#endregion
1787

1788
    ngOnDestroy() {
1789
        this.editorResizeObserver?.disconnect();
22✔
1790
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1791
        this.manualListeners.forEach(manualListener => {
22✔
1792
            manualListener();
462✔
1793
        });
1794
        this.destroy$.complete();
22✔
1795
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1796
    }
1797
}
1798

1799
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1800
    // This was affecting the selection of multiple blocks and dragging behavior,
1801
    // so enabled only if the selection has been collapsed.
1802
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1803
        const leafEl = domRange.startContainer.parentElement!;
×
1804

1805
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1806
        // When this happens, do not scroll like most editors do.
1807
        const domRect = domRange.getBoundingClientRect();
×
1808
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1809

1810
        if (isZeroDimensionRect) {
×
1811
            const leafRect = leafEl.getBoundingClientRect();
×
1812
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1813

1814
            if (leafHasDimensions) {
×
1815
                return;
×
1816
            }
1817
        }
1818

1819
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1820
        scrollIntoView(leafEl, {
×
1821
            scrollMode: 'if-needed'
1822
        });
1823
        delete leafEl.getBoundingClientRect;
×
1824
    }
1825
};
1826

1827
/**
1828
 * Check if the target is inside void and in the editor.
1829
 */
1830

1831
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1832
    let slateNode: Node | null = null;
1✔
1833
    try {
1✔
1834
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1835
    } catch (error) {}
1836
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1837
};
1838

1839
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1840
    return (
2✔
1841
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1842
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1843
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1844
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1845
    );
1846
};
1847

1848
/**
1849
 * remove default insert from composition
1850
 * @param text
1851
 */
1852
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1853
    const types = ['compositionend', 'insertFromComposition'];
×
1854
    if (!types.includes(event.type)) {
×
1855
        return;
×
1856
    }
1857
    const insertText = (event as CompositionEvent).data;
×
1858
    const window = AngularEditor.getWindow(editor);
×
1859
    const domSelection = window.getSelection();
×
1860
    // ensure text node insert composition input text
1861
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1862
        const textNode = domSelection.anchorNode;
×
1863
        textNode.splitText(textNode.length - insertText.length).remove();
×
1864
    }
1865
};
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