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

worktile / slate-angular / f234f4d2-94ea-4792-8e04-3d89d68db68f

05 Dec 2025 10:19AM UTC coverage: 43.653% (-0.02%) from 43.676%
f234f4d2-94ea-4792-8e04-3d89d68db68f

push

circleci

web-flow
feat(virtual): simplify scrolling area calculation and increase business height (#311)

* feat(virtual): simplify scrolling area calculation and increase business height

* fix: optimize

* chore: add changeset and rename and add note

---------

Co-authored-by: pubuzhixing8 <pubuzhixing@gmail.com>

384 of 1112 branches covered (34.53%)

Branch coverage included in aggregate %.

1 of 23 new or added lines in 1 file covered. (4.35%)

1 existing line in 1 file now uncovered.

1057 of 2189 relevant lines covered (48.29%)

29.72 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(() => {
×
143
            let virtualView = this.refreshVirtualView();
×
144
            let diff = this.diffVirtualView(virtualView);
×
145
            if (!diff.isDiff) {
×
146
                return;
×
147
            }
148
            if (diff.isMissingTop) {
×
149
                const result = this.remeasureHeightByIndics([...diff.diffTopRenderedIndexes]);
×
150
                if (result) {
×
151
                    virtualView = this.refreshVirtualView();
×
152
                    diff = this.diffVirtualView(virtualView, 'second');
×
153
                    if (!diff.isDiff) {
×
154
                        return;
×
155
                    }
156
                }
157
            }
158
            this.applyVirtualView(virtualView);
×
159
            if (this.listRender.initialized) {
×
160
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
161
            }
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
    // the height from scroll container top to editor top height element
572
    private businessHeight: number = 0;
23✔
573

574
    virtualScrollInitialized = false;
23✔
575

576
    virtualTopHeightElement: HTMLElement;
577

578
    virtualBottomHeightElement: HTMLElement;
579

580
    virtualCenterOutlet: HTMLElement;
581

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

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

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

NEW
639
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
NEW
640
            const currentHeight = this.getBlockHeight(i);
×
NEW
641
            const nextOffset = accumulatedOffset + currentHeight;
×
642
            // 可视区域有交集,加入渲染
NEW
643
            if (nextOffset > adjustedScrollTop && accumulatedOffset < viewBottom) {
×
NEW
644
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
NEW
645
                visible.push(children[i]);
×
NEW
646
                visibleIndexes.push(i);
×
647
            }
NEW
648
            accumulatedOffset = nextOffset;
×
649
        }
650

NEW
651
        const visibleEndIndex = visibleStartIndex === -1 ? elementLength - 1 : visibleIndexes.length - 1;
×
NEW
652
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
NEW
653
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
NEW
654
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
NEW
655
        const bottom = accumulatedHeights[elementLength] - accumulatedHeights[visibleEndIndex];
×
656

657
        return {
×
658
            renderedChildren: visible.length ? visible : children,
×
659
            visibleIndexes: new Set(visibleIndexes),
660
            top,
661
            bottom,
662
            heights
663
        };
664
    }
665

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1133
        const window = AngularEditor.getWindow(this.editor);
×
1134

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

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

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

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

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

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

1171
        IS_FOCUSED.delete(this.editor);
×
1172
    }
1173

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1305
            this.isDraggingInternally = true;
×
1306

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

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

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

1322
            Transforms.select(editor, range);
×
1323

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

1331
                this.isDraggingInternally = false;
×
1332
            }
1333

1334
            AngularEditor.insertData(editor, data);
×
1335

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

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

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

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

1374
            IS_FOCUSED.set(this.editor, true);
2✔
1375
        }
1376
    }
1377

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

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

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

1403
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1404
                        editor.redo();
×
1405
                    }
1406

1407
                    return;
×
1408
                }
1409

1410
                if (Hotkeys.isUndo(nativeEvent)) {
×
1411
                    event.preventDefault();
×
1412

1413
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1414
                        editor.undo();
×
1415
                    }
1416

1417
                    return;
×
1418
                }
1419

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

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

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

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

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

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

1466
                    return;
×
1467
                }
1468

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

1477
                    return;
×
1478
                }
1479

1480
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1481
                    event.preventDefault();
×
1482

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

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

1491
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1492
                    event.preventDefault();
×
1493

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

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

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

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

1519
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1520
                        event.preventDefault();
×
1521

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

1530
                        return;
×
1531
                    }
1532

1533
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1534
                        event.preventDefault();
×
1535

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

1544
                        return;
×
1545
                    }
1546

1547
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1548
                        event.preventDefault();
×
1549

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

1558
                        return;
×
1559
                    }
1560

1561
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1562
                        event.preventDefault();
×
1563

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

1572
                        return;
×
1573
                    }
1574

1575
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1576
                        event.preventDefault();
×
1577

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

1586
                        return;
×
1587
                    }
1588

1589
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1590
                        event.preventDefault();
×
1591

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

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

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

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

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

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

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

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

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

1715
            if (leafHasDimensions) {
×
1716
                return;
×
1717
            }
1718
        }
1719

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

1728
/**
1729
 * Check if the target is inside void and in the editor.
1730
 */
1731

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

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

1749
/**
1750
 * remove default insert from composition
1751
 * @param text
1752
 */
1753
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1754
    const types = ['compositionend', 'insertFromComposition'];
×
1755
    if (!types.includes(event.type)) {
×
1756
        return;
×
1757
    }
1758
    const insertText = (event as CompositionEvent).data;
×
1759
    const window = AngularEditor.getWindow(editor);
×
1760
    const domSelection = window.getSelection();
×
1761
    // ensure text node insert composition input text
1762
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1763
        const textNode = domSelection.anchorNode;
×
1764
        textNode.splitText(textNode.length - insertText.length).remove();
×
1765
    }
1766
};
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