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

worktile / slate-angular / 8761b131-9b0c-4e5d-a2cf-604ae8009d65

09 Dec 2025 06:04AM UTC coverage: 43.281% (-0.3%) from 43.597%
8761b131-9b0c-4e5d-a2cf-604ae8009d65

push

circleci

web-flow
feat(virtual-scroll): support selection in visible range #WIK-19488 (#315)

384 of 1129 branches covered (34.01%)

Branch coverage included in aggregate %.

4 of 20 new or added lines in 2 files covered. (20.0%)

1059 of 2205 relevant lines covered (48.03%)

29.52 hits per line

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

25.56
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    HostBinding,
6
    Renderer2,
7
    ElementRef,
8
    ChangeDetectionStrategy,
9
    OnDestroy,
10
    ChangeDetectorRef,
11
    NgZone,
12
    Injector,
13
    forwardRef,
14
    OnChanges,
15
    SimpleChanges,
16
    AfterViewChecked,
17
    DoCheck,
18
    inject,
19
    ViewContainerRef
20
} from '@angular/core';
21
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
22
import { direction } from 'direction';
23
import scrollIntoView from 'scroll-into-view-if-needed';
24
import { AngularEditor } from '../../plugins/angular-editor';
25
import {
26
    DOMElement,
27
    isDOMNode,
28
    DOMStaticRange,
29
    DOMRange,
30
    isDOMElement,
31
    isPlainTextOnlyPaste,
32
    DOMSelection,
33
    getDefaultView,
34
    EDITOR_TO_WINDOW,
35
    EDITOR_TO_ELEMENT,
36
    NODE_TO_ELEMENT,
37
    ELEMENT_TO_NODE,
38
    IS_FOCUSED,
39
    IS_READ_ONLY
40
} from 'slate-dom';
41
import { Subject } from 'rxjs';
42
import {
43
    IS_FIREFOX,
44
    IS_SAFARI,
45
    IS_CHROME,
46
    HAS_BEFORE_INPUT_SUPPORT,
47
    IS_ANDROID,
48
    VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT,
49
    VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT,
50
    SLATE_DEBUG_KEY
51
} from '../../utils/environment';
52
import Hotkeys from '../../utils/hotkeys';
53
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
54
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
55
import { SlateErrorCode } from '../../types/error';
56
import { NG_VALUE_ACCESSOR } from '@angular/forms';
57
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
58
import { ViewType } from '../../types/view';
59
import { HistoryEditor } from 'slate-history';
60
import { ELEMENT_TO_COMPONENT, isDecoratorRangeListEqual } from '../../utils';
61
import { SlatePlaceholder } from '../../types/feature';
62
import { restoreDom } from '../../utils/restore-dom';
63
import { ListRender } from '../../view/render/list-render';
64
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
65
import { BaseElementComponent } from '../../view/base';
66
import { BaseElementFlavour } from '../../view/flavour/element';
67
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
68
import { isKeyHotkey } from 'is-hotkey';
69

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

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

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

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

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

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

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

111
    private initialized: boolean;
112

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

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

117
    @Input() editor: AngularEditor;
118

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

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

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

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

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

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

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

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

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

137
    @Input() placeholder: string;
138

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

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

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

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

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

202
    viewContainerRef = inject(ViewContainerRef);
23✔
203

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

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

216
    listRender: ListRender;
217

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

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

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

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

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

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

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

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

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

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

369
            const hasDomSelection = domSelection.type !== 'None';
1✔
370

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

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

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

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

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

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

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

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

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

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

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

465
    ngAfterViewChecked() {}
466

467
    ngDoCheck() {}
468

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

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

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

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

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

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

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

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

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

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

595
    virtualScrollInitialized = false;
23✔
596

597
    virtualTopHeightElement: HTMLElement;
598

599
    virtualBottomHeightElement: HTMLElement;
600

601
    virtualCenterOutlet: HTMLElement;
602

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1151
        const window = AngularEditor.getWindow(this.editor);
×
1152

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

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

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

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

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

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

1189
        IS_FOCUSED.delete(this.editor);
×
1190
    }
1191

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1323
            this.isDraggingInternally = true;
×
1324

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

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

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

1340
            Transforms.select(editor, range);
×
1341

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

1349
                this.isDraggingInternally = false;
×
1350
            }
1351

1352
            AngularEditor.insertData(editor, data);
×
1353

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

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

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

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

1392
            IS_FOCUSED.set(this.editor, true);
2✔
1393
        }
1394
    }
1395

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

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

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

1421
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1422
                        editor.redo();
×
1423
                    }
1424

1425
                    return;
×
1426
                }
1427

1428
                if (Hotkeys.isUndo(nativeEvent)) {
×
1429
                    event.preventDefault();
×
1430

1431
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1432
                        editor.undo();
×
1433
                    }
1434

1435
                    return;
×
1436
                }
1437

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

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

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

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

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

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

1484
                    return;
×
1485
                }
1486

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

1495
                    return;
×
1496
                }
1497

1498
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1499
                    event.preventDefault();
×
1500

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

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

1509
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1510
                    event.preventDefault();
×
1511

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

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

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

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

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

1543
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1544
                        event.preventDefault();
×
1545

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

1554
                        return;
×
1555
                    }
1556

1557
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1558
                        event.preventDefault();
×
1559

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

1568
                        return;
×
1569
                    }
1570

1571
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1572
                        event.preventDefault();
×
1573

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

1582
                        return;
×
1583
                    }
1584

1585
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1586
                        event.preventDefault();
×
1587

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

1596
                        return;
×
1597
                    }
1598

1599
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1600
                        event.preventDefault();
×
1601

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

1610
                        return;
×
1611
                    }
1612

1613
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1614
                        event.preventDefault();
×
1615

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

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

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

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

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

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

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

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

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

1739
            if (leafHasDimensions) {
×
1740
                return;
×
1741
            }
1742
        }
1743

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

1752
/**
1753
 * Check if the target is inside void and in the editor.
1754
 */
1755

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

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

1773
/**
1774
 * remove default insert from composition
1775
 * @param text
1776
 */
1777
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1778
    const types = ['compositionend', 'insertFromComposition'];
×
1779
    if (!types.includes(event.type)) {
×
1780
        return;
×
1781
    }
1782
    const insertText = (event as CompositionEvent).data;
×
1783
    const window = AngularEditor.getWindow(editor);
×
1784
    const domSelection = window.getSelection();
×
1785
    // ensure text node insert composition input text
1786
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1787
        const textNode = domSelection.anchorNode;
×
1788
        textNode.splitText(textNode.length - insertText.length).remove();
×
1789
    }
1790
};
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