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

worktile / slate-angular / 0465968b-d9a6-4449-ae63-83a7637890d3

07 Dec 2025 04:35PM UTC coverage: 43.377% (-0.3%) from 43.653%
0465968b-d9a6-4449-ae63-83a7637890d3

push

circleci

Xwatson
fix(virtual): fix scrolling lag

384 of 1122 branches covered (34.22%)

Branch coverage included in aggregate %.

1 of 36 new or added lines in 1 file covered. (2.78%)

1057 of 2200 relevant lines covered (48.05%)

29.59 hits per line

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

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

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

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

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

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

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

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

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

110
    private initialized: boolean;
111

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

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

116
    @Input() editor: AngularEditor;
117

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

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

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

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

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

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

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

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

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

136
    @Input() placeholder: string;
137

138
    @Input()
139
    set virtualScroll(config: SlateVirtualScrollConfig) {
140
        this.virtualConfig = config;
×
141
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
142
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
143
            let virtualView = this.refreshVirtualView();
×
144
            let diff = this.diffVirtualView(virtualView);
×
145
            if (!diff.isDiff) {
×
146
                return;
×
147
            }
148
            if (diff.isMissingTop) {
×
NEW
149
                const syncIndics = diff.diffTopRenderedIndexes.sort((a, b) => b - a).slice(0, 5);
×
NEW
150
                const result = syncIndics.length ? this.remeasureHeightByIndics(syncIndics) : false;
×
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
            }
163
            this.scheduleMeasureVisibleHeights();
×
164
        });
165
    }
166

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

185
    //#region DOM attr
186
    @Input() spellCheck = false;
23✔
187
    @Input() autoCorrect = false;
23✔
188
    @Input() autoCapitalize = false;
23✔
189

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

194
    get hasBeforeInputSupport() {
195
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
196
    }
197
    //#endregion
198

199
    viewContainerRef = inject(ViewContainerRef);
23✔
200

201
    getOutletParent = () => {
23✔
202
        return this.elementRef.nativeElement;
43✔
203
    };
204

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

213
    listRender: ListRender;
214

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

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

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

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

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

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

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

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

338
    toNativeSelection() {
339
        try {
15✔
340
            const { selection } = this.editor;
15✔
341
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
342
            const { activeElement } = root;
15✔
343
            const domSelection = (root as Document).getSelection();
15✔
344

345
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
346
                return;
14✔
347
            }
348

349
            const hasDomSelection = domSelection.type !== 'None';
1✔
350

351
            // If the DOM selection is properly unset, we're done.
352
            if (!selection && !hasDomSelection) {
1!
353
                return;
×
354
            }
355

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

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

375
            // prevent updating native selection when active element is void element
376
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
377
                return;
×
378
            }
379

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

389
            // Otherwise the DOM selection is out of sync, so update it.
390
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
391
            this.isUpdatingSelection = true;
1✔
392

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

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

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

429
                this.isUpdatingSelection = false;
1✔
430
            });
431
        } catch (error) {
432
            this.editor.onError({
×
433
                code: SlateErrorCode.ToNativeSelectionError,
434
                nativeError: error
435
            });
436
            this.isUpdatingSelection = false;
×
437
        }
438
    }
439

440
    onChange() {
441
        this.forceRender();
13✔
442
        this.onChangeCallback(this.editor.children);
13✔
443
    }
444

445
    ngAfterViewChecked() {}
446

447
    ngDoCheck() {}
448

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

491
    render() {
492
        const changed = this.updateContext();
2✔
493
        if (changed) {
2✔
494
            const virtualView = this.refreshVirtualView();
2✔
495
            this.applyVirtualView(virtualView);
2✔
496
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
497
            this.scheduleMeasureVisibleHeights();
2✔
498
        }
499
    }
500

501
    updateContext() {
502
        const decorations = this.generateDecorations();
17✔
503
        if (
17✔
504
            this.context.selection !== this.editor.selection ||
46✔
505
            this.context.decorate !== this.decorate ||
506
            this.context.readonly !== this.readonly ||
507
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
508
        ) {
509
            this.context = {
10✔
510
                parent: this.editor,
511
                selection: this.editor.selection,
512
                decorations: decorations,
513
                decorate: this.decorate,
514
                readonly: this.readonly
515
            };
516
            return true;
10✔
517
        }
518
        return false;
7✔
519
    }
520

521
    initializeContext() {
522
        this.context = {
49✔
523
            parent: this.editor,
524
            selection: this.editor.selection,
525
            decorations: this.generateDecorations(),
526
            decorate: this.decorate,
527
            readonly: this.readonly
528
        };
529
    }
530

531
    initializeViewContext() {
532
        this.viewContext = {
23✔
533
            editor: this.editor,
534
            renderElement: this.renderElement,
535
            renderLeaf: this.renderLeaf,
536
            renderText: this.renderText,
537
            trackBy: this.trackBy,
538
            isStrictDecorate: this.isStrictDecorate
539
        };
540
    }
541

542
    composePlaceholderDecorate(editor: Editor) {
543
        if (this.placeholderDecorate) {
64!
544
            return this.placeholderDecorate(editor) || [];
×
545
        }
546

547
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
548
            const start = Editor.start(editor, []);
3✔
549
            return [
3✔
550
                {
551
                    placeholder: this.placeholder,
552
                    anchor: start,
553
                    focus: start
554
                }
555
            ];
556
        } else {
557
            return [];
61✔
558
        }
559
    }
560

561
    generateDecorations() {
562
        const decorations = this.decorate([this.editor, []]);
66✔
563
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
564
        decorations.push(...placeholderDecorations);
66✔
565
        return decorations;
66✔
566
    }
567

568
    private shouldUseVirtual() {
569
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
570
    }
571

572
    // the height from scroll container top to editor top height element
573
    private businessHeight: number = 0;
23✔
574

575
    virtualScrollInitialized = false;
23✔
576

577
    virtualTopHeightElement: HTMLElement;
578

579
    virtualBottomHeightElement: HTMLElement;
580

581
    virtualCenterOutlet: HTMLElement;
582

583
    initializeVirtualScrolling() {
584
        if (this.virtualScrollInitialized) {
23!
585
            return;
×
586
        }
587
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
588
            this.virtualScrollInitialized = true;
×
589
            this.virtualTopHeightElement = document.createElement('div');
×
590
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
591
            this.virtualBottomHeightElement = document.createElement('div');
×
592
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
593
            this.virtualCenterOutlet = document.createElement('div');
×
594
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
595
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
596
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
597
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
598
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
599
        }
600
    }
601

602
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
603
        if (!this.virtualScrollInitialized) {
43✔
604
            return;
43✔
605
        }
606
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
607
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
608
    }
609

610
    private refreshVirtualView() {
611
        const children = (this.editor.children || []) as Element[];
43!
612
        if (!children.length || !this.shouldUseVirtual()) {
43✔
613
            return {
43✔
614
                renderedChildren: children,
615
                visibleIndexes: new Set<number>(),
616
                top: 0,
617
                bottom: 0,
618
                heights: []
619
            };
620
        }
621
        const scrollTop = this.virtualConfig.scrollTop;
×
622
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
623
        if (!viewportHeight) {
×
624
            return {
×
625
                renderedChildren: [],
626
                visibleIndexes: new Set<number>(),
627
                top: 0,
628
                bottom: 0,
629
                heights: []
630
            };
631
        }
632
        const elementLength = children.length;
×
633
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
NEW
634
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
NEW
635
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
NEW
636
        const totalHeight = accumulatedHeights[elementLength];
×
NEW
637
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
NEW
638
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
NEW
639
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
640
        let accumulatedOffset = 0;
×
641
        let visibleStartIndex = -1;
×
642
        const visible: Element[] = [];
×
643
        const visibleIndexes: number[] = [];
×
644

645
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
NEW
646
            const currentHeight = heights[i];
×
647
            const nextOffset = accumulatedOffset + currentHeight;
×
648
            // 可视区域有交集,加入渲染
NEW
649
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
650
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
651
                visible.push(children[i]);
×
652
                visibleIndexes.push(i);
×
653
            }
654
            accumulatedOffset = nextOffset;
×
655
        }
656

NEW
657
        if (visibleStartIndex === -1 && elementLength) {
×
NEW
658
            visibleStartIndex = elementLength - 1;
×
NEW
659
            visible.push(children[visibleStartIndex]);
×
NEW
660
            visibleIndexes.push(visibleStartIndex);
×
661
        }
662

663
        const visibleEndIndex =
NEW
664
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
665
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
NEW
666
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
667

668
        return {
×
669
            renderedChildren: visible.length ? visible : children,
×
670
            visibleIndexes: new Set(visibleIndexes),
671
            top,
672
            bottom,
673
            heights
674
        };
675
    }
676

677
    private applyVirtualView(virtualView: VirtualViewResult) {
678
        this.renderedChildren = virtualView.renderedChildren;
43✔
679
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
680
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
681
    }
682

683
    private diffVirtualView(virtualView: VirtualViewResult, stage: 'first' | 'second' = 'first') {
×
684
        if (!this.renderedChildren.length) {
×
685
            return {
×
686
                isDiff: true,
687
                diffTopRenderedIndexes: [],
688
                diffBottomRenderedIndexes: []
689
            };
690
        }
691
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
692
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
693
        const firstNewIndex = newVisibleIndexes[0];
×
694
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
695
        const firstOldIndex = oldVisibleIndexes[0];
×
696
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
697
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
698
            const diffTopRenderedIndexes = [];
×
699
            const diffBottomRenderedIndexes = [];
×
700
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
701
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
702
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
703
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
704
            if (isMissingTop || isAddedBottom) {
×
705
                // 向下
706
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
707
                    const element = oldVisibleIndexes[index];
×
708
                    if (!newVisibleIndexes.includes(element)) {
×
709
                        diffTopRenderedIndexes.push(element);
×
710
                    } else {
711
                        break;
×
712
                    }
713
                }
714
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
715
                    const element = newVisibleIndexes[index];
×
716
                    if (!oldVisibleIndexes.includes(element)) {
×
717
                        diffBottomRenderedIndexes.push(element);
×
718
                    } else {
719
                        break;
×
720
                    }
721
                }
722
            } else if (isAddedTop || isMissingBottom) {
×
723
                // 向上
724
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
725
                    const element = newVisibleIndexes[index];
×
726
                    if (!oldVisibleIndexes.includes(element)) {
×
727
                        diffTopRenderedIndexes.push(element);
×
728
                    } else {
729
                        break;
×
730
                    }
731
                }
732
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
733
                    const element = oldVisibleIndexes[index];
×
734
                    if (!newVisibleIndexes.includes(element)) {
×
735
                        diffBottomRenderedIndexes.push(element);
×
736
                    } else {
737
                        break;
×
738
                    }
739
                }
740
            }
741
            if (isDebug) {
×
742
                console.log(`====== diffVirtualView stage: ${stage} ======`);
×
743
                console.log('oldVisibleIndexes:', oldVisibleIndexes);
×
744
                console.log('newVisibleIndexes:', newVisibleIndexes);
×
745
                console.log(
×
746
                    'diffTopRenderedIndexes:',
747
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
748
                    diffTopRenderedIndexes,
749
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
750
                );
751
                console.log(
×
752
                    'diffBottomRenderedIndexes:',
753
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
754
                    diffBottomRenderedIndexes,
755
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
756
                );
757
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
758
                const needBottom = virtualView.heights
×
759
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
760
                    .reduce((acc, height) => acc + height, 0);
×
761
                console.log('newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
762
                console.log('newBottomHeight:', needBottom, 'prevBottomHeight:', parseFloat(this.virtualBottomHeightElement.style.height));
×
763
                console.warn('=========== Dividing line ===========');
×
764
            }
765
            return {
×
766
                isDiff: true,
767
                isMissingTop,
768
                isAddedTop,
769
                isMissingBottom,
770
                isAddedBottom,
771
                diffTopRenderedIndexes,
772
                diffBottomRenderedIndexes
773
            };
774
        }
775
        return {
×
776
            isDiff: false,
777
            diffTopRenderedIndexes: [],
778
            diffBottomRenderedIndexes: []
779
        };
780
    }
781

782
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
783
        const node = this.editor.children[index];
×
784
        if (!node) {
×
785
            return defaultHeight;
×
786
        }
787
        const key = AngularEditor.findKey(this.editor, node);
×
788
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
789
    }
790

791
    private buildAccumulatedHeight(heights: number[]) {
792
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
793
        for (let i = 0; i < heights.length; i++) {
×
794
            // 存储前 i 个的累计高度
795
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
796
        }
797
        return accumulatedHeights;
×
798
    }
799

800
    private scheduleMeasureVisibleHeights() {
801
        if (!this.shouldUseVirtual()) {
43✔
802
            return;
43✔
803
        }
804
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
805
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
806
            this.measureVisibleHeights();
×
807
        });
808
    }
809

810
    private measureVisibleHeights() {
811
        const children = (this.editor.children || []) as Element[];
×
812
        this.virtualVisibleIndexes.forEach(index => {
×
813
            const node = children[index];
×
814
            if (!node) {
×
815
                return;
×
816
            }
817
            const key = AngularEditor.findKey(this.editor, node);
×
818
            // 跳过已测过的块
819
            if (this.measuredHeights.has(key.id)) {
×
820
                return;
×
821
            }
822
            const view = ELEMENT_TO_COMPONENT.get(node);
×
823
            if (!view) {
×
824
                return;
×
825
            }
826
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
827
            if (ret instanceof Promise) {
×
828
                ret.then(height => {
×
829
                    this.measuredHeights.set(key.id, height);
×
830
                });
831
            } else {
832
                this.measuredHeights.set(key.id, ret);
×
833
            }
834
        });
835
    }
836

837
    private remeasureHeightByIndics(indics: number[]): boolean {
838
        const children = (this.editor.children || []) as Element[];
×
839
        let isHeightChanged = false;
×
840
        indics.forEach(index => {
×
841
            const node = children[index];
×
842
            if (!node) {
×
843
                return;
×
844
            }
845
            const key = AngularEditor.findKey(this.editor, node);
×
NEW
846
            const stableHeight = this.stableHiddenHeights.get(key.id);
×
NEW
847
            if (stableHeight !== undefined) {
×
NEW
848
                const prevHeight = this.measuredHeights.get(key.id);
×
NEW
849
                if (prevHeight !== stableHeight) {
×
NEW
850
                    this.measuredHeights.set(key.id, stableHeight);
×
NEW
851
                    isHeightChanged = true;
×
NEW
852
                    if (isDebug) {
×
NEW
853
                        console.log(
×
854
                            `remeasureHeightByIndics(stable), index: ${index} prevHeight: ${prevHeight} stableHeight: ${stableHeight}`
855
                        );
856
                    }
857
                }
NEW
858
                return;
×
859
            }
860
            const view = ELEMENT_TO_COMPONENT.get(node);
×
861
            if (!view) {
×
862
                return;
×
863
            }
NEW
864
            const slateView = view as BaseElementComponent | BaseElementFlavour;
×
865
            const prevHeight = this.measuredHeights.get(key.id);
×
NEW
866
            const ret = slateView.getRealHeight();
×
867
            if (ret instanceof Promise) {
×
868
                ret.then(height => {
×
869
                    if (height !== prevHeight) {
×
870
                        isHeightChanged = true;
×
871
                    }
NEW
872
                    this.measuredHeights.set(key.id, height);
×
NEW
873
                    this.stableHiddenHeights.set(key.id, height);
×
NEW
874
                    if (isDebug) {
×
NEW
875
                        console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
876
                    }
877
                });
878
            } else {
879
                if (ret !== prevHeight) {
×
880
                    isHeightChanged = true;
×
881
                }
NEW
882
                this.measuredHeights.set(key.id, ret);
×
NEW
883
                this.stableHiddenHeights.set(key.id, ret);
×
NEW
884
                if (isDebug) {
×
NEW
885
                    console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
886
                }
887
            }
888
        });
889
        return isHeightChanged;
×
890
    }
891

892
    //#region event proxy
893
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
894
        this.manualListeners.push(
483✔
895
            this.renderer2.listen(target, eventName, (event: Event) => {
896
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
897
                if (beforeInputEvent) {
5!
898
                    this.onFallbackBeforeInput(beforeInputEvent);
×
899
                }
900
                listener(event);
5✔
901
            })
902
        );
903
    }
904

905
    private toSlateSelection() {
906
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
907
            try {
1✔
908
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
909
                const { activeElement } = root;
1✔
910
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
911
                const domSelection = (root as Document).getSelection();
1✔
912

913
                if (activeElement === el) {
1!
914
                    this.latestElement = activeElement;
1✔
915
                    IS_FOCUSED.set(this.editor, true);
1✔
916
                } else {
917
                    IS_FOCUSED.delete(this.editor);
×
918
                }
919

920
                if (!domSelection) {
1!
921
                    return Transforms.deselect(this.editor);
×
922
                }
923

924
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
925
                const hasDomSelectionInEditor =
926
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
927
                if (!hasDomSelectionInEditor) {
1!
928
                    Transforms.deselect(this.editor);
×
929
                    return;
×
930
                }
931

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

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

1032
                // COMPAT: If the selection is expanded, even if the command seems like
1033
                // a delete forward/backward command it should delete the selection.
1034
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1035
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1036
                    Editor.deleteFragment(editor, { direction });
×
1037
                    return;
×
1038
                }
1039

1040
                switch (type) {
×
1041
                    case 'deleteByComposition':
1042
                    case 'deleteByCut':
1043
                    case 'deleteByDrag': {
1044
                        Editor.deleteFragment(editor);
×
1045
                        break;
×
1046
                    }
1047

1048
                    case 'deleteContent':
1049
                    case 'deleteContentForward': {
1050
                        Editor.deleteForward(editor);
×
1051
                        break;
×
1052
                    }
1053

1054
                    case 'deleteContentBackward': {
1055
                        Editor.deleteBackward(editor);
×
1056
                        break;
×
1057
                    }
1058

1059
                    case 'deleteEntireSoftLine': {
1060
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1061
                        Editor.deleteForward(editor, { unit: 'line' });
×
1062
                        break;
×
1063
                    }
1064

1065
                    case 'deleteHardLineBackward': {
1066
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1067
                        break;
×
1068
                    }
1069

1070
                    case 'deleteSoftLineBackward': {
1071
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1072
                        break;
×
1073
                    }
1074

1075
                    case 'deleteHardLineForward': {
1076
                        Editor.deleteForward(editor, { unit: 'block' });
×
1077
                        break;
×
1078
                    }
1079

1080
                    case 'deleteSoftLineForward': {
1081
                        Editor.deleteForward(editor, { unit: 'line' });
×
1082
                        break;
×
1083
                    }
1084

1085
                    case 'deleteWordBackward': {
1086
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1087
                        break;
×
1088
                    }
1089

1090
                    case 'deleteWordForward': {
1091
                        Editor.deleteForward(editor, { unit: 'word' });
×
1092
                        break;
×
1093
                    }
1094

1095
                    case 'insertLineBreak':
1096
                    case 'insertParagraph': {
1097
                        Editor.insertBreak(editor);
×
1098
                        break;
×
1099
                    }
1100

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

1136
    private onDOMBlur(event: FocusEvent) {
1137
        if (
×
1138
            this.readonly ||
×
1139
            this.isUpdatingSelection ||
1140
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1141
            this.isDOMEventHandled(event, this.blur)
1142
        ) {
1143
            return;
×
1144
        }
1145

1146
        const window = AngularEditor.getWindow(this.editor);
×
1147

1148
        // COMPAT: If the current `activeElement` is still the previous
1149
        // one, this is due to the window being blurred when the tab
1150
        // itself becomes unfocused, so we want to abort early to allow to
1151
        // editor to stay focused when the tab becomes focused again.
1152
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1153
        if (this.latestElement === root.activeElement) {
×
1154
            return;
×
1155
        }
1156

1157
        const { relatedTarget } = event;
×
1158
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1159

1160
        // COMPAT: The event should be ignored if the focus is returning
1161
        // to the editor from an embedded editable element (eg. an <input>
1162
        // element inside a void node).
1163
        if (relatedTarget === el) {
×
1164
            return;
×
1165
        }
1166

1167
        // COMPAT: The event should be ignored if the focus is moving from
1168
        // the editor to inside a void node's spacer element.
1169
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1170
            return;
×
1171
        }
1172

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

1179
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1180
                return;
×
1181
            }
1182
        }
1183

1184
        IS_FOCUSED.delete(this.editor);
×
1185
    }
1186

1187
    private onDOMClick(event: MouseEvent) {
1188
        if (
×
1189
            !this.readonly &&
×
1190
            AngularEditor.hasTarget(this.editor, event.target) &&
1191
            !this.isDOMEventHandled(event, this.click) &&
1192
            isDOMNode(event.target)
1193
        ) {
1194
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1195
            const path = AngularEditor.findPath(this.editor, node);
×
1196
            const start = Editor.start(this.editor, path);
×
1197
            const end = Editor.end(this.editor, path);
×
1198

1199
            const startVoid = Editor.void(this.editor, { at: start });
×
1200
            const endVoid = Editor.void(this.editor, { at: end });
×
1201

1202
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1203
                let blockPath = path;
×
1204
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1205
                    const block = Editor.above(this.editor, {
×
1206
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1207
                        at: path
1208
                    });
1209

1210
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1211
                }
1212

1213
                const range = Editor.range(this.editor, blockPath);
×
1214
                Transforms.select(this.editor, range);
×
1215
                return;
×
1216
            }
1217

1218
            if (
×
1219
                startVoid &&
×
1220
                endVoid &&
1221
                Path.equals(startVoid[1], endVoid[1]) &&
1222
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1223
            ) {
1224
                const range = Editor.range(this.editor, start);
×
1225
                Transforms.select(this.editor, range);
×
1226
            }
1227
        }
1228
    }
1229

1230
    private onDOMCompositionStart(event: CompositionEvent) {
1231
        const { selection } = this.editor;
1✔
1232
        if (selection) {
1!
1233
            // solve the problem of cross node Chinese input
1234
            if (Range.isExpanded(selection)) {
×
1235
                Editor.deleteFragment(this.editor);
×
1236
                this.forceRender();
×
1237
            }
1238
        }
1239
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1240
            this.isComposing = true;
1✔
1241
        }
1242
        this.render();
1✔
1243
    }
1244

1245
    private onDOMCompositionUpdate(event: CompositionEvent) {
1246
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1247
    }
1248

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

1263
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1264
            // so we need avoid repeat isnertText by isComposing === true,
1265
            this.isComposing = false;
×
1266
        }
1267
        this.render();
×
1268
    }
1269

1270
    private onDOMCopy(event: ClipboardEvent) {
1271
        const window = AngularEditor.getWindow(this.editor);
×
1272
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1273
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1274
            event.preventDefault();
×
1275
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1276
        }
1277
    }
1278

1279
    private onDOMCut(event: ClipboardEvent) {
1280
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1281
            event.preventDefault();
×
1282
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1283
            const { selection } = this.editor;
×
1284

1285
            if (selection) {
×
1286
                AngularEditor.deleteCutData(this.editor);
×
1287
            }
1288
        }
1289
    }
1290

1291
    private onDOMDragOver(event: DragEvent) {
1292
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1293
            // Only when the target is void, call `preventDefault` to signal
1294
            // that drops are allowed. Editable content is droppable by
1295
            // default, and calling `preventDefault` hides the cursor.
1296
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1297

1298
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1299
                event.preventDefault();
×
1300
            }
1301
        }
1302
    }
1303

1304
    private onDOMDragStart(event: DragEvent) {
1305
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1306
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1307
            const path = AngularEditor.findPath(this.editor, node);
×
1308
            const voidMatch =
1309
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1310

1311
            // If starting a drag on a void node, make sure it is selected
1312
            // so that it shows up in the selection's fragment.
1313
            if (voidMatch) {
×
1314
                const range = Editor.range(this.editor, path);
×
1315
                Transforms.select(this.editor, range);
×
1316
            }
1317

1318
            this.isDraggingInternally = true;
×
1319

1320
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1321
        }
1322
    }
1323

1324
    private onDOMDrop(event: DragEvent) {
1325
        const editor = this.editor;
×
1326
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1327
            event.preventDefault();
×
1328
            // Keep a reference to the dragged range before updating selection
1329
            const draggedRange = editor.selection;
×
1330

1331
            // Find the range where the drop happened
1332
            const range = AngularEditor.findEventRange(editor, event);
×
1333
            const data = event.dataTransfer;
×
1334

1335
            Transforms.select(editor, range);
×
1336

1337
            if (this.isDraggingInternally) {
×
1338
                if (draggedRange) {
×
1339
                    Transforms.delete(editor, {
×
1340
                        at: draggedRange
1341
                    });
1342
                }
1343

1344
                this.isDraggingInternally = false;
×
1345
            }
1346

1347
            AngularEditor.insertData(editor, data);
×
1348

1349
            // When dragging from another source into the editor, it's possible
1350
            // that the current editor does not have focus.
1351
            if (!AngularEditor.isFocused(editor)) {
×
1352
                AngularEditor.focus(editor);
×
1353
            }
1354
        }
1355
    }
1356

1357
    private onDOMDragEnd(event: DragEvent) {
1358
        if (
×
1359
            !this.readonly &&
×
1360
            this.isDraggingInternally &&
1361
            AngularEditor.hasTarget(this.editor, event.target) &&
1362
            !this.isDOMEventHandled(event, this.dragEnd)
1363
        ) {
1364
            this.isDraggingInternally = false;
×
1365
        }
1366
    }
1367

1368
    private onDOMFocus(event: Event) {
1369
        if (
2✔
1370
            !this.readonly &&
8✔
1371
            !this.isUpdatingSelection &&
1372
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1373
            !this.isDOMEventHandled(event, this.focus)
1374
        ) {
1375
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1376
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1377
            this.latestElement = root.activeElement;
2✔
1378

1379
            // COMPAT: If the editor has nested editable elements, the focus
1380
            // can go to them. In Firefox, this must be prevented because it
1381
            // results in issues with keyboard navigation. (2017/03/30)
1382
            if (IS_FIREFOX && event.target !== el) {
2!
1383
                el.focus();
×
1384
                return;
×
1385
            }
1386

1387
            IS_FOCUSED.set(this.editor, true);
2✔
1388
        }
1389
    }
1390

1391
    private onDOMKeydown(event: KeyboardEvent) {
1392
        const editor = this.editor;
×
1393
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1394
        const { activeElement } = root;
×
1395
        if (
×
1396
            !this.readonly &&
×
1397
            AngularEditor.hasEditableTarget(editor, event.target) &&
1398
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1399
            !this.isComposing &&
1400
            !this.isDOMEventHandled(event, this.keydown)
1401
        ) {
1402
            const nativeEvent = event;
×
1403
            const { selection } = editor;
×
1404

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

1408
            try {
×
1409
                // COMPAT: Since we prevent the default behavior on
1410
                // `beforeinput` events, the browser doesn't think there's ever
1411
                // any history stack to undo or redo, so we have to manage these
1412
                // hotkeys ourselves. (2019/11/06)
1413
                if (Hotkeys.isRedo(nativeEvent)) {
×
1414
                    event.preventDefault();
×
1415

1416
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1417
                        editor.redo();
×
1418
                    }
1419

1420
                    return;
×
1421
                }
1422

1423
                if (Hotkeys.isUndo(nativeEvent)) {
×
1424
                    event.preventDefault();
×
1425

1426
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1427
                        editor.undo();
×
1428
                    }
1429

1430
                    return;
×
1431
                }
1432

1433
                // COMPAT: Certain browsers don't handle the selection updates
1434
                // properly. In Chrome, the selection isn't properly extended.
1435
                // And in Firefox, the selection isn't properly collapsed.
1436
                // (2017/10/17)
1437
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1438
                    event.preventDefault();
×
1439
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1440
                    return;
×
1441
                }
1442

1443
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1444
                    event.preventDefault();
×
1445
                    Transforms.move(editor, { unit: 'line' });
×
1446
                    return;
×
1447
                }
1448

1449
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1450
                    event.preventDefault();
×
1451
                    Transforms.move(editor, {
×
1452
                        unit: 'line',
1453
                        edge: 'focus',
1454
                        reverse: true
1455
                    });
1456
                    return;
×
1457
                }
1458

1459
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1460
                    event.preventDefault();
×
1461
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1462
                    return;
×
1463
                }
1464

1465
                // COMPAT: If a void node is selected, or a zero-width text node
1466
                // adjacent to an inline is selected, we need to handle these
1467
                // hotkeys manually because browsers won't be able to skip over
1468
                // the void node with the zero-width space not being an empty
1469
                // string.
1470
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1471
                    event.preventDefault();
×
1472

1473
                    if (selection && Range.isCollapsed(selection)) {
×
1474
                        Transforms.move(editor, { reverse: !isRTL });
×
1475
                    } else {
1476
                        Transforms.collapse(editor, { edge: 'start' });
×
1477
                    }
1478

1479
                    return;
×
1480
                }
1481

1482
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1483
                    event.preventDefault();
×
1484
                    if (selection && Range.isCollapsed(selection)) {
×
1485
                        Transforms.move(editor, { reverse: isRTL });
×
1486
                    } else {
1487
                        Transforms.collapse(editor, { edge: 'end' });
×
1488
                    }
1489

1490
                    return;
×
1491
                }
1492

1493
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1494
                    event.preventDefault();
×
1495

1496
                    if (selection && Range.isExpanded(selection)) {
×
1497
                        Transforms.collapse(editor, { edge: 'focus' });
×
1498
                    }
1499

1500
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1501
                    return;
×
1502
                }
1503

1504
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1505
                    event.preventDefault();
×
1506

1507
                    if (selection && Range.isExpanded(selection)) {
×
1508
                        Transforms.collapse(editor, { edge: 'focus' });
×
1509
                    }
1510

1511
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1512
                    return;
×
1513
                }
1514

1515
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1516
                // fall back to guessing at the input intention for hotkeys.
1517
                // COMPAT: In iOS, some of these hotkeys are handled in the
1518
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1519
                    // We don't have a core behavior for these, but they change the
1520
                    // DOM if we don't prevent them, so we have to.
1521
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1522
                        event.preventDefault();
×
1523
                        return;
×
1524
                    }
1525

1526
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1527
                        event.preventDefault();
×
1528
                        Editor.insertBreak(editor);
×
1529
                        return;
×
1530
                    }
1531

1532
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1533
                        event.preventDefault();
×
1534

1535
                        if (selection && Range.isExpanded(selection)) {
×
1536
                            Editor.deleteFragment(editor, {
×
1537
                                direction: 'backward'
1538
                            });
1539
                        } else {
1540
                            Editor.deleteBackward(editor);
×
1541
                        }
1542

1543
                        return;
×
1544
                    }
1545

1546
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1547
                        event.preventDefault();
×
1548

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

1557
                        return;
×
1558
                    }
1559

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

1563
                        if (selection && Range.isExpanded(selection)) {
×
1564
                            Editor.deleteFragment(editor, {
×
1565
                                direction: 'backward'
1566
                            });
1567
                        } else {
1568
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1569
                        }
1570

1571
                        return;
×
1572
                    }
1573

1574
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1575
                        event.preventDefault();
×
1576

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

1585
                        return;
×
1586
                    }
1587

1588
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1589
                        event.preventDefault();
×
1590

1591
                        if (selection && Range.isExpanded(selection)) {
×
1592
                            Editor.deleteFragment(editor, {
×
1593
                                direction: 'backward'
1594
                            });
1595
                        } else {
1596
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1597
                        }
1598

1599
                        return;
×
1600
                    }
1601

1602
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1603
                        event.preventDefault();
×
1604

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

1613
                        return;
×
1614
                    }
1615
                } else {
1616
                    if (IS_CHROME || IS_SAFARI) {
×
1617
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1618
                        // an event when deleting backwards in a selected void inline node
1619
                        if (
×
1620
                            selection &&
×
1621
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1622
                            Range.isCollapsed(selection)
1623
                        ) {
1624
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1625
                            if (
×
1626
                                Element.isElement(currentNode) &&
×
1627
                                Editor.isVoid(editor, currentNode) &&
1628
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1629
                            ) {
1630
                                event.preventDefault();
×
1631
                                Editor.deleteBackward(editor, {
×
1632
                                    unit: 'block'
1633
                                });
1634
                                return;
×
1635
                            }
1636
                        }
1637
                    }
1638
                }
1639
            } catch (error) {
1640
                this.editor.onError({
×
1641
                    code: SlateErrorCode.OnDOMKeydownError,
1642
                    nativeError: error
1643
                });
1644
            }
1645
        }
1646
    }
1647

1648
    private onDOMPaste(event: ClipboardEvent) {
1649
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1650
        // fall back to React's `onPaste` here instead.
1651
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1652
        // when "paste without formatting" option is used.
1653
        // This unfortunately needs to be handled with paste events instead.
1654
        if (
×
1655
            !this.isDOMEventHandled(event, this.paste) &&
×
1656
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1657
            !this.readonly &&
1658
            AngularEditor.hasEditableTarget(this.editor, event.target)
1659
        ) {
1660
            event.preventDefault();
×
1661
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1662
        }
1663
    }
1664

1665
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1666
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1667
        // fall back to React's leaky polyfill instead just for it. It
1668
        // only works for the `insertText` input type.
1669
        if (
×
1670
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1671
            !this.readonly &&
1672
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1673
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1674
        ) {
1675
            event.nativeEvent.preventDefault();
×
1676
            try {
×
1677
                const text = event.data;
×
1678
                if (!Range.isCollapsed(this.editor.selection)) {
×
1679
                    Editor.deleteFragment(this.editor);
×
1680
                }
1681
                // just handle Non-IME input
1682
                if (!this.isComposing) {
×
1683
                    Editor.insertText(this.editor, text);
×
1684
                }
1685
            } catch (error) {
1686
                this.editor.onError({
×
1687
                    code: SlateErrorCode.ToNativeSelectionError,
1688
                    nativeError: error
1689
                });
1690
            }
1691
        }
1692
    }
1693

1694
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1695
        if (!handler) {
3✔
1696
            return false;
3✔
1697
        }
1698
        handler(event);
×
1699
        return event.defaultPrevented;
×
1700
    }
1701
    //#endregion
1702

1703
    ngOnDestroy() {
1704
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1705
        this.manualListeners.forEach(manualListener => {
23✔
1706
            manualListener();
483✔
1707
        });
1708
        this.destroy$.complete();
23✔
1709
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1710
    }
1711
}
1712

1713
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1714
    // This was affecting the selection of multiple blocks and dragging behavior,
1715
    // so enabled only if the selection has been collapsed.
1716
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1717
        const leafEl = domRange.startContainer.parentElement!;
×
1718

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

1724
        if (isZeroDimensionRect) {
×
1725
            const leafRect = leafEl.getBoundingClientRect();
×
1726
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1727

1728
            if (leafHasDimensions) {
×
1729
                return;
×
1730
            }
1731
        }
1732

1733
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1734
        scrollIntoView(leafEl, {
×
1735
            scrollMode: 'if-needed'
1736
        });
1737
        delete leafEl.getBoundingClientRect;
×
1738
    }
1739
};
1740

1741
/**
1742
 * Check if the target is inside void and in the editor.
1743
 */
1744

1745
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1746
    let slateNode: Node | null = null;
1✔
1747
    try {
1✔
1748
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1749
    } catch (error) {}
1750
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1751
};
1752

1753
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1754
    return (
2✔
1755
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1756
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1757
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1758
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1759
    );
1760
};
1761

1762
/**
1763
 * remove default insert from composition
1764
 * @param text
1765
 */
1766
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1767
    const types = ['compositionend', 'insertFromComposition'];
×
1768
    if (!types.includes(event.type)) {
×
1769
        return;
×
1770
    }
1771
    const insertText = (event as CompositionEvent).data;
×
1772
    const window = AngularEditor.getWindow(editor);
×
1773
    const domSelection = window.getSelection();
×
1774
    // ensure text node insert composition input text
1775
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1776
        const textNode = domSelection.anchorNode;
×
1777
        textNode.splitText(textNode.length - insertText.length).remove();
×
1778
    }
1779
};
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