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

worktile / slate-angular / 3babd116-77a8-46a9-85c9-11a0790b4dea

15 Dec 2025 03:25AM UTC coverage: 38.108%. Remained the same
3babd116-77a8-46a9-85c9-11a0790b4dea

push

circleci

pubuzhixing8
refactor: rename virtual-scroll

386 of 1205 branches covered (32.03%)

Branch coverage included in aggregate %.

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

1 existing line in 1 file now uncovered.

1072 of 2621 relevant lines covered (40.9%)

24.87 hits per line

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

25.37
/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) {
NEW
144
        this.virtualScrollConfig = config;
×
NEW
145
        this.tryUpdateVirtualViewport();
×
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 virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
197
        enabled: false,
198
        scrollTop: 0,
199
        viewportHeight: 0
200
    };
201

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

451
    ngAfterViewChecked() {}
452

453
    ngDoCheck() {}
454

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

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

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

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

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

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

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

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

575
    private isEnabledVirtualScroll() {
576
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
71✔
577
    }
578

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

582
    virtualScrollInitialized = false;
23✔
583

584
    virtualTopHeightElement: HTMLElement;
585

586
    virtualBottomHeightElement: HTMLElement;
587

588
    virtualCenterOutlet: HTMLElement;
589

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

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

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

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

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

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

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

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

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

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

737
    private applyVirtualView(virtualView: VirtualViewResult) {
738
        this.inViewportChildren = virtualView.inViewportChildren;
43✔
739
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
43✔
740
        this.inViewportIndics = virtualView.visibleIndexes;
43✔
741
    }
742

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

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

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

879
    private scheduleMeasureVisibleHeights() {
880
        if (!this.isEnabledVirtualScroll()) {
28✔
881
            return;
28✔
882
        }
883
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
884
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
885
            this.measureVisibleHeights();
×
886
        });
887
    }
888

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

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

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

967
    private toSlateSelection() {
968
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
969
            try {
1✔
970
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
971
                const { activeElement } = root;
1✔
972
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
973
                const domSelection = (root as Document).getSelection();
1✔
974

975
                if (activeElement === el) {
1!
976
                    this.latestElement = activeElement;
1✔
977
                    IS_FOCUSED.set(this.editor, true);
1✔
978
                } else {
979
                    IS_FOCUSED.delete(this.editor);
×
980
                }
981

982
                if (!domSelection) {
1!
983
                    return Transforms.deselect(this.editor);
×
984
                }
985

986
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
987
                const hasDomSelectionInEditor =
988
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
989
                if (!hasDomSelectionInEditor) {
1!
990
                    Transforms.deselect(this.editor);
×
991
                    return;
×
992
                }
993

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

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

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

1102
                switch (type) {
×
1103
                    case 'deleteByComposition':
1104
                    case 'deleteByCut':
1105
                    case 'deleteByDrag': {
1106
                        Editor.deleteFragment(editor);
×
1107
                        break;
×
1108
                    }
1109

1110
                    case 'deleteContent':
1111
                    case 'deleteContentForward': {
1112
                        Editor.deleteForward(editor);
×
1113
                        break;
×
1114
                    }
1115

1116
                    case 'deleteContentBackward': {
1117
                        Editor.deleteBackward(editor);
×
1118
                        break;
×
1119
                    }
1120

1121
                    case 'deleteEntireSoftLine': {
1122
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1123
                        Editor.deleteForward(editor, { unit: 'line' });
×
1124
                        break;
×
1125
                    }
1126

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

1132
                    case 'deleteSoftLineBackward': {
1133
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1134
                        break;
×
1135
                    }
1136

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

1142
                    case 'deleteSoftLineForward': {
1143
                        Editor.deleteForward(editor, { unit: 'line' });
×
1144
                        break;
×
1145
                    }
1146

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

1152
                    case 'deleteWordForward': {
1153
                        Editor.deleteForward(editor, { unit: 'word' });
×
1154
                        break;
×
1155
                    }
1156

1157
                    case 'insertLineBreak':
1158
                    case 'insertParagraph': {
1159
                        Editor.insertBreak(editor);
×
1160
                        break;
×
1161
                    }
1162

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

1198
    private onDOMBlur(event: FocusEvent) {
1199
        if (
×
1200
            this.readonly ||
×
1201
            this.isUpdatingSelection ||
1202
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1203
            this.isDOMEventHandled(event, this.blur)
1204
        ) {
1205
            return;
×
1206
        }
1207

1208
        const window = AngularEditor.getWindow(this.editor);
×
1209

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

1219
        const { relatedTarget } = event;
×
1220
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1221

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

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

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

1241
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1242
                return;
×
1243
            }
1244
        }
1245

1246
        IS_FOCUSED.delete(this.editor);
×
1247
    }
1248

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

1261
            const startVoid = Editor.void(this.editor, { at: start });
×
1262
            const endVoid = Editor.void(this.editor, { at: end });
×
1263

1264
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1265
                let blockPath = path;
×
1266
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1267
                    const block = Editor.above(this.editor, {
×
1268
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1269
                        at: path
1270
                    });
1271

1272
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1273
                }
1274

1275
                const range = Editor.range(this.editor, blockPath);
×
1276
                Transforms.select(this.editor, range);
×
1277
                return;
×
1278
            }
1279

1280
            if (
×
1281
                startVoid &&
×
1282
                endVoid &&
1283
                Path.equals(startVoid[1], endVoid[1]) &&
1284
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1285
            ) {
1286
                const range = Editor.range(this.editor, start);
×
1287
                Transforms.select(this.editor, range);
×
1288
            }
1289
        }
1290
    }
1291

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

1307
    private onDOMCompositionUpdate(event: CompositionEvent) {
1308
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1309
    }
1310

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

1325
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1326
            // so we need avoid repeat isnertText by isComposing === true,
1327
            this.isComposing = false;
×
1328
        }
1329
        this.render();
×
1330
    }
1331

1332
    private onDOMCopy(event: ClipboardEvent) {
1333
        const window = AngularEditor.getWindow(this.editor);
×
1334
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1335
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1336
            event.preventDefault();
×
1337
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1338
        }
1339
    }
1340

1341
    private onDOMCut(event: ClipboardEvent) {
1342
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1343
            event.preventDefault();
×
1344
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1345
            const { selection } = this.editor;
×
1346

1347
            if (selection) {
×
1348
                AngularEditor.deleteCutData(this.editor);
×
1349
            }
1350
        }
1351
    }
1352

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

1360
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1361
                event.preventDefault();
×
1362
            }
1363
        }
1364
    }
1365

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

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

1380
            this.isDraggingInternally = true;
×
1381

1382
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1383
        }
1384
    }
1385

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

1393
            // Find the range where the drop happened
1394
            const range = AngularEditor.findEventRange(editor, event);
×
1395
            const data = event.dataTransfer;
×
1396

1397
            Transforms.select(editor, range);
×
1398

1399
            if (this.isDraggingInternally) {
×
1400
                if (draggedRange) {
×
1401
                    Transforms.delete(editor, {
×
1402
                        at: draggedRange
1403
                    });
1404
                }
1405

1406
                this.isDraggingInternally = false;
×
1407
            }
1408

1409
            AngularEditor.insertData(editor, data);
×
1410

1411
            // When dragging from another source into the editor, it's possible
1412
            // that the current editor does not have focus.
1413
            if (!AngularEditor.isFocused(editor)) {
×
1414
                AngularEditor.focus(editor);
×
1415
            }
1416
        }
1417
    }
1418

1419
    private onDOMDragEnd(event: DragEvent) {
1420
        if (
×
1421
            !this.readonly &&
×
1422
            this.isDraggingInternally &&
1423
            AngularEditor.hasTarget(this.editor, event.target) &&
1424
            !this.isDOMEventHandled(event, this.dragEnd)
1425
        ) {
1426
            this.isDraggingInternally = false;
×
1427
        }
1428
    }
1429

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

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

1449
            IS_FOCUSED.set(this.editor, true);
2✔
1450
        }
1451
    }
1452

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

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

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

1478
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1479
                        editor.redo();
×
1480
                    }
1481

1482
                    return;
×
1483
                }
1484

1485
                if (Hotkeys.isUndo(nativeEvent)) {
×
1486
                    event.preventDefault();
×
1487

1488
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1489
                        editor.undo();
×
1490
                    }
1491

1492
                    return;
×
1493
                }
1494

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

1505
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1506
                    event.preventDefault();
×
1507
                    Transforms.move(editor, { unit: 'line' });
×
1508
                    return;
×
1509
                }
1510

1511
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1512
                    event.preventDefault();
×
1513
                    Transforms.move(editor, {
×
1514
                        unit: 'line',
1515
                        edge: 'focus',
1516
                        reverse: true
1517
                    });
1518
                    return;
×
1519
                }
1520

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

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

1535
                    if (selection && Range.isCollapsed(selection)) {
×
1536
                        Transforms.move(editor, { reverse: !isRTL });
×
1537
                    } else {
1538
                        Transforms.collapse(editor, { edge: 'start' });
×
1539
                    }
1540

1541
                    return;
×
1542
                }
1543

1544
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1545
                    event.preventDefault();
×
1546
                    if (selection && Range.isCollapsed(selection)) {
×
1547
                        Transforms.move(editor, { reverse: isRTL });
×
1548
                    } else {
1549
                        Transforms.collapse(editor, { edge: 'end' });
×
1550
                    }
1551

1552
                    return;
×
1553
                }
1554

1555
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1556
                    event.preventDefault();
×
1557

1558
                    if (selection && Range.isExpanded(selection)) {
×
1559
                        Transforms.collapse(editor, { edge: 'focus' });
×
1560
                    }
1561

1562
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1563
                    return;
×
1564
                }
1565

1566
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1567
                    event.preventDefault();
×
1568

1569
                    if (selection && Range.isExpanded(selection)) {
×
1570
                        Transforms.collapse(editor, { edge: 'focus' });
×
1571
                    }
1572

1573
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1574
                    return;
×
1575
                }
1576

1577
                if (isKeyHotkey('mod+a', event)) {
×
1578
                    this.editor.selectAll();
×
1579
                    event.preventDefault();
×
1580
                    return;
×
1581
                }
1582

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

1594
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1595
                        event.preventDefault();
×
1596
                        Editor.insertBreak(editor);
×
1597
                        return;
×
1598
                    }
1599

1600
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1601
                        event.preventDefault();
×
1602

1603
                        if (selection && Range.isExpanded(selection)) {
×
1604
                            Editor.deleteFragment(editor, {
×
1605
                                direction: 'backward'
1606
                            });
1607
                        } else {
1608
                            Editor.deleteBackward(editor);
×
1609
                        }
1610

1611
                        return;
×
1612
                    }
1613

1614
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1615
                        event.preventDefault();
×
1616

1617
                        if (selection && Range.isExpanded(selection)) {
×
1618
                            Editor.deleteFragment(editor, {
×
1619
                                direction: 'forward'
1620
                            });
1621
                        } else {
1622
                            Editor.deleteForward(editor);
×
1623
                        }
1624

1625
                        return;
×
1626
                    }
1627

1628
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1629
                        event.preventDefault();
×
1630

1631
                        if (selection && Range.isExpanded(selection)) {
×
1632
                            Editor.deleteFragment(editor, {
×
1633
                                direction: 'backward'
1634
                            });
1635
                        } else {
1636
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1637
                        }
1638

1639
                        return;
×
1640
                    }
1641

1642
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1643
                        event.preventDefault();
×
1644

1645
                        if (selection && Range.isExpanded(selection)) {
×
1646
                            Editor.deleteFragment(editor, {
×
1647
                                direction: 'forward'
1648
                            });
1649
                        } else {
1650
                            Editor.deleteForward(editor, { unit: 'line' });
×
1651
                        }
1652

1653
                        return;
×
1654
                    }
1655

1656
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1657
                        event.preventDefault();
×
1658

1659
                        if (selection && Range.isExpanded(selection)) {
×
1660
                            Editor.deleteFragment(editor, {
×
1661
                                direction: 'backward'
1662
                            });
1663
                        } else {
1664
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1665
                        }
1666

1667
                        return;
×
1668
                    }
1669

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

1673
                        if (selection && Range.isExpanded(selection)) {
×
1674
                            Editor.deleteFragment(editor, {
×
1675
                                direction: 'forward'
1676
                            });
1677
                        } else {
1678
                            Editor.deleteForward(editor, { unit: 'word' });
×
1679
                        }
1680

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

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

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

1762
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1763
        if (!handler) {
3✔
1764
            return false;
3✔
1765
        }
1766
        handler(event);
×
1767
        return event.defaultPrevented;
×
1768
    }
1769
    //#endregion
1770

1771
    ngOnDestroy() {
1772
        this.editorResizeObserver?.disconnect();
22✔
1773
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1774
        this.manualListeners.forEach(manualListener => {
22✔
1775
            manualListener();
462✔
1776
        });
1777
        this.destroy$.complete();
22✔
1778
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1779
    }
1780
}
1781

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

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

1793
        if (isZeroDimensionRect) {
×
1794
            const leafRect = leafEl.getBoundingClientRect();
×
1795
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1796

1797
            if (leafHasDimensions) {
×
1798
                return;
×
1799
            }
1800
        }
1801

1802
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1803
        scrollIntoView(leafEl, {
×
1804
            scrollMode: 'if-needed'
1805
        });
1806
        delete leafEl.getBoundingClientRect;
×
1807
    }
1808
};
1809

1810
/**
1811
 * Check if the target is inside void and in the editor.
1812
 */
1813

1814
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1815
    let slateNode: Node | null = null;
1✔
1816
    try {
1✔
1817
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1818
    } catch (error) {}
1819
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1820
};
1821

1822
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1823
    return (
2✔
1824
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1825
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1826
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1827
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1828
    );
1829
};
1830

1831
/**
1832
 * remove default insert from composition
1833
 * @param text
1834
 */
1835
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1836
    const types = ['compositionend', 'insertFromComposition'];
×
1837
    if (!types.includes(event.type)) {
×
1838
        return;
×
1839
    }
1840
    const insertText = (event as CompositionEvent).data;
×
1841
    const window = AngularEditor.getWindow(editor);
×
1842
    const domSelection = window.getSelection();
×
1843
    // ensure text node insert composition input text
1844
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1845
        const textNode = domSelection.anchorNode;
×
1846
        textNode.splitText(textNode.length - insertText.length).remove();
×
1847
    }
1848
};
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