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

worktile / slate-angular / 7a0817de-8493-40cc-b8f9-0e9c0e3d45d2

11 Dec 2025 08:37AM UTC coverage: 38.236% (-2.4%) from 40.669%
7a0817de-8493-40cc-b8f9-0e9c0e3d45d2

push

circleci

Xwatson
chore: optimize debug view

387 of 1206 branches covered (32.09%)

Branch coverage included in aggregate %.

5 of 226 new or added lines in 2 files covered. (2.21%)

3 existing lines in 1 file now uncovered.

1074 of 2615 relevant lines covered (41.07%)

24.95 hits per line

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

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

503
    render() {
504
        const changed = this.updateContext();
2✔
505
        if (changed) {
2✔
506
            const virtualView = this.refreshVirtualView();
2✔
507
            this.applyVirtualView(virtualView);
2✔
508
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
509
            this.scheduleMeasureVisibleHeights();
2✔
510
        }
511
    }
512

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

533
    initializeContext() {
534
        this.context = {
49✔
535
            parent: this.editor,
536
            selection: this.editor.selection,
537
            decorations: this.generateDecorations(),
538
            decorate: this.decorate,
539
            readonly: this.readonly
540
        };
541
    }
542

543
    initializeViewContext() {
544
        this.viewContext = {
23✔
545
            editor: this.editor,
546
            renderElement: this.renderElement,
547
            renderLeaf: this.renderLeaf,
548
            renderText: this.renderText,
549
            trackBy: this.trackBy,
550
            isStrictDecorate: this.isStrictDecorate
551
        };
552
    }
553

554
    composePlaceholderDecorate(editor: Editor) {
555
        if (this.placeholderDecorate) {
64!
556
            return this.placeholderDecorate(editor) || [];
×
557
        }
558

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

573
    generateDecorations() {
574
        const decorations = this.decorate([this.editor, []]);
66✔
575
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
576
        decorations.push(...placeholderDecorations);
66✔
577
        return decorations;
66✔
578
    }
579

580
    private shouldUseVirtual() {
581
        return !!(this.virtualConfig && this.virtualConfig.enabled);
71✔
582
    }
583

584
    // the height from scroll container top to editor top height element
585
    private businessHeight: number = 0;
23✔
586

587
    virtualScrollInitialized = false;
23✔
588

589
    virtualTopHeightElement: HTMLElement;
590

591
    virtualBottomHeightElement: HTMLElement;
592

593
    virtualCenterOutlet: HTMLElement;
594

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

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

629
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
630
        if (!this.virtualScrollInitialized) {
43✔
631
            return;
43✔
632
        }
633
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
634
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
635
    }
636

637
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
NEW
638
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
NEW
639
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
640
    }
641

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

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

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

722
        if (visibleStartIndex === -1 && elementLength) {
×
723
            visibleStartIndex = elementLength - 1;
×
724
            visible.push(children[visibleStartIndex]);
×
725
            visibleIndexes.push(visibleStartIndex);
×
726
        }
727

728
        const visibleEndIndex =
729
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
730
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
731
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
732

733
        return {
×
734
            renderedChildren: visible.length ? visible : children,
×
735
            visibleIndexes: new Set(visibleIndexes),
736
            top,
737
            bottom,
738
            heights
739
        };
740
    }
741

742
    private applyVirtualView(virtualView: VirtualViewResult) {
743
        this.renderedChildren = virtualView.renderedChildren;
43✔
744
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
745
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
746
    }
747

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

855
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
856
        const node = this.editor.children[index];
×
857
        if (!node) {
×
858
            return defaultHeight;
×
859
        }
860
        const key = AngularEditor.findKey(this.editor, node);
×
861
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
862
    }
863

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1374
            this.isDraggingInternally = true;
×
1375

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

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

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

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

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

1400
                this.isDraggingInternally = false;
×
1401
            }
1402

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

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

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

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

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

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

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

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

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

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

1476
                    return;
×
1477
                }
1478

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

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

1486
                    return;
×
1487
                }
1488

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

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

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

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

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

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

1535
                    return;
×
1536
                }
1537

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

1546
                    return;
×
1547
                }
1548

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

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

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

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

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

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

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

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

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

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

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

1605
                        return;
×
1606
                    }
1607

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

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

1619
                        return;
×
1620
                    }
1621

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

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

1633
                        return;
×
1634
                    }
1635

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

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

1647
                        return;
×
1648
                    }
1649

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

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

1661
                        return;
×
1662
                    }
1663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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