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

worktile / slate-angular / 1e31912b-770c-4ba8-bf3d-2cb06dd51f67

11 Dec 2025 01:10PM UTC coverage: 38.141% (-0.05%) from 38.191%
1e31912b-770c-4ba8-bf3d-2cb06dd51f67

push

circleci

web-flow
fix(virtual-scroll): get measured height strengthen the judgment of numeric types (#321)

* fix(virtual-scroll): get measured height strengthen the judgment of numeric types

* chore: add changeset

* fix: add error

* fix: optimize

386 of 1204 branches covered (32.06%)

Branch coverage included in aggregate %.

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

1071 of 2616 relevant lines covered (40.94%)

24.92 hits per line

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

25.44
/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.virtualConfig = config;
×
145
        this.doVirtualScroll();
×
146
    }
147

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

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

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

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

180
    viewContainerRef = inject(ViewContainerRef);
23✔
181

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

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

194
    listRender: ListRender;
195

196
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
197
        enabled: false,
198
        scrollTop: 0,
199
        viewportHeight: 0
200
    };
201
    private renderedChildren: Element[] = [];
23✔
202
    private virtualVisibleIndexes = new Set<number>();
23✔
203
    private measuredHeights = new Map<string, number>();
23✔
204
    private refreshVirtualViewAnimId: number;
205
    private measureVisibleHeightsAnimId: number;
206
    private editorResizeObserver?: ResizeObserver;
207

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

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

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

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

264
    registerOnChange(fn: any) {
265
        this.onChangeCallback = fn;
23✔
266
    }
267
    registerOnTouched(fn: any) {
268
        this.onTouchedCallback = fn;
23✔
269
    }
270

271
    writeValue(value: Element[]) {
272
        if (value && value.length) {
49✔
273
            this.editor.children = value;
26✔
274
            this.initializeContext();
26✔
275
            const virtualView = this.refreshVirtualView();
26✔
276
            this.applyVirtualView(virtualView);
26✔
277
            const childrenForRender = virtualView.renderedChildren;
26✔
278
            if (!this.listRender.initialized) {
26✔
279
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
280
            } else {
281
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
282
            }
283
            this.scheduleMeasureVisibleHeights();
26✔
284
            this.cdr.markForCheck();
26✔
285
        }
286
    }
287

288
    initialize() {
289
        this.initialized = true;
23✔
290
        const window = AngularEditor.getWindow(this.editor);
23✔
291
        this.addEventListener(
23✔
292
            'selectionchange',
293
            event => {
294
                this.toSlateSelection();
2✔
295
            },
296
            window.document
297
        );
298
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
299
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
300
        }
301
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
302
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
303
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
304
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
305
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
306
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
307
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
308
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
309
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
310
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
311
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
312
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
313
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
314
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
315
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
316
            this.addEventListener(event.name, () => {});
115✔
317
        });
318
    }
319

320
    toNativeSelection() {
321
        try {
15✔
322
            let { selection } = this.editor;
15✔
323
            if (this.virtualConfig?.enabled && selection) {
15!
324
                const indics = Array.from(this.virtualVisibleIndexes.values());
×
325
                if (indics.length > 0) {
×
326
                    const currentVisibleRange: Range = {
×
327
                        anchor: Editor.start(this.editor, [indics[0]]),
328
                        focus: Editor.end(this.editor, [indics[indics.length - 1]])
329
                    };
330
                    const [start, end] = Range.edges(selection);
×
331
                    const forwardSelection = { anchor: start, focus: end };
×
332
                    const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
333
                    if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
334
                        selection = intersectedSelection;
×
335
                        if (isDebug) {
×
336
                            this.debugLog(
×
337
                                'log',
338
                                `selection is not in visible range, selection: ${JSON.stringify(
339
                                    selection
340
                                )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
341
                            );
342
                        }
343
                    }
344
                }
345
            }
346
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
347
            const { activeElement } = root;
15✔
348
            const domSelection = (root as Document).getSelection();
15✔
349

350
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
351
                return;
14✔
352
            }
353

354
            const hasDomSelection = domSelection.type !== 'None';
1✔
355

356
            // If the DOM selection is properly unset, we're done.
357
            if (!selection && !hasDomSelection) {
1!
358
                return;
×
359
            }
360

361
            // If the DOM selection is already correct, we're done.
362
            // verify that the dom selection is in the editor
363
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
364
            let hasDomSelectionInEditor = false;
1✔
365
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
366
                hasDomSelectionInEditor = true;
1✔
367
            }
368

369
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
370
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
371
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
372
                    exactMatch: false,
373
                    suppressThrow: true
374
                });
375
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
376
                    return;
×
377
                }
378
            }
379

380
            // prevent updating native selection when active element is void element
381
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
382
                return;
×
383
            }
384

385
            // when <Editable/> is being controlled through external value
386
            // then its children might just change - DOM responds to it on its own
387
            // but Slate's value is not being updated through any operation
388
            // and thus it doesn't transform selection on its own
389
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
390
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
391
                return;
×
392
            }
393

394
            // Otherwise the DOM selection is out of sync, so update it.
395
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
396
            this.isUpdatingSelection = true;
1✔
397

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

400
            if (newDomRange) {
1!
401
                // COMPAT: Since the DOM range has no concept of backwards/forwards
402
                // we need to check and do the right thing here.
403
                if (Range.isBackward(selection)) {
1!
404
                    // eslint-disable-next-line max-len
405
                    domSelection.setBaseAndExtent(
×
406
                        newDomRange.endContainer,
407
                        newDomRange.endOffset,
408
                        newDomRange.startContainer,
409
                        newDomRange.startOffset
410
                    );
411
                } else {
412
                    // eslint-disable-next-line max-len
413
                    domSelection.setBaseAndExtent(
1✔
414
                        newDomRange.startContainer,
415
                        newDomRange.startOffset,
416
                        newDomRange.endContainer,
417
                        newDomRange.endOffset
418
                    );
419
                }
420
            } else {
421
                domSelection.removeAllRanges();
×
422
            }
423

424
            setTimeout(() => {
1✔
425
                // handle scrolling in setTimeout because of
426
                // dom should not have updated immediately after listRender's updating
427
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
428
                // COMPAT: In Firefox, it's not enough to create a range, you also need
429
                // to focus the contenteditable element too. (2016/11/16)
430
                if (newDomRange && IS_FIREFOX) {
1!
431
                    el.focus();
×
432
                }
433

434
                this.isUpdatingSelection = false;
1✔
435
            });
436
        } catch (error) {
437
            this.editor.onError({
×
438
                code: SlateErrorCode.ToNativeSelectionError,
439
                nativeError: error
440
            });
441
            this.isUpdatingSelection = false;
×
442
        }
443
    }
444

445
    onChange() {
446
        this.forceRender();
13✔
447
        this.onChangeCallback(this.editor.children);
13✔
448
    }
449

450
    ngAfterViewChecked() {}
451

452
    ngDoCheck() {}
453

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

497
    render() {
498
        const changed = this.updateContext();
2✔
499
        if (changed) {
2✔
500
            const virtualView = this.refreshVirtualView();
2✔
501
            this.applyVirtualView(virtualView);
2✔
502
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
503
            this.scheduleMeasureVisibleHeights();
2✔
504
        }
505
    }
506

507
    updateContext() {
508
        const decorations = this.generateDecorations();
17✔
509
        if (
17✔
510
            this.context.selection !== this.editor.selection ||
46✔
511
            this.context.decorate !== this.decorate ||
512
            this.context.readonly !== this.readonly ||
513
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
514
        ) {
515
            this.context = {
10✔
516
                parent: this.editor,
517
                selection: this.editor.selection,
518
                decorations: decorations,
519
                decorate: this.decorate,
520
                readonly: this.readonly
521
            };
522
            return true;
10✔
523
        }
524
        return false;
7✔
525
    }
526

527
    initializeContext() {
528
        this.context = {
49✔
529
            parent: this.editor,
530
            selection: this.editor.selection,
531
            decorations: this.generateDecorations(),
532
            decorate: this.decorate,
533
            readonly: this.readonly
534
        };
535
    }
536

537
    initializeViewContext() {
538
        this.viewContext = {
23✔
539
            editor: this.editor,
540
            renderElement: this.renderElement,
541
            renderLeaf: this.renderLeaf,
542
            renderText: this.renderText,
543
            trackBy: this.trackBy,
544
            isStrictDecorate: this.isStrictDecorate
545
        };
546
    }
547

548
    composePlaceholderDecorate(editor: Editor) {
549
        if (this.placeholderDecorate) {
64!
550
            return this.placeholderDecorate(editor) || [];
×
551
        }
552

553
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
554
            const start = Editor.start(editor, []);
3✔
555
            return [
3✔
556
                {
557
                    placeholder: this.placeholder,
558
                    anchor: start,
559
                    focus: start
560
                }
561
            ];
562
        } else {
563
            return [];
61✔
564
        }
565
    }
566

567
    generateDecorations() {
568
        const decorations = this.decorate([this.editor, []]);
66✔
569
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
570
        decorations.push(...placeholderDecorations);
66✔
571
        return decorations;
66✔
572
    }
573

574
    private shouldUseVirtual() {
575
        return !!(this.virtualConfig && this.virtualConfig.enabled);
71✔
576
    }
577

578
    // the height from scroll container top to editor top height element
579
    private businessHeight: number = 0;
23✔
580

581
    virtualScrollInitialized = false;
23✔
582

583
    virtualTopHeightElement: HTMLElement;
584

585
    virtualBottomHeightElement: HTMLElement;
586

587
    virtualCenterOutlet: HTMLElement;
588

589
    initializeVirtualScrolling() {
590
        if (this.virtualScrollInitialized) {
23!
591
            return;
×
592
        }
593
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
594
            this.virtualScrollInitialized = true;
×
595
            this.virtualTopHeightElement = document.createElement('div');
×
596
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
597
            this.virtualTopHeightElement.contentEditable = 'false';
×
598
            this.virtualBottomHeightElement = document.createElement('div');
×
599
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
600
            this.virtualBottomHeightElement.contentEditable = 'false';
×
601
            this.virtualCenterOutlet = document.createElement('div');
×
602
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
603
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
604
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
605
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
606
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
607

608
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
609
            this.editorResizeObserver = new ResizeObserver(entries => {
×
610
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
611
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
612
                    this.remeasureHeightByIndics(Array.from(this.virtualVisibleIndexes));
×
613
                }
614
            });
615
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
616
            if (isDebug) {
×
617
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
618
                VirtualScrollDebugOverlay.getInstance(doc);
×
619
            }
620
        }
621
    }
622

623
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
624
        if (!this.virtualScrollInitialized) {
43✔
625
            return;
43✔
626
        }
627
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
628
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
629
    }
630

631
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
632
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
633
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
634
    }
635

636
    private doVirtualScroll() {
637
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
638
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
639
            let virtualView = this.refreshVirtualView();
×
640
            let diff = this.diffVirtualView(virtualView);
×
641
            if (!diff.isDiff) {
×
642
                return;
×
643
            }
644
            if (diff.isMissingTop) {
×
645
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
646
                if (result) {
×
647
                    virtualView = this.refreshVirtualView();
×
648
                    diff = this.diffVirtualView(virtualView, 'second');
×
649
                    if (!diff.isDiff) {
×
650
                        return;
×
651
                    }
652
                }
653
            }
654
            this.applyVirtualView(virtualView);
×
655
            if (this.listRender.initialized) {
×
656
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
657
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
658
                    this.toNativeSelection();
×
659
                }
660
            }
661
            this.scheduleMeasureVisibleHeights();
×
662
        });
663
    }
664

665
    private refreshVirtualView() {
666
        const children = (this.editor.children || []) as Element[];
43!
667
        if (!children.length || !this.shouldUseVirtual()) {
43✔
668
            return {
43✔
669
                renderedChildren: children,
670
                visibleIndexes: new Set<number>(),
671
                top: 0,
672
                bottom: 0,
673
                heights: []
674
            };
675
        }
676
        const scrollTop = this.virtualConfig.scrollTop;
×
677
        if (isDebug) {
×
678
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
679
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
680
        }
681
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
682
        if (!viewportHeight) {
×
683
            return {
×
684
                renderedChildren: [],
685
                visibleIndexes: new Set<number>(),
686
                top: 0,
687
                bottom: 0,
688
                heights: []
689
            };
690
        }
691
        const elementLength = children.length;
×
692
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
693
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
694
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
695
        const totalHeight = accumulatedHeights[elementLength];
×
696
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
697
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
698
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
699
        let accumulatedOffset = 0;
×
700
        let visibleStartIndex = -1;
×
701
        const visible: Element[] = [];
×
702
        const visibleIndexes: number[] = [];
×
703

704
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
705
            const currentHeight = heights[i];
×
706
            const nextOffset = accumulatedOffset + currentHeight;
×
707
            // 可视区域有交集,加入渲染
708
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
709
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
710
                visible.push(children[i]);
×
711
                visibleIndexes.push(i);
×
712
            }
713
            accumulatedOffset = nextOffset;
×
714
        }
715

716
        if (visibleStartIndex === -1 && elementLength) {
×
717
            visibleStartIndex = elementLength - 1;
×
718
            visible.push(children[visibleStartIndex]);
×
719
            visibleIndexes.push(visibleStartIndex);
×
720
        }
721

722
        const visibleEndIndex =
723
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
724
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
725
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
726

727
        return {
×
728
            renderedChildren: visible.length ? visible : children,
×
729
            visibleIndexes: new Set(visibleIndexes),
730
            top,
731
            bottom,
732
            heights
733
        };
734
    }
735

736
    private applyVirtualView(virtualView: VirtualViewResult) {
737
        this.renderedChildren = virtualView.renderedChildren;
43✔
738
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
739
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
740
    }
741

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

849
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
850
        const node = this.editor.children[index];
×
851
        if (!node) {
×
852
            return defaultHeight;
×
853
        }
854
        const key = AngularEditor.findKey(this.editor, node);
×
NEW
855
        const height = this.measuredHeights.get(key.id);
×
NEW
856
        if (typeof height === 'number') {
×
NEW
857
            return height;
×
858
        }
NEW
859
        if (this.measuredHeights.has(key.id)) {
×
NEW
860
            console.error('getBlockHeight: invalid height value', key.id, height);
×
861
        }
NEW
862
        return defaultHeight;
×
863
    }
864

865
    private buildAccumulatedHeight(heights: number[]) {
866
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
867
        for (let i = 0; i < heights.length; i++) {
×
868
            // 存储前 i 个的累计高度
869
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
870
        }
871
        return accumulatedHeights;
×
872
    }
873

874
    private scheduleMeasureVisibleHeights() {
875
        if (!this.shouldUseVirtual()) {
28✔
876
            return;
28✔
877
        }
878
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
879
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
880
            this.measureVisibleHeights();
×
881
        });
882
    }
883

884
    private measureVisibleHeights() {
885
        const children = (this.editor.children || []) as Element[];
×
886
        this.virtualVisibleIndexes.forEach(index => {
×
887
            const node = children[index];
×
888
            if (!node) {
×
889
                return;
×
890
            }
891
            const key = AngularEditor.findKey(this.editor, node);
×
892
            // 跳过已测过的块,除非强制测量
893
            if (this.measuredHeights.has(key.id)) {
×
894
                return;
×
895
            }
896
            const view = ELEMENT_TO_COMPONENT.get(node);
×
897
            if (!view) {
×
898
                return;
×
899
            }
900
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
901
            if (ret instanceof Promise) {
×
902
                ret.then(height => {
×
903
                    this.measuredHeights.set(key.id, height);
×
904
                });
905
            } else {
906
                this.measuredHeights.set(key.id, ret);
×
907
            }
908
        });
909
    }
910

911
    private remeasureHeightByIndics(indics: number[]): boolean {
912
        const children = (this.editor.children || []) as Element[];
15!
913
        let isHeightChanged = false;
15✔
914
        indics.forEach(index => {
15✔
915
            const node = children[index];
×
916
            if (!node) {
×
917
                return;
×
918
            }
919
            const key = AngularEditor.findKey(this.editor, node);
×
920
            const view = ELEMENT_TO_COMPONENT.get(node);
×
921
            if (!view) {
×
922
                return;
×
923
            }
924
            const prevHeight = this.measuredHeights.get(key.id);
×
925
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
926
            if (ret instanceof Promise) {
×
927
                ret.then(height => {
×
928
                    if (height !== prevHeight) {
×
929
                        this.measuredHeights.set(key.id, height);
×
930
                        isHeightChanged = true;
×
931
                        if (isDebug) {
×
932
                            this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
933
                        }
934
                    }
935
                });
936
            } else {
937
                if (ret !== prevHeight) {
×
938
                    this.measuredHeights.set(key.id, ret);
×
939
                    isHeightChanged = true;
×
940
                    if (isDebug) {
×
941
                        this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
942
                    }
943
                }
944
            }
945
        });
946
        return isHeightChanged;
15✔
947
    }
948

949
    //#region event proxy
950
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
951
        this.manualListeners.push(
483✔
952
            this.renderer2.listen(target, eventName, (event: Event) => {
953
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
954
                if (beforeInputEvent) {
5!
955
                    this.onFallbackBeforeInput(beforeInputEvent);
×
956
                }
957
                listener(event);
5✔
958
            })
959
        );
960
    }
961

962
    private toSlateSelection() {
963
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
964
            try {
1✔
965
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
966
                const { activeElement } = root;
1✔
967
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
968
                const domSelection = (root as Document).getSelection();
1✔
969

970
                if (activeElement === el) {
1!
971
                    this.latestElement = activeElement;
1✔
972
                    IS_FOCUSED.set(this.editor, true);
1✔
973
                } else {
974
                    IS_FOCUSED.delete(this.editor);
×
975
                }
976

977
                if (!domSelection) {
1!
978
                    return Transforms.deselect(this.editor);
×
979
                }
980

981
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
982
                const hasDomSelectionInEditor =
983
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
984
                if (!hasDomSelectionInEditor) {
1!
985
                    Transforms.deselect(this.editor);
×
986
                    return;
×
987
                }
988

989
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
990
                // for example, double-click the last cell of the table to select a non-editable DOM
991
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
992
                if (range) {
1✔
993
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
994
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
995
                            // force adjust DOMSelection
996
                            this.toNativeSelection();
×
997
                        }
998
                    } else {
999
                        Transforms.select(this.editor, range);
1✔
1000
                    }
1001
                }
1002
            } catch (error) {
1003
                this.editor.onError({
×
1004
                    code: SlateErrorCode.ToSlateSelectionError,
1005
                    nativeError: error
1006
                });
1007
            }
1008
        }
1009
    }
1010

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

1089
                // COMPAT: If the selection is expanded, even if the command seems like
1090
                // a delete forward/backward command it should delete the selection.
1091
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1092
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1093
                    Editor.deleteFragment(editor, { direction });
×
1094
                    return;
×
1095
                }
1096

1097
                switch (type) {
×
1098
                    case 'deleteByComposition':
1099
                    case 'deleteByCut':
1100
                    case 'deleteByDrag': {
1101
                        Editor.deleteFragment(editor);
×
1102
                        break;
×
1103
                    }
1104

1105
                    case 'deleteContent':
1106
                    case 'deleteContentForward': {
1107
                        Editor.deleteForward(editor);
×
1108
                        break;
×
1109
                    }
1110

1111
                    case 'deleteContentBackward': {
1112
                        Editor.deleteBackward(editor);
×
1113
                        break;
×
1114
                    }
1115

1116
                    case 'deleteEntireSoftLine': {
1117
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1118
                        Editor.deleteForward(editor, { unit: 'line' });
×
1119
                        break;
×
1120
                    }
1121

1122
                    case 'deleteHardLineBackward': {
1123
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1124
                        break;
×
1125
                    }
1126

1127
                    case 'deleteSoftLineBackward': {
1128
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1129
                        break;
×
1130
                    }
1131

1132
                    case 'deleteHardLineForward': {
1133
                        Editor.deleteForward(editor, { unit: 'block' });
×
1134
                        break;
×
1135
                    }
1136

1137
                    case 'deleteSoftLineForward': {
1138
                        Editor.deleteForward(editor, { unit: 'line' });
×
1139
                        break;
×
1140
                    }
1141

1142
                    case 'deleteWordBackward': {
1143
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1144
                        break;
×
1145
                    }
1146

1147
                    case 'deleteWordForward': {
1148
                        Editor.deleteForward(editor, { unit: 'word' });
×
1149
                        break;
×
1150
                    }
1151

1152
                    case 'insertLineBreak':
1153
                    case 'insertParagraph': {
1154
                        Editor.insertBreak(editor);
×
1155
                        break;
×
1156
                    }
1157

1158
                    case 'insertFromComposition': {
1159
                        // COMPAT: in safari, `compositionend` event is dispatched after
1160
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1161
                        // https://www.w3.org/TR/input-events-2/
1162
                        // so the following code is the right logic
1163
                        // because DOM selection in sync will be exec before `compositionend` event
1164
                        // isComposing is true will prevent DOM selection being update correctly.
1165
                        this.isComposing = false;
×
1166
                        preventInsertFromComposition(event, this.editor);
×
1167
                    }
1168
                    case 'insertFromDrop':
1169
                    case 'insertFromPaste':
1170
                    case 'insertFromYank':
1171
                    case 'insertReplacementText':
1172
                    case 'insertText': {
1173
                        // use a weak comparison instead of 'instanceof' to allow
1174
                        // programmatic access of paste events coming from external windows
1175
                        // like cypress where cy.window does not work realibly
1176
                        if (data?.constructor.name === 'DataTransfer') {
×
1177
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1178
                        } else if (typeof data === 'string') {
×
1179
                            Editor.insertText(editor, data);
×
1180
                        }
1181
                        break;
×
1182
                    }
1183
                }
1184
            } catch (error) {
1185
                this.editor.onError({
×
1186
                    code: SlateErrorCode.OnDOMBeforeInputError,
1187
                    nativeError: error
1188
                });
1189
            }
1190
        }
1191
    }
1192

1193
    private onDOMBlur(event: FocusEvent) {
1194
        if (
×
1195
            this.readonly ||
×
1196
            this.isUpdatingSelection ||
1197
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1198
            this.isDOMEventHandled(event, this.blur)
1199
        ) {
1200
            return;
×
1201
        }
1202

1203
        const window = AngularEditor.getWindow(this.editor);
×
1204

1205
        // COMPAT: If the current `activeElement` is still the previous
1206
        // one, this is due to the window being blurred when the tab
1207
        // itself becomes unfocused, so we want to abort early to allow to
1208
        // editor to stay focused when the tab becomes focused again.
1209
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1210
        if (this.latestElement === root.activeElement) {
×
1211
            return;
×
1212
        }
1213

1214
        const { relatedTarget } = event;
×
1215
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1216

1217
        // COMPAT: The event should be ignored if the focus is returning
1218
        // to the editor from an embedded editable element (eg. an <input>
1219
        // element inside a void node).
1220
        if (relatedTarget === el) {
×
1221
            return;
×
1222
        }
1223

1224
        // COMPAT: The event should be ignored if the focus is moving from
1225
        // the editor to inside a void node's spacer element.
1226
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1227
            return;
×
1228
        }
1229

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

1236
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1237
                return;
×
1238
            }
1239
        }
1240

1241
        IS_FOCUSED.delete(this.editor);
×
1242
    }
1243

1244
    private onDOMClick(event: MouseEvent) {
1245
        if (
×
1246
            !this.readonly &&
×
1247
            AngularEditor.hasTarget(this.editor, event.target) &&
1248
            !this.isDOMEventHandled(event, this.click) &&
1249
            isDOMNode(event.target)
1250
        ) {
1251
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1252
            const path = AngularEditor.findPath(this.editor, node);
×
1253
            const start = Editor.start(this.editor, path);
×
1254
            const end = Editor.end(this.editor, path);
×
1255

1256
            const startVoid = Editor.void(this.editor, { at: start });
×
1257
            const endVoid = Editor.void(this.editor, { at: end });
×
1258

1259
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1260
                let blockPath = path;
×
1261
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1262
                    const block = Editor.above(this.editor, {
×
1263
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1264
                        at: path
1265
                    });
1266

1267
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1268
                }
1269

1270
                const range = Editor.range(this.editor, blockPath);
×
1271
                Transforms.select(this.editor, range);
×
1272
                return;
×
1273
            }
1274

1275
            if (
×
1276
                startVoid &&
×
1277
                endVoid &&
1278
                Path.equals(startVoid[1], endVoid[1]) &&
1279
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1280
            ) {
1281
                const range = Editor.range(this.editor, start);
×
1282
                Transforms.select(this.editor, range);
×
1283
            }
1284
        }
1285
    }
1286

1287
    private onDOMCompositionStart(event: CompositionEvent) {
1288
        const { selection } = this.editor;
1✔
1289
        if (selection) {
1!
1290
            // solve the problem of cross node Chinese input
1291
            if (Range.isExpanded(selection)) {
×
1292
                Editor.deleteFragment(this.editor);
×
1293
                this.forceRender();
×
1294
            }
1295
        }
1296
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1297
            this.isComposing = true;
1✔
1298
        }
1299
        this.render();
1✔
1300
    }
1301

1302
    private onDOMCompositionUpdate(event: CompositionEvent) {
1303
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1304
    }
1305

1306
    private onDOMCompositionEnd(event: CompositionEvent) {
1307
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1308
            Transforms.delete(this.editor);
×
1309
        }
1310
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1311
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1312
            // aren't correct and never fire the "insertFromComposition"
1313
            // type that we need. So instead, insert whenever a composition
1314
            // ends since it will already have been committed to the DOM.
1315
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1316
                preventInsertFromComposition(event, this.editor);
×
1317
                Editor.insertText(this.editor, event.data);
×
1318
            }
1319

1320
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1321
            // so we need avoid repeat isnertText by isComposing === true,
1322
            this.isComposing = false;
×
1323
        }
1324
        this.render();
×
1325
    }
1326

1327
    private onDOMCopy(event: ClipboardEvent) {
1328
        const window = AngularEditor.getWindow(this.editor);
×
1329
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1330
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1331
            event.preventDefault();
×
1332
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1333
        }
1334
    }
1335

1336
    private onDOMCut(event: ClipboardEvent) {
1337
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1338
            event.preventDefault();
×
1339
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1340
            const { selection } = this.editor;
×
1341

1342
            if (selection) {
×
1343
                AngularEditor.deleteCutData(this.editor);
×
1344
            }
1345
        }
1346
    }
1347

1348
    private onDOMDragOver(event: DragEvent) {
1349
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1350
            // Only when the target is void, call `preventDefault` to signal
1351
            // that drops are allowed. Editable content is droppable by
1352
            // default, and calling `preventDefault` hides the cursor.
1353
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1354

1355
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1356
                event.preventDefault();
×
1357
            }
1358
        }
1359
    }
1360

1361
    private onDOMDragStart(event: DragEvent) {
1362
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1363
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1364
            const path = AngularEditor.findPath(this.editor, node);
×
1365
            const voidMatch =
1366
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1367

1368
            // If starting a drag on a void node, make sure it is selected
1369
            // so that it shows up in the selection's fragment.
1370
            if (voidMatch) {
×
1371
                const range = Editor.range(this.editor, path);
×
1372
                Transforms.select(this.editor, range);
×
1373
            }
1374

1375
            this.isDraggingInternally = true;
×
1376

1377
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1378
        }
1379
    }
1380

1381
    private onDOMDrop(event: DragEvent) {
1382
        const editor = this.editor;
×
1383
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1384
            event.preventDefault();
×
1385
            // Keep a reference to the dragged range before updating selection
1386
            const draggedRange = editor.selection;
×
1387

1388
            // Find the range where the drop happened
1389
            const range = AngularEditor.findEventRange(editor, event);
×
1390
            const data = event.dataTransfer;
×
1391

1392
            Transforms.select(editor, range);
×
1393

1394
            if (this.isDraggingInternally) {
×
1395
                if (draggedRange) {
×
1396
                    Transforms.delete(editor, {
×
1397
                        at: draggedRange
1398
                    });
1399
                }
1400

1401
                this.isDraggingInternally = false;
×
1402
            }
1403

1404
            AngularEditor.insertData(editor, data);
×
1405

1406
            // When dragging from another source into the editor, it's possible
1407
            // that the current editor does not have focus.
1408
            if (!AngularEditor.isFocused(editor)) {
×
1409
                AngularEditor.focus(editor);
×
1410
            }
1411
        }
1412
    }
1413

1414
    private onDOMDragEnd(event: DragEvent) {
1415
        if (
×
1416
            !this.readonly &&
×
1417
            this.isDraggingInternally &&
1418
            AngularEditor.hasTarget(this.editor, event.target) &&
1419
            !this.isDOMEventHandled(event, this.dragEnd)
1420
        ) {
1421
            this.isDraggingInternally = false;
×
1422
        }
1423
    }
1424

1425
    private onDOMFocus(event: Event) {
1426
        if (
2✔
1427
            !this.readonly &&
8✔
1428
            !this.isUpdatingSelection &&
1429
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1430
            !this.isDOMEventHandled(event, this.focus)
1431
        ) {
1432
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1433
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1434
            this.latestElement = root.activeElement;
2✔
1435

1436
            // COMPAT: If the editor has nested editable elements, the focus
1437
            // can go to them. In Firefox, this must be prevented because it
1438
            // results in issues with keyboard navigation. (2017/03/30)
1439
            if (IS_FIREFOX && event.target !== el) {
2!
1440
                el.focus();
×
1441
                return;
×
1442
            }
1443

1444
            IS_FOCUSED.set(this.editor, true);
2✔
1445
        }
1446
    }
1447

1448
    private onDOMKeydown(event: KeyboardEvent) {
1449
        const editor = this.editor;
×
1450
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1451
        const { activeElement } = root;
×
1452
        if (
×
1453
            !this.readonly &&
×
1454
            AngularEditor.hasEditableTarget(editor, event.target) &&
1455
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1456
            !this.isComposing &&
1457
            !this.isDOMEventHandled(event, this.keydown)
1458
        ) {
1459
            const nativeEvent = event;
×
1460
            const { selection } = editor;
×
1461

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

1465
            try {
×
1466
                // COMPAT: Since we prevent the default behavior on
1467
                // `beforeinput` events, the browser doesn't think there's ever
1468
                // any history stack to undo or redo, so we have to manage these
1469
                // hotkeys ourselves. (2019/11/06)
1470
                if (Hotkeys.isRedo(nativeEvent)) {
×
1471
                    event.preventDefault();
×
1472

1473
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1474
                        editor.redo();
×
1475
                    }
1476

1477
                    return;
×
1478
                }
1479

1480
                if (Hotkeys.isUndo(nativeEvent)) {
×
1481
                    event.preventDefault();
×
1482

1483
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1484
                        editor.undo();
×
1485
                    }
1486

1487
                    return;
×
1488
                }
1489

1490
                // COMPAT: Certain browsers don't handle the selection updates
1491
                // properly. In Chrome, the selection isn't properly extended.
1492
                // And in Firefox, the selection isn't properly collapsed.
1493
                // (2017/10/17)
1494
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1495
                    event.preventDefault();
×
1496
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1497
                    return;
×
1498
                }
1499

1500
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1501
                    event.preventDefault();
×
1502
                    Transforms.move(editor, { unit: 'line' });
×
1503
                    return;
×
1504
                }
1505

1506
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1507
                    event.preventDefault();
×
1508
                    Transforms.move(editor, {
×
1509
                        unit: 'line',
1510
                        edge: 'focus',
1511
                        reverse: true
1512
                    });
1513
                    return;
×
1514
                }
1515

1516
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1517
                    event.preventDefault();
×
1518
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1519
                    return;
×
1520
                }
1521

1522
                // COMPAT: If a void node is selected, or a zero-width text node
1523
                // adjacent to an inline is selected, we need to handle these
1524
                // hotkeys manually because browsers won't be able to skip over
1525
                // the void node with the zero-width space not being an empty
1526
                // string.
1527
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1528
                    event.preventDefault();
×
1529

1530
                    if (selection && Range.isCollapsed(selection)) {
×
1531
                        Transforms.move(editor, { reverse: !isRTL });
×
1532
                    } else {
1533
                        Transforms.collapse(editor, { edge: 'start' });
×
1534
                    }
1535

1536
                    return;
×
1537
                }
1538

1539
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1540
                    event.preventDefault();
×
1541
                    if (selection && Range.isCollapsed(selection)) {
×
1542
                        Transforms.move(editor, { reverse: isRTL });
×
1543
                    } else {
1544
                        Transforms.collapse(editor, { edge: 'end' });
×
1545
                    }
1546

1547
                    return;
×
1548
                }
1549

1550
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1551
                    event.preventDefault();
×
1552

1553
                    if (selection && Range.isExpanded(selection)) {
×
1554
                        Transforms.collapse(editor, { edge: 'focus' });
×
1555
                    }
1556

1557
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1558
                    return;
×
1559
                }
1560

1561
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1562
                    event.preventDefault();
×
1563

1564
                    if (selection && Range.isExpanded(selection)) {
×
1565
                        Transforms.collapse(editor, { edge: 'focus' });
×
1566
                    }
1567

1568
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1569
                    return;
×
1570
                }
1571

1572
                if (isKeyHotkey('mod+a', event)) {
×
1573
                    this.editor.selectAll();
×
1574
                    event.preventDefault();
×
1575
                    return;
×
1576
                }
1577

1578
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1579
                // fall back to guessing at the input intention for hotkeys.
1580
                // COMPAT: In iOS, some of these hotkeys are handled in the
1581
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1582
                    // We don't have a core behavior for these, but they change the
1583
                    // DOM if we don't prevent them, so we have to.
1584
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1585
                        event.preventDefault();
×
1586
                        return;
×
1587
                    }
1588

1589
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1590
                        event.preventDefault();
×
1591
                        Editor.insertBreak(editor);
×
1592
                        return;
×
1593
                    }
1594

1595
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1596
                        event.preventDefault();
×
1597

1598
                        if (selection && Range.isExpanded(selection)) {
×
1599
                            Editor.deleteFragment(editor, {
×
1600
                                direction: 'backward'
1601
                            });
1602
                        } else {
1603
                            Editor.deleteBackward(editor);
×
1604
                        }
1605

1606
                        return;
×
1607
                    }
1608

1609
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1610
                        event.preventDefault();
×
1611

1612
                        if (selection && Range.isExpanded(selection)) {
×
1613
                            Editor.deleteFragment(editor, {
×
1614
                                direction: 'forward'
1615
                            });
1616
                        } else {
1617
                            Editor.deleteForward(editor);
×
1618
                        }
1619

1620
                        return;
×
1621
                    }
1622

1623
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1624
                        event.preventDefault();
×
1625

1626
                        if (selection && Range.isExpanded(selection)) {
×
1627
                            Editor.deleteFragment(editor, {
×
1628
                                direction: 'backward'
1629
                            });
1630
                        } else {
1631
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1632
                        }
1633

1634
                        return;
×
1635
                    }
1636

1637
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1638
                        event.preventDefault();
×
1639

1640
                        if (selection && Range.isExpanded(selection)) {
×
1641
                            Editor.deleteFragment(editor, {
×
1642
                                direction: 'forward'
1643
                            });
1644
                        } else {
1645
                            Editor.deleteForward(editor, { unit: 'line' });
×
1646
                        }
1647

1648
                        return;
×
1649
                    }
1650

1651
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1652
                        event.preventDefault();
×
1653

1654
                        if (selection && Range.isExpanded(selection)) {
×
1655
                            Editor.deleteFragment(editor, {
×
1656
                                direction: 'backward'
1657
                            });
1658
                        } else {
1659
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1660
                        }
1661

1662
                        return;
×
1663
                    }
1664

1665
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1666
                        event.preventDefault();
×
1667

1668
                        if (selection && Range.isExpanded(selection)) {
×
1669
                            Editor.deleteFragment(editor, {
×
1670
                                direction: 'forward'
1671
                            });
1672
                        } else {
1673
                            Editor.deleteForward(editor, { unit: 'word' });
×
1674
                        }
1675

1676
                        return;
×
1677
                    }
1678
                } else {
1679
                    if (IS_CHROME || IS_SAFARI) {
×
1680
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1681
                        // an event when deleting backwards in a selected void inline node
1682
                        if (
×
1683
                            selection &&
×
1684
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1685
                            Range.isCollapsed(selection)
1686
                        ) {
1687
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1688
                            if (
×
1689
                                Element.isElement(currentNode) &&
×
1690
                                Editor.isVoid(editor, currentNode) &&
1691
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1692
                            ) {
1693
                                event.preventDefault();
×
1694
                                Editor.deleteBackward(editor, {
×
1695
                                    unit: 'block'
1696
                                });
1697
                                return;
×
1698
                            }
1699
                        }
1700
                    }
1701
                }
1702
            } catch (error) {
1703
                this.editor.onError({
×
1704
                    code: SlateErrorCode.OnDOMKeydownError,
1705
                    nativeError: error
1706
                });
1707
            }
1708
        }
1709
    }
1710

1711
    private onDOMPaste(event: ClipboardEvent) {
1712
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1713
        // fall back to React's `onPaste` here instead.
1714
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1715
        // when "paste without formatting" option is used.
1716
        // This unfortunately needs to be handled with paste events instead.
1717
        if (
×
1718
            !this.isDOMEventHandled(event, this.paste) &&
×
1719
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1720
            !this.readonly &&
1721
            AngularEditor.hasEditableTarget(this.editor, event.target)
1722
        ) {
1723
            event.preventDefault();
×
1724
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1725
        }
1726
    }
1727

1728
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1729
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1730
        // fall back to React's leaky polyfill instead just for it. It
1731
        // only works for the `insertText` input type.
1732
        if (
×
1733
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1734
            !this.readonly &&
1735
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1736
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1737
        ) {
1738
            event.nativeEvent.preventDefault();
×
1739
            try {
×
1740
                const text = event.data;
×
1741
                if (!Range.isCollapsed(this.editor.selection)) {
×
1742
                    Editor.deleteFragment(this.editor);
×
1743
                }
1744
                // just handle Non-IME input
1745
                if (!this.isComposing) {
×
1746
                    Editor.insertText(this.editor, text);
×
1747
                }
1748
            } catch (error) {
1749
                this.editor.onError({
×
1750
                    code: SlateErrorCode.ToNativeSelectionError,
1751
                    nativeError: error
1752
                });
1753
            }
1754
        }
1755
    }
1756

1757
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1758
        if (!handler) {
3✔
1759
            return false;
3✔
1760
        }
1761
        handler(event);
×
1762
        return event.defaultPrevented;
×
1763
    }
1764
    //#endregion
1765

1766
    ngOnDestroy() {
1767
        this.editorResizeObserver?.disconnect();
23✔
1768
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1769
        this.manualListeners.forEach(manualListener => {
23✔
1770
            manualListener();
483✔
1771
        });
1772
        this.destroy$.complete();
23✔
1773
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1774
    }
1775
}
1776

1777
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1778
    // This was affecting the selection of multiple blocks and dragging behavior,
1779
    // so enabled only if the selection has been collapsed.
1780
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1781
        const leafEl = domRange.startContainer.parentElement!;
×
1782

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

1788
        if (isZeroDimensionRect) {
×
1789
            const leafRect = leafEl.getBoundingClientRect();
×
1790
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1791

1792
            if (leafHasDimensions) {
×
1793
                return;
×
1794
            }
1795
        }
1796

1797
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1798
        scrollIntoView(leafEl, {
×
1799
            scrollMode: 'if-needed'
1800
        });
1801
        delete leafEl.getBoundingClientRect;
×
1802
    }
1803
};
1804

1805
/**
1806
 * Check if the target is inside void and in the editor.
1807
 */
1808

1809
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1810
    let slateNode: Node | null = null;
1✔
1811
    try {
1✔
1812
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1813
    } catch (error) {}
1814
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1815
};
1816

1817
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1818
    return (
2✔
1819
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1820
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1821
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1822
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1823
    );
1824
};
1825

1826
/**
1827
 * remove default insert from composition
1828
 * @param text
1829
 */
1830
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1831
    const types = ['compositionend', 'insertFromComposition'];
×
1832
    if (!types.includes(event.type)) {
×
1833
        return;
×
1834
    }
1835
    const insertText = (event as CompositionEvent).data;
×
1836
    const window = AngularEditor.getWindow(editor);
×
1837
    const domSelection = window.getSelection();
×
1838
    // ensure text node insert composition input text
1839
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1840
        const textNode = domSelection.anchorNode;
×
1841
        textNode.splitText(textNode.length - insertText.length).remove();
×
1842
    }
1843
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc