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

worktile / slate-angular / 3d08e0d4-b6fc-4d7f-80b0-eb862f93633d

05 Dec 2025 07:59AM UTC coverage: 43.676% (-0.1%) from 43.815%
3d08e0d4-b6fc-4d7f-80b0-eb862f93633d

push

circleci

pubuzhixing8
feat(virtual-scroll): getRealHeight support both number and promise return type
remeasureHeightByIndics changed to sync method and improve logs

384 of 1108 branches covered (34.66%)

Branch coverage included in aggregate %.

2 of 52 new or added lines in 3 files covered. (3.85%)

1 existing line in 1 file now uncovered.

1056 of 2189 relevant lines covered (48.24%)

29.71 hits per line

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

26.13
/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(() => {
×
NEW
143
            let virtualView = this.refreshVirtualView();
×
NEW
144
            let diff = this.diffVirtualView(virtualView);
×
NEW
145
            if (!diff.isDiff) {
×
NEW
146
                return;
×
147
            }
NEW
148
            if (diff.isMissingTop) {
×
NEW
149
                const result = this.remeasureHeightByIndics([...diff.diffTopRenderedIndexes]);
×
NEW
150
                if (result) {
×
NEW
151
                    virtualView = this.refreshVirtualView();
×
NEW
152
                    diff = this.diffVirtualView(virtualView, 'second');
×
NEW
153
                    if (!diff.isDiff) {
×
NEW
154
                        return;
×
155
                    }
156
                }
157
            }
NEW
158
            this.applyVirtualView(virtualView);
×
NEW
159
            if (this.listRender.initialized) {
×
NEW
160
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
161
            }
NEW
162
            this.scheduleMeasureVisibleHeights();
×
163
        });
164
    }
165

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

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

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

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

198
    viewContainerRef = inject(ViewContainerRef);
23✔
199

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

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

212
    listRender: ListRender;
213

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

444
    ngAfterViewChecked() {}
445

446
    ngDoCheck() {}
447

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

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

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

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

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

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

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

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

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

571
    virtualScrollInitialized = false;
23✔
572

573
    virtualTopHeightElement: HTMLElement;
574

575
    virtualBottomHeightElement: HTMLElement;
576

577
    virtualCenterOutlet: HTMLElement;
578

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

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

606
    private refreshVirtualView() {
607
        const children = (this.editor.children || []) as Element[];
43!
608
        if (!children.length || !this.shouldUseVirtual()) {
43✔
609
            return {
43✔
610
                renderedChildren: children,
611
                visibleIndexes: new Set<number>(),
612
                top: 0,
613
                bottom: 0,
614
                heights: []
615
            };
616
        }
617
        const scrollTop = this.virtualConfig.scrollTop ?? 0;
×
618
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
619
        if (!viewportHeight) {
×
620
            // 已经启用虚拟滚动,但可视区域高度还未获取到,先置空不渲染
621
            return {
×
622
                renderedChildren: [],
623
                visibleIndexes: new Set<number>(),
624
                top: 0,
625
                bottom: 0,
626
                heights: []
627
            };
628
        }
629
        const bufferCount = this.virtualConfig.bufferCount ?? VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT;
×
630
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
631
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
632

633
        let visibleStart = 0;
×
634
        // 按真实或估算高度往后累加,找到滚动起点所在块
635
        while (visibleStart < heights.length && accumulatedHeights[visibleStart + 1] <= scrollTop) {
×
636
            visibleStart++;
×
637
        }
638

639
        // 向上预留 bufferCount 块
640
        const startIndex = Math.max(0, visibleStart - bufferCount);
×
641
        const top = accumulatedHeights[startIndex];
×
642
        const bufferBelowHeight = this.getBufferBelowHeight(viewportHeight, visibleStart, bufferCount);
×
643
        const targetHeight = accumulatedHeights[visibleStart] - top + viewportHeight + bufferBelowHeight;
×
644

645
        const visible: Element[] = [];
×
646
        const visibleIndexes: number[] = [];
×
647
        let accumulated = 0;
×
648
        let cursor = startIndex;
×
649
        // 循环累计高度超出目标高度(可视高度 + 上下 buffer)
650
        while (cursor < children.length && accumulated < targetHeight) {
×
651
            visible.push(children[cursor]);
×
652
            visibleIndexes.push(cursor);
×
653
            accumulated += this.getBlockHeight(cursor);
×
654
            cursor++;
×
655
        }
656
        const bottom = heights.slice(cursor).reduce((acc, height) => acc + height, 0);
×
657
        const renderedChildren = visible.length ? visible : children;
×
658
        const visibleIndexesSet = new Set(visibleIndexes);
×
659
        return {
×
660
            renderedChildren,
661
            visibleIndexes: visibleIndexesSet,
662
            top,
663
            bottom,
664
            heights
665
        };
666
    }
667

668
    private applyVirtualView(virtualView: VirtualViewResult) {
669
        this.renderedChildren = virtualView.renderedChildren;
43✔
670
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
671
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
672
    }
673

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

773
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
774
        const node = this.editor.children[index];
×
775
        if (!node) {
×
776
            return defaultHeight;
×
777
        }
778
        const key = AngularEditor.findKey(this.editor, node);
×
779
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
780
    }
781

782
    private buildAccumulatedHeight(heights: number[]) {
783
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
784
        for (let i = 0; i < heights.length; i++) {
×
785
            // 存储前 i 个的累计高度
786
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
787
        }
788
        return accumulatedHeights;
×
789
    }
790

791
    private getBufferBelowHeight(viewportHeight: number, visibleStart: number, bufferCount: number) {
792
        let blockHeight = 0;
×
793
        let start = visibleStart;
×
794
        // 循环累计高度超出视图高度代表找到向下缓冲区的起始位置
795
        while (blockHeight < viewportHeight) {
×
796
            blockHeight += this.getBlockHeight(start);
×
797
            start++;
×
798
        }
799
        let bufferHeight = 0;
×
800
        for (let i = start; i < start + bufferCount; i++) {
×
801
            bufferHeight += this.getBlockHeight(i);
×
802
        }
803
        return bufferHeight;
×
804
    }
805

806
    private scheduleMeasureVisibleHeights() {
807
        if (!this.shouldUseVirtual()) {
43✔
808
            return;
43✔
809
        }
810
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
811
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
812
            this.measureVisibleHeights();
×
813
        });
814
    }
815

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

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

881
    //#region event proxy
882
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
883
        this.manualListeners.push(
483✔
884
            this.renderer2.listen(target, eventName, (event: Event) => {
885
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
886
                if (beforeInputEvent) {
5!
887
                    this.onFallbackBeforeInput(beforeInputEvent);
×
888
                }
889
                listener(event);
5✔
890
            })
891
        );
892
    }
893

894
    private toSlateSelection() {
895
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
896
            try {
1✔
897
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
898
                const { activeElement } = root;
1✔
899
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
900
                const domSelection = (root as Document).getSelection();
1✔
901

902
                if (activeElement === el) {
1!
903
                    this.latestElement = activeElement;
1✔
904
                    IS_FOCUSED.set(this.editor, true);
1✔
905
                } else {
906
                    IS_FOCUSED.delete(this.editor);
×
907
                }
908

909
                if (!domSelection) {
1!
910
                    return Transforms.deselect(this.editor);
×
911
                }
912

913
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
914
                const hasDomSelectionInEditor =
915
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
916
                if (!hasDomSelectionInEditor) {
1!
917
                    Transforms.deselect(this.editor);
×
918
                    return;
×
919
                }
920

921
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
922
                // for example, double-click the last cell of the table to select a non-editable DOM
923
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
924
                if (range) {
1✔
925
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
926
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
927
                            // force adjust DOMSelection
928
                            this.toNativeSelection();
×
929
                        }
930
                    } else {
931
                        Transforms.select(this.editor, range);
1✔
932
                    }
933
                }
934
            } catch (error) {
935
                this.editor.onError({
×
936
                    code: SlateErrorCode.ToSlateSelectionError,
937
                    nativeError: error
938
                });
939
            }
940
        }
941
    }
942

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

1021
                // COMPAT: If the selection is expanded, even if the command seems like
1022
                // a delete forward/backward command it should delete the selection.
1023
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1024
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1025
                    Editor.deleteFragment(editor, { direction });
×
1026
                    return;
×
1027
                }
1028

1029
                switch (type) {
×
1030
                    case 'deleteByComposition':
1031
                    case 'deleteByCut':
1032
                    case 'deleteByDrag': {
1033
                        Editor.deleteFragment(editor);
×
1034
                        break;
×
1035
                    }
1036

1037
                    case 'deleteContent':
1038
                    case 'deleteContentForward': {
1039
                        Editor.deleteForward(editor);
×
1040
                        break;
×
1041
                    }
1042

1043
                    case 'deleteContentBackward': {
1044
                        Editor.deleteBackward(editor);
×
1045
                        break;
×
1046
                    }
1047

1048
                    case 'deleteEntireSoftLine': {
1049
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1050
                        Editor.deleteForward(editor, { unit: 'line' });
×
1051
                        break;
×
1052
                    }
1053

1054
                    case 'deleteHardLineBackward': {
1055
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1056
                        break;
×
1057
                    }
1058

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

1064
                    case 'deleteHardLineForward': {
1065
                        Editor.deleteForward(editor, { unit: 'block' });
×
1066
                        break;
×
1067
                    }
1068

1069
                    case 'deleteSoftLineForward': {
1070
                        Editor.deleteForward(editor, { unit: 'line' });
×
1071
                        break;
×
1072
                    }
1073

1074
                    case 'deleteWordBackward': {
1075
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1076
                        break;
×
1077
                    }
1078

1079
                    case 'deleteWordForward': {
1080
                        Editor.deleteForward(editor, { unit: 'word' });
×
1081
                        break;
×
1082
                    }
1083

1084
                    case 'insertLineBreak':
1085
                    case 'insertParagraph': {
1086
                        Editor.insertBreak(editor);
×
1087
                        break;
×
1088
                    }
1089

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

1125
    private onDOMBlur(event: FocusEvent) {
1126
        if (
×
1127
            this.readonly ||
×
1128
            this.isUpdatingSelection ||
1129
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1130
            this.isDOMEventHandled(event, this.blur)
1131
        ) {
1132
            return;
×
1133
        }
1134

1135
        const window = AngularEditor.getWindow(this.editor);
×
1136

1137
        // COMPAT: If the current `activeElement` is still the previous
1138
        // one, this is due to the window being blurred when the tab
1139
        // itself becomes unfocused, so we want to abort early to allow to
1140
        // editor to stay focused when the tab becomes focused again.
1141
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1142
        if (this.latestElement === root.activeElement) {
×
1143
            return;
×
1144
        }
1145

1146
        const { relatedTarget } = event;
×
1147
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1148

1149
        // COMPAT: The event should be ignored if the focus is returning
1150
        // to the editor from an embedded editable element (eg. an <input>
1151
        // element inside a void node).
1152
        if (relatedTarget === el) {
×
1153
            return;
×
1154
        }
1155

1156
        // COMPAT: The event should be ignored if the focus is moving from
1157
        // the editor to inside a void node's spacer element.
1158
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1159
            return;
×
1160
        }
1161

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

1168
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1169
                return;
×
1170
            }
1171
        }
1172

1173
        IS_FOCUSED.delete(this.editor);
×
1174
    }
1175

1176
    private onDOMClick(event: MouseEvent) {
1177
        if (
×
1178
            !this.readonly &&
×
1179
            AngularEditor.hasTarget(this.editor, event.target) &&
1180
            !this.isDOMEventHandled(event, this.click) &&
1181
            isDOMNode(event.target)
1182
        ) {
1183
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1184
            const path = AngularEditor.findPath(this.editor, node);
×
1185
            const start = Editor.start(this.editor, path);
×
1186
            const end = Editor.end(this.editor, path);
×
1187

1188
            const startVoid = Editor.void(this.editor, { at: start });
×
1189
            const endVoid = Editor.void(this.editor, { at: end });
×
1190

1191
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1192
                let blockPath = path;
×
1193
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1194
                    const block = Editor.above(this.editor, {
×
1195
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1196
                        at: path
1197
                    });
1198

1199
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1200
                }
1201

1202
                const range = Editor.range(this.editor, blockPath);
×
1203
                Transforms.select(this.editor, range);
×
1204
                return;
×
1205
            }
1206

1207
            if (
×
1208
                startVoid &&
×
1209
                endVoid &&
1210
                Path.equals(startVoid[1], endVoid[1]) &&
1211
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1212
            ) {
1213
                const range = Editor.range(this.editor, start);
×
1214
                Transforms.select(this.editor, range);
×
1215
            }
1216
        }
1217
    }
1218

1219
    private onDOMCompositionStart(event: CompositionEvent) {
1220
        const { selection } = this.editor;
1✔
1221
        if (selection) {
1!
1222
            // solve the problem of cross node Chinese input
1223
            if (Range.isExpanded(selection)) {
×
1224
                Editor.deleteFragment(this.editor);
×
1225
                this.forceRender();
×
1226
            }
1227
        }
1228
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1229
            this.isComposing = true;
1✔
1230
        }
1231
        this.render();
1✔
1232
    }
1233

1234
    private onDOMCompositionUpdate(event: CompositionEvent) {
1235
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1236
    }
1237

1238
    private onDOMCompositionEnd(event: CompositionEvent) {
1239
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1240
            Transforms.delete(this.editor);
×
1241
        }
1242
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1243
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1244
            // aren't correct and never fire the "insertFromComposition"
1245
            // type that we need. So instead, insert whenever a composition
1246
            // ends since it will already have been committed to the DOM.
1247
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1248
                preventInsertFromComposition(event, this.editor);
×
1249
                Editor.insertText(this.editor, event.data);
×
1250
            }
1251

1252
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1253
            // so we need avoid repeat isnertText by isComposing === true,
1254
            this.isComposing = false;
×
1255
        }
1256
        this.render();
×
1257
    }
1258

1259
    private onDOMCopy(event: ClipboardEvent) {
1260
        const window = AngularEditor.getWindow(this.editor);
×
1261
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1262
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1263
            event.preventDefault();
×
1264
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1265
        }
1266
    }
1267

1268
    private onDOMCut(event: ClipboardEvent) {
1269
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1270
            event.preventDefault();
×
1271
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1272
            const { selection } = this.editor;
×
1273

1274
            if (selection) {
×
1275
                AngularEditor.deleteCutData(this.editor);
×
1276
            }
1277
        }
1278
    }
1279

1280
    private onDOMDragOver(event: DragEvent) {
1281
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1282
            // Only when the target is void, call `preventDefault` to signal
1283
            // that drops are allowed. Editable content is droppable by
1284
            // default, and calling `preventDefault` hides the cursor.
1285
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1286

1287
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1288
                event.preventDefault();
×
1289
            }
1290
        }
1291
    }
1292

1293
    private onDOMDragStart(event: DragEvent) {
1294
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1295
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1296
            const path = AngularEditor.findPath(this.editor, node);
×
1297
            const voidMatch =
1298
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1299

1300
            // If starting a drag on a void node, make sure it is selected
1301
            // so that it shows up in the selection's fragment.
1302
            if (voidMatch) {
×
1303
                const range = Editor.range(this.editor, path);
×
1304
                Transforms.select(this.editor, range);
×
1305
            }
1306

1307
            this.isDraggingInternally = true;
×
1308

1309
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1310
        }
1311
    }
1312

1313
    private onDOMDrop(event: DragEvent) {
1314
        const editor = this.editor;
×
1315
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1316
            event.preventDefault();
×
1317
            // Keep a reference to the dragged range before updating selection
1318
            const draggedRange = editor.selection;
×
1319

1320
            // Find the range where the drop happened
1321
            const range = AngularEditor.findEventRange(editor, event);
×
1322
            const data = event.dataTransfer;
×
1323

1324
            Transforms.select(editor, range);
×
1325

1326
            if (this.isDraggingInternally) {
×
1327
                if (draggedRange) {
×
1328
                    Transforms.delete(editor, {
×
1329
                        at: draggedRange
1330
                    });
1331
                }
1332

1333
                this.isDraggingInternally = false;
×
1334
            }
1335

1336
            AngularEditor.insertData(editor, data);
×
1337

1338
            // When dragging from another source into the editor, it's possible
1339
            // that the current editor does not have focus.
1340
            if (!AngularEditor.isFocused(editor)) {
×
1341
                AngularEditor.focus(editor);
×
1342
            }
1343
        }
1344
    }
1345

1346
    private onDOMDragEnd(event: DragEvent) {
1347
        if (
×
1348
            !this.readonly &&
×
1349
            this.isDraggingInternally &&
1350
            AngularEditor.hasTarget(this.editor, event.target) &&
1351
            !this.isDOMEventHandled(event, this.dragEnd)
1352
        ) {
1353
            this.isDraggingInternally = false;
×
1354
        }
1355
    }
1356

1357
    private onDOMFocus(event: Event) {
1358
        if (
2✔
1359
            !this.readonly &&
8✔
1360
            !this.isUpdatingSelection &&
1361
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1362
            !this.isDOMEventHandled(event, this.focus)
1363
        ) {
1364
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1365
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1366
            this.latestElement = root.activeElement;
2✔
1367

1368
            // COMPAT: If the editor has nested editable elements, the focus
1369
            // can go to them. In Firefox, this must be prevented because it
1370
            // results in issues with keyboard navigation. (2017/03/30)
1371
            if (IS_FIREFOX && event.target !== el) {
2!
1372
                el.focus();
×
1373
                return;
×
1374
            }
1375

1376
            IS_FOCUSED.set(this.editor, true);
2✔
1377
        }
1378
    }
1379

1380
    private onDOMKeydown(event: KeyboardEvent) {
1381
        const editor = this.editor;
×
1382
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1383
        const { activeElement } = root;
×
1384
        if (
×
1385
            !this.readonly &&
×
1386
            AngularEditor.hasEditableTarget(editor, event.target) &&
1387
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1388
            !this.isComposing &&
1389
            !this.isDOMEventHandled(event, this.keydown)
1390
        ) {
1391
            const nativeEvent = event;
×
1392
            const { selection } = editor;
×
1393

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

1397
            try {
×
1398
                // COMPAT: Since we prevent the default behavior on
1399
                // `beforeinput` events, the browser doesn't think there's ever
1400
                // any history stack to undo or redo, so we have to manage these
1401
                // hotkeys ourselves. (2019/11/06)
1402
                if (Hotkeys.isRedo(nativeEvent)) {
×
1403
                    event.preventDefault();
×
1404

1405
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1406
                        editor.redo();
×
1407
                    }
1408

1409
                    return;
×
1410
                }
1411

1412
                if (Hotkeys.isUndo(nativeEvent)) {
×
1413
                    event.preventDefault();
×
1414

1415
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1416
                        editor.undo();
×
1417
                    }
1418

1419
                    return;
×
1420
                }
1421

1422
                // COMPAT: Certain browsers don't handle the selection updates
1423
                // properly. In Chrome, the selection isn't properly extended.
1424
                // And in Firefox, the selection isn't properly collapsed.
1425
                // (2017/10/17)
1426
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1427
                    event.preventDefault();
×
1428
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1429
                    return;
×
1430
                }
1431

1432
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1433
                    event.preventDefault();
×
1434
                    Transforms.move(editor, { unit: 'line' });
×
1435
                    return;
×
1436
                }
1437

1438
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1439
                    event.preventDefault();
×
1440
                    Transforms.move(editor, {
×
1441
                        unit: 'line',
1442
                        edge: 'focus',
1443
                        reverse: true
1444
                    });
1445
                    return;
×
1446
                }
1447

1448
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1449
                    event.preventDefault();
×
1450
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1451
                    return;
×
1452
                }
1453

1454
                // COMPAT: If a void node is selected, or a zero-width text node
1455
                // adjacent to an inline is selected, we need to handle these
1456
                // hotkeys manually because browsers won't be able to skip over
1457
                // the void node with the zero-width space not being an empty
1458
                // string.
1459
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1460
                    event.preventDefault();
×
1461

1462
                    if (selection && Range.isCollapsed(selection)) {
×
1463
                        Transforms.move(editor, { reverse: !isRTL });
×
1464
                    } else {
1465
                        Transforms.collapse(editor, { edge: 'start' });
×
1466
                    }
1467

1468
                    return;
×
1469
                }
1470

1471
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1472
                    event.preventDefault();
×
1473
                    if (selection && Range.isCollapsed(selection)) {
×
1474
                        Transforms.move(editor, { reverse: isRTL });
×
1475
                    } else {
1476
                        Transforms.collapse(editor, { edge: 'end' });
×
1477
                    }
1478

1479
                    return;
×
1480
                }
1481

1482
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1483
                    event.preventDefault();
×
1484

1485
                    if (selection && Range.isExpanded(selection)) {
×
1486
                        Transforms.collapse(editor, { edge: 'focus' });
×
1487
                    }
1488

1489
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1490
                    return;
×
1491
                }
1492

1493
                if (Hotkeys.isMoveWordForward(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
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1505
                // fall back to guessing at the input intention for hotkeys.
1506
                // COMPAT: In iOS, some of these hotkeys are handled in the
1507
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1508
                    // We don't have a core behavior for these, but they change the
1509
                    // DOM if we don't prevent them, so we have to.
1510
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1511
                        event.preventDefault();
×
1512
                        return;
×
1513
                    }
1514

1515
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1516
                        event.preventDefault();
×
1517
                        Editor.insertBreak(editor);
×
1518
                        return;
×
1519
                    }
1520

1521
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1522
                        event.preventDefault();
×
1523

1524
                        if (selection && Range.isExpanded(selection)) {
×
1525
                            Editor.deleteFragment(editor, {
×
1526
                                direction: 'backward'
1527
                            });
1528
                        } else {
1529
                            Editor.deleteBackward(editor);
×
1530
                        }
1531

1532
                        return;
×
1533
                    }
1534

1535
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1536
                        event.preventDefault();
×
1537

1538
                        if (selection && Range.isExpanded(selection)) {
×
1539
                            Editor.deleteFragment(editor, {
×
1540
                                direction: 'forward'
1541
                            });
1542
                        } else {
1543
                            Editor.deleteForward(editor);
×
1544
                        }
1545

1546
                        return;
×
1547
                    }
1548

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

1552
                        if (selection && Range.isExpanded(selection)) {
×
1553
                            Editor.deleteFragment(editor, {
×
1554
                                direction: 'backward'
1555
                            });
1556
                        } else {
1557
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1558
                        }
1559

1560
                        return;
×
1561
                    }
1562

1563
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1564
                        event.preventDefault();
×
1565

1566
                        if (selection && Range.isExpanded(selection)) {
×
1567
                            Editor.deleteFragment(editor, {
×
1568
                                direction: 'forward'
1569
                            });
1570
                        } else {
1571
                            Editor.deleteForward(editor, { unit: 'line' });
×
1572
                        }
1573

1574
                        return;
×
1575
                    }
1576

1577
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1578
                        event.preventDefault();
×
1579

1580
                        if (selection && Range.isExpanded(selection)) {
×
1581
                            Editor.deleteFragment(editor, {
×
1582
                                direction: 'backward'
1583
                            });
1584
                        } else {
1585
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1586
                        }
1587

1588
                        return;
×
1589
                    }
1590

1591
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1592
                        event.preventDefault();
×
1593

1594
                        if (selection && Range.isExpanded(selection)) {
×
1595
                            Editor.deleteFragment(editor, {
×
1596
                                direction: 'forward'
1597
                            });
1598
                        } else {
1599
                            Editor.deleteForward(editor, { unit: 'word' });
×
1600
                        }
1601

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

1637
    private onDOMPaste(event: ClipboardEvent) {
1638
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1639
        // fall back to React's `onPaste` here instead.
1640
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1641
        // when "paste without formatting" option is used.
1642
        // This unfortunately needs to be handled with paste events instead.
1643
        if (
×
1644
            !this.isDOMEventHandled(event, this.paste) &&
×
1645
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1646
            !this.readonly &&
1647
            AngularEditor.hasEditableTarget(this.editor, event.target)
1648
        ) {
1649
            event.preventDefault();
×
1650
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1651
        }
1652
    }
1653

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

1683
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1684
        if (!handler) {
3✔
1685
            return false;
3✔
1686
        }
1687
        handler(event);
×
1688
        return event.defaultPrevented;
×
1689
    }
1690
    //#endregion
1691

1692
    ngOnDestroy() {
1693
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1694
        this.manualListeners.forEach(manualListener => {
22✔
1695
            manualListener();
462✔
1696
        });
1697
        this.destroy$.complete();
22✔
1698
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1699
    }
1700
}
1701

1702
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1703
    // This was affecting the selection of multiple blocks and dragging behavior,
1704
    // so enabled only if the selection has been collapsed.
1705
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1706
        const leafEl = domRange.startContainer.parentElement!;
×
1707

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

1713
        if (isZeroDimensionRect) {
×
1714
            const leafRect = leafEl.getBoundingClientRect();
×
1715
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1716

1717
            if (leafHasDimensions) {
×
1718
                return;
×
1719
            }
1720
        }
1721

1722
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1723
        scrollIntoView(leafEl, {
×
1724
            scrollMode: 'if-needed'
1725
        });
1726
        delete leafEl.getBoundingClientRect;
×
1727
    }
1728
};
1729

1730
/**
1731
 * Check if the target is inside void and in the editor.
1732
 */
1733

1734
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1735
    let slateNode: Node | null = null;
1✔
1736
    try {
1✔
1737
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1738
    } catch (error) {}
1739
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1740
};
1741

1742
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1743
    return (
2✔
1744
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1745
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1746
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1747
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1748
    );
1749
};
1750

1751
/**
1752
 * remove default insert from composition
1753
 * @param text
1754
 */
1755
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1756
    const types = ['compositionend', 'insertFromComposition'];
×
1757
    if (!types.includes(event.type)) {
×
1758
        return;
×
1759
    }
1760
    const insertText = (event as CompositionEvent).data;
×
1761
    const window = AngularEditor.getWindow(editor);
×
1762
    const domSelection = window.getSelection();
×
1763
    // ensure text node insert composition input text
1764
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1765
        const textNode = domSelection.anchorNode;
×
1766
        textNode.splitText(textNode.length - insertText.length).remove();
×
1767
    }
1768
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc