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

worktile / slate-angular / 6408168d-d8c9-4b7d-9ddb-60e5d55c874f

16 Dec 2025 12:57PM UTC coverage: 37.323% (-0.1%) from 37.429%
6408168d-d8c9-4b7d-9ddb-60e5d55c874f

push

circleci

web-flow
perf(virtual-scroll): support remeasure height only when element is c… (#326)

* perf(virtual-scroll): support remeasure height only when element is changed or added #WIK-19585

* chore: remove getPreviousHeightsAndClear

* chore: changeset

380 of 1222 branches covered (31.1%)

Branch coverage included in aggregate %.

0 of 29 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

1070 of 2663 relevant lines covered (40.18%)

24.43 hits per line

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

22.46
/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
    VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT,
49
    SLATE_DEBUG_KEY
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
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
61
    ELEMENT_KEY_TO_HEIGHTS,
62
    ELEMENT_TO_COMPONENT,
63
    IS_ENABLED_VIRTUAL_SCROLL,
64
    isDecoratorRangeListEqual
65
} from '../../utils';
66
import { SlatePlaceholder } from '../../types/feature';
67
import { restoreDom } from '../../utils/restore-dom';
68
import { ListRender } from '../../view/render/list-render';
69
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
70
import { BaseElementComponent } from '../../view/base';
71
import { BaseElementFlavour } from '../../view/flavour/element';
72
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
73
import { isKeyHotkey } from 'is-hotkey';
74
import { VirtualScrollDebugOverlay } from './debug';
75

76
// not correctly clipboardData on beforeinput
77
const forceOnDOMPaste = IS_SAFARI;
1✔
78

79
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
80

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

106
    private destroy$ = new Subject();
23✔
107

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

113
    protected manualListeners: (() => void)[] = [];
23✔
114

115
    private initialized: boolean;
116

117
    private onTouchedCallback: () => void = () => {};
23✔
118

119
    private onChangeCallback: (_: any) => void = () => {};
23✔
120

121
    @Input() editor: AngularEditor;
122

123
    @Input() renderElement: (element: Element) => ViewType | null;
124

125
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
126

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

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

131
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
132

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

135
    @Input() isStrictDecorate: boolean = true;
23✔
136

137
    @Input() trackBy: (node: Element) => any = () => null;
206✔
138

139
    @Input() readonly = false;
23✔
140

141
    @Input() placeholder: string;
142

143
    @Input()
144
    set virtualScroll(config: SlateVirtualScrollConfig) {
145
        this.virtualScrollConfig = config;
×
146
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
147
        if (this.isEnabledVirtualScroll()) {
×
148
            this.tryUpdateVirtualViewport();
×
149
        }
150
    }
151

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

170
    //#region DOM attr
171
    @Input() spellCheck = false;
23✔
172
    @Input() autoCorrect = false;
23✔
173
    @Input() autoCapitalize = false;
23✔
174

175
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
176
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
177
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
178

179
    get hasBeforeInputSupport() {
180
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
181
    }
182
    //#endregion
183

184
    viewContainerRef = inject(ViewContainerRef);
23✔
185

186
    getOutletParent = () => {
23✔
187
        return this.elementRef.nativeElement;
43✔
188
    };
189

190
    getOutletElement = () => {
23✔
191
        if (this.virtualScrollInitialized) {
23!
192
            return this.virtualCenterOutlet;
×
193
        } else {
194
            return null;
23✔
195
        }
196
    };
197

198
    listRender: ListRender;
199

200
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
201
        enabled: false,
202
        scrollTop: 0,
203
        viewportHeight: 0
204
    };
205

206
    private inViewportChildren: Element[] = [];
23✔
207
    private inViewportIndics = new Set<number>();
23✔
208
    private keyHeightMap = new Map<string, number>();
23✔
209
    private tryUpdateVirtualViewportAnimId: number;
210
    private tryMeasureInViewportChildrenHeightsAnimId: number;
211
    private editorResizeObserver?: ResizeObserver;
212

213
    constructor(
214
        public elementRef: ElementRef,
23✔
215
        public renderer2: Renderer2,
23✔
216
        public cdr: ChangeDetectorRef,
23✔
217
        private ngZone: NgZone,
23✔
218
        private injector: Injector
23✔
219
    ) {}
220

221
    ngOnInit() {
222
        this.editor.injector = this.injector;
23✔
223
        this.editor.children = [];
23✔
224
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
225
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
226
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
227
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
228
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
229
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
230
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
231
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
232
            this.ngZone.run(() => {
13✔
233
                this.onChange();
13✔
234
            });
235
        });
236
        this.ngZone.runOutsideAngular(() => {
23✔
237
            this.initialize();
23✔
238
        });
239
        this.initializeViewContext();
23✔
240
        this.initializeContext();
23✔
241

242
        // add browser class
243
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
244
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
245
        this.initializeVirtualScroll();
23✔
246
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
247
    }
248

249
    ngOnChanges(simpleChanges: SimpleChanges) {
250
        if (!this.initialized) {
30✔
251
            return;
23✔
252
        }
253
        const decorateChange = simpleChanges['decorate'];
7✔
254
        if (decorateChange) {
7✔
255
            this.forceRender();
2✔
256
        }
257
        const placeholderChange = simpleChanges['placeholder'];
7✔
258
        if (placeholderChange) {
7✔
259
            this.render();
1✔
260
        }
261
        const readonlyChange = simpleChanges['readonly'];
7✔
262
        if (readonlyChange) {
7!
263
            IS_READ_ONLY.set(this.editor, this.readonly);
×
264
            this.render();
×
265
            this.toSlateSelection();
×
266
        }
267
    }
268

269
    registerOnChange(fn: any) {
270
        this.onChangeCallback = fn;
23✔
271
    }
272
    registerOnTouched(fn: any) {
273
        this.onTouchedCallback = fn;
23✔
274
    }
275

276
    writeValue(value: Element[]) {
277
        if (value && value.length) {
49✔
278
            this.editor.children = value;
26✔
279
            this.initializeContext();
26✔
280
            if (this.isEnabledVirtualScroll()) {
26!
281
                const virtualView = this.calculateVirtualViewport();
×
282
                this.applyVirtualView(virtualView);
×
283
                const childrenForRender = virtualView.inViewportChildren;
×
284
                if (!this.listRender.initialized) {
×
285
                    this.listRender.initialize(childrenForRender, this.editor, this.context);
×
286
                } else {
287
                    this.listRender.update(childrenForRender, this.editor, this.context);
×
288
                }
NEW
289
                this.tryMeasureInViewportChildrenHeights();
×
290
            } else {
291
                if (!this.listRender.initialized) {
26✔
292
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
293
                } else {
294
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
295
                }
296
            }
297
            this.cdr.markForCheck();
26✔
298
        }
299
    }
300

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

333
    calculateVirtualScrollSelection(selection: Selection) {
334
        if (selection) {
×
335
            const indics = Array.from(this.inViewportIndics.values());
×
336
            if (indics.length > 0) {
×
337
                const currentVisibleRange: Range = {
×
338
                    anchor: Editor.start(this.editor, [indics[0]]),
339
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
340
                };
341
                const [start, end] = Range.edges(selection);
×
342
                const forwardSelection = { anchor: start, focus: end };
×
343
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
344
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
345
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
346
                    if (isDebug) {
×
347
                        this.debugLog(
×
348
                            'log',
349
                            `selection is not in visible range, selection: ${JSON.stringify(
350
                                selection
351
                            )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
352
                        );
353
                    }
354
                    return intersectedSelection;
×
355
                }
356
                return selection;
×
357
            }
358
        }
359
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
360
        return selection;
×
361
    }
362

363
    toNativeSelection() {
364
        try {
15✔
365
            let { selection } = this.editor;
15✔
366
            if (this.isEnabledVirtualScroll()) {
15!
367
                selection = this.calculateVirtualScrollSelection(selection);
×
368
            }
369
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
370
            const { activeElement } = root;
15✔
371
            const domSelection = (root as Document).getSelection();
15✔
372

373
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
374
                return;
14✔
375
            }
376

377
            const hasDomSelection = domSelection.type !== 'None';
1✔
378

379
            // If the DOM selection is properly unset, we're done.
380
            if (!selection && !hasDomSelection) {
1!
381
                return;
×
382
            }
383

384
            // If the DOM selection is already correct, we're done.
385
            // verify that the dom selection is in the editor
386
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
387
            let hasDomSelectionInEditor = false;
1✔
388
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
389
                hasDomSelectionInEditor = true;
1✔
390
            }
391

392
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
393
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
394
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
395
                    exactMatch: false,
396
                    suppressThrow: true
397
                });
398
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
399
                    return;
×
400
                }
401
            }
402

403
            // prevent updating native selection when active element is void element
404
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
405
                return;
×
406
            }
407

408
            // when <Editable/> is being controlled through external value
409
            // then its children might just change - DOM responds to it on its own
410
            // but Slate's value is not being updated through any operation
411
            // and thus it doesn't transform selection on its own
412
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
413
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
414
                return;
×
415
            }
416

417
            // Otherwise the DOM selection is out of sync, so update it.
418
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
419
            this.isUpdatingSelection = true;
1✔
420

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

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

447
            setTimeout(() => {
1✔
448
                // handle scrolling in setTimeout because of
449
                // dom should not have updated immediately after listRender's updating
450
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
451
                // COMPAT: In Firefox, it's not enough to create a range, you also need
452
                // to focus the contenteditable element too. (2016/11/16)
453
                if (newDomRange && IS_FIREFOX) {
1!
454
                    el.focus();
×
455
                }
456

457
                this.isUpdatingSelection = false;
1✔
458
            });
459
        } catch (error) {
460
            this.editor.onError({
×
461
                code: SlateErrorCode.ToNativeSelectionError,
462
                nativeError: error
463
            });
464
            this.isUpdatingSelection = false;
×
465
        }
466
    }
467

468
    onChange() {
469
        this.forceRender();
13✔
470
        this.onChangeCallback(this.editor.children);
13✔
471
    }
472

473
    ngAfterViewChecked() {}
474

475
    ngDoCheck() {}
476

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

520
    render() {
521
        const changed = this.updateContext();
2✔
522
        if (changed) {
2✔
523
            if (this.isEnabledVirtualScroll()) {
2!
NEW
524
                this.updateListRenderAndRemeasureHeights();
×
525
            } else {
526
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
527
            }
528
        }
529
    }
530

531
    updateListRenderAndRemeasureHeights() {
NEW
532
        const virtualView = this.calculateVirtualViewport();
×
NEW
533
        const oldInViewportChildren = this.inViewportChildren;
×
NEW
534
        this.applyVirtualView(virtualView);
×
NEW
535
        this.listRender.update(this.inViewportChildren, this.editor, this.context);
×
536
        // 新增或者修改的才需要重算,计算出这个结果
NEW
537
        const remeasureIndics = [];
×
NEW
538
        const newInViewportIndics = Array.from(this.inViewportIndics);
×
NEW
539
        this.inViewportChildren.forEach((child, index) => {
×
NEW
540
            if (oldInViewportChildren.indexOf(child) === -1) {
×
NEW
541
                remeasureIndics.push(newInViewportIndics[index]);
×
542
            }
543
        });
NEW
544
        if (isDebug && remeasureIndics.length > 0) {
×
NEW
545
            console.log('remeasure height by indics: ', remeasureIndics);
×
546
        }
NEW
547
        this.remeasureHeightByIndics(remeasureIndics);
×
548
    }
549

550
    updateContext() {
551
        const decorations = this.generateDecorations();
17✔
552
        if (
17✔
553
            this.context.selection !== this.editor.selection ||
46✔
554
            this.context.decorate !== this.decorate ||
555
            this.context.readonly !== this.readonly ||
556
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
557
        ) {
558
            this.context = {
10✔
559
                parent: this.editor,
560
                selection: this.editor.selection,
561
                decorations: decorations,
562
                decorate: this.decorate,
563
                readonly: this.readonly
564
            };
565
            return true;
10✔
566
        }
567
        return false;
7✔
568
    }
569

570
    initializeContext() {
571
        this.context = {
49✔
572
            parent: this.editor,
573
            selection: this.editor.selection,
574
            decorations: this.generateDecorations(),
575
            decorate: this.decorate,
576
            readonly: this.readonly
577
        };
578
    }
579

580
    initializeViewContext() {
581
        this.viewContext = {
23✔
582
            editor: this.editor,
583
            renderElement: this.renderElement,
584
            renderLeaf: this.renderLeaf,
585
            renderText: this.renderText,
586
            trackBy: this.trackBy,
587
            isStrictDecorate: this.isStrictDecorate
588
        };
589
    }
590

591
    composePlaceholderDecorate(editor: Editor) {
592
        if (this.placeholderDecorate) {
64!
593
            return this.placeholderDecorate(editor) || [];
×
594
        }
595

596
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
597
            const start = Editor.start(editor, []);
3✔
598
            return [
3✔
599
                {
600
                    placeholder: this.placeholder,
601
                    anchor: start,
602
                    focus: start
603
                }
604
            ];
605
        } else {
606
            return [];
61✔
607
        }
608
    }
609

610
    generateDecorations() {
611
        const decorations = this.decorate([this.editor, []]);
66✔
612
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
613
        decorations.push(...placeholderDecorations);
66✔
614
        return decorations;
66✔
615
    }
616

617
    private isEnabledVirtualScroll() {
618
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
81✔
619
    }
620

621
    // the height from scroll container top to editor top height element
622
    private businessHeight: number = 0;
23✔
623

624
    virtualScrollInitialized = false;
23✔
625

626
    virtualTopHeightElement: HTMLElement;
627

628
    virtualBottomHeightElement: HTMLElement;
629

630
    virtualCenterOutlet: HTMLElement;
631

632
    initializeVirtualScroll() {
633
        if (this.virtualScrollInitialized) {
23!
634
            return;
×
635
        }
636
        if (this.isEnabledVirtualScroll()) {
23!
637
            this.virtualScrollInitialized = true;
×
638
            this.virtualTopHeightElement = document.createElement('div');
×
639
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
640
            this.virtualTopHeightElement.contentEditable = 'false';
×
641
            this.virtualBottomHeightElement = document.createElement('div');
×
642
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
643
            this.virtualBottomHeightElement.contentEditable = 'false';
×
644
            this.virtualCenterOutlet = document.createElement('div');
×
645
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
646
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
647
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
648
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
649
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
650
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
651
            this.editorResizeObserver = new ResizeObserver(entries => {
×
652
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
653
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
NEW
654
                    const remeasureIndics = Array.from(this.inViewportIndics);
×
NEW
655
                    this.remeasureHeightByIndics(remeasureIndics);
×
656
                }
657
            });
658
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
659
            if (isDebug) {
×
660
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
661
                VirtualScrollDebugOverlay.getInstance(doc);
×
662
            }
663
        }
664
    }
665

666
    setVirtualSpaceHeight(topHeight: number, bottomHeight: number) {
667
        if (!this.virtualScrollInitialized) {
×
668
            return;
×
669
        }
670
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
671
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
672
    }
673

674
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
675
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
676
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
677
    }
678

679
    private tryUpdateVirtualViewport() {
NEW
680
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
NEW
681
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
682
            let virtualView = this.calculateVirtualViewport();
×
683
            let diff = this.diffVirtualViewport(virtualView);
×
684
            if (!diff.isDiff) {
×
685
                return;
×
686
            }
687
            if (diff.isMissingTop) {
×
NEW
688
                const remeasureIndics = diff.diffTopRenderedIndexes;
×
NEW
689
                const result = this.remeasureHeightByIndics(remeasureIndics);
×
690
                if (result) {
×
691
                    virtualView = this.calculateVirtualViewport();
×
692
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
693
                    if (!diff.isDiff) {
×
694
                        return;
×
695
                    }
696
                }
697
            }
698
            this.applyVirtualView(virtualView);
×
699
            if (this.listRender.initialized) {
×
700
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
701
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
702
                    this.toNativeSelection();
×
703
                }
704
            }
NEW
705
            this.tryMeasureInViewportChildrenHeights();
×
706
        });
707
    }
708

709
    private calculateVirtualViewport() {
710
        const children = (this.editor.children || []) as Element[];
×
711
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
712
            return {
×
713
                inViewportChildren: children,
714
                visibleIndexes: new Set<number>(),
715
                top: 0,
716
                bottom: 0,
717
                heights: []
718
            };
719
        }
720
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
721
        if (isDebug) {
×
722
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
723
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
724
        }
725
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
726
        if (!viewportHeight) {
×
727
            return {
×
728
                inViewportChildren: [],
729
                visibleIndexes: new Set<number>(),
730
                top: 0,
731
                bottom: 0,
732
                heights: []
733
            };
734
        }
735
        const elementLength = children.length;
×
736
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
737
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
738
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
739
        const totalHeight = accumulatedHeights[elementLength];
×
740
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
741
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
742
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
743
        let accumulatedOffset = 0;
×
744
        let visibleStartIndex = -1;
×
745
        const visible: Element[] = [];
×
746
        const visibleIndexes: number[] = [];
×
747

748
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
749
            const currentHeight = heights[i];
×
750
            const nextOffset = accumulatedOffset + currentHeight;
×
751
            // 可视区域有交集,加入渲染
752
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
753
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
754
                visible.push(children[i]);
×
755
                visibleIndexes.push(i);
×
756
            }
757
            accumulatedOffset = nextOffset;
×
758
        }
759

760
        if (visibleStartIndex === -1 && elementLength) {
×
761
            visibleStartIndex = elementLength - 1;
×
762
            visible.push(children[visibleStartIndex]);
×
763
            visibleIndexes.push(visibleStartIndex);
×
764
        }
765

766
        const visibleEndIndex =
767
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
768
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
769
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
770

771
        return {
×
772
            inViewportChildren: visible.length ? visible : children,
×
773
            visibleIndexes: new Set(visibleIndexes),
774
            top,
775
            bottom,
776
            heights
777
        };
778
    }
779

780
    private applyVirtualView(virtualView: VirtualViewResult) {
781
        this.inViewportChildren = virtualView.inViewportChildren;
×
782
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
783
        this.inViewportIndics = virtualView.visibleIndexes;
×
784
    }
785

786
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
787
        if (!this.inViewportChildren.length) {
×
788
            return {
×
789
                isDiff: true,
790
                diffTopRenderedIndexes: [],
791
                diffBottomRenderedIndexes: []
792
            };
793
        }
794
        const oldVisibleIndexes = [...this.inViewportIndics];
×
795
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
796
        const firstNewIndex = newVisibleIndexes[0];
×
797
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
798
        const firstOldIndex = oldVisibleIndexes[0];
×
799
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
800
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
801
            const diffTopRenderedIndexes = [];
×
802
            const diffBottomRenderedIndexes = [];
×
803
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
804
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
805
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
806
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
807
            if (isMissingTop || isAddedBottom) {
×
808
                // 向下
809
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
810
                    const element = oldVisibleIndexes[index];
×
811
                    if (!newVisibleIndexes.includes(element)) {
×
812
                        diffTopRenderedIndexes.push(element);
×
813
                    } else {
814
                        break;
×
815
                    }
816
                }
817
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
818
                    const element = newVisibleIndexes[index];
×
819
                    if (!oldVisibleIndexes.includes(element)) {
×
820
                        diffBottomRenderedIndexes.push(element);
×
821
                    } else {
822
                        break;
×
823
                    }
824
                }
825
            } else if (isAddedTop || isMissingBottom) {
×
826
                // 向上
827
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
828
                    const element = newVisibleIndexes[index];
×
829
                    if (!oldVisibleIndexes.includes(element)) {
×
830
                        diffTopRenderedIndexes.push(element);
×
831
                    } else {
832
                        break;
×
833
                    }
834
                }
835
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
836
                    const element = oldVisibleIndexes[index];
×
837
                    if (!newVisibleIndexes.includes(element)) {
×
838
                        diffBottomRenderedIndexes.push(element);
×
839
                    } else {
840
                        break;
×
841
                    }
842
                }
843
            }
844
            if (isDebug) {
×
845
                this.debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
846
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
847
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
848
                this.debugLog(
×
849
                    'log',
850
                    'diffTopRenderedIndexes:',
851
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
852
                    diffTopRenderedIndexes,
853
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
854
                );
855
                this.debugLog(
×
856
                    'log',
857
                    'diffBottomRenderedIndexes:',
858
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
859
                    diffBottomRenderedIndexes,
860
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
861
                );
862
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
863
                const needBottom = virtualView.heights
×
864
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
865
                    .reduce((acc, height) => acc + height, 0);
×
866
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
867
                this.debugLog(
×
868
                    'log',
869
                    'newBottomHeight:',
870
                    needBottom,
871
                    'prevBottomHeight:',
872
                    parseFloat(this.virtualBottomHeightElement.style.height)
873
                );
874
                this.debugLog('warn', '=========== Dividing line ===========');
×
875
            }
876
            return {
×
877
                isDiff: true,
878
                isMissingTop,
879
                isAddedTop,
880
                isMissingBottom,
881
                isAddedBottom,
882
                diffTopRenderedIndexes,
883
                diffBottomRenderedIndexes
884
            };
885
        }
886
        return {
×
887
            isDiff: false,
888
            diffTopRenderedIndexes: [],
889
            diffBottomRenderedIndexes: []
890
        };
891
    }
892

893
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
894
        const node = this.editor.children[index] as Element;
×
895
        const isVisible = this.editor.isVisible(node);
×
896
        if (!isVisible) {
×
897
            return 0;
×
898
        }
899
        if (!node) {
×
900
            return defaultHeight;
×
901
        }
902
        const key = AngularEditor.findKey(this.editor, node);
×
903
        const height = this.keyHeightMap.get(key.id);
×
904
        if (typeof height === 'number') {
×
905
            return height;
×
906
        }
907
        if (this.keyHeightMap.has(key.id)) {
×
908
            console.error('getBlockHeight: invalid height value', key.id, height);
×
909
        }
910
        return defaultHeight;
×
911
    }
912

913
    private buildAccumulatedHeight(heights: number[]) {
914
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
915
        for (let i = 0; i < heights.length; i++) {
×
916
            // 存储前 i 个的累计高度
917
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
918
        }
919
        return accumulatedHeights;
×
920
    }
921

922
    private tryMeasureInViewportChildrenHeights() {
923
        if (!this.isEnabledVirtualScroll()) {
×
924
            return;
×
925
        }
NEW
926
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
NEW
927
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
UNCOV
928
            this.measureVisibleHeights();
×
929
        });
930
    }
931

932
    private measureVisibleHeights() {
933
        const children = (this.editor.children || []) as Element[];
×
934
        this.inViewportIndics.forEach(index => {
×
935
            const node = children[index];
×
936
            if (!node) {
×
937
                return;
×
938
            }
939
            const key = AngularEditor.findKey(this.editor, node);
×
940
            // 跳过已测过的块,除非强制测量
941
            if (this.keyHeightMap.has(key.id)) {
×
942
                return;
×
943
            }
944
            const view = ELEMENT_TO_COMPONENT.get(node);
×
945
            if (!view) {
×
946
                return;
×
947
            }
948
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
949
            if (ret instanceof Promise) {
×
950
                ret.then(height => {
×
951
                    this.keyHeightMap.set(key.id, height);
×
952
                });
953
            } else {
954
                this.keyHeightMap.set(key.id, ret);
×
955
            }
956
        });
957
    }
958

959
    private remeasureHeightByIndics(indics: number[]): boolean {
960
        const children = (this.editor.children || []) as Element[];
×
961
        let isHeightChanged = false;
×
NEW
962
        indics.forEach((index, i) => {
×
963
            const node = children[index];
×
964
            if (!node) {
×
965
                return;
×
966
            }
967
            const key = AngularEditor.findKey(this.editor, node);
×
968
            const view = ELEMENT_TO_COMPONENT.get(node);
×
969
            if (!view) {
×
970
                return;
×
971
            }
972
            const prevHeight = this.keyHeightMap.get(key.id);
×
973
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
974
            if (ret instanceof Promise) {
×
975
                ret.then(height => {
×
NEW
976
                    this.keyHeightMap.set(key.id, height);
×
977
                    if (height !== prevHeight) {
×
978
                        isHeightChanged = true;
×
979
                        if (isDebug) {
×
NEW
980
                            this.debugLog(
×
981
                                'log',
982
                                `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`
983
                            );
984
                        }
985
                    }
986
                });
987
            } else {
NEW
988
                this.keyHeightMap.set(key.id, ret);
×
989
                if (ret !== prevHeight) {
×
990
                    isHeightChanged = true;
×
991
                    if (isDebug) {
×
NEW
992
                        this.debugLog('log', `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
993
                    }
994
                }
995
            }
996
        });
997
        return isHeightChanged;
×
998
    }
999

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

1013
    private toSlateSelection() {
1014
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1015
            try {
1✔
1016
                if (isDebug) {
1!
1017
                    console.log('toSlateSelection');
×
1018
                }
1019
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1020
                const { activeElement } = root;
1✔
1021
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1022
                const domSelection = (root as Document).getSelection();
1✔
1023

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1257
        const window = AngularEditor.getWindow(this.editor);
×
1258

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

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

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

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

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

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

1295
        IS_FOCUSED.delete(this.editor);
×
1296
    }
1297

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1429
            this.isDraggingInternally = true;
×
1430

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

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

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

1446
            Transforms.select(editor, range);
×
1447

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

1455
                this.isDraggingInternally = false;
×
1456
            }
1457

1458
            AngularEditor.insertData(editor, data);
×
1459

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

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

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

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

1498
            IS_FOCUSED.set(this.editor, true);
2✔
1499
        }
1500
    }
1501

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

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

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

1527
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1528
                        editor.redo();
×
1529
                    }
1530

1531
                    return;
×
1532
                }
1533

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

1537
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1538
                        editor.undo();
×
1539
                    }
1540

1541
                    return;
×
1542
                }
1543

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

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

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

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

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

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

1590
                    return;
×
1591
                }
1592

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

1601
                    return;
×
1602
                }
1603

1604
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1605
                    event.preventDefault();
×
1606

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

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

1615
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1616
                    event.preventDefault();
×
1617

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

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

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

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

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

1649
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1650
                        event.preventDefault();
×
1651

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

1660
                        return;
×
1661
                    }
1662

1663
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1664
                        event.preventDefault();
×
1665

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

1674
                        return;
×
1675
                    }
1676

1677
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1678
                        event.preventDefault();
×
1679

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

1688
                        return;
×
1689
                    }
1690

1691
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1692
                        event.preventDefault();
×
1693

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

1702
                        return;
×
1703
                    }
1704

1705
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1706
                        event.preventDefault();
×
1707

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

1716
                        return;
×
1717
                    }
1718

1719
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1720
                        event.preventDefault();
×
1721

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

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

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

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

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

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

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

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

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

1846
            if (leafHasDimensions) {
×
1847
                return;
×
1848
            }
1849
        }
1850

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

1859
/**
1860
 * Check if the target is inside void and in the editor.
1861
 */
1862

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

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

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