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

worktile / slate-angular / 7a864531-2427-452a-9fe2-5602e19d25b7

05 Jan 2026 04:01PM UTC coverage: 36.842% (-0.06%) from 36.9%
7a864531-2427-452a-9fe2-5602e19d25b7

push

circleci

pubuzhixing8
fix(virtual-scroll): cache root node width and set pre-rendering width

386 of 1250 branches covered (30.88%)

Branch coverage included in aggregate %.

2 of 14 new or added lines in 3 files covered. (14.29%)

1 existing line in 1 file now uncovered.

1084 of 2740 relevant lines covered (39.56%)

23.86 hits per line

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

22.8
/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, Selection } 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
    SLATE_DEBUG_KEY,
49
    SLATE_DEBUG_KEY_SCROLL_TOP
50
} from '../../utils/environment';
51
import Hotkeys from '../../utils/hotkeys';
52
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
53
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
54
import { SlateErrorCode } from '../../types/error';
55
import { NG_VALUE_ACCESSOR } from '@angular/forms';
56
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
57
import { ViewType } from '../../types/view';
58
import { HistoryEditor } from 'slate-history';
59
import {
60
    buildHeightsAndAccumulatedHeights,
61
    EDITOR_TO_BUSINESS_TOP,
62
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
63
    ELEMENT_KEY_TO_HEIGHTS,
64
    getBusinessTop,
65
    getRealHeightByElement,
66
    IS_ENABLED_VIRTUAL_SCROLL,
67
    isDebug,
68
    isDebugScrollTop,
69
    isDecoratorRangeListEqual,
70
    measureHeightByIndics
71
} from '../../utils';
72
import { SlatePlaceholder } from '../../types/feature';
73
import { restoreDom } from '../../utils/restore-dom';
74
import { ListRender } from '../../view/render/list-render';
75
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
76
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
77
import { isKeyHotkey } from 'is-hotkey';
78
import { calculateVirtualTopHeight, debugLog, EDITOR_TO_ROOT_NODE_WIDTH } from '../../utils/virtual-scroll';
79

80
// not correctly clipboardData on beforeinput
81
const forceOnDOMPaste = IS_SAFARI;
1✔
82

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

108
    private destroy$ = new Subject();
23✔
109

110
    isComposing = false;
23✔
111
    isDraggingInternally = false;
23✔
112
    isUpdatingSelection = false;
23✔
113
    latestElement = null as DOMElement | null;
23✔
114

115
    protected manualListeners: (() => void)[] = [];
23✔
116

117
    private initialized: boolean;
118

119
    private onTouchedCallback: () => void = () => {};
23✔
120

121
    private onChangeCallback: (_: any) => void = () => {};
23✔
122

123
    @Input() editor: AngularEditor;
124

125
    @Input() renderElement: (element: Element) => ViewType | null;
126

127
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
128

129
    @Input() renderText: (text: SlateText) => ViewType | null;
130

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

133
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
134

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

137
    @Input() isStrictDecorate: boolean = true;
23✔
138

139
    @Input() trackBy: (node: Element) => any = () => null;
206✔
140

141
    @Input() readonly = false;
23✔
142

143
    @Input() placeholder: string;
144

145
    @Input()
146
    set virtualScroll(config: SlateVirtualScrollConfig) {
147
        this.virtualScrollConfig = config;
×
148
        if (isDebugScrollTop) {
×
149
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
150
        }
151
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
152
        if (this.isEnabledVirtualScroll()) {
×
153
            this.tryUpdateVirtualViewport();
×
154
        }
155
    }
156

157
    //#region input event handler
158
    @Input() beforeInput: (event: Event) => void;
159
    @Input() blur: (event: Event) => void;
160
    @Input() click: (event: MouseEvent) => void;
161
    @Input() compositionEnd: (event: CompositionEvent) => void;
162
    @Input() compositionUpdate: (event: CompositionEvent) => void;
163
    @Input() compositionStart: (event: CompositionEvent) => void;
164
    @Input() copy: (event: ClipboardEvent) => void;
165
    @Input() cut: (event: ClipboardEvent) => void;
166
    @Input() dragOver: (event: DragEvent) => void;
167
    @Input() dragStart: (event: DragEvent) => void;
168
    @Input() dragEnd: (event: DragEvent) => void;
169
    @Input() drop: (event: DragEvent) => void;
170
    @Input() focus: (event: Event) => void;
171
    @Input() keydown: (event: KeyboardEvent) => void;
172
    @Input() paste: (event: ClipboardEvent) => void;
173
    //#endregion
174

175
    //#region DOM attr
176
    @Input() spellCheck = false;
23✔
177
    @Input() autoCorrect = false;
23✔
178
    @Input() autoCapitalize = false;
23✔
179

180
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
181
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
182
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
183

184
    get hasBeforeInputSupport() {
185
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
186
    }
187
    //#endregion
188

189
    viewContainerRef = inject(ViewContainerRef);
23✔
190

191
    getOutletParent = () => {
23✔
192
        return this.elementRef.nativeElement;
43✔
193
    };
194

195
    getOutletElement = () => {
23✔
196
        if (this.virtualScrollInitialized) {
23!
197
            return this.virtualCenterOutlet;
×
198
        } else {
199
            return null;
23✔
200
        }
201
    };
202

203
    listRender: ListRender;
204

205
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
206
        enabled: false,
207
        scrollTop: 0,
208
        viewportHeight: 0,
209
        viewportBoundingTop: 0,
210
        scrollContainer: null
211
    };
212

213
    private inViewportChildren: Element[] = [];
23✔
214
    private inViewportIndics: number[] = [];
23✔
215
    private keyHeightMap = new Map<string, number>();
23✔
216
    private tryUpdateVirtualViewportAnimId: number;
217
    private tryMeasureInViewportChildrenHeightsAnimId: number;
218
    private editorResizeObserver?: ResizeObserver;
219

220
    constructor(
221
        public elementRef: ElementRef,
23✔
222
        public renderer2: Renderer2,
23✔
223
        public cdr: ChangeDetectorRef,
23✔
224
        private ngZone: NgZone,
23✔
225
        private injector: Injector
23✔
226
    ) {}
227

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

249
        // add browser class
250
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
251
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
252
        this.initializeVirtualScroll();
23✔
253
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
254
    }
255

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

276
    registerOnChange(fn: any) {
277
        this.onChangeCallback = fn;
23✔
278
    }
279
    registerOnTouched(fn: any) {
280
        this.onTouchedCallback = fn;
23✔
281
    }
282

283
    writeValue(value: Element[]) {
284
        if (value && value.length) {
49✔
285
            this.editor.children = value;
26✔
286
            this.initializeContext();
26✔
287
            if (this.isEnabledVirtualScroll()) {
26!
288
                const virtualView = this.calculateVirtualViewport();
×
289
                this.applyVirtualView(virtualView);
×
290
                const childrenForRender = virtualView.inViewportChildren;
×
291
                if (isDebug) {
×
292
                    debugLog('log', 'writeValue calculate: ', virtualView.inViewportIndics, 'initialized: ', this.listRender.initialized);
×
293
                }
294
                if (!this.listRender.initialized) {
×
295
                    this.listRender.initialize(childrenForRender, this.editor, this.context);
×
296
                } else {
297
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
298
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
299
                }
300
            } else {
301
                if (!this.listRender.initialized) {
26✔
302
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
303
                } else {
304
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
305
                }
306
            }
307
            this.cdr.markForCheck();
26✔
308
        }
309
    }
310

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

343
    calculateVirtualScrollSelection(selection: Selection) {
344
        if (selection) {
×
345
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
346
            const indics = this.inViewportIndics;
×
347
            if (indics.length > 0) {
×
348
                const currentVisibleRange: Range = {
×
349
                    anchor: Editor.start(this.editor, [indics[0]]),
350
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
351
                };
352
                const [start, end] = Range.edges(selection);
×
353
                let forwardSelection = { anchor: start, focus: end };
×
354
                if (!isBlockCardCursor) {
×
355
                    forwardSelection = { anchor: start, focus: end };
×
356
                } else {
357
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
358
                }
359
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
360
                if (intersectedSelection && isBlockCardCursor) {
×
361
                    return selection;
×
362
                }
363
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
364
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
365
                    if (isDebug) {
×
366
                        debugLog(
×
367
                            'log',
368
                            `selection is not in visible range, selection: ${JSON.stringify(
369
                                selection
370
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
371
                        );
372
                    }
373
                    return intersectedSelection;
×
374
                }
375
                return selection;
×
376
            }
377
        }
378
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
379
        return selection;
×
380
    }
381

382
    toNativeSelection(autoScroll = true) {
15✔
383
        try {
15✔
384
            let { selection } = this.editor;
15✔
385
            if (this.isEnabledVirtualScroll()) {
15!
386
                selection = this.calculateVirtualScrollSelection(selection);
×
387
            }
388
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
389
            const { activeElement } = root;
15✔
390
            const domSelection = (root as Document).getSelection();
15✔
391

392
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
393
                return;
14✔
394
            }
395

396
            const hasDomSelection = domSelection.type !== 'None';
1✔
397

398
            // If the DOM selection is properly unset, we're done.
399
            if (!selection && !hasDomSelection) {
1!
400
                return;
×
401
            }
402

403
            // If the DOM selection is already correct, we're done.
404
            // verify that the dom selection is in the editor
405
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
406
            let hasDomSelectionInEditor = false;
1✔
407
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
408
                hasDomSelectionInEditor = true;
1✔
409
            }
410

411
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
412
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
413
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
414
                    exactMatch: false,
415
                    suppressThrow: true
416
                });
417
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
418
                    return;
×
419
                }
420
            }
421

422
            // prevent updating native selection when active element is void element
423
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
424
                return;
×
425
            }
426

427
            // when <Editable/> is being controlled through external value
428
            // then its children might just change - DOM responds to it on its own
429
            // but Slate's value is not being updated through any operation
430
            // and thus it doesn't transform selection on its own
431
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
432
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
433
                return;
×
434
            }
435

436
            // Otherwise the DOM selection is out of sync, so update it.
437
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
438
            this.isUpdatingSelection = true;
1✔
439

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

442
            if (newDomRange) {
1!
443
                // COMPAT: Since the DOM range has no concept of backwards/forwards
444
                // we need to check and do the right thing here.
445
                if (Range.isBackward(selection)) {
1!
446
                    // eslint-disable-next-line max-len
447
                    domSelection.setBaseAndExtent(
×
448
                        newDomRange.endContainer,
449
                        newDomRange.endOffset,
450
                        newDomRange.startContainer,
451
                        newDomRange.startOffset
452
                    );
453
                } else {
454
                    // eslint-disable-next-line max-len
455
                    domSelection.setBaseAndExtent(
1✔
456
                        newDomRange.startContainer,
457
                        newDomRange.startOffset,
458
                        newDomRange.endContainer,
459
                        newDomRange.endOffset
460
                    );
461
                }
462
            } else {
463
                domSelection.removeAllRanges();
×
464
            }
465

466
            setTimeout(() => {
1✔
467
                if (
1!
468
                    this.isEnabledVirtualScroll() &&
1!
469
                    !selection &&
470
                    this.editor.selection &&
471
                    autoScroll &&
472
                    this.virtualScrollConfig.scrollContainer
473
                ) {
474
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
475
                    return;
×
476
                } else {
477
                    // handle scrolling in setTimeout because of
478
                    // dom should not have updated immediately after listRender's updating
479
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
480
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
481
                    // to focus the contenteditable element too. (2016/11/16)
482
                    if (newDomRange && IS_FIREFOX) {
1!
483
                        el.focus();
×
484
                    }
485
                }
486
                this.isUpdatingSelection = false;
1✔
487
            });
488
        } catch (error) {
489
            this.editor.onError({
×
490
                code: SlateErrorCode.ToNativeSelectionError,
491
                nativeError: error
492
            });
493
            this.isUpdatingSelection = false;
×
494
        }
495
    }
496

497
    onChange() {
498
        this.forceRender();
13✔
499
        this.onChangeCallback(this.editor.children);
13✔
500
    }
501

502
    ngAfterViewChecked() {}
503

504
    ngDoCheck() {}
505

506
    forceRender() {
507
        this.updateContext();
15✔
508
        if (this.isEnabledVirtualScroll()) {
15!
509
            this.updateListRenderAndRemeasureHeights();
×
510
        } else {
511
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
512
        }
513
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
514
        // when the DOMElement where the selection is located is removed
515
        // the compositionupdate and compositionend events will no longer be fired
516
        // so isComposing needs to be corrected
517
        // need exec after this.cdr.detectChanges() to render HTML
518
        // need exec before this.toNativeSelection() to correct native selection
519
        if (this.isComposing) {
15!
520
            // Composition input text be not rendered when user composition input with selection is expanded
521
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
522
            // this time condition is true and isComposing is assigned false
523
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
524
            setTimeout(() => {
×
525
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
526
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
527
                let textContent = '';
×
528
                // skip decorate text
529
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
530
                    let text = stringDOMNode.textContent;
×
531
                    const zeroChar = '\uFEFF';
×
532
                    // remove zero with char
533
                    if (text.startsWith(zeroChar)) {
×
534
                        text = text.slice(1);
×
535
                    }
536
                    if (text.endsWith(zeroChar)) {
×
537
                        text = text.slice(0, text.length - 1);
×
538
                    }
539
                    textContent += text;
×
540
                });
541
                if (Node.string(textNode).endsWith(textContent)) {
×
542
                    this.isComposing = false;
×
543
                }
544
            }, 0);
545
        }
546
        this.toNativeSelection();
15✔
547
    }
548

549
    render() {
550
        const changed = this.updateContext();
2✔
551
        if (changed) {
2✔
552
            if (this.isEnabledVirtualScroll()) {
2!
553
                this.updateListRenderAndRemeasureHeights();
×
554
            } else {
555
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
556
            }
557
        }
558
    }
559

560
    updateListRenderAndRemeasureHeights() {
561
        const virtualView = this.calculateVirtualViewport();
×
562
        const oldInViewportChildren = this.inViewportChildren;
×
563
        this.applyVirtualView(virtualView);
×
564
        const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
565
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
566
        // 新增或者修改的才需要重算,计算出这个结果
567
        const remeasureIndics = [];
×
568
        this.inViewportChildren.forEach((child, index) => {
×
569
            if (oldInViewportChildren.indexOf(child) === -1) {
×
570
                remeasureIndics.push(this.inViewportIndics[index]);
×
571
            }
572
        });
573
        if (isDebug && remeasureIndics.length > 0) {
×
574
            console.log('remeasure height by indics: ', remeasureIndics);
×
575
        }
576
        measureHeightByIndics(this.editor, remeasureIndics, true);
×
577
    }
578

579
    updateContext() {
580
        const decorations = this.generateDecorations();
17✔
581
        if (
17✔
582
            this.context.selection !== this.editor.selection ||
46✔
583
            this.context.decorate !== this.decorate ||
584
            this.context.readonly !== this.readonly ||
585
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
586
        ) {
587
            this.context = {
10✔
588
                parent: this.editor,
589
                selection: this.editor.selection,
590
                decorations: decorations,
591
                decorate: this.decorate,
592
                readonly: this.readonly
593
            };
594
            return true;
10✔
595
        }
596
        return false;
7✔
597
    }
598

599
    initializeContext() {
600
        this.context = {
49✔
601
            parent: this.editor,
602
            selection: this.editor.selection,
603
            decorations: this.generateDecorations(),
604
            decorate: this.decorate,
605
            readonly: this.readonly
606
        };
607
    }
608

609
    initializeViewContext() {
610
        this.viewContext = {
23✔
611
            editor: this.editor,
612
            renderElement: this.renderElement,
613
            renderLeaf: this.renderLeaf,
614
            renderText: this.renderText,
615
            trackBy: this.trackBy,
616
            isStrictDecorate: this.isStrictDecorate
617
        };
618
    }
619

620
    composePlaceholderDecorate(editor: Editor) {
621
        if (this.placeholderDecorate) {
64!
622
            return this.placeholderDecorate(editor) || [];
×
623
        }
624

625
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
626
            const start = Editor.start(editor, []);
3✔
627
            return [
3✔
628
                {
629
                    placeholder: this.placeholder,
630
                    anchor: start,
631
                    focus: start
632
                }
633
            ];
634
        } else {
635
            return [];
61✔
636
        }
637
    }
638

639
    generateDecorations() {
640
        const decorations = this.decorate([this.editor, []]);
66✔
641
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
642
        decorations.push(...placeholderDecorations);
66✔
643
        return decorations;
66✔
644
    }
645

646
    private isEnabledVirtualScroll() {
647
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
648
    }
649

650
    virtualScrollInitialized = false;
23✔
651

652
    virtualTopHeightElement: HTMLElement;
653

654
    virtualBottomHeightElement: HTMLElement;
655

656
    virtualCenterOutlet: HTMLElement;
657

658
    initializeVirtualScroll() {
659
        if (this.virtualScrollInitialized) {
23!
660
            return;
×
661
        }
662
        if (this.isEnabledVirtualScroll()) {
23!
663
            this.virtualScrollInitialized = true;
×
664
            this.virtualTopHeightElement = document.createElement('div');
×
665
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
666
            this.virtualTopHeightElement.contentEditable = 'false';
×
667
            this.virtualBottomHeightElement = document.createElement('div');
×
668
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
669
            this.virtualBottomHeightElement.contentEditable = 'false';
×
670
            this.virtualCenterOutlet = document.createElement('div');
×
671
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
672
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
673
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
674
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
NEW
675
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
NEW
676
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
677
            this.editorResizeObserver = new ResizeObserver(entries => {
×
678
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
679
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
680
                    this.keyHeightMap.clear();
×
681
                    const remeasureIndics = this.inViewportIndics;
×
682
                    measureHeightByIndics(this.editor, remeasureIndics, true);
×
NEW
683
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
NEW
684
                    if (isDebug) {
×
NEW
685
                        debugLog(
×
686
                            'log',
687
                            'editorResizeObserverRectWidth: ',
688
                            editorResizeObserverRectWidth,
689
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
690
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
691
                        );
692
                    }
693
                }
694
            });
695
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
696
        }
697
    }
698

699
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
700
        if (!this.virtualScrollInitialized) {
×
701
            return;
×
702
        }
703
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
704
        if (bottomHeight !== undefined) {
×
705
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
706
        }
707
    }
708

709
    getActualVirtualTopHeight() {
710
        if (!this.virtualScrollInitialized) {
×
711
            return 0;
×
712
        }
713
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
714
    }
715

716
    handlePreRendering() {
717
        let preRenderingCount = 1;
×
718
        const childrenWithPreRendering = [...this.inViewportChildren];
×
719
        if (this.inViewportIndics[0] !== 0) {
×
720
            childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
721
        } else {
722
            preRenderingCount = 0;
×
723
        }
724
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
725
        if (lastIndex !== this.editor.children.length - 1) {
×
726
            childrenWithPreRendering.push(this.editor.children[lastIndex + 1] as Element);
×
727
        }
728
        return { preRenderingCount, childrenWithPreRendering };
×
729
    }
730

731
    private tryUpdateVirtualViewport() {
732
        if (isDebug) {
×
733
            debugLog('log', 'tryUpdateVirtualViewport');
×
734
        }
735
        if (this.inViewportIndics.length > 0) {
×
736
            const topHeight = this.getActualVirtualTopHeight();
×
737
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0]);
×
738
            if (topHeight !== refreshVirtualTopHeight) {
×
739
                if (isDebug) {
×
740
                    debugLog(
×
741
                        'log',
742
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
743
                        topHeight - refreshVirtualTopHeight
744
                    );
745
                }
746
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
747
                return;
×
748
            }
749
        }
750
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
751
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
752
            if (isDebug) {
×
753
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
754
            }
755
            let virtualView = this.calculateVirtualViewport();
×
756
            let diff = this.diffVirtualViewport(virtualView);
×
757
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
758
                const remeasureIndics = diff.changedIndexesOfTop;
×
759
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
760
                if (changed) {
×
761
                    virtualView = this.calculateVirtualViewport();
×
762
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
763
                }
764
            }
765
            if (diff.isDifferent) {
×
766
                this.applyVirtualView(virtualView);
×
767
                if (this.listRender.initialized) {
×
768
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
769
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
770
                    if (diff.needAddOnTop) {
×
771
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
772
                        if (isDebug) {
×
773
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
774
                        }
775
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
776
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
777
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
778
                        if (changed) {
×
779
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
780
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
781
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
782
                            this.setVirtualSpaceHeight(newTopHeight);
×
783
                            if (isDebug) {
×
784
                                debugLog(
×
785
                                    'log',
786
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
787
                                );
788
                            }
789
                        }
790
                    }
791
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
792
                        this.toNativeSelection(false);
×
793
                    }
794
                }
795
            }
796
            if (isDebug) {
×
797
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
798
            }
799
        });
800
    }
801

802
    private calculateVirtualViewport() {
803
        const children = (this.editor.children || []) as Element[];
×
804
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
805
            return {
×
806
                inViewportChildren: children,
807
                inViewportIndics: [],
808
                top: 0,
809
                bottom: 0,
810
                heights: []
811
            };
812
        }
813
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
814
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
815
        if (!viewportHeight) {
×
816
            return {
×
817
                inViewportChildren: [],
818
                inViewportIndics: [],
819
                top: 0,
820
                bottom: 0,
821
                heights: []
822
            };
823
        }
824
        const elementLength = children.length;
×
825
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
826
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
827
            setTimeout(() => {
×
828
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
829
                const businessTop =
830
                    Math.ceil(virtualTopBoundingTop) +
×
831
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
832
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
833
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
834
                if (isDebug) {
×
835
                    debugLog('log', 'businessTop', businessTop);
×
836
                }
837
            }, 100);
838
        }
839
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
840
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
841
        const totalHeight = accumulatedHeights[elementLength];
×
842
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
843
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
844
        const viewBottom = limitedScrollTop + viewportHeight;
×
845
        let accumulatedOffset = 0;
×
846
        let inViewportStartIndex = -1;
×
847
        const visible: Element[] = [];
×
848
        const inViewportIndics: number[] = [];
×
849

850
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
851
            const currentHeight = heights[i];
×
852
            const nextOffset = accumulatedOffset + currentHeight;
×
853
            // 可视区域有交集,加入渲染
854
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
855
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
856
                visible.push(children[i]);
×
857
                inViewportIndics.push(i);
×
858
            }
859
            accumulatedOffset = nextOffset;
×
860
        }
861

862
        if (inViewportStartIndex === -1 && elementLength) {
×
863
            inViewportStartIndex = elementLength - 1;
×
864
            visible.push(children[inViewportStartIndex]);
×
865
            inViewportIndics.push(inViewportStartIndex);
×
866
        }
867

868
        const inViewportEndIndex =
869
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
870
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
871
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
872
        return {
×
873
            inViewportChildren: visible.length ? visible : children,
×
874
            inViewportIndics,
875
            top,
876
            bottom,
877
            heights,
878
            accumulatedHeights
879
        };
880
    }
881

882
    private applyVirtualView(virtualView: VirtualViewResult) {
883
        this.inViewportChildren = virtualView.inViewportChildren;
×
884
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
885
        this.inViewportIndics = virtualView.inViewportIndics;
×
886
    }
887

888
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
889
        if (!this.inViewportChildren.length) {
×
890
            if (isDebug) {
×
891
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
892
            }
893
            return {
×
894
                isDifferent: true,
895
                changedIndexesOfTop: [],
896
                changedIndexesOfBottom: []
897
            };
898
        }
899
        const oldIndexesInViewport = [...this.inViewportIndics];
×
900
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
901
        const firstNewIndex = newIndexesInViewport[0];
×
902
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
903
        const firstOldIndex = oldIndexesInViewport[0];
×
904
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
905
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
906
            const changedIndexesOfTop = [];
×
907
            const changedIndexesOfBottom = [];
×
908
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
909
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
910
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
911
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
912
            if (needRemoveOnTop || needAddOnBottom) {
×
913
                // 向下
914
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
915
                    const element = oldIndexesInViewport[index];
×
916
                    if (!newIndexesInViewport.includes(element)) {
×
917
                        changedIndexesOfTop.push(element);
×
918
                    } else {
919
                        break;
×
920
                    }
921
                }
922
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
923
                    const element = newIndexesInViewport[index];
×
924
                    if (!oldIndexesInViewport.includes(element)) {
×
925
                        changedIndexesOfBottom.push(element);
×
926
                    } else {
927
                        break;
×
928
                    }
929
                }
930
            } else if (needAddOnTop || needRemoveOnBottom) {
×
931
                // 向上
932
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
933
                    const element = newIndexesInViewport[index];
×
934
                    if (!oldIndexesInViewport.includes(element)) {
×
935
                        changedIndexesOfTop.push(element);
×
936
                    } else {
937
                        break;
×
938
                    }
939
                }
940
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
941
                    const element = oldIndexesInViewport[index];
×
942
                    if (!newIndexesInViewport.includes(element)) {
×
943
                        changedIndexesOfBottom.push(element);
×
944
                    } else {
945
                        break;
×
946
                    }
947
                }
948
            }
949
            if (isDebug) {
×
950
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
951
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
952
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
953
                debugLog(
×
954
                    'log',
955
                    'changedIndexesOfTop:',
956
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
957
                    changedIndexesOfTop,
958
                    changedIndexesOfTop.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
959
                );
960
                debugLog(
×
961
                    'log',
962
                    'changedIndexesOfBottom:',
963
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
964
                    changedIndexesOfBottom,
965
                    changedIndexesOfBottom.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
966
                );
967
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
968
                const needBottom = virtualView.heights
×
969
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
970
                    .reduce((acc, height) => acc + height, 0);
×
971
                debugLog(
×
972
                    'log',
973
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
974
                    'newTopHeight:',
975
                    needTop,
976
                    'prevTopHeight:',
977
                    parseFloat(this.virtualTopHeightElement.style.height)
978
                );
979
                debugLog(
×
980
                    'log',
981
                    'newBottomHeight:',
982
                    needBottom,
983
                    'prevBottomHeight:',
984
                    parseFloat(this.virtualBottomHeightElement.style.height)
985
                );
986
                debugLog('warn', '=========== Dividing line ===========');
×
987
            }
988
            return {
×
989
                isDifferent: true,
990
                needRemoveOnTop,
991
                needAddOnTop,
992
                needRemoveOnBottom,
993
                needAddOnBottom,
994
                changedIndexesOfTop,
995
                changedIndexesOfBottom
996
            };
997
        }
998
        return {
×
999
            isDifferent: false,
1000
            changedIndexesOfTop: [],
1001
            changedIndexesOfBottom: []
1002
        };
1003
    }
1004

1005
    //#region event proxy
1006
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1007
        this.manualListeners.push(
483✔
1008
            this.renderer2.listen(target, eventName, (event: Event) => {
1009
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1010
                if (beforeInputEvent) {
5!
1011
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1012
                }
1013
                listener(event);
5✔
1014
            })
1015
        );
1016
    }
1017

1018
    private toSlateSelection() {
1019
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1020
            try {
1✔
1021
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1022
                const { activeElement } = root;
1✔
1023
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1024
                const domSelection = (root as Document).getSelection();
1✔
1025

1026
                if (activeElement === el) {
1!
1027
                    this.latestElement = activeElement;
1✔
1028
                    IS_FOCUSED.set(this.editor, true);
1✔
1029
                } else {
1030
                    IS_FOCUSED.delete(this.editor);
×
1031
                }
1032

1033
                if (!domSelection) {
1!
1034
                    return Transforms.deselect(this.editor);
×
1035
                }
1036

1037
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1038
                const hasDomSelectionInEditor =
1039
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1040
                if (!hasDomSelectionInEditor) {
1!
1041
                    Transforms.deselect(this.editor);
×
1042
                    return;
×
1043
                }
1044

1045
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1046
                // for example, double-click the last cell of the table to select a non-editable DOM
1047
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1048
                if (range) {
1✔
1049
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1050
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1051
                            // force adjust DOMSelection
1052
                            this.toNativeSelection(false);
×
1053
                        }
1054
                    } else {
1055
                        Transforms.select(this.editor, range);
1✔
1056
                    }
1057
                }
1058
            } catch (error) {
1059
                this.editor.onError({
×
1060
                    code: SlateErrorCode.ToSlateSelectionError,
1061
                    nativeError: error
1062
                });
1063
            }
1064
        }
1065
    }
1066

1067
    private onDOMBeforeInput(
1068
        event: Event & {
1069
            inputType: string;
1070
            isComposing: boolean;
1071
            data: string | null;
1072
            dataTransfer: DataTransfer | null;
1073
            getTargetRanges(): DOMStaticRange[];
1074
        }
1075
    ) {
1076
        const editor = this.editor;
×
1077
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1078
        const { activeElement } = root;
×
1079
        const { selection } = editor;
×
1080
        const { inputType: type } = event;
×
1081
        const data = event.dataTransfer || event.data || undefined;
×
1082
        if (IS_ANDROID) {
×
1083
            let targetRange: Range | null = null;
×
1084
            let [nativeTargetRange] = event.getTargetRanges();
×
1085
            if (nativeTargetRange) {
×
1086
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1087
            }
1088
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1089
            // have to manually get the selection here to ensure it's up-to-date.
1090
            const window = AngularEditor.getWindow(editor);
×
1091
            const domSelection = window.getSelection();
×
1092
            if (!targetRange && domSelection) {
×
1093
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1094
            }
1095
            targetRange = targetRange ?? editor.selection;
×
1096
            if (type === 'insertCompositionText') {
×
1097
                if (data && data.toString().includes('\n')) {
×
1098
                    restoreDom(editor, () => {
×
1099
                        Editor.insertBreak(editor);
×
1100
                    });
1101
                } else {
1102
                    if (targetRange) {
×
1103
                        if (data) {
×
1104
                            restoreDom(editor, () => {
×
1105
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1106
                            });
1107
                        } else {
1108
                            restoreDom(editor, () => {
×
1109
                                Transforms.delete(editor, { at: targetRange });
×
1110
                            });
1111
                        }
1112
                    }
1113
                }
1114
                return;
×
1115
            }
1116
            if (type === 'deleteContentBackward') {
×
1117
                // gboard can not prevent default action, so must use restoreDom,
1118
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1119
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1120
                if (!Range.isCollapsed(targetRange)) {
×
1121
                    restoreDom(editor, () => {
×
1122
                        Transforms.delete(editor, { at: targetRange });
×
1123
                    });
1124
                    return;
×
1125
                }
1126
            }
1127
            if (type === 'insertText') {
×
1128
                restoreDom(editor, () => {
×
1129
                    if (typeof data === 'string') {
×
1130
                        Editor.insertText(editor, data);
×
1131
                    }
1132
                });
1133
                return;
×
1134
            }
1135
        }
1136
        if (
×
1137
            !this.readonly &&
×
1138
            AngularEditor.hasEditableTarget(editor, event.target) &&
1139
            !isTargetInsideVoid(editor, activeElement) &&
1140
            !this.isDOMEventHandled(event, this.beforeInput)
1141
        ) {
1142
            try {
×
1143
                event.preventDefault();
×
1144

1145
                // COMPAT: If the selection is expanded, even if the command seems like
1146
                // a delete forward/backward command it should delete the selection.
1147
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1148
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1149
                    Editor.deleteFragment(editor, { direction });
×
1150
                    return;
×
1151
                }
1152

1153
                switch (type) {
×
1154
                    case 'deleteByComposition':
1155
                    case 'deleteByCut':
1156
                    case 'deleteByDrag': {
1157
                        Editor.deleteFragment(editor);
×
1158
                        break;
×
1159
                    }
1160

1161
                    case 'deleteContent':
1162
                    case 'deleteContentForward': {
1163
                        Editor.deleteForward(editor);
×
1164
                        break;
×
1165
                    }
1166

1167
                    case 'deleteContentBackward': {
1168
                        Editor.deleteBackward(editor);
×
1169
                        break;
×
1170
                    }
1171

1172
                    case 'deleteEntireSoftLine': {
1173
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1174
                        Editor.deleteForward(editor, { unit: 'line' });
×
1175
                        break;
×
1176
                    }
1177

1178
                    case 'deleteHardLineBackward': {
1179
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1180
                        break;
×
1181
                    }
1182

1183
                    case 'deleteSoftLineBackward': {
1184
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1185
                        break;
×
1186
                    }
1187

1188
                    case 'deleteHardLineForward': {
1189
                        Editor.deleteForward(editor, { unit: 'block' });
×
1190
                        break;
×
1191
                    }
1192

1193
                    case 'deleteSoftLineForward': {
1194
                        Editor.deleteForward(editor, { unit: 'line' });
×
1195
                        break;
×
1196
                    }
1197

1198
                    case 'deleteWordBackward': {
1199
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1200
                        break;
×
1201
                    }
1202

1203
                    case 'deleteWordForward': {
1204
                        Editor.deleteForward(editor, { unit: 'word' });
×
1205
                        break;
×
1206
                    }
1207

1208
                    case 'insertLineBreak':
1209
                    case 'insertParagraph': {
1210
                        Editor.insertBreak(editor);
×
1211
                        break;
×
1212
                    }
1213

1214
                    case 'insertFromComposition': {
1215
                        // COMPAT: in safari, `compositionend` event is dispatched after
1216
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1217
                        // https://www.w3.org/TR/input-events-2/
1218
                        // so the following code is the right logic
1219
                        // because DOM selection in sync will be exec before `compositionend` event
1220
                        // isComposing is true will prevent DOM selection being update correctly.
1221
                        this.isComposing = false;
×
1222
                        preventInsertFromComposition(event, this.editor);
×
1223
                    }
1224
                    case 'insertFromDrop':
1225
                    case 'insertFromPaste':
1226
                    case 'insertFromYank':
1227
                    case 'insertReplacementText':
1228
                    case 'insertText': {
1229
                        // use a weak comparison instead of 'instanceof' to allow
1230
                        // programmatic access of paste events coming from external windows
1231
                        // like cypress where cy.window does not work realibly
1232
                        if (data?.constructor.name === 'DataTransfer') {
×
1233
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1234
                        } else if (typeof data === 'string') {
×
1235
                            Editor.insertText(editor, data);
×
1236
                        }
1237
                        break;
×
1238
                    }
1239
                }
1240
            } catch (error) {
1241
                this.editor.onError({
×
1242
                    code: SlateErrorCode.OnDOMBeforeInputError,
1243
                    nativeError: error
1244
                });
1245
            }
1246
        }
1247
    }
1248

1249
    private onDOMBlur(event: FocusEvent) {
1250
        if (
×
1251
            this.readonly ||
×
1252
            this.isUpdatingSelection ||
1253
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1254
            this.isDOMEventHandled(event, this.blur)
1255
        ) {
1256
            return;
×
1257
        }
1258

1259
        const window = AngularEditor.getWindow(this.editor);
×
1260

1261
        // COMPAT: If the current `activeElement` is still the previous
1262
        // one, this is due to the window being blurred when the tab
1263
        // itself becomes unfocused, so we want to abort early to allow to
1264
        // editor to stay focused when the tab becomes focused again.
1265
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1266
        if (this.latestElement === root.activeElement) {
×
1267
            return;
×
1268
        }
1269

1270
        const { relatedTarget } = event;
×
1271
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1272

1273
        // COMPAT: The event should be ignored if the focus is returning
1274
        // to the editor from an embedded editable element (eg. an <input>
1275
        // element inside a void node).
1276
        if (relatedTarget === el) {
×
1277
            return;
×
1278
        }
1279

1280
        // COMPAT: The event should be ignored if the focus is moving from
1281
        // the editor to inside a void node's spacer element.
1282
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1283
            return;
×
1284
        }
1285

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

1292
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1293
                return;
×
1294
            }
1295
        }
1296

1297
        IS_FOCUSED.delete(this.editor);
×
1298
    }
1299

1300
    private onDOMClick(event: MouseEvent) {
1301
        if (
×
1302
            !this.readonly &&
×
1303
            AngularEditor.hasTarget(this.editor, event.target) &&
1304
            !this.isDOMEventHandled(event, this.click) &&
1305
            isDOMNode(event.target)
1306
        ) {
1307
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1308
            const path = AngularEditor.findPath(this.editor, node);
×
1309
            const start = Editor.start(this.editor, path);
×
1310
            const end = Editor.end(this.editor, path);
×
1311

1312
            const startVoid = Editor.void(this.editor, { at: start });
×
1313
            const endVoid = Editor.void(this.editor, { at: end });
×
1314

1315
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1316
                let blockPath = path;
×
1317
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1318
                    const block = Editor.above(this.editor, {
×
1319
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1320
                        at: path
1321
                    });
1322

1323
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1324
                }
1325

1326
                const range = Editor.range(this.editor, blockPath);
×
1327
                Transforms.select(this.editor, range);
×
1328
                return;
×
1329
            }
1330

1331
            if (
×
1332
                startVoid &&
×
1333
                endVoid &&
1334
                Path.equals(startVoid[1], endVoid[1]) &&
1335
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1336
            ) {
1337
                const range = Editor.range(this.editor, start);
×
1338
                Transforms.select(this.editor, range);
×
1339
            }
1340
        }
1341
    }
1342

1343
    private onDOMCompositionStart(event: CompositionEvent) {
1344
        const { selection } = this.editor;
1✔
1345
        if (selection) {
1!
1346
            // solve the problem of cross node Chinese input
1347
            if (Range.isExpanded(selection)) {
×
1348
                Editor.deleteFragment(this.editor);
×
1349
                this.forceRender();
×
1350
            }
1351
        }
1352
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1353
            this.isComposing = true;
1✔
1354
        }
1355
        this.render();
1✔
1356
    }
1357

1358
    private onDOMCompositionUpdate(event: CompositionEvent) {
1359
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1360
    }
1361

1362
    private onDOMCompositionEnd(event: CompositionEvent) {
1363
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1364
            Transforms.delete(this.editor);
×
1365
        }
1366
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1367
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1368
            // aren't correct and never fire the "insertFromComposition"
1369
            // type that we need. So instead, insert whenever a composition
1370
            // ends since it will already have been committed to the DOM.
1371
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1372
                preventInsertFromComposition(event, this.editor);
×
1373
                Editor.insertText(this.editor, event.data);
×
1374
            }
1375

1376
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1377
            // so we need avoid repeat isnertText by isComposing === true,
1378
            this.isComposing = false;
×
1379
        }
1380
        this.render();
×
1381
    }
1382

1383
    private onDOMCopy(event: ClipboardEvent) {
1384
        const window = AngularEditor.getWindow(this.editor);
×
1385
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1386
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1387
            event.preventDefault();
×
1388
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1389
        }
1390
    }
1391

1392
    private onDOMCut(event: ClipboardEvent) {
1393
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1394
            event.preventDefault();
×
1395
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1396
            const { selection } = this.editor;
×
1397

1398
            if (selection) {
×
1399
                AngularEditor.deleteCutData(this.editor);
×
1400
            }
1401
        }
1402
    }
1403

1404
    private onDOMDragOver(event: DragEvent) {
1405
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1406
            // Only when the target is void, call `preventDefault` to signal
1407
            // that drops are allowed. Editable content is droppable by
1408
            // default, and calling `preventDefault` hides the cursor.
1409
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1410

1411
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1412
                event.preventDefault();
×
1413
            }
1414
        }
1415
    }
1416

1417
    private onDOMDragStart(event: DragEvent) {
1418
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1419
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1420
            const path = AngularEditor.findPath(this.editor, node);
×
1421
            const voidMatch =
1422
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1423

1424
            // If starting a drag on a void node, make sure it is selected
1425
            // so that it shows up in the selection's fragment.
1426
            if (voidMatch) {
×
1427
                const range = Editor.range(this.editor, path);
×
1428
                Transforms.select(this.editor, range);
×
1429
            }
1430

1431
            this.isDraggingInternally = true;
×
1432

1433
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1434
        }
1435
    }
1436

1437
    private onDOMDrop(event: DragEvent) {
1438
        const editor = this.editor;
×
1439
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1440
            event.preventDefault();
×
1441
            // Keep a reference to the dragged range before updating selection
1442
            const draggedRange = editor.selection;
×
1443

1444
            // Find the range where the drop happened
1445
            const range = AngularEditor.findEventRange(editor, event);
×
1446
            const data = event.dataTransfer;
×
1447

1448
            Transforms.select(editor, range);
×
1449

1450
            if (this.isDraggingInternally) {
×
1451
                if (draggedRange) {
×
1452
                    Transforms.delete(editor, {
×
1453
                        at: draggedRange
1454
                    });
1455
                }
1456

1457
                this.isDraggingInternally = false;
×
1458
            }
1459

1460
            AngularEditor.insertData(editor, data);
×
1461

1462
            // When dragging from another source into the editor, it's possible
1463
            // that the current editor does not have focus.
1464
            if (!AngularEditor.isFocused(editor)) {
×
1465
                AngularEditor.focus(editor);
×
1466
            }
1467
        }
1468
    }
1469

1470
    private onDOMDragEnd(event: DragEvent) {
1471
        if (
×
1472
            !this.readonly &&
×
1473
            this.isDraggingInternally &&
1474
            AngularEditor.hasTarget(this.editor, event.target) &&
1475
            !this.isDOMEventHandled(event, this.dragEnd)
1476
        ) {
1477
            this.isDraggingInternally = false;
×
1478
        }
1479
    }
1480

1481
    private onDOMFocus(event: Event) {
1482
        if (
2✔
1483
            !this.readonly &&
8✔
1484
            !this.isUpdatingSelection &&
1485
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1486
            !this.isDOMEventHandled(event, this.focus)
1487
        ) {
1488
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1489
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1490
            this.latestElement = root.activeElement;
2✔
1491

1492
            // COMPAT: If the editor has nested editable elements, the focus
1493
            // can go to them. In Firefox, this must be prevented because it
1494
            // results in issues with keyboard navigation. (2017/03/30)
1495
            if (IS_FIREFOX && event.target !== el) {
2!
1496
                el.focus();
×
1497
                return;
×
1498
            }
1499

1500
            IS_FOCUSED.set(this.editor, true);
2✔
1501
        }
1502
    }
1503

1504
    private onDOMKeydown(event: KeyboardEvent) {
1505
        const editor = this.editor;
×
1506
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1507
        const { activeElement } = root;
×
1508
        if (
×
1509
            !this.readonly &&
×
1510
            AngularEditor.hasEditableTarget(editor, event.target) &&
1511
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1512
            !this.isComposing &&
1513
            !this.isDOMEventHandled(event, this.keydown)
1514
        ) {
1515
            const nativeEvent = event;
×
1516
            const { selection } = editor;
×
1517

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

1521
            try {
×
1522
                // COMPAT: Since we prevent the default behavior on
1523
                // `beforeinput` events, the browser doesn't think there's ever
1524
                // any history stack to undo or redo, so we have to manage these
1525
                // hotkeys ourselves. (2019/11/06)
1526
                if (Hotkeys.isRedo(nativeEvent)) {
×
1527
                    event.preventDefault();
×
1528

1529
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1530
                        editor.redo();
×
1531
                    }
1532

1533
                    return;
×
1534
                }
1535

1536
                if (Hotkeys.isUndo(nativeEvent)) {
×
1537
                    event.preventDefault();
×
1538

1539
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1540
                        editor.undo();
×
1541
                    }
1542

1543
                    return;
×
1544
                }
1545

1546
                // COMPAT: Certain browsers don't handle the selection updates
1547
                // properly. In Chrome, the selection isn't properly extended.
1548
                // And in Firefox, the selection isn't properly collapsed.
1549
                // (2017/10/17)
1550
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1551
                    event.preventDefault();
×
1552
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1553
                    return;
×
1554
                }
1555

1556
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1557
                    event.preventDefault();
×
1558
                    Transforms.move(editor, { unit: 'line' });
×
1559
                    return;
×
1560
                }
1561

1562
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1563
                    event.preventDefault();
×
1564
                    Transforms.move(editor, {
×
1565
                        unit: 'line',
1566
                        edge: 'focus',
1567
                        reverse: true
1568
                    });
1569
                    return;
×
1570
                }
1571

1572
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1573
                    event.preventDefault();
×
1574
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1575
                    return;
×
1576
                }
1577

1578
                // COMPAT: If a void node is selected, or a zero-width text node
1579
                // adjacent to an inline is selected, we need to handle these
1580
                // hotkeys manually because browsers won't be able to skip over
1581
                // the void node with the zero-width space not being an empty
1582
                // string.
1583
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1584
                    event.preventDefault();
×
1585

1586
                    if (selection && Range.isCollapsed(selection)) {
×
1587
                        Transforms.move(editor, { reverse: !isRTL });
×
1588
                    } else {
1589
                        Transforms.collapse(editor, { edge: 'start' });
×
1590
                    }
1591

1592
                    return;
×
1593
                }
1594

1595
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1596
                    event.preventDefault();
×
1597
                    if (selection && Range.isCollapsed(selection)) {
×
1598
                        Transforms.move(editor, { reverse: isRTL });
×
1599
                    } else {
1600
                        Transforms.collapse(editor, { edge: 'end' });
×
1601
                    }
1602

1603
                    return;
×
1604
                }
1605

1606
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1607
                    event.preventDefault();
×
1608

1609
                    if (selection && Range.isExpanded(selection)) {
×
1610
                        Transforms.collapse(editor, { edge: 'focus' });
×
1611
                    }
1612

1613
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1614
                    return;
×
1615
                }
1616

1617
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1618
                    event.preventDefault();
×
1619

1620
                    if (selection && Range.isExpanded(selection)) {
×
1621
                        Transforms.collapse(editor, { edge: 'focus' });
×
1622
                    }
1623

1624
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1625
                    return;
×
1626
                }
1627

1628
                if (isKeyHotkey('mod+a', event)) {
×
1629
                    this.editor.selectAll();
×
1630
                    event.preventDefault();
×
1631
                    return;
×
1632
                }
1633

1634
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1635
                // fall back to guessing at the input intention for hotkeys.
1636
                // COMPAT: In iOS, some of these hotkeys are handled in the
1637
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1638
                    // We don't have a core behavior for these, but they change the
1639
                    // DOM if we don't prevent them, so we have to.
1640
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1641
                        event.preventDefault();
×
1642
                        return;
×
1643
                    }
1644

1645
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1646
                        event.preventDefault();
×
1647
                        Editor.insertBreak(editor);
×
1648
                        return;
×
1649
                    }
1650

1651
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1652
                        event.preventDefault();
×
1653

1654
                        if (selection && Range.isExpanded(selection)) {
×
1655
                            Editor.deleteFragment(editor, {
×
1656
                                direction: 'backward'
1657
                            });
1658
                        } else {
1659
                            Editor.deleteBackward(editor);
×
1660
                        }
1661

1662
                        return;
×
1663
                    }
1664

1665
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1666
                        event.preventDefault();
×
1667

1668
                        if (selection && Range.isExpanded(selection)) {
×
1669
                            Editor.deleteFragment(editor, {
×
1670
                                direction: 'forward'
1671
                            });
1672
                        } else {
1673
                            Editor.deleteForward(editor);
×
1674
                        }
1675

1676
                        return;
×
1677
                    }
1678

1679
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1680
                        event.preventDefault();
×
1681

1682
                        if (selection && Range.isExpanded(selection)) {
×
1683
                            Editor.deleteFragment(editor, {
×
1684
                                direction: 'backward'
1685
                            });
1686
                        } else {
1687
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1688
                        }
1689

1690
                        return;
×
1691
                    }
1692

1693
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1694
                        event.preventDefault();
×
1695

1696
                        if (selection && Range.isExpanded(selection)) {
×
1697
                            Editor.deleteFragment(editor, {
×
1698
                                direction: 'forward'
1699
                            });
1700
                        } else {
1701
                            Editor.deleteForward(editor, { unit: 'line' });
×
1702
                        }
1703

1704
                        return;
×
1705
                    }
1706

1707
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1708
                        event.preventDefault();
×
1709

1710
                        if (selection && Range.isExpanded(selection)) {
×
1711
                            Editor.deleteFragment(editor, {
×
1712
                                direction: 'backward'
1713
                            });
1714
                        } else {
1715
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1716
                        }
1717

1718
                        return;
×
1719
                    }
1720

1721
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1722
                        event.preventDefault();
×
1723

1724
                        if (selection && Range.isExpanded(selection)) {
×
1725
                            Editor.deleteFragment(editor, {
×
1726
                                direction: 'forward'
1727
                            });
1728
                        } else {
1729
                            Editor.deleteForward(editor, { unit: 'word' });
×
1730
                        }
1731

1732
                        return;
×
1733
                    }
1734
                } else {
1735
                    if (IS_CHROME || IS_SAFARI) {
×
1736
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1737
                        // an event when deleting backwards in a selected void inline node
1738
                        if (
×
1739
                            selection &&
×
1740
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1741
                            Range.isCollapsed(selection)
1742
                        ) {
1743
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1744
                            if (
×
1745
                                Element.isElement(currentNode) &&
×
1746
                                Editor.isVoid(editor, currentNode) &&
1747
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1748
                            ) {
1749
                                event.preventDefault();
×
1750
                                Editor.deleteBackward(editor, {
×
1751
                                    unit: 'block'
1752
                                });
1753
                                return;
×
1754
                            }
1755
                        }
1756
                    }
1757
                }
1758
            } catch (error) {
1759
                this.editor.onError({
×
1760
                    code: SlateErrorCode.OnDOMKeydownError,
1761
                    nativeError: error
1762
                });
1763
            }
1764
        }
1765
    }
1766

1767
    private onDOMPaste(event: ClipboardEvent) {
1768
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1769
        // fall back to React's `onPaste` here instead.
1770
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1771
        // when "paste without formatting" option is used.
1772
        // This unfortunately needs to be handled with paste events instead.
1773
        if (
×
1774
            !this.isDOMEventHandled(event, this.paste) &&
×
1775
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1776
            !this.readonly &&
1777
            AngularEditor.hasEditableTarget(this.editor, event.target)
1778
        ) {
1779
            event.preventDefault();
×
1780
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1781
        }
1782
    }
1783

1784
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1785
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1786
        // fall back to React's leaky polyfill instead just for it. It
1787
        // only works for the `insertText` input type.
1788
        if (
×
1789
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1790
            !this.readonly &&
1791
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1792
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1793
        ) {
1794
            event.nativeEvent.preventDefault();
×
1795
            try {
×
1796
                const text = event.data;
×
1797
                if (!Range.isCollapsed(this.editor.selection)) {
×
1798
                    Editor.deleteFragment(this.editor);
×
1799
                }
1800
                // just handle Non-IME input
1801
                if (!this.isComposing) {
×
1802
                    Editor.insertText(this.editor, text);
×
1803
                }
1804
            } catch (error) {
1805
                this.editor.onError({
×
1806
                    code: SlateErrorCode.ToNativeSelectionError,
1807
                    nativeError: error
1808
                });
1809
            }
1810
        }
1811
    }
1812

1813
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1814
        if (!handler) {
3✔
1815
            return false;
3✔
1816
        }
1817
        handler(event);
×
1818
        return event.defaultPrevented;
×
1819
    }
1820
    //#endregion
1821

1822
    ngOnDestroy() {
1823
        this.editorResizeObserver?.disconnect();
23✔
1824
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1825
        this.manualListeners.forEach(manualListener => {
23✔
1826
            manualListener();
483✔
1827
        });
1828
        this.destroy$.complete();
23✔
1829
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1830
    }
1831
}
1832

1833
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1834
    // This was affecting the selection of multiple blocks and dragging behavior,
1835
    // so enabled only if the selection has been collapsed.
1836
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1837
        const leafEl = domRange.startContainer.parentElement!;
×
1838

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

1844
        if (isZeroDimensionRect) {
×
1845
            const leafRect = leafEl.getBoundingClientRect();
×
1846
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1847

1848
            if (leafHasDimensions) {
×
1849
                return;
×
1850
            }
1851
        }
1852

1853
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1854
        scrollIntoView(leafEl, {
×
1855
            scrollMode: 'if-needed'
1856
        });
1857
        delete leafEl.getBoundingClientRect;
×
1858
    }
1859
};
1860

1861
/**
1862
 * Check if the target is inside void and in the editor.
1863
 */
1864

1865
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1866
    let slateNode: Node | null = null;
1✔
1867
    try {
1✔
1868
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1869
    } catch (error) {}
1870
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1871
};
1872

1873
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1874
    return (
2✔
1875
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1876
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1877
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1878
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1879
    );
1880
};
1881

1882
/**
1883
 * remove default insert from composition
1884
 * @param text
1885
 */
1886
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1887
    const types = ['compositionend', 'insertFromComposition'];
×
1888
    if (!types.includes(event.type)) {
×
1889
        return;
×
1890
    }
1891
    const insertText = (event as CompositionEvent).data;
×
1892
    const window = AngularEditor.getWindow(editor);
×
1893
    const domSelection = window.getSelection();
×
1894
    // ensure text node insert composition input text
1895
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1896
        const textNode = domSelection.anchorNode;
×
1897
        textNode.splitText(textNode.length - insertText.length).remove();
×
1898
    }
1899
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc