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

worktile / slate-angular / 5b1a9f00-ffe6-4874-b6ff-095a41131561

05 Dec 2025 05:28AM UTC coverage: 43.815% (-0.9%) from 44.711%
5b1a9f00-ffe6-4874-b6ff-095a41131561

push

circleci

web-flow
feat(virtual): #WIK-19501 strategy for getting realHeight when scrolling (#310)

* feat(virtual): #WIK-19501 strategy for getting realHeight when scrolling

* chore: add changeset

384 of 1107 branches covered (34.69%)

Branch coverage included in aggregate %.

1 of 76 new or added lines in 1 file covered. (1.32%)

1054 of 2175 relevant lines covered (48.46%)

29.83 hits per line

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

25.98
/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
            const virtualView = this.refreshVirtualView();
×
144
            const diff = this.diffVirtualView(virtualView);
×
NEW
145
            if (diff.isDiff) {
×
NEW
146
                if (diff.isMissingTop || diff.isMissingBottom) {
×
NEW
147
                    this.measureHeightByIndexes([...diff.diffTopRenderedIndexes, ...diff.diffBottomRenderedIndexes], true).then(result => {
×
NEW
148
                        if (isDebug) {
×
NEW
149
                            console.log('async measureHeightByIndexes:', result);
×
150
                        }
NEW
151
                        this.applyVirtualView(result || virtualView);
×
NEW
152
                        if (this.listRender.initialized) {
×
NEW
153
                            this.listRender.update(this.renderedChildren, this.editor, this.context);
×
154
                        }
NEW
155
                        this.scheduleMeasureVisibleHeights();
×
156
                    });
157
                } else {
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
    }
167

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

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

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

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

200
    viewContainerRef = inject(ViewContainerRef);
23✔
201

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

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

214
    listRender: ListRender;
215

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

446
    ngAfterViewChecked() {}
447

448
    ngDoCheck() {}
449

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

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

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

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

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

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

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

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

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

573
    virtualScrollInitialized = false;
23✔
574

575
    virtualTopHeightElement: HTMLElement;
576

577
    virtualBottomHeightElement: HTMLElement;
578

579
    virtualCenterOutlet: HTMLElement;
580

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

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

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

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

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

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

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

675
    private diffVirtualView(virtualView: VirtualViewResult) {
676
        if (!this.renderedChildren.length) {
×
NEW
677
            return {
×
678
                isDiff: true,
679
                diffTopRenderedIndexes: [],
680
                diffBottomRenderedIndexes: []
681
            };
682
        }
683
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
684
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
NEW
685
        const firstNewIndex = newVisibleIndexes[0];
×
NEW
686
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
NEW
687
        const firstOldIndex = oldVisibleIndexes[0];
×
NEW
688
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
NEW
689
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
NEW
690
            const diffTopRenderedIndexes = [];
×
NEW
691
            const diffBottomRenderedIndexes = [];
×
NEW
692
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
NEW
693
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
NEW
694
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
NEW
695
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
NEW
696
            if (isMissingTop || isAddedBottom) {
×
697
                // 向下
NEW
698
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
NEW
699
                    const element = oldVisibleIndexes[index];
×
NEW
700
                    if (!newVisibleIndexes.includes(element)) {
×
NEW
701
                        diffTopRenderedIndexes.push(element);
×
702
                    } else {
NEW
703
                        break;
×
704
                    }
705
                }
NEW
706
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
NEW
707
                    const element = newVisibleIndexes[index];
×
NEW
708
                    if (!oldVisibleIndexes.includes(element)) {
×
NEW
709
                        diffBottomRenderedIndexes.push(element);
×
710
                    } else {
NEW
711
                        break;
×
712
                    }
713
                }
NEW
714
            } else if (isAddedTop || isMissingBottom) {
×
715
                // 向上
NEW
716
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
NEW
717
                    const element = newVisibleIndexes[index];
×
NEW
718
                    if (!oldVisibleIndexes.includes(element)) {
×
NEW
719
                        diffTopRenderedIndexes.push(element);
×
720
                    } else {
NEW
721
                        break;
×
722
                    }
723
                }
NEW
724
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
NEW
725
                    const element = oldVisibleIndexes[index];
×
NEW
726
                    if (!newVisibleIndexes.includes(element)) {
×
NEW
727
                        diffBottomRenderedIndexes.push(element);
×
728
                    } else {
NEW
729
                        break;
×
730
                    }
731
                }
732
            }
NEW
733
            if (isDebug) {
×
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
            }
NEW
756
            return {
×
757
                isDiff: true,
758
                isMissingTop,
759
                isAddedTop,
760
                isMissingBottom,
761
                isAddedBottom,
762
                diffTopRenderedIndexes,
763
                diffBottomRenderedIndexes
764
            };
765
        }
NEW
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
        if (this.measurePending) {
×
811
            return;
×
812
        }
813
        this.measurePending = true;
×
814
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
815
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
816
            this.measureVisibleHeights();
×
817
            this.measurePending = false;
×
818
        });
819
    }
820

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

843
    private async measureHeightByIndexes(indexes: number[], isRefresh: boolean = false): Promise<VirtualViewResult | null> {
×
NEW
844
        const children = (this.editor.children || []) as Element[];
×
NEW
845
        let isHeightChanged = false;
×
NEW
846
        const promises: Promise<void>[] = [];
×
NEW
847
        indexes.forEach(index => {
×
NEW
848
            const node = children[index];
×
NEW
849
            if (!node) {
×
NEW
850
                return;
×
851
            }
NEW
852
            const key = AngularEditor.findKey(this.editor, node);
×
NEW
853
            const view = ELEMENT_TO_COMPONENT.get(node);
×
NEW
854
            if (!view) {
×
NEW
855
                return;
×
856
            }
NEW
857
            const promise = (view as BaseElementComponent | BaseElementFlavour).getRealHeight()?.then(height => {
×
NEW
858
                const prevHeight = this.measuredHeights.get(key.id);
×
NEW
859
                if (isDebug) {
×
NEW
860
                    console.log('measureHeightByIndexes: get index:', index, 'prevHeight:', prevHeight, 'newHeight:', height);
×
861
                }
NEW
862
                if (prevHeight && height !== prevHeight) {
×
NEW
863
                    this.measuredHeights.set(key.id, height);
×
NEW
864
                    isHeightChanged = true;
×
865
                }
866
            });
NEW
867
            if (promise) {
×
NEW
868
                promises.push(promise);
×
869
            }
870
        });
NEW
871
        if (promises.length > 0) {
×
NEW
872
            await Promise.all(promises);
×
NEW
873
            if (isHeightChanged && isRefresh) {
×
NEW
874
                return this.refreshVirtualView();
×
875
            }
876
        }
NEW
877
        return null;
×
878
    }
879

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1306
            this.isDraggingInternally = true;
×
1307

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

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

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

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

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

1332
                this.isDraggingInternally = false;
×
1333
            }
1334

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

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

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

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

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

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

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

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

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

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

1408
                    return;
×
1409
                }
1410

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

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

1418
                    return;
×
1419
                }
1420

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

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

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

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

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

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

1467
                    return;
×
1468
                }
1469

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

1478
                    return;
×
1479
                }
1480

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

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

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

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

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

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

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

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

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

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

1531
                        return;
×
1532
                    }
1533

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

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

1545
                        return;
×
1546
                    }
1547

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

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

1559
                        return;
×
1560
                    }
1561

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

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

1573
                        return;
×
1574
                    }
1575

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

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

1587
                        return;
×
1588
                    }
1589

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc