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

worktile / slate-angular / 2945ae67-f456-4380-a170-ec3b897b71a3

04 Jan 2026 09:54AM UTC coverage: 36.977% (-0.08%) from 37.055%
2945ae67-f456-4380-a170-ec3b897b71a3

push

circleci

pubuzhixing8
fix(virtual-scroll): correct virtual top height when scroll and prevent current calculation of calculateVirtualViewport #WIK-19715

386 of 1245 branches covered (31.0%)

Branch coverage included in aggregate %.

1 of 15 new or added lines in 2 files covered. (6.67%)

1 existing line in 1 file now uncovered.

1082 of 2725 relevant lines covered (39.71%)

23.99 hits per line

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

22.85
/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 } 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;
×
NEW
291
                if (isDebug) {
×
NEW
292
                    debugLog('log', 'writeValue calculate: ', virtualView.visibleIndexes, '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);
×
675
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
676
            this.editorResizeObserver = new ResizeObserver(entries => {
×
677
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
678
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
679
                    this.keyHeightMap.clear();
×
680
                    const remeasureIndics = this.inViewportIndics;
×
681
                    measureHeightByIndics(this.editor, remeasureIndics, true);
×
682
                }
683
            });
684
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
685
        }
686
    }
687

688
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
689
        if (!this.virtualScrollInitialized) {
×
690
            return;
×
691
        }
692
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
693
        if (bottomHeight !== undefined) {
×
694
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
695
        }
696
    }
697

698
    getActualVirtualTopHeight() {
699
        if (!this.virtualScrollInitialized) {
×
700
            return 0;
×
701
        }
702
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
703
    }
704

705
    handlePreRendering() {
706
        let preRenderingCount = 1;
×
707
        const childrenWithPreRendering = [...this.inViewportChildren];
×
708
        if (this.inViewportIndics[0] !== 0) {
×
709
            childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
710
        } else {
711
            preRenderingCount = 0;
×
712
        }
713
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
714
        if (lastIndex !== this.editor.children.length - 1) {
×
715
            childrenWithPreRendering.push(this.editor.children[lastIndex + 1] as Element);
×
716
        }
717
        return { preRenderingCount, childrenWithPreRendering };
×
718
    }
719

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

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

839
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
840
            const currentHeight = heights[i];
×
841
            const nextOffset = accumulatedOffset + currentHeight;
×
842
            // 可视区域有交集,加入渲染
843
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
844
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
845
                visible.push(children[i]);
×
846
                visibleIndexes.push(i);
×
847
            }
848
            accumulatedOffset = nextOffset;
×
849
        }
850

851
        if (visibleStartIndex === -1 && elementLength) {
×
852
            visibleStartIndex = elementLength - 1;
×
853
            visible.push(children[visibleStartIndex]);
×
854
            visibleIndexes.push(visibleStartIndex);
×
855
        }
856

857
        const visibleEndIndex =
858
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
859
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
860
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
861
        return {
×
862
            inViewportChildren: visible.length ? visible : children,
×
863
            visibleIndexes,
864
            top,
865
            bottom,
866
            heights,
867
            accumulatedHeights
868
        };
869
    }
870

871
    private applyVirtualView(virtualView: VirtualViewResult) {
872
        this.inViewportChildren = virtualView.inViewportChildren;
×
873
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
874
        this.inViewportIndics = virtualView.visibleIndexes;
×
875
    }
876

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

994
    //#region event proxy
995
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
996
        this.manualListeners.push(
483✔
997
            this.renderer2.listen(target, eventName, (event: Event) => {
998
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
999
                if (beforeInputEvent) {
5!
1000
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1001
                }
1002
                listener(event);
5✔
1003
            })
1004
        );
1005
    }
1006

1007
    private toSlateSelection() {
1008
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1009
            try {
1✔
1010
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1011
                const { activeElement } = root;
1✔
1012
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1013
                const domSelection = (root as Document).getSelection();
1✔
1014

1015
                if (activeElement === el) {
1!
1016
                    this.latestElement = activeElement;
1✔
1017
                    IS_FOCUSED.set(this.editor, true);
1✔
1018
                } else {
1019
                    IS_FOCUSED.delete(this.editor);
×
1020
                }
1021

1022
                if (!domSelection) {
1!
1023
                    return Transforms.deselect(this.editor);
×
1024
                }
1025

1026
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1027
                const hasDomSelectionInEditor =
1028
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1029
                if (!hasDomSelectionInEditor) {
1!
1030
                    Transforms.deselect(this.editor);
×
1031
                    return;
×
1032
                }
1033

1034
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1035
                // for example, double-click the last cell of the table to select a non-editable DOM
1036
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1037
                if (range) {
1✔
1038
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1039
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1040
                            // force adjust DOMSelection
1041
                            this.toNativeSelection(false);
×
1042
                        }
1043
                    } else {
1044
                        Transforms.select(this.editor, range);
1✔
1045
                    }
1046
                }
1047
            } catch (error) {
1048
                this.editor.onError({
×
1049
                    code: SlateErrorCode.ToSlateSelectionError,
1050
                    nativeError: error
1051
                });
1052
            }
1053
        }
1054
    }
1055

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

1134
                // COMPAT: If the selection is expanded, even if the command seems like
1135
                // a delete forward/backward command it should delete the selection.
1136
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1137
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1138
                    Editor.deleteFragment(editor, { direction });
×
1139
                    return;
×
1140
                }
1141

1142
                switch (type) {
×
1143
                    case 'deleteByComposition':
1144
                    case 'deleteByCut':
1145
                    case 'deleteByDrag': {
1146
                        Editor.deleteFragment(editor);
×
1147
                        break;
×
1148
                    }
1149

1150
                    case 'deleteContent':
1151
                    case 'deleteContentForward': {
1152
                        Editor.deleteForward(editor);
×
1153
                        break;
×
1154
                    }
1155

1156
                    case 'deleteContentBackward': {
1157
                        Editor.deleteBackward(editor);
×
1158
                        break;
×
1159
                    }
1160

1161
                    case 'deleteEntireSoftLine': {
1162
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1163
                        Editor.deleteForward(editor, { unit: 'line' });
×
1164
                        break;
×
1165
                    }
1166

1167
                    case 'deleteHardLineBackward': {
1168
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1169
                        break;
×
1170
                    }
1171

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

1177
                    case 'deleteHardLineForward': {
1178
                        Editor.deleteForward(editor, { unit: 'block' });
×
1179
                        break;
×
1180
                    }
1181

1182
                    case 'deleteSoftLineForward': {
1183
                        Editor.deleteForward(editor, { unit: 'line' });
×
1184
                        break;
×
1185
                    }
1186

1187
                    case 'deleteWordBackward': {
1188
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1189
                        break;
×
1190
                    }
1191

1192
                    case 'deleteWordForward': {
1193
                        Editor.deleteForward(editor, { unit: 'word' });
×
1194
                        break;
×
1195
                    }
1196

1197
                    case 'insertLineBreak':
1198
                    case 'insertParagraph': {
1199
                        Editor.insertBreak(editor);
×
1200
                        break;
×
1201
                    }
1202

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

1238
    private onDOMBlur(event: FocusEvent) {
1239
        if (
×
1240
            this.readonly ||
×
1241
            this.isUpdatingSelection ||
1242
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1243
            this.isDOMEventHandled(event, this.blur)
1244
        ) {
1245
            return;
×
1246
        }
1247

1248
        const window = AngularEditor.getWindow(this.editor);
×
1249

1250
        // COMPAT: If the current `activeElement` is still the previous
1251
        // one, this is due to the window being blurred when the tab
1252
        // itself becomes unfocused, so we want to abort early to allow to
1253
        // editor to stay focused when the tab becomes focused again.
1254
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1255
        if (this.latestElement === root.activeElement) {
×
1256
            return;
×
1257
        }
1258

1259
        const { relatedTarget } = event;
×
1260
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1261

1262
        // COMPAT: The event should be ignored if the focus is returning
1263
        // to the editor from an embedded editable element (eg. an <input>
1264
        // element inside a void node).
1265
        if (relatedTarget === el) {
×
1266
            return;
×
1267
        }
1268

1269
        // COMPAT: The event should be ignored if the focus is moving from
1270
        // the editor to inside a void node's spacer element.
1271
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1272
            return;
×
1273
        }
1274

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

1281
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1282
                return;
×
1283
            }
1284
        }
1285

1286
        IS_FOCUSED.delete(this.editor);
×
1287
    }
1288

1289
    private onDOMClick(event: MouseEvent) {
1290
        if (
×
1291
            !this.readonly &&
×
1292
            AngularEditor.hasTarget(this.editor, event.target) &&
1293
            !this.isDOMEventHandled(event, this.click) &&
1294
            isDOMNode(event.target)
1295
        ) {
1296
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1297
            const path = AngularEditor.findPath(this.editor, node);
×
1298
            const start = Editor.start(this.editor, path);
×
1299
            const end = Editor.end(this.editor, path);
×
1300

1301
            const startVoid = Editor.void(this.editor, { at: start });
×
1302
            const endVoid = Editor.void(this.editor, { at: end });
×
1303

1304
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1305
                let blockPath = path;
×
1306
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1307
                    const block = Editor.above(this.editor, {
×
1308
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1309
                        at: path
1310
                    });
1311

1312
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1313
                }
1314

1315
                const range = Editor.range(this.editor, blockPath);
×
1316
                Transforms.select(this.editor, range);
×
1317
                return;
×
1318
            }
1319

1320
            if (
×
1321
                startVoid &&
×
1322
                endVoid &&
1323
                Path.equals(startVoid[1], endVoid[1]) &&
1324
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1325
            ) {
1326
                const range = Editor.range(this.editor, start);
×
1327
                Transforms.select(this.editor, range);
×
1328
            }
1329
        }
1330
    }
1331

1332
    private onDOMCompositionStart(event: CompositionEvent) {
1333
        const { selection } = this.editor;
1✔
1334
        if (selection) {
1!
1335
            // solve the problem of cross node Chinese input
1336
            if (Range.isExpanded(selection)) {
×
1337
                Editor.deleteFragment(this.editor);
×
1338
                this.forceRender();
×
1339
            }
1340
        }
1341
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1342
            this.isComposing = true;
1✔
1343
        }
1344
        this.render();
1✔
1345
    }
1346

1347
    private onDOMCompositionUpdate(event: CompositionEvent) {
1348
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1349
    }
1350

1351
    private onDOMCompositionEnd(event: CompositionEvent) {
1352
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1353
            Transforms.delete(this.editor);
×
1354
        }
1355
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1356
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1357
            // aren't correct and never fire the "insertFromComposition"
1358
            // type that we need. So instead, insert whenever a composition
1359
            // ends since it will already have been committed to the DOM.
1360
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1361
                preventInsertFromComposition(event, this.editor);
×
1362
                Editor.insertText(this.editor, event.data);
×
1363
            }
1364

1365
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1366
            // so we need avoid repeat isnertText by isComposing === true,
1367
            this.isComposing = false;
×
1368
        }
1369
        this.render();
×
1370
    }
1371

1372
    private onDOMCopy(event: ClipboardEvent) {
1373
        const window = AngularEditor.getWindow(this.editor);
×
1374
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1375
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1376
            event.preventDefault();
×
1377
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1378
        }
1379
    }
1380

1381
    private onDOMCut(event: ClipboardEvent) {
1382
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1383
            event.preventDefault();
×
1384
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1385
            const { selection } = this.editor;
×
1386

1387
            if (selection) {
×
1388
                AngularEditor.deleteCutData(this.editor);
×
1389
            }
1390
        }
1391
    }
1392

1393
    private onDOMDragOver(event: DragEvent) {
1394
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1395
            // Only when the target is void, call `preventDefault` to signal
1396
            // that drops are allowed. Editable content is droppable by
1397
            // default, and calling `preventDefault` hides the cursor.
1398
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1399

1400
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1401
                event.preventDefault();
×
1402
            }
1403
        }
1404
    }
1405

1406
    private onDOMDragStart(event: DragEvent) {
1407
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1408
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1409
            const path = AngularEditor.findPath(this.editor, node);
×
1410
            const voidMatch =
1411
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1412

1413
            // If starting a drag on a void node, make sure it is selected
1414
            // so that it shows up in the selection's fragment.
1415
            if (voidMatch) {
×
1416
                const range = Editor.range(this.editor, path);
×
1417
                Transforms.select(this.editor, range);
×
1418
            }
1419

1420
            this.isDraggingInternally = true;
×
1421

1422
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1423
        }
1424
    }
1425

1426
    private onDOMDrop(event: DragEvent) {
1427
        const editor = this.editor;
×
1428
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1429
            event.preventDefault();
×
1430
            // Keep a reference to the dragged range before updating selection
1431
            const draggedRange = editor.selection;
×
1432

1433
            // Find the range where the drop happened
1434
            const range = AngularEditor.findEventRange(editor, event);
×
1435
            const data = event.dataTransfer;
×
1436

1437
            Transforms.select(editor, range);
×
1438

1439
            if (this.isDraggingInternally) {
×
1440
                if (draggedRange) {
×
1441
                    Transforms.delete(editor, {
×
1442
                        at: draggedRange
1443
                    });
1444
                }
1445

1446
                this.isDraggingInternally = false;
×
1447
            }
1448

1449
            AngularEditor.insertData(editor, data);
×
1450

1451
            // When dragging from another source into the editor, it's possible
1452
            // that the current editor does not have focus.
1453
            if (!AngularEditor.isFocused(editor)) {
×
1454
                AngularEditor.focus(editor);
×
1455
            }
1456
        }
1457
    }
1458

1459
    private onDOMDragEnd(event: DragEvent) {
1460
        if (
×
1461
            !this.readonly &&
×
1462
            this.isDraggingInternally &&
1463
            AngularEditor.hasTarget(this.editor, event.target) &&
1464
            !this.isDOMEventHandled(event, this.dragEnd)
1465
        ) {
1466
            this.isDraggingInternally = false;
×
1467
        }
1468
    }
1469

1470
    private onDOMFocus(event: Event) {
1471
        if (
2✔
1472
            !this.readonly &&
8✔
1473
            !this.isUpdatingSelection &&
1474
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1475
            !this.isDOMEventHandled(event, this.focus)
1476
        ) {
1477
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1478
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1479
            this.latestElement = root.activeElement;
2✔
1480

1481
            // COMPAT: If the editor has nested editable elements, the focus
1482
            // can go to them. In Firefox, this must be prevented because it
1483
            // results in issues with keyboard navigation. (2017/03/30)
1484
            if (IS_FIREFOX && event.target !== el) {
2!
1485
                el.focus();
×
1486
                return;
×
1487
            }
1488

1489
            IS_FOCUSED.set(this.editor, true);
2✔
1490
        }
1491
    }
1492

1493
    private onDOMKeydown(event: KeyboardEvent) {
1494
        const editor = this.editor;
×
1495
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1496
        const { activeElement } = root;
×
1497
        if (
×
1498
            !this.readonly &&
×
1499
            AngularEditor.hasEditableTarget(editor, event.target) &&
1500
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1501
            !this.isComposing &&
1502
            !this.isDOMEventHandled(event, this.keydown)
1503
        ) {
1504
            const nativeEvent = event;
×
1505
            const { selection } = editor;
×
1506

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

1510
            try {
×
1511
                // COMPAT: Since we prevent the default behavior on
1512
                // `beforeinput` events, the browser doesn't think there's ever
1513
                // any history stack to undo or redo, so we have to manage these
1514
                // hotkeys ourselves. (2019/11/06)
1515
                if (Hotkeys.isRedo(nativeEvent)) {
×
1516
                    event.preventDefault();
×
1517

1518
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1519
                        editor.redo();
×
1520
                    }
1521

1522
                    return;
×
1523
                }
1524

1525
                if (Hotkeys.isUndo(nativeEvent)) {
×
1526
                    event.preventDefault();
×
1527

1528
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1529
                        editor.undo();
×
1530
                    }
1531

1532
                    return;
×
1533
                }
1534

1535
                // COMPAT: Certain browsers don't handle the selection updates
1536
                // properly. In Chrome, the selection isn't properly extended.
1537
                // And in Firefox, the selection isn't properly collapsed.
1538
                // (2017/10/17)
1539
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1540
                    event.preventDefault();
×
1541
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1542
                    return;
×
1543
                }
1544

1545
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1546
                    event.preventDefault();
×
1547
                    Transforms.move(editor, { unit: 'line' });
×
1548
                    return;
×
1549
                }
1550

1551
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1552
                    event.preventDefault();
×
1553
                    Transforms.move(editor, {
×
1554
                        unit: 'line',
1555
                        edge: 'focus',
1556
                        reverse: true
1557
                    });
1558
                    return;
×
1559
                }
1560

1561
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1562
                    event.preventDefault();
×
1563
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1564
                    return;
×
1565
                }
1566

1567
                // COMPAT: If a void node is selected, or a zero-width text node
1568
                // adjacent to an inline is selected, we need to handle these
1569
                // hotkeys manually because browsers won't be able to skip over
1570
                // the void node with the zero-width space not being an empty
1571
                // string.
1572
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1573
                    event.preventDefault();
×
1574

1575
                    if (selection && Range.isCollapsed(selection)) {
×
1576
                        Transforms.move(editor, { reverse: !isRTL });
×
1577
                    } else {
1578
                        Transforms.collapse(editor, { edge: 'start' });
×
1579
                    }
1580

1581
                    return;
×
1582
                }
1583

1584
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1585
                    event.preventDefault();
×
1586
                    if (selection && Range.isCollapsed(selection)) {
×
1587
                        Transforms.move(editor, { reverse: isRTL });
×
1588
                    } else {
1589
                        Transforms.collapse(editor, { edge: 'end' });
×
1590
                    }
1591

1592
                    return;
×
1593
                }
1594

1595
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1596
                    event.preventDefault();
×
1597

1598
                    if (selection && Range.isExpanded(selection)) {
×
1599
                        Transforms.collapse(editor, { edge: 'focus' });
×
1600
                    }
1601

1602
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1603
                    return;
×
1604
                }
1605

1606
                if (Hotkeys.isMoveWordForward(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 (isKeyHotkey('mod+a', event)) {
×
1618
                    this.editor.selectAll();
×
1619
                    event.preventDefault();
×
1620
                    return;
×
1621
                }
1622

1623
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1624
                // fall back to guessing at the input intention for hotkeys.
1625
                // COMPAT: In iOS, some of these hotkeys are handled in the
1626
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1627
                    // We don't have a core behavior for these, but they change the
1628
                    // DOM if we don't prevent them, so we have to.
1629
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1630
                        event.preventDefault();
×
1631
                        return;
×
1632
                    }
1633

1634
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1635
                        event.preventDefault();
×
1636
                        Editor.insertBreak(editor);
×
1637
                        return;
×
1638
                    }
1639

1640
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1641
                        event.preventDefault();
×
1642

1643
                        if (selection && Range.isExpanded(selection)) {
×
1644
                            Editor.deleteFragment(editor, {
×
1645
                                direction: 'backward'
1646
                            });
1647
                        } else {
1648
                            Editor.deleteBackward(editor);
×
1649
                        }
1650

1651
                        return;
×
1652
                    }
1653

1654
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1655
                        event.preventDefault();
×
1656

1657
                        if (selection && Range.isExpanded(selection)) {
×
1658
                            Editor.deleteFragment(editor, {
×
1659
                                direction: 'forward'
1660
                            });
1661
                        } else {
1662
                            Editor.deleteForward(editor);
×
1663
                        }
1664

1665
                        return;
×
1666
                    }
1667

1668
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1669
                        event.preventDefault();
×
1670

1671
                        if (selection && Range.isExpanded(selection)) {
×
1672
                            Editor.deleteFragment(editor, {
×
1673
                                direction: 'backward'
1674
                            });
1675
                        } else {
1676
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1677
                        }
1678

1679
                        return;
×
1680
                    }
1681

1682
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1683
                        event.preventDefault();
×
1684

1685
                        if (selection && Range.isExpanded(selection)) {
×
1686
                            Editor.deleteFragment(editor, {
×
1687
                                direction: 'forward'
1688
                            });
1689
                        } else {
1690
                            Editor.deleteForward(editor, { unit: 'line' });
×
1691
                        }
1692

1693
                        return;
×
1694
                    }
1695

1696
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1697
                        event.preventDefault();
×
1698

1699
                        if (selection && Range.isExpanded(selection)) {
×
1700
                            Editor.deleteFragment(editor, {
×
1701
                                direction: 'backward'
1702
                            });
1703
                        } else {
1704
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1705
                        }
1706

1707
                        return;
×
1708
                    }
1709

1710
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1711
                        event.preventDefault();
×
1712

1713
                        if (selection && Range.isExpanded(selection)) {
×
1714
                            Editor.deleteFragment(editor, {
×
1715
                                direction: 'forward'
1716
                            });
1717
                        } else {
1718
                            Editor.deleteForward(editor, { unit: 'word' });
×
1719
                        }
1720

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

1756
    private onDOMPaste(event: ClipboardEvent) {
1757
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1758
        // fall back to React's `onPaste` here instead.
1759
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1760
        // when "paste without formatting" option is used.
1761
        // This unfortunately needs to be handled with paste events instead.
1762
        if (
×
1763
            !this.isDOMEventHandled(event, this.paste) &&
×
1764
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1765
            !this.readonly &&
1766
            AngularEditor.hasEditableTarget(this.editor, event.target)
1767
        ) {
1768
            event.preventDefault();
×
1769
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1770
        }
1771
    }
1772

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

1802
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1803
        if (!handler) {
3✔
1804
            return false;
3✔
1805
        }
1806
        handler(event);
×
1807
        return event.defaultPrevented;
×
1808
    }
1809
    //#endregion
1810

1811
    ngOnDestroy() {
1812
        this.editorResizeObserver?.disconnect();
23✔
1813
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1814
        this.manualListeners.forEach(manualListener => {
23✔
1815
            manualListener();
483✔
1816
        });
1817
        this.destroy$.complete();
23✔
1818
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1819
    }
1820
}
1821

1822
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1823
    // This was affecting the selection of multiple blocks and dragging behavior,
1824
    // so enabled only if the selection has been collapsed.
1825
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1826
        const leafEl = domRange.startContainer.parentElement!;
×
1827

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

1833
        if (isZeroDimensionRect) {
×
1834
            const leafRect = leafEl.getBoundingClientRect();
×
1835
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1836

1837
            if (leafHasDimensions) {
×
1838
                return;
×
1839
            }
1840
        }
1841

1842
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1843
        scrollIntoView(leafEl, {
×
1844
            scrollMode: 'if-needed'
1845
        });
1846
        delete leafEl.getBoundingClientRect;
×
1847
    }
1848
};
1849

1850
/**
1851
 * Check if the target is inside void and in the editor.
1852
 */
1853

1854
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1855
    let slateNode: Node | null = null;
1✔
1856
    try {
1✔
1857
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1858
    } catch (error) {}
1859
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1860
};
1861

1862
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1863
    return (
2✔
1864
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1865
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1866
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1867
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1868
    );
1869
};
1870

1871
/**
1872
 * remove default insert from composition
1873
 * @param text
1874
 */
1875
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1876
    const types = ['compositionend', 'insertFromComposition'];
×
1877
    if (!types.includes(event.type)) {
×
1878
        return;
×
1879
    }
1880
    const insertText = (event as CompositionEvent).data;
×
1881
    const window = AngularEditor.getWindow(editor);
×
1882
    const domSelection = window.getSelection();
×
1883
    // ensure text node insert composition input text
1884
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1885
        const textNode = domSelection.anchorNode;
×
1886
        textNode.splitText(textNode.length - insertText.length).remove();
×
1887
    }
1888
};
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