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

worktile / slate-angular / bc126b13-6434-45df-823a-9c3a048c84b6

09 Dec 2025 07:09AM UTC coverage: 43.255% (-0.03%) from 43.281%
bc126b13-6434-45df-823a-9c3a048c84b6

push

circleci

pubuzhixing8
fix(virtual-scroll): fix select in backward scenario and selection is null scenario

385 of 1129 branches covered (34.1%)

Branch coverage included in aggregate %.

2 of 7 new or added lines in 1 file covered. (28.57%)

1058 of 2207 relevant lines covered (47.94%)

29.49 hits per line

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

25.52
/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

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

72
// not correctly clipboardData on beforeinput
73
const forceOnDOMPaste = IS_SAFARI;
1✔
74

75
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
76

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

102
    private destroy$ = new Subject();
23✔
103

104
    isComposing = false;
23✔
105
    isDraggingInternally = false;
23✔
106
    isUpdatingSelection = false;
23✔
107
    latestElement = null as DOMElement | null;
23✔
108

109
    protected manualListeners: (() => void)[] = [];
23✔
110

111
    private initialized: boolean;
112

113
    private onTouchedCallback: () => void = () => {};
23✔
114

115
    private onChangeCallback: (_: any) => void = () => {};
23✔
116

117
    @Input() editor: AngularEditor;
118

119
    @Input() renderElement: (element: Element) => ViewType | null;
120

121
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
122

123
    @Input() renderText: (text: SlateText) => ViewType | null;
124

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

127
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
128

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

131
    @Input() isStrictDecorate: boolean = true;
23✔
132

133
    @Input() trackBy: (node: Element) => any = () => null;
206✔
134

135
    @Input() readonly = false;
23✔
136

137
    @Input() placeholder: string;
138

139
    @Input()
140
    set virtualScroll(config: SlateVirtualScrollConfig) {
141
        this.virtualConfig = config;
×
142
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
143
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
144
            let virtualView = this.refreshVirtualView();
×
145
            let diff = this.diffVirtualView(virtualView);
×
146
            if (!diff.isDiff) {
×
147
                return;
×
148
            }
149
            if (diff.isMissingTop) {
×
150
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
151
                if (result) {
×
152
                    virtualView = this.refreshVirtualView();
×
153
                    diff = this.diffVirtualView(virtualView, 'second');
×
154
                    if (!diff.isDiff) {
×
155
                        return;
×
156
                    }
157
                }
158
            }
159
            this.applyVirtualView(virtualView);
×
160
            if (this.listRender.initialized) {
×
161
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
162
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
163
                    this.toNativeSelection();
×
164
                }
165
            }
166
            this.scheduleMeasureVisibleHeights();
×
167
        });
168
    }
169

170
    //#region input event handler
171
    @Input() beforeInput: (event: Event) => void;
172
    @Input() blur: (event: Event) => void;
173
    @Input() click: (event: MouseEvent) => void;
174
    @Input() compositionEnd: (event: CompositionEvent) => void;
175
    @Input() compositionUpdate: (event: CompositionEvent) => void;
176
    @Input() compositionStart: (event: CompositionEvent) => void;
177
    @Input() copy: (event: ClipboardEvent) => void;
178
    @Input() cut: (event: ClipboardEvent) => void;
179
    @Input() dragOver: (event: DragEvent) => void;
180
    @Input() dragStart: (event: DragEvent) => void;
181
    @Input() dragEnd: (event: DragEvent) => void;
182
    @Input() drop: (event: DragEvent) => void;
183
    @Input() focus: (event: Event) => void;
184
    @Input() keydown: (event: KeyboardEvent) => void;
185
    @Input() paste: (event: ClipboardEvent) => void;
186
    //#endregion
187

188
    //#region DOM attr
189
    @Input() spellCheck = false;
23✔
190
    @Input() autoCorrect = false;
23✔
191
    @Input() autoCapitalize = false;
23✔
192

193
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
194
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
195
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
196

197
    get hasBeforeInputSupport() {
198
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
199
    }
200
    //#endregion
201

202
    viewContainerRef = inject(ViewContainerRef);
23✔
203

204
    getOutletParent = () => {
23✔
205
        return this.elementRef.nativeElement;
43✔
206
    };
207

208
    getOutletElement = () => {
23✔
209
        if (this.virtualScrollInitialized) {
23!
210
            return this.virtualCenterOutlet;
×
211
        } else {
212
            return null;
23✔
213
        }
214
    };
215

216
    listRender: ListRender;
217

218
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
219
        enabled: false,
220
        scrollTop: 0,
221
        viewportHeight: 0
222
    };
223
    private renderedChildren: Element[] = [];
23✔
224
    private virtualVisibleIndexes = new Set<number>();
23✔
225
    private measuredHeights = new Map<string, number>();
23✔
226
    private refreshVirtualViewAnimId: number;
227
    private measureVisibleHeightsAnimId: number;
228

229
    constructor(
230
        public elementRef: ElementRef,
23✔
231
        public renderer2: Renderer2,
23✔
232
        public cdr: ChangeDetectorRef,
23✔
233
        private ngZone: NgZone,
23✔
234
        private injector: Injector
23✔
235
    ) {}
236

237
    ngOnInit() {
238
        this.editor.injector = this.injector;
23✔
239
        this.editor.children = [];
23✔
240
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
241
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
242
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
243
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
244
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
245
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
246
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
247
            this.ngZone.run(() => {
13✔
248
                this.onChange();
13✔
249
            });
250
        });
251
        this.ngZone.runOutsideAngular(() => {
23✔
252
            this.initialize();
23✔
253
        });
254
        this.initializeViewContext();
23✔
255
        this.initializeContext();
23✔
256

257
        // add browser class
258
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
259
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
260
        this.initializeVirtualScrolling();
23✔
261
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
262
    }
263

264
    ngOnChanges(simpleChanges: SimpleChanges) {
265
        if (!this.initialized) {
30✔
266
            return;
23✔
267
        }
268
        const decorateChange = simpleChanges['decorate'];
7✔
269
        if (decorateChange) {
7✔
270
            this.forceRender();
2✔
271
        }
272
        const placeholderChange = simpleChanges['placeholder'];
7✔
273
        if (placeholderChange) {
7✔
274
            this.render();
1✔
275
        }
276
        const readonlyChange = simpleChanges['readonly'];
7✔
277
        if (readonlyChange) {
7!
278
            IS_READ_ONLY.set(this.editor, this.readonly);
×
279
            this.render();
×
280
            this.toSlateSelection();
×
281
        }
282
    }
283

284
    registerOnChange(fn: any) {
285
        this.onChangeCallback = fn;
23✔
286
    }
287
    registerOnTouched(fn: any) {
288
        this.onTouchedCallback = fn;
23✔
289
    }
290

291
    writeValue(value: Element[]) {
292
        if (value && value.length) {
49✔
293
            this.editor.children = value;
26✔
294
            this.initializeContext();
26✔
295
            const virtualView = this.refreshVirtualView();
26✔
296
            this.applyVirtualView(virtualView);
26✔
297
            const childrenForRender = virtualView.renderedChildren;
26✔
298
            if (!this.listRender.initialized) {
26✔
299
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
300
            } else {
301
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
302
            }
303
            this.scheduleMeasureVisibleHeights();
26✔
304
            this.cdr.markForCheck();
26✔
305
        }
306
    }
307

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

340
    toNativeSelection() {
341
        try {
15✔
342
            let { selection } = this.editor;
15✔
343
            if (this.virtualConfig?.enabled && selection) {
15!
344
                const indics = Array.from(this.virtualVisibleIndexes.values());
×
345
                if (indics.length > 0) {
×
346
                    const currentVisibleRange: Range = {
×
347
                        anchor: Editor.start(this.editor, [indics[0]]),
348
                        focus: Editor.end(this.editor, [indics[indics.length - 1]])
349
                    };
NEW
350
                    const [start, end] = Range.edges(selection);
×
NEW
351
                    const forwardSelection = { anchor: start, focus: end };
×
NEW
352
                    const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
NEW
353
                    if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
NEW
354
                        selection = intersectedSelection;
×
355
                        if (isDebug) {
×
356
                            console.log(
×
357
                                `selection is not in visible range, selection: ${JSON.stringify(selection)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
358
                            );
359
                        }
360
                    }
361
                }
362
            }
363
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
364
            const { activeElement } = root;
15✔
365
            const domSelection = (root as Document).getSelection();
15✔
366

367
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
368
                return;
14✔
369
            }
370

371
            const hasDomSelection = domSelection.type !== 'None';
1✔
372

373
            // If the DOM selection is properly unset, we're done.
374
            if (!selection && !hasDomSelection) {
1!
375
                return;
×
376
            }
377

378
            // If the DOM selection is already correct, we're done.
379
            // verify that the dom selection is in the editor
380
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
381
            let hasDomSelectionInEditor = false;
1✔
382
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
383
                hasDomSelectionInEditor = true;
1✔
384
            }
385

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

397
            // prevent updating native selection when active element is void element
398
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
399
                return;
×
400
            }
401

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

411
            // Otherwise the DOM selection is out of sync, so update it.
412
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
413
            this.isUpdatingSelection = true;
1✔
414

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

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

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

451
                this.isUpdatingSelection = false;
1✔
452
            });
453
        } catch (error) {
454
            this.editor.onError({
×
455
                code: SlateErrorCode.ToNativeSelectionError,
456
                nativeError: error
457
            });
458
            this.isUpdatingSelection = false;
×
459
        }
460
    }
461

462
    onChange() {
463
        this.forceRender();
13✔
464
        this.onChangeCallback(this.editor.children);
13✔
465
    }
466

467
    ngAfterViewChecked() {}
468

469
    ngDoCheck() {}
470

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

513
    render() {
514
        const changed = this.updateContext();
2✔
515
        if (changed) {
2✔
516
            const virtualView = this.refreshVirtualView();
2✔
517
            this.applyVirtualView(virtualView);
2✔
518
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
519
            this.scheduleMeasureVisibleHeights();
2✔
520
        }
521
    }
522

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

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

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

564
    composePlaceholderDecorate(editor: Editor) {
565
        if (this.placeholderDecorate) {
64!
566
            return this.placeholderDecorate(editor) || [];
×
567
        }
568

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

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

590
    private shouldUseVirtual() {
591
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
592
    }
593

594
    // the height from scroll container top to editor top height element
595
    private businessHeight: number = 0;
23✔
596

597
    virtualScrollInitialized = false;
23✔
598

599
    virtualTopHeightElement: HTMLElement;
600

601
    virtualBottomHeightElement: HTMLElement;
602

603
    virtualCenterOutlet: HTMLElement;
604

605
    initializeVirtualScrolling() {
606
        if (this.virtualScrollInitialized) {
23!
607
            return;
×
608
        }
609
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
610
            this.virtualScrollInitialized = true;
×
611
            this.virtualTopHeightElement = document.createElement('div');
×
612
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
613
            this.virtualTopHeightElement.contentEditable = 'false';
×
614
            this.virtualBottomHeightElement = document.createElement('div');
×
615
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
616
            this.virtualBottomHeightElement.contentEditable = 'false';
×
617
            this.virtualCenterOutlet = document.createElement('div');
×
618
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
619
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
620
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
621
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
622
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
623
        }
624
    }
625

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

634
    private refreshVirtualView() {
635
        const children = (this.editor.children || []) as Element[];
43!
636
        if (!children.length || !this.shouldUseVirtual()) {
43✔
637
            return {
43✔
638
                renderedChildren: children,
639
                visibleIndexes: new Set<number>(),
640
                top: 0,
641
                bottom: 0,
642
                heights: []
643
            };
644
        }
645
        const scrollTop = this.virtualConfig.scrollTop;
×
646
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
647
        if (!viewportHeight) {
×
648
            return {
×
649
                renderedChildren: [],
650
                visibleIndexes: new Set<number>(),
651
                top: 0,
652
                bottom: 0,
653
                heights: []
654
            };
655
        }
656
        const elementLength = children.length;
×
657
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
658
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
659
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
660
        const totalHeight = accumulatedHeights[elementLength];
×
661
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
662
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
663
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
664
        let accumulatedOffset = 0;
×
665
        let visibleStartIndex = -1;
×
666
        const visible: Element[] = [];
×
667
        const visibleIndexes: number[] = [];
×
668

669
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
670
            const currentHeight = heights[i];
×
671
            const nextOffset = accumulatedOffset + currentHeight;
×
672
            // 可视区域有交集,加入渲染
673
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
674
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
675
                visible.push(children[i]);
×
676
                visibleIndexes.push(i);
×
677
            }
678
            accumulatedOffset = nextOffset;
×
679
        }
680

681
        if (visibleStartIndex === -1 && elementLength) {
×
682
            visibleStartIndex = elementLength - 1;
×
683
            visible.push(children[visibleStartIndex]);
×
684
            visibleIndexes.push(visibleStartIndex);
×
685
        }
686

687
        const visibleEndIndex =
688
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
689
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
690
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
691

692
        return {
×
693
            renderedChildren: visible.length ? visible : children,
×
694
            visibleIndexes: new Set(visibleIndexes),
695
            top,
696
            bottom,
697
            heights
698
        };
699
    }
700

701
    private applyVirtualView(virtualView: VirtualViewResult) {
702
        this.renderedChildren = virtualView.renderedChildren;
43✔
703
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
704
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
705
    }
706

707
    private diffVirtualView(virtualView: VirtualViewResult, stage: 'first' | 'second' = 'first') {
×
708
        if (!this.renderedChildren.length) {
×
709
            return {
×
710
                isDiff: true,
711
                diffTopRenderedIndexes: [],
712
                diffBottomRenderedIndexes: []
713
            };
714
        }
715
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
716
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
717
        const firstNewIndex = newVisibleIndexes[0];
×
718
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
719
        const firstOldIndex = oldVisibleIndexes[0];
×
720
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
721
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
722
            const diffTopRenderedIndexes = [];
×
723
            const diffBottomRenderedIndexes = [];
×
724
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
725
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
726
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
727
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
728
            if (isMissingTop || isAddedBottom) {
×
729
                // 向下
730
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
731
                    const element = oldVisibleIndexes[index];
×
732
                    if (!newVisibleIndexes.includes(element)) {
×
733
                        diffTopRenderedIndexes.push(element);
×
734
                    } else {
735
                        break;
×
736
                    }
737
                }
738
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
739
                    const element = newVisibleIndexes[index];
×
740
                    if (!oldVisibleIndexes.includes(element)) {
×
741
                        diffBottomRenderedIndexes.push(element);
×
742
                    } else {
743
                        break;
×
744
                    }
745
                }
746
            } else if (isAddedTop || isMissingBottom) {
×
747
                // 向上
748
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
749
                    const element = newVisibleIndexes[index];
×
750
                    if (!oldVisibleIndexes.includes(element)) {
×
751
                        diffTopRenderedIndexes.push(element);
×
752
                    } else {
753
                        break;
×
754
                    }
755
                }
756
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
757
                    const element = oldVisibleIndexes[index];
×
758
                    if (!newVisibleIndexes.includes(element)) {
×
759
                        diffBottomRenderedIndexes.push(element);
×
760
                    } else {
761
                        break;
×
762
                    }
763
                }
764
            }
765
            if (isDebug) {
×
766
                console.log(`====== diffVirtualView stage: ${stage} ======`);
×
767
                console.log('oldVisibleIndexes:', oldVisibleIndexes);
×
768
                console.log('newVisibleIndexes:', newVisibleIndexes);
×
769
                console.log(
×
770
                    'diffTopRenderedIndexes:',
771
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
772
                    diffTopRenderedIndexes,
773
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
774
                );
775
                console.log(
×
776
                    'diffBottomRenderedIndexes:',
777
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
778
                    diffBottomRenderedIndexes,
779
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
780
                );
781
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
782
                const needBottom = virtualView.heights
×
783
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
784
                    .reduce((acc, height) => acc + height, 0);
×
785
                console.log('newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
786
                console.log('newBottomHeight:', needBottom, 'prevBottomHeight:', parseFloat(this.virtualBottomHeightElement.style.height));
×
787
                console.warn('=========== Dividing line ===========');
×
788
            }
789
            return {
×
790
                isDiff: true,
791
                isMissingTop,
792
                isAddedTop,
793
                isMissingBottom,
794
                isAddedBottom,
795
                diffTopRenderedIndexes,
796
                diffBottomRenderedIndexes
797
            };
798
        }
799
        return {
×
800
            isDiff: false,
801
            diffTopRenderedIndexes: [],
802
            diffBottomRenderedIndexes: []
803
        };
804
    }
805

806
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
807
        const node = this.editor.children[index];
×
808
        if (!node) {
×
809
            return defaultHeight;
×
810
        }
811
        const key = AngularEditor.findKey(this.editor, node);
×
812
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
813
    }
814

815
    private buildAccumulatedHeight(heights: number[]) {
816
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
817
        for (let i = 0; i < heights.length; i++) {
×
818
            // 存储前 i 个的累计高度
819
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
820
        }
821
        return accumulatedHeights;
×
822
    }
823

824
    private scheduleMeasureVisibleHeights() {
825
        if (!this.shouldUseVirtual()) {
43✔
826
            return;
43✔
827
        }
828
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
829
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
830
            this.measureVisibleHeights();
×
831
        });
832
    }
833

834
    private measureVisibleHeights() {
835
        const children = (this.editor.children || []) as Element[];
×
836
        this.virtualVisibleIndexes.forEach(index => {
×
837
            const node = children[index];
×
838
            if (!node) {
×
839
                return;
×
840
            }
841
            const key = AngularEditor.findKey(this.editor, node);
×
842
            // 跳过已测过的块
843
            if (this.measuredHeights.has(key.id)) {
×
844
                return;
×
845
            }
846
            const view = ELEMENT_TO_COMPONENT.get(node);
×
847
            if (!view) {
×
848
                return;
×
849
            }
850
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
851
            if (ret instanceof Promise) {
×
852
                ret.then(height => {
×
853
                    this.measuredHeights.set(key.id, height);
×
854
                });
855
            } else {
856
                this.measuredHeights.set(key.id, ret);
×
857
            }
858
        });
859
    }
860

861
    private remeasureHeightByIndics(indics: number[]): boolean {
862
        const children = (this.editor.children || []) as Element[];
×
863
        let isHeightChanged = false;
×
864
        indics.forEach(index => {
×
865
            const node = children[index];
×
866
            if (!node) {
×
867
                return;
×
868
            }
869
            const key = AngularEditor.findKey(this.editor, node);
×
870
            const view = ELEMENT_TO_COMPONENT.get(node);
×
871
            if (!view) {
×
872
                return;
×
873
            }
874
            const prevHeight = this.measuredHeights.get(key.id);
×
875
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
876
            if (ret instanceof Promise) {
×
877
                ret.then(height => {
×
878
                    if (height !== prevHeight) {
×
879
                        this.measuredHeights.set(key.id, height);
×
880
                        isHeightChanged = true;
×
881
                        if (isDebug) {
×
882
                            console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
883
                        }
884
                    }
885
                });
886
            } else {
887
                if (ret !== prevHeight) {
×
888
                    this.measuredHeights.set(key.id, ret);
×
889
                    isHeightChanged = true;
×
890
                    if (isDebug) {
×
891
                        console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
892
                    }
893
                }
894
            }
895
        });
896
        return isHeightChanged;
×
897
    }
898

899
    //#region event proxy
900
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
901
        this.manualListeners.push(
483✔
902
            this.renderer2.listen(target, eventName, (event: Event) => {
903
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
904
                if (beforeInputEvent) {
5!
905
                    this.onFallbackBeforeInput(beforeInputEvent);
×
906
                }
907
                listener(event);
5✔
908
            })
909
        );
910
    }
911

912
    private toSlateSelection() {
913
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
914
            try {
1✔
915
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
916
                const { activeElement } = root;
1✔
917
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
918
                const domSelection = (root as Document).getSelection();
1✔
919

920
                if (activeElement === el) {
1!
921
                    this.latestElement = activeElement;
1✔
922
                    IS_FOCUSED.set(this.editor, true);
1✔
923
                } else {
924
                    IS_FOCUSED.delete(this.editor);
×
925
                }
926

927
                if (!domSelection) {
1!
928
                    return Transforms.deselect(this.editor);
×
929
                }
930

931
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
932
                const hasDomSelectionInEditor =
933
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
934
                if (!hasDomSelectionInEditor) {
1!
935
                    Transforms.deselect(this.editor);
×
936
                    return;
×
937
                }
938

939
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
940
                // for example, double-click the last cell of the table to select a non-editable DOM
941
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
942
                if (range) {
1✔
943
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
944
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
945
                            // force adjust DOMSelection
946
                            this.toNativeSelection();
×
947
                        }
948
                    } else {
949
                        Transforms.select(this.editor, range);
1✔
950
                    }
951
                }
952
            } catch (error) {
953
                this.editor.onError({
×
954
                    code: SlateErrorCode.ToSlateSelectionError,
955
                    nativeError: error
956
                });
957
            }
958
        }
959
    }
960

961
    private onDOMBeforeInput(
962
        event: Event & {
963
            inputType: string;
964
            isComposing: boolean;
965
            data: string | null;
966
            dataTransfer: DataTransfer | null;
967
            getTargetRanges(): DOMStaticRange[];
968
        }
969
    ) {
970
        const editor = this.editor;
×
971
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
972
        const { activeElement } = root;
×
973
        const { selection } = editor;
×
974
        const { inputType: type } = event;
×
975
        const data = event.dataTransfer || event.data || undefined;
×
976
        if (IS_ANDROID) {
×
977
            let targetRange: Range | null = null;
×
978
            let [nativeTargetRange] = event.getTargetRanges();
×
979
            if (nativeTargetRange) {
×
980
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
981
            }
982
            // COMPAT: SelectionChange event is fired after the action is performed, so we
983
            // have to manually get the selection here to ensure it's up-to-date.
984
            const window = AngularEditor.getWindow(editor);
×
985
            const domSelection = window.getSelection();
×
986
            if (!targetRange && domSelection) {
×
987
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
988
            }
989
            targetRange = targetRange ?? editor.selection;
×
990
            if (type === 'insertCompositionText') {
×
991
                if (data && data.toString().includes('\n')) {
×
992
                    restoreDom(editor, () => {
×
993
                        Editor.insertBreak(editor);
×
994
                    });
995
                } else {
996
                    if (targetRange) {
×
997
                        if (data) {
×
998
                            restoreDom(editor, () => {
×
999
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1000
                            });
1001
                        } else {
1002
                            restoreDom(editor, () => {
×
1003
                                Transforms.delete(editor, { at: targetRange });
×
1004
                            });
1005
                        }
1006
                    }
1007
                }
1008
                return;
×
1009
            }
1010
            if (type === 'deleteContentBackward') {
×
1011
                // gboard can not prevent default action, so must use restoreDom,
1012
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1013
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1014
                if (!Range.isCollapsed(targetRange)) {
×
1015
                    restoreDom(editor, () => {
×
1016
                        Transforms.delete(editor, { at: targetRange });
×
1017
                    });
1018
                    return;
×
1019
                }
1020
            }
1021
            if (type === 'insertText') {
×
1022
                restoreDom(editor, () => {
×
1023
                    if (typeof data === 'string') {
×
1024
                        Editor.insertText(editor, data);
×
1025
                    }
1026
                });
1027
                return;
×
1028
            }
1029
        }
1030
        if (
×
1031
            !this.readonly &&
×
1032
            AngularEditor.hasEditableTarget(editor, event.target) &&
1033
            !isTargetInsideVoid(editor, activeElement) &&
1034
            !this.isDOMEventHandled(event, this.beforeInput)
1035
        ) {
1036
            try {
×
1037
                event.preventDefault();
×
1038

1039
                // COMPAT: If the selection is expanded, even if the command seems like
1040
                // a delete forward/backward command it should delete the selection.
1041
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1042
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1043
                    Editor.deleteFragment(editor, { direction });
×
1044
                    return;
×
1045
                }
1046

1047
                switch (type) {
×
1048
                    case 'deleteByComposition':
1049
                    case 'deleteByCut':
1050
                    case 'deleteByDrag': {
1051
                        Editor.deleteFragment(editor);
×
1052
                        break;
×
1053
                    }
1054

1055
                    case 'deleteContent':
1056
                    case 'deleteContentForward': {
1057
                        Editor.deleteForward(editor);
×
1058
                        break;
×
1059
                    }
1060

1061
                    case 'deleteContentBackward': {
1062
                        Editor.deleteBackward(editor);
×
1063
                        break;
×
1064
                    }
1065

1066
                    case 'deleteEntireSoftLine': {
1067
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1068
                        Editor.deleteForward(editor, { unit: 'line' });
×
1069
                        break;
×
1070
                    }
1071

1072
                    case 'deleteHardLineBackward': {
1073
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1074
                        break;
×
1075
                    }
1076

1077
                    case 'deleteSoftLineBackward': {
1078
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1079
                        break;
×
1080
                    }
1081

1082
                    case 'deleteHardLineForward': {
1083
                        Editor.deleteForward(editor, { unit: 'block' });
×
1084
                        break;
×
1085
                    }
1086

1087
                    case 'deleteSoftLineForward': {
1088
                        Editor.deleteForward(editor, { unit: 'line' });
×
1089
                        break;
×
1090
                    }
1091

1092
                    case 'deleteWordBackward': {
1093
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1094
                        break;
×
1095
                    }
1096

1097
                    case 'deleteWordForward': {
1098
                        Editor.deleteForward(editor, { unit: 'word' });
×
1099
                        break;
×
1100
                    }
1101

1102
                    case 'insertLineBreak':
1103
                    case 'insertParagraph': {
1104
                        Editor.insertBreak(editor);
×
1105
                        break;
×
1106
                    }
1107

1108
                    case 'insertFromComposition': {
1109
                        // COMPAT: in safari, `compositionend` event is dispatched after
1110
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1111
                        // https://www.w3.org/TR/input-events-2/
1112
                        // so the following code is the right logic
1113
                        // because DOM selection in sync will be exec before `compositionend` event
1114
                        // isComposing is true will prevent DOM selection being update correctly.
1115
                        this.isComposing = false;
×
1116
                        preventInsertFromComposition(event, this.editor);
×
1117
                    }
1118
                    case 'insertFromDrop':
1119
                    case 'insertFromPaste':
1120
                    case 'insertFromYank':
1121
                    case 'insertReplacementText':
1122
                    case 'insertText': {
1123
                        // use a weak comparison instead of 'instanceof' to allow
1124
                        // programmatic access of paste events coming from external windows
1125
                        // like cypress where cy.window does not work realibly
1126
                        if (data?.constructor.name === 'DataTransfer') {
×
1127
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1128
                        } else if (typeof data === 'string') {
×
1129
                            Editor.insertText(editor, data);
×
1130
                        }
1131
                        break;
×
1132
                    }
1133
                }
1134
            } catch (error) {
1135
                this.editor.onError({
×
1136
                    code: SlateErrorCode.OnDOMBeforeInputError,
1137
                    nativeError: error
1138
                });
1139
            }
1140
        }
1141
    }
1142

1143
    private onDOMBlur(event: FocusEvent) {
1144
        if (
×
1145
            this.readonly ||
×
1146
            this.isUpdatingSelection ||
1147
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1148
            this.isDOMEventHandled(event, this.blur)
1149
        ) {
1150
            return;
×
1151
        }
1152

1153
        const window = AngularEditor.getWindow(this.editor);
×
1154

1155
        // COMPAT: If the current `activeElement` is still the previous
1156
        // one, this is due to the window being blurred when the tab
1157
        // itself becomes unfocused, so we want to abort early to allow to
1158
        // editor to stay focused when the tab becomes focused again.
1159
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1160
        if (this.latestElement === root.activeElement) {
×
1161
            return;
×
1162
        }
1163

1164
        const { relatedTarget } = event;
×
1165
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1166

1167
        // COMPAT: The event should be ignored if the focus is returning
1168
        // to the editor from an embedded editable element (eg. an <input>
1169
        // element inside a void node).
1170
        if (relatedTarget === el) {
×
1171
            return;
×
1172
        }
1173

1174
        // COMPAT: The event should be ignored if the focus is moving from
1175
        // the editor to inside a void node's spacer element.
1176
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1177
            return;
×
1178
        }
1179

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

1186
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1187
                return;
×
1188
            }
1189
        }
1190

1191
        IS_FOCUSED.delete(this.editor);
×
1192
    }
1193

1194
    private onDOMClick(event: MouseEvent) {
1195
        if (
×
1196
            !this.readonly &&
×
1197
            AngularEditor.hasTarget(this.editor, event.target) &&
1198
            !this.isDOMEventHandled(event, this.click) &&
1199
            isDOMNode(event.target)
1200
        ) {
1201
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1202
            const path = AngularEditor.findPath(this.editor, node);
×
1203
            const start = Editor.start(this.editor, path);
×
1204
            const end = Editor.end(this.editor, path);
×
1205

1206
            const startVoid = Editor.void(this.editor, { at: start });
×
1207
            const endVoid = Editor.void(this.editor, { at: end });
×
1208

1209
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1210
                let blockPath = path;
×
1211
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1212
                    const block = Editor.above(this.editor, {
×
1213
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1214
                        at: path
1215
                    });
1216

1217
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1218
                }
1219

1220
                const range = Editor.range(this.editor, blockPath);
×
1221
                Transforms.select(this.editor, range);
×
1222
                return;
×
1223
            }
1224

1225
            if (
×
1226
                startVoid &&
×
1227
                endVoid &&
1228
                Path.equals(startVoid[1], endVoid[1]) &&
1229
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1230
            ) {
1231
                const range = Editor.range(this.editor, start);
×
1232
                Transforms.select(this.editor, range);
×
1233
            }
1234
        }
1235
    }
1236

1237
    private onDOMCompositionStart(event: CompositionEvent) {
1238
        const { selection } = this.editor;
1✔
1239
        if (selection) {
1!
1240
            // solve the problem of cross node Chinese input
1241
            if (Range.isExpanded(selection)) {
×
1242
                Editor.deleteFragment(this.editor);
×
1243
                this.forceRender();
×
1244
            }
1245
        }
1246
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1247
            this.isComposing = true;
1✔
1248
        }
1249
        this.render();
1✔
1250
    }
1251

1252
    private onDOMCompositionUpdate(event: CompositionEvent) {
1253
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1254
    }
1255

1256
    private onDOMCompositionEnd(event: CompositionEvent) {
1257
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1258
            Transforms.delete(this.editor);
×
1259
        }
1260
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1261
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1262
            // aren't correct and never fire the "insertFromComposition"
1263
            // type that we need. So instead, insert whenever a composition
1264
            // ends since it will already have been committed to the DOM.
1265
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1266
                preventInsertFromComposition(event, this.editor);
×
1267
                Editor.insertText(this.editor, event.data);
×
1268
            }
1269

1270
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1271
            // so we need avoid repeat isnertText by isComposing === true,
1272
            this.isComposing = false;
×
1273
        }
1274
        this.render();
×
1275
    }
1276

1277
    private onDOMCopy(event: ClipboardEvent) {
1278
        const window = AngularEditor.getWindow(this.editor);
×
1279
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1280
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1281
            event.preventDefault();
×
1282
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1283
        }
1284
    }
1285

1286
    private onDOMCut(event: ClipboardEvent) {
1287
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1288
            event.preventDefault();
×
1289
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1290
            const { selection } = this.editor;
×
1291

1292
            if (selection) {
×
1293
                AngularEditor.deleteCutData(this.editor);
×
1294
            }
1295
        }
1296
    }
1297

1298
    private onDOMDragOver(event: DragEvent) {
1299
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1300
            // Only when the target is void, call `preventDefault` to signal
1301
            // that drops are allowed. Editable content is droppable by
1302
            // default, and calling `preventDefault` hides the cursor.
1303
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1304

1305
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1306
                event.preventDefault();
×
1307
            }
1308
        }
1309
    }
1310

1311
    private onDOMDragStart(event: DragEvent) {
1312
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1313
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1314
            const path = AngularEditor.findPath(this.editor, node);
×
1315
            const voidMatch =
1316
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1317

1318
            // If starting a drag on a void node, make sure it is selected
1319
            // so that it shows up in the selection's fragment.
1320
            if (voidMatch) {
×
1321
                const range = Editor.range(this.editor, path);
×
1322
                Transforms.select(this.editor, range);
×
1323
            }
1324

1325
            this.isDraggingInternally = true;
×
1326

1327
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1328
        }
1329
    }
1330

1331
    private onDOMDrop(event: DragEvent) {
1332
        const editor = this.editor;
×
1333
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1334
            event.preventDefault();
×
1335
            // Keep a reference to the dragged range before updating selection
1336
            const draggedRange = editor.selection;
×
1337

1338
            // Find the range where the drop happened
1339
            const range = AngularEditor.findEventRange(editor, event);
×
1340
            const data = event.dataTransfer;
×
1341

1342
            Transforms.select(editor, range);
×
1343

1344
            if (this.isDraggingInternally) {
×
1345
                if (draggedRange) {
×
1346
                    Transforms.delete(editor, {
×
1347
                        at: draggedRange
1348
                    });
1349
                }
1350

1351
                this.isDraggingInternally = false;
×
1352
            }
1353

1354
            AngularEditor.insertData(editor, data);
×
1355

1356
            // When dragging from another source into the editor, it's possible
1357
            // that the current editor does not have focus.
1358
            if (!AngularEditor.isFocused(editor)) {
×
1359
                AngularEditor.focus(editor);
×
1360
            }
1361
        }
1362
    }
1363

1364
    private onDOMDragEnd(event: DragEvent) {
1365
        if (
×
1366
            !this.readonly &&
×
1367
            this.isDraggingInternally &&
1368
            AngularEditor.hasTarget(this.editor, event.target) &&
1369
            !this.isDOMEventHandled(event, this.dragEnd)
1370
        ) {
1371
            this.isDraggingInternally = false;
×
1372
        }
1373
    }
1374

1375
    private onDOMFocus(event: Event) {
1376
        if (
2✔
1377
            !this.readonly &&
8✔
1378
            !this.isUpdatingSelection &&
1379
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1380
            !this.isDOMEventHandled(event, this.focus)
1381
        ) {
1382
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1383
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1384
            this.latestElement = root.activeElement;
2✔
1385

1386
            // COMPAT: If the editor has nested editable elements, the focus
1387
            // can go to them. In Firefox, this must be prevented because it
1388
            // results in issues with keyboard navigation. (2017/03/30)
1389
            if (IS_FIREFOX && event.target !== el) {
2!
1390
                el.focus();
×
1391
                return;
×
1392
            }
1393

1394
            IS_FOCUSED.set(this.editor, true);
2✔
1395
        }
1396
    }
1397

1398
    private onDOMKeydown(event: KeyboardEvent) {
1399
        const editor = this.editor;
×
1400
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1401
        const { activeElement } = root;
×
1402
        if (
×
1403
            !this.readonly &&
×
1404
            AngularEditor.hasEditableTarget(editor, event.target) &&
1405
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1406
            !this.isComposing &&
1407
            !this.isDOMEventHandled(event, this.keydown)
1408
        ) {
1409
            const nativeEvent = event;
×
1410
            const { selection } = editor;
×
1411

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

1415
            try {
×
1416
                // COMPAT: Since we prevent the default behavior on
1417
                // `beforeinput` events, the browser doesn't think there's ever
1418
                // any history stack to undo or redo, so we have to manage these
1419
                // hotkeys ourselves. (2019/11/06)
1420
                if (Hotkeys.isRedo(nativeEvent)) {
×
1421
                    event.preventDefault();
×
1422

1423
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1424
                        editor.redo();
×
1425
                    }
1426

1427
                    return;
×
1428
                }
1429

1430
                if (Hotkeys.isUndo(nativeEvent)) {
×
1431
                    event.preventDefault();
×
1432

1433
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1434
                        editor.undo();
×
1435
                    }
1436

1437
                    return;
×
1438
                }
1439

1440
                // COMPAT: Certain browsers don't handle the selection updates
1441
                // properly. In Chrome, the selection isn't properly extended.
1442
                // And in Firefox, the selection isn't properly collapsed.
1443
                // (2017/10/17)
1444
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1445
                    event.preventDefault();
×
1446
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1447
                    return;
×
1448
                }
1449

1450
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1451
                    event.preventDefault();
×
1452
                    Transforms.move(editor, { unit: 'line' });
×
1453
                    return;
×
1454
                }
1455

1456
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1457
                    event.preventDefault();
×
1458
                    Transforms.move(editor, {
×
1459
                        unit: 'line',
1460
                        edge: 'focus',
1461
                        reverse: true
1462
                    });
1463
                    return;
×
1464
                }
1465

1466
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1467
                    event.preventDefault();
×
1468
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1469
                    return;
×
1470
                }
1471

1472
                // COMPAT: If a void node is selected, or a zero-width text node
1473
                // adjacent to an inline is selected, we need to handle these
1474
                // hotkeys manually because browsers won't be able to skip over
1475
                // the void node with the zero-width space not being an empty
1476
                // string.
1477
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1478
                    event.preventDefault();
×
1479

1480
                    if (selection && Range.isCollapsed(selection)) {
×
1481
                        Transforms.move(editor, { reverse: !isRTL });
×
1482
                    } else {
1483
                        Transforms.collapse(editor, { edge: 'start' });
×
1484
                    }
1485

1486
                    return;
×
1487
                }
1488

1489
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1490
                    event.preventDefault();
×
1491
                    if (selection && Range.isCollapsed(selection)) {
×
1492
                        Transforms.move(editor, { reverse: isRTL });
×
1493
                    } else {
1494
                        Transforms.collapse(editor, { edge: 'end' });
×
1495
                    }
1496

1497
                    return;
×
1498
                }
1499

1500
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1501
                    event.preventDefault();
×
1502

1503
                    if (selection && Range.isExpanded(selection)) {
×
1504
                        Transforms.collapse(editor, { edge: 'focus' });
×
1505
                    }
1506

1507
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1508
                    return;
×
1509
                }
1510

1511
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1512
                    event.preventDefault();
×
1513

1514
                    if (selection && Range.isExpanded(selection)) {
×
1515
                        Transforms.collapse(editor, { edge: 'focus' });
×
1516
                    }
1517

1518
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1519
                    return;
×
1520
                }
1521

1522
                if (isKeyHotkey('mod+a', event)) {
×
1523
                    this.editor.selectAll();
×
1524
                    event.preventDefault();
×
1525
                    return;
×
1526
                }
1527

1528
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1529
                // fall back to guessing at the input intention for hotkeys.
1530
                // COMPAT: In iOS, some of these hotkeys are handled in the
1531
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1532
                    // We don't have a core behavior for these, but they change the
1533
                    // DOM if we don't prevent them, so we have to.
1534
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1535
                        event.preventDefault();
×
1536
                        return;
×
1537
                    }
1538

1539
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1540
                        event.preventDefault();
×
1541
                        Editor.insertBreak(editor);
×
1542
                        return;
×
1543
                    }
1544

1545
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1546
                        event.preventDefault();
×
1547

1548
                        if (selection && Range.isExpanded(selection)) {
×
1549
                            Editor.deleteFragment(editor, {
×
1550
                                direction: 'backward'
1551
                            });
1552
                        } else {
1553
                            Editor.deleteBackward(editor);
×
1554
                        }
1555

1556
                        return;
×
1557
                    }
1558

1559
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1560
                        event.preventDefault();
×
1561

1562
                        if (selection && Range.isExpanded(selection)) {
×
1563
                            Editor.deleteFragment(editor, {
×
1564
                                direction: 'forward'
1565
                            });
1566
                        } else {
1567
                            Editor.deleteForward(editor);
×
1568
                        }
1569

1570
                        return;
×
1571
                    }
1572

1573
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1574
                        event.preventDefault();
×
1575

1576
                        if (selection && Range.isExpanded(selection)) {
×
1577
                            Editor.deleteFragment(editor, {
×
1578
                                direction: 'backward'
1579
                            });
1580
                        } else {
1581
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1582
                        }
1583

1584
                        return;
×
1585
                    }
1586

1587
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1588
                        event.preventDefault();
×
1589

1590
                        if (selection && Range.isExpanded(selection)) {
×
1591
                            Editor.deleteFragment(editor, {
×
1592
                                direction: 'forward'
1593
                            });
1594
                        } else {
1595
                            Editor.deleteForward(editor, { unit: 'line' });
×
1596
                        }
1597

1598
                        return;
×
1599
                    }
1600

1601
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1602
                        event.preventDefault();
×
1603

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

1612
                        return;
×
1613
                    }
1614

1615
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1616
                        event.preventDefault();
×
1617

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

1626
                        return;
×
1627
                    }
1628
                } else {
1629
                    if (IS_CHROME || IS_SAFARI) {
×
1630
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1631
                        // an event when deleting backwards in a selected void inline node
1632
                        if (
×
1633
                            selection &&
×
1634
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1635
                            Range.isCollapsed(selection)
1636
                        ) {
1637
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1638
                            if (
×
1639
                                Element.isElement(currentNode) &&
×
1640
                                Editor.isVoid(editor, currentNode) &&
1641
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1642
                            ) {
1643
                                event.preventDefault();
×
1644
                                Editor.deleteBackward(editor, {
×
1645
                                    unit: 'block'
1646
                                });
1647
                                return;
×
1648
                            }
1649
                        }
1650
                    }
1651
                }
1652
            } catch (error) {
1653
                this.editor.onError({
×
1654
                    code: SlateErrorCode.OnDOMKeydownError,
1655
                    nativeError: error
1656
                });
1657
            }
1658
        }
1659
    }
1660

1661
    private onDOMPaste(event: ClipboardEvent) {
1662
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1663
        // fall back to React's `onPaste` here instead.
1664
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1665
        // when "paste without formatting" option is used.
1666
        // This unfortunately needs to be handled with paste events instead.
1667
        if (
×
1668
            !this.isDOMEventHandled(event, this.paste) &&
×
1669
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1670
            !this.readonly &&
1671
            AngularEditor.hasEditableTarget(this.editor, event.target)
1672
        ) {
1673
            event.preventDefault();
×
1674
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1675
        }
1676
    }
1677

1678
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1679
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1680
        // fall back to React's leaky polyfill instead just for it. It
1681
        // only works for the `insertText` input type.
1682
        if (
×
1683
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1684
            !this.readonly &&
1685
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1686
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1687
        ) {
1688
            event.nativeEvent.preventDefault();
×
1689
            try {
×
1690
                const text = event.data;
×
1691
                if (!Range.isCollapsed(this.editor.selection)) {
×
1692
                    Editor.deleteFragment(this.editor);
×
1693
                }
1694
                // just handle Non-IME input
1695
                if (!this.isComposing) {
×
1696
                    Editor.insertText(this.editor, text);
×
1697
                }
1698
            } catch (error) {
1699
                this.editor.onError({
×
1700
                    code: SlateErrorCode.ToNativeSelectionError,
1701
                    nativeError: error
1702
                });
1703
            }
1704
        }
1705
    }
1706

1707
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1708
        if (!handler) {
3✔
1709
            return false;
3✔
1710
        }
1711
        handler(event);
×
1712
        return event.defaultPrevented;
×
1713
    }
1714
    //#endregion
1715

1716
    ngOnDestroy() {
1717
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1718
        this.manualListeners.forEach(manualListener => {
22✔
1719
            manualListener();
462✔
1720
        });
1721
        this.destroy$.complete();
22✔
1722
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1723
    }
1724
}
1725

1726
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1727
    // This was affecting the selection of multiple blocks and dragging behavior,
1728
    // so enabled only if the selection has been collapsed.
1729
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1730
        const leafEl = domRange.startContainer.parentElement!;
×
1731

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

1737
        if (isZeroDimensionRect) {
×
1738
            const leafRect = leafEl.getBoundingClientRect();
×
1739
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1740

1741
            if (leafHasDimensions) {
×
1742
                return;
×
1743
            }
1744
        }
1745

1746
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1747
        scrollIntoView(leafEl, {
×
1748
            scrollMode: 'if-needed'
1749
        });
1750
        delete leafEl.getBoundingClientRect;
×
1751
    }
1752
};
1753

1754
/**
1755
 * Check if the target is inside void and in the editor.
1756
 */
1757

1758
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1759
    let slateNode: Node | null = null;
1✔
1760
    try {
1✔
1761
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1762
    } catch (error) {}
1763
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1764
};
1765

1766
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1767
    return (
2✔
1768
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1769
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1770
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1771
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1772
    );
1773
};
1774

1775
/**
1776
 * remove default insert from composition
1777
 * @param text
1778
 */
1779
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1780
    const types = ['compositionend', 'insertFromComposition'];
×
1781
    if (!types.includes(event.type)) {
×
1782
        return;
×
1783
    }
1784
    const insertText = (event as CompositionEvent).data;
×
1785
    const window = AngularEditor.getWindow(editor);
×
1786
    const domSelection = window.getSelection();
×
1787
    // ensure text node insert composition input text
1788
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1789
        const textNode = domSelection.anchorNode;
×
1790
        textNode.splitText(textNode.length - insertText.length).remove();
×
1791
    }
1792
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc