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

worktile / slate-angular / 0852f9db-eca7-4f71-9cdc-69a9a5e0c8e1

16 Dec 2025 08:50AM UTC coverage: 37.202% (-0.3%) from 37.461%
0852f9db-eca7-4f71-9cdc-69a9a5e0c8e1

Pull #326

circleci

pubuzhixing8
perf(virtual-scroll): support remeasure height only when element is changed or added #WIK-19585
Pull Request #326: perf(virtual-scroll): support remeasure height only when element is c…

380 of 1225 branches covered (31.02%)

Branch coverage included in aggregate %.

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

1 existing line in 1 file now uncovered.

1069 of 2670 relevant lines covered (40.04%)

24.38 hits per line

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

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

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

77
export const ELEMENT_KEY_TO_HEIGHTS = new WeakMap<AngularEditor, Map<string, number>>();
1✔
78

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

82
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
83

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

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

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

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

118
    private initialized: boolean;
119

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

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

124
    @Input() editor: AngularEditor;
125

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

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

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

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

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

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

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

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

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

144
    @Input() placeholder: string;
145

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

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

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

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

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

187
    viewContainerRef = inject(ViewContainerRef);
23✔
188

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

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

201
    listRender: ListRender;
202

203
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
204
        enabled: false,
205
        scrollTop: 0,
206
        viewportHeight: 0
207
    };
208

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

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

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

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

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

272
    registerOnChange(fn: any) {
273
        this.onChangeCallback = fn;
23✔
274
    }
275
    registerOnTouched(fn: any) {
276
        this.onTouchedCallback = fn;
23✔
277
    }
278

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

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

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

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

376
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
377
                return;
14✔
378
            }
379

380
            const hasDomSelection = domSelection.type !== 'None';
1✔
381

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

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

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

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

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

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

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

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

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

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

471
    onChange() {
472
        this.forceRender();
13✔
473
        this.onChangeCallback(this.editor.children);
13✔
474
    }
475

476
    ngAfterViewChecked() {}
477

478
    ngDoCheck() {}
479

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

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

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

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

575
    initializeContext() {
576
        this.context = {
49✔
577
            parent: this.editor,
578
            selection: this.editor.selection,
579
            decorations: this.generateDecorations(),
580
            decorate: this.decorate,
581
            readonly: this.readonly
582
        };
583
    }
584

585
    initializeViewContext() {
586
        this.viewContext = {
23✔
587
            editor: this.editor,
588
            renderElement: this.renderElement,
589
            renderLeaf: this.renderLeaf,
590
            renderText: this.renderText,
591
            trackBy: this.trackBy,
592
            isStrictDecorate: this.isStrictDecorate
593
        };
594
    }
595

596
    composePlaceholderDecorate(editor: Editor) {
597
        if (this.placeholderDecorate) {
64!
598
            return this.placeholderDecorate(editor) || [];
×
599
        }
600

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

615
    generateDecorations() {
616
        const decorations = this.decorate([this.editor, []]);
66✔
617
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
618
        decorations.push(...placeholderDecorations);
66✔
619
        return decorations;
66✔
620
    }
621

622
    private isEnabledVirtualScroll() {
623
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
81✔
624
    }
625

626
    // the height from scroll container top to editor top height element
627
    private businessHeight: number = 0;
23✔
628

629
    virtualScrollInitialized = false;
23✔
630

631
    virtualTopHeightElement: HTMLElement;
632

633
    virtualBottomHeightElement: HTMLElement;
634

635
    virtualCenterOutlet: HTMLElement;
636

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

672
    setVirtualSpaceHeight(topHeight: number, bottomHeight: number) {
673
        if (!this.virtualScrollInitialized) {
×
674
            return;
×
675
        }
676
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
677
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
678
    }
679

680
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
681
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
682
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
683
    }
684

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

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

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

767
        if (visibleStartIndex === -1 && elementLength) {
×
768
            visibleStartIndex = elementLength - 1;
×
769
            visible.push(children[visibleStartIndex]);
×
770
            visibleIndexes.push(visibleStartIndex);
×
771
        }
772

773
        const visibleEndIndex =
774
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
775
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
776
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
777

778
        return {
×
779
            inViewportChildren: visible.length ? visible : children,
×
780
            visibleIndexes: new Set(visibleIndexes),
781
            top,
782
            bottom,
783
            heights
784
        };
785
    }
786

787
    private applyVirtualView(virtualView: VirtualViewResult) {
788
        this.inViewportChildren = virtualView.inViewportChildren;
×
789
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
790
        this.inViewportIndics = virtualView.visibleIndexes;
×
791
    }
792

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

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

920
    private buildAccumulatedHeight(heights: number[]) {
921
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
922
        for (let i = 0; i < heights.length; i++) {
×
923
            // 存储前 i 个的累计高度
924
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
925
        }
926
        return accumulatedHeights;
×
927
    }
928

929
    private tryMeasureInViewportChildrenHeights() {
930
        if (!this.isEnabledVirtualScroll()) {
×
931
            return;
×
932
        }
NEW
933
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
NEW
934
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
UNCOV
935
            this.measureVisibleHeights();
×
936
        });
937
    }
938

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

966
    private getPreviousHeightsAndClear(indics: number[]): number[] {
NEW
967
        const previousHeights = [];
×
NEW
968
        indics.forEach(index => {
×
NEW
969
            const element = this.editor.children[index];
×
NEW
970
            const key = element && AngularEditor.findKey(this.editor, element);
×
NEW
971
            const previousHeight = (key && this.keyHeightMap.get(key.id)) || -1;
×
NEW
972
            this.keyHeightMap.delete(key.id);
×
NEW
973
            previousHeights.push(previousHeight);
×
974
        });
NEW
975
        return previousHeights;
×
976
    }
977

978
    private remeasureHeightByIndics(indics: number[], previousHeights: number[]): boolean {
979
        const children = (this.editor.children || []) as Element[];
×
980
        let isHeightChanged = false;
×
NEW
981
        indics.forEach((index, i) => {
×
982
            const node = children[index];
×
983
            if (!node) {
×
984
                return;
×
985
            }
986
            const key = AngularEditor.findKey(this.editor, node);
×
987
            const view = ELEMENT_TO_COMPONENT.get(node);
×
988
            if (!view) {
×
989
                return;
×
990
            }
NEW
991
            const prevHeight = previousHeights[i];
×
992
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
993
            if (ret instanceof Promise) {
×
994
                ret.then(height => {
×
NEW
995
                    this.keyHeightMap.set(key.id, height);
×
996
                    if (height !== prevHeight) {
×
997
                        isHeightChanged = true;
×
998
                        if (isDebug) {
×
NEW
999
                            this.debugLog(
×
1000
                                'log',
1001
                                `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`
1002
                            );
1003
                        }
1004
                    }
1005
                });
1006
            } else {
NEW
1007
                this.keyHeightMap.set(key.id, ret);
×
1008
                if (ret !== prevHeight) {
×
1009
                    isHeightChanged = true;
×
1010
                    if (isDebug) {
×
NEW
1011
                        this.debugLog('log', `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
1012
                    }
1013
                }
1014
            }
1015
        });
1016
        return isHeightChanged;
×
1017
    }
1018

1019
    //#region event proxy
1020
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1021
        this.manualListeners.push(
483✔
1022
            this.renderer2.listen(target, eventName, (event: Event) => {
1023
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1024
                if (beforeInputEvent) {
5!
1025
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1026
                }
1027
                listener(event);
5✔
1028
            })
1029
        );
1030
    }
1031

1032
    private toSlateSelection() {
1033
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1034
            try {
1✔
1035
                if (isDebug) {
1!
1036
                    console.log('toSlateSelection');
×
1037
                }
1038
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1039
                const { activeElement } = root;
1✔
1040
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1041
                const domSelection = (root as Document).getSelection();
1✔
1042

1043
                if (activeElement === el) {
1!
1044
                    this.latestElement = activeElement;
1✔
1045
                    IS_FOCUSED.set(this.editor, true);
1✔
1046
                } else {
1047
                    IS_FOCUSED.delete(this.editor);
×
1048
                }
1049

1050
                if (!domSelection) {
1!
1051
                    return Transforms.deselect(this.editor);
×
1052
                }
1053

1054
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1055
                const hasDomSelectionInEditor =
1056
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1057
                if (!hasDomSelectionInEditor) {
1!
1058
                    Transforms.deselect(this.editor);
×
1059
                    return;
×
1060
                }
1061

1062
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1063
                // for example, double-click the last cell of the table to select a non-editable DOM
1064
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1065
                if (range) {
1✔
1066
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1067
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1068
                            // force adjust DOMSelection
1069
                            this.toNativeSelection();
×
1070
                        }
1071
                    } else {
1072
                        Transforms.select(this.editor, range);
1✔
1073
                    }
1074
                }
1075
            } catch (error) {
1076
                this.editor.onError({
×
1077
                    code: SlateErrorCode.ToSlateSelectionError,
1078
                    nativeError: error
1079
                });
1080
            }
1081
        }
1082
    }
1083

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

1162
                // COMPAT: If the selection is expanded, even if the command seems like
1163
                // a delete forward/backward command it should delete the selection.
1164
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1165
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1166
                    Editor.deleteFragment(editor, { direction });
×
1167
                    return;
×
1168
                }
1169

1170
                switch (type) {
×
1171
                    case 'deleteByComposition':
1172
                    case 'deleteByCut':
1173
                    case 'deleteByDrag': {
1174
                        Editor.deleteFragment(editor);
×
1175
                        break;
×
1176
                    }
1177

1178
                    case 'deleteContent':
1179
                    case 'deleteContentForward': {
1180
                        Editor.deleteForward(editor);
×
1181
                        break;
×
1182
                    }
1183

1184
                    case 'deleteContentBackward': {
1185
                        Editor.deleteBackward(editor);
×
1186
                        break;
×
1187
                    }
1188

1189
                    case 'deleteEntireSoftLine': {
1190
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1191
                        Editor.deleteForward(editor, { unit: 'line' });
×
1192
                        break;
×
1193
                    }
1194

1195
                    case 'deleteHardLineBackward': {
1196
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1197
                        break;
×
1198
                    }
1199

1200
                    case 'deleteSoftLineBackward': {
1201
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1202
                        break;
×
1203
                    }
1204

1205
                    case 'deleteHardLineForward': {
1206
                        Editor.deleteForward(editor, { unit: 'block' });
×
1207
                        break;
×
1208
                    }
1209

1210
                    case 'deleteSoftLineForward': {
1211
                        Editor.deleteForward(editor, { unit: 'line' });
×
1212
                        break;
×
1213
                    }
1214

1215
                    case 'deleteWordBackward': {
1216
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1217
                        break;
×
1218
                    }
1219

1220
                    case 'deleteWordForward': {
1221
                        Editor.deleteForward(editor, { unit: 'word' });
×
1222
                        break;
×
1223
                    }
1224

1225
                    case 'insertLineBreak':
1226
                    case 'insertParagraph': {
1227
                        Editor.insertBreak(editor);
×
1228
                        break;
×
1229
                    }
1230

1231
                    case 'insertFromComposition': {
1232
                        // COMPAT: in safari, `compositionend` event is dispatched after
1233
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1234
                        // https://www.w3.org/TR/input-events-2/
1235
                        // so the following code is the right logic
1236
                        // because DOM selection in sync will be exec before `compositionend` event
1237
                        // isComposing is true will prevent DOM selection being update correctly.
1238
                        this.isComposing = false;
×
1239
                        preventInsertFromComposition(event, this.editor);
×
1240
                    }
1241
                    case 'insertFromDrop':
1242
                    case 'insertFromPaste':
1243
                    case 'insertFromYank':
1244
                    case 'insertReplacementText':
1245
                    case 'insertText': {
1246
                        // use a weak comparison instead of 'instanceof' to allow
1247
                        // programmatic access of paste events coming from external windows
1248
                        // like cypress where cy.window does not work realibly
1249
                        if (data?.constructor.name === 'DataTransfer') {
×
1250
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1251
                        } else if (typeof data === 'string') {
×
1252
                            Editor.insertText(editor, data);
×
1253
                        }
1254
                        break;
×
1255
                    }
1256
                }
1257
            } catch (error) {
1258
                this.editor.onError({
×
1259
                    code: SlateErrorCode.OnDOMBeforeInputError,
1260
                    nativeError: error
1261
                });
1262
            }
1263
        }
1264
    }
1265

1266
    private onDOMBlur(event: FocusEvent) {
1267
        if (
×
1268
            this.readonly ||
×
1269
            this.isUpdatingSelection ||
1270
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1271
            this.isDOMEventHandled(event, this.blur)
1272
        ) {
1273
            return;
×
1274
        }
1275

1276
        const window = AngularEditor.getWindow(this.editor);
×
1277

1278
        // COMPAT: If the current `activeElement` is still the previous
1279
        // one, this is due to the window being blurred when the tab
1280
        // itself becomes unfocused, so we want to abort early to allow to
1281
        // editor to stay focused when the tab becomes focused again.
1282
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1283
        if (this.latestElement === root.activeElement) {
×
1284
            return;
×
1285
        }
1286

1287
        const { relatedTarget } = event;
×
1288
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1289

1290
        // COMPAT: The event should be ignored if the focus is returning
1291
        // to the editor from an embedded editable element (eg. an <input>
1292
        // element inside a void node).
1293
        if (relatedTarget === el) {
×
1294
            return;
×
1295
        }
1296

1297
        // COMPAT: The event should be ignored if the focus is moving from
1298
        // the editor to inside a void node's spacer element.
1299
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1300
            return;
×
1301
        }
1302

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

1309
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1310
                return;
×
1311
            }
1312
        }
1313

1314
        IS_FOCUSED.delete(this.editor);
×
1315
    }
1316

1317
    private onDOMClick(event: MouseEvent) {
1318
        if (
×
1319
            !this.readonly &&
×
1320
            AngularEditor.hasTarget(this.editor, event.target) &&
1321
            !this.isDOMEventHandled(event, this.click) &&
1322
            isDOMNode(event.target)
1323
        ) {
1324
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1325
            const path = AngularEditor.findPath(this.editor, node);
×
1326
            const start = Editor.start(this.editor, path);
×
1327
            const end = Editor.end(this.editor, path);
×
1328

1329
            const startVoid = Editor.void(this.editor, { at: start });
×
1330
            const endVoid = Editor.void(this.editor, { at: end });
×
1331

1332
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1333
                let blockPath = path;
×
1334
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1335
                    const block = Editor.above(this.editor, {
×
1336
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1337
                        at: path
1338
                    });
1339

1340
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1341
                }
1342

1343
                const range = Editor.range(this.editor, blockPath);
×
1344
                Transforms.select(this.editor, range);
×
1345
                return;
×
1346
            }
1347

1348
            if (
×
1349
                startVoid &&
×
1350
                endVoid &&
1351
                Path.equals(startVoid[1], endVoid[1]) &&
1352
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1353
            ) {
1354
                const range = Editor.range(this.editor, start);
×
1355
                Transforms.select(this.editor, range);
×
1356
            }
1357
        }
1358
    }
1359

1360
    private onDOMCompositionStart(event: CompositionEvent) {
1361
        const { selection } = this.editor;
1✔
1362
        if (selection) {
1!
1363
            // solve the problem of cross node Chinese input
1364
            if (Range.isExpanded(selection)) {
×
1365
                Editor.deleteFragment(this.editor);
×
1366
                this.forceRender();
×
1367
            }
1368
        }
1369
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1370
            this.isComposing = true;
1✔
1371
        }
1372
        this.render();
1✔
1373
    }
1374

1375
    private onDOMCompositionUpdate(event: CompositionEvent) {
1376
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1377
    }
1378

1379
    private onDOMCompositionEnd(event: CompositionEvent) {
1380
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1381
            Transforms.delete(this.editor);
×
1382
        }
1383
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1384
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1385
            // aren't correct and never fire the "insertFromComposition"
1386
            // type that we need. So instead, insert whenever a composition
1387
            // ends since it will already have been committed to the DOM.
1388
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1389
                preventInsertFromComposition(event, this.editor);
×
1390
                Editor.insertText(this.editor, event.data);
×
1391
            }
1392

1393
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1394
            // so we need avoid repeat isnertText by isComposing === true,
1395
            this.isComposing = false;
×
1396
        }
1397
        this.render();
×
1398
    }
1399

1400
    private onDOMCopy(event: ClipboardEvent) {
1401
        const window = AngularEditor.getWindow(this.editor);
×
1402
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1403
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1404
            event.preventDefault();
×
1405
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1406
        }
1407
    }
1408

1409
    private onDOMCut(event: ClipboardEvent) {
1410
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1411
            event.preventDefault();
×
1412
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1413
            const { selection } = this.editor;
×
1414

1415
            if (selection) {
×
1416
                AngularEditor.deleteCutData(this.editor);
×
1417
            }
1418
        }
1419
    }
1420

1421
    private onDOMDragOver(event: DragEvent) {
1422
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1423
            // Only when the target is void, call `preventDefault` to signal
1424
            // that drops are allowed. Editable content is droppable by
1425
            // default, and calling `preventDefault` hides the cursor.
1426
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1427

1428
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1429
                event.preventDefault();
×
1430
            }
1431
        }
1432
    }
1433

1434
    private onDOMDragStart(event: DragEvent) {
1435
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1436
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1437
            const path = AngularEditor.findPath(this.editor, node);
×
1438
            const voidMatch =
1439
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1440

1441
            // If starting a drag on a void node, make sure it is selected
1442
            // so that it shows up in the selection's fragment.
1443
            if (voidMatch) {
×
1444
                const range = Editor.range(this.editor, path);
×
1445
                Transforms.select(this.editor, range);
×
1446
            }
1447

1448
            this.isDraggingInternally = true;
×
1449

1450
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1451
        }
1452
    }
1453

1454
    private onDOMDrop(event: DragEvent) {
1455
        const editor = this.editor;
×
1456
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1457
            event.preventDefault();
×
1458
            // Keep a reference to the dragged range before updating selection
1459
            const draggedRange = editor.selection;
×
1460

1461
            // Find the range where the drop happened
1462
            const range = AngularEditor.findEventRange(editor, event);
×
1463
            const data = event.dataTransfer;
×
1464

1465
            Transforms.select(editor, range);
×
1466

1467
            if (this.isDraggingInternally) {
×
1468
                if (draggedRange) {
×
1469
                    Transforms.delete(editor, {
×
1470
                        at: draggedRange
1471
                    });
1472
                }
1473

1474
                this.isDraggingInternally = false;
×
1475
            }
1476

1477
            AngularEditor.insertData(editor, data);
×
1478

1479
            // When dragging from another source into the editor, it's possible
1480
            // that the current editor does not have focus.
1481
            if (!AngularEditor.isFocused(editor)) {
×
1482
                AngularEditor.focus(editor);
×
1483
            }
1484
        }
1485
    }
1486

1487
    private onDOMDragEnd(event: DragEvent) {
1488
        if (
×
1489
            !this.readonly &&
×
1490
            this.isDraggingInternally &&
1491
            AngularEditor.hasTarget(this.editor, event.target) &&
1492
            !this.isDOMEventHandled(event, this.dragEnd)
1493
        ) {
1494
            this.isDraggingInternally = false;
×
1495
        }
1496
    }
1497

1498
    private onDOMFocus(event: Event) {
1499
        if (
2✔
1500
            !this.readonly &&
8✔
1501
            !this.isUpdatingSelection &&
1502
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1503
            !this.isDOMEventHandled(event, this.focus)
1504
        ) {
1505
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1506
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1507
            this.latestElement = root.activeElement;
2✔
1508

1509
            // COMPAT: If the editor has nested editable elements, the focus
1510
            // can go to them. In Firefox, this must be prevented because it
1511
            // results in issues with keyboard navigation. (2017/03/30)
1512
            if (IS_FIREFOX && event.target !== el) {
2!
1513
                el.focus();
×
1514
                return;
×
1515
            }
1516

1517
            IS_FOCUSED.set(this.editor, true);
2✔
1518
        }
1519
    }
1520

1521
    private onDOMKeydown(event: KeyboardEvent) {
1522
        const editor = this.editor;
×
1523
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1524
        const { activeElement } = root;
×
1525
        if (
×
1526
            !this.readonly &&
×
1527
            AngularEditor.hasEditableTarget(editor, event.target) &&
1528
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1529
            !this.isComposing &&
1530
            !this.isDOMEventHandled(event, this.keydown)
1531
        ) {
1532
            const nativeEvent = event;
×
1533
            const { selection } = editor;
×
1534

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

1538
            try {
×
1539
                // COMPAT: Since we prevent the default behavior on
1540
                // `beforeinput` events, the browser doesn't think there's ever
1541
                // any history stack to undo or redo, so we have to manage these
1542
                // hotkeys ourselves. (2019/11/06)
1543
                if (Hotkeys.isRedo(nativeEvent)) {
×
1544
                    event.preventDefault();
×
1545

1546
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1547
                        editor.redo();
×
1548
                    }
1549

1550
                    return;
×
1551
                }
1552

1553
                if (Hotkeys.isUndo(nativeEvent)) {
×
1554
                    event.preventDefault();
×
1555

1556
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1557
                        editor.undo();
×
1558
                    }
1559

1560
                    return;
×
1561
                }
1562

1563
                // COMPAT: Certain browsers don't handle the selection updates
1564
                // properly. In Chrome, the selection isn't properly extended.
1565
                // And in Firefox, the selection isn't properly collapsed.
1566
                // (2017/10/17)
1567
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1568
                    event.preventDefault();
×
1569
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1570
                    return;
×
1571
                }
1572

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

1579
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1580
                    event.preventDefault();
×
1581
                    Transforms.move(editor, {
×
1582
                        unit: 'line',
1583
                        edge: 'focus',
1584
                        reverse: true
1585
                    });
1586
                    return;
×
1587
                }
1588

1589
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1590
                    event.preventDefault();
×
1591
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1592
                    return;
×
1593
                }
1594

1595
                // COMPAT: If a void node is selected, or a zero-width text node
1596
                // adjacent to an inline is selected, we need to handle these
1597
                // hotkeys manually because browsers won't be able to skip over
1598
                // the void node with the zero-width space not being an empty
1599
                // string.
1600
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1601
                    event.preventDefault();
×
1602

1603
                    if (selection && Range.isCollapsed(selection)) {
×
1604
                        Transforms.move(editor, { reverse: !isRTL });
×
1605
                    } else {
1606
                        Transforms.collapse(editor, { edge: 'start' });
×
1607
                    }
1608

1609
                    return;
×
1610
                }
1611

1612
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1613
                    event.preventDefault();
×
1614
                    if (selection && Range.isCollapsed(selection)) {
×
1615
                        Transforms.move(editor, { reverse: isRTL });
×
1616
                    } else {
1617
                        Transforms.collapse(editor, { edge: 'end' });
×
1618
                    }
1619

1620
                    return;
×
1621
                }
1622

1623
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1624
                    event.preventDefault();
×
1625

1626
                    if (selection && Range.isExpanded(selection)) {
×
1627
                        Transforms.collapse(editor, { edge: 'focus' });
×
1628
                    }
1629

1630
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1631
                    return;
×
1632
                }
1633

1634
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1635
                    event.preventDefault();
×
1636

1637
                    if (selection && Range.isExpanded(selection)) {
×
1638
                        Transforms.collapse(editor, { edge: 'focus' });
×
1639
                    }
1640

1641
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1642
                    return;
×
1643
                }
1644

1645
                if (isKeyHotkey('mod+a', event)) {
×
1646
                    this.editor.selectAll();
×
1647
                    event.preventDefault();
×
1648
                    return;
×
1649
                }
1650

1651
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1652
                // fall back to guessing at the input intention for hotkeys.
1653
                // COMPAT: In iOS, some of these hotkeys are handled in the
1654
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1655
                    // We don't have a core behavior for these, but they change the
1656
                    // DOM if we don't prevent them, so we have to.
1657
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1658
                        event.preventDefault();
×
1659
                        return;
×
1660
                    }
1661

1662
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1663
                        event.preventDefault();
×
1664
                        Editor.insertBreak(editor);
×
1665
                        return;
×
1666
                    }
1667

1668
                    if (Hotkeys.isDeleteBackward(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);
×
1677
                        }
1678

1679
                        return;
×
1680
                    }
1681

1682
                    if (Hotkeys.isDeleteForward(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);
×
1691
                        }
1692

1693
                        return;
×
1694
                    }
1695

1696
                    if (Hotkeys.isDeleteLineBackward(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: 'line' });
×
1705
                        }
1706

1707
                        return;
×
1708
                    }
1709

1710
                    if (Hotkeys.isDeleteLineForward(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: 'line' });
×
1719
                        }
1720

1721
                        return;
×
1722
                    }
1723

1724
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1725
                        event.preventDefault();
×
1726

1727
                        if (selection && Range.isExpanded(selection)) {
×
1728
                            Editor.deleteFragment(editor, {
×
1729
                                direction: 'backward'
1730
                            });
1731
                        } else {
1732
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1733
                        }
1734

1735
                        return;
×
1736
                    }
1737

1738
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1739
                        event.preventDefault();
×
1740

1741
                        if (selection && Range.isExpanded(selection)) {
×
1742
                            Editor.deleteFragment(editor, {
×
1743
                                direction: 'forward'
1744
                            });
1745
                        } else {
1746
                            Editor.deleteForward(editor, { unit: 'word' });
×
1747
                        }
1748

1749
                        return;
×
1750
                    }
1751
                } else {
1752
                    if (IS_CHROME || IS_SAFARI) {
×
1753
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1754
                        // an event when deleting backwards in a selected void inline node
1755
                        if (
×
1756
                            selection &&
×
1757
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1758
                            Range.isCollapsed(selection)
1759
                        ) {
1760
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1761
                            if (
×
1762
                                Element.isElement(currentNode) &&
×
1763
                                Editor.isVoid(editor, currentNode) &&
1764
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1765
                            ) {
1766
                                event.preventDefault();
×
1767
                                Editor.deleteBackward(editor, {
×
1768
                                    unit: 'block'
1769
                                });
1770
                                return;
×
1771
                            }
1772
                        }
1773
                    }
1774
                }
1775
            } catch (error) {
1776
                this.editor.onError({
×
1777
                    code: SlateErrorCode.OnDOMKeydownError,
1778
                    nativeError: error
1779
                });
1780
            }
1781
        }
1782
    }
1783

1784
    private onDOMPaste(event: ClipboardEvent) {
1785
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1786
        // fall back to React's `onPaste` here instead.
1787
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1788
        // when "paste without formatting" option is used.
1789
        // This unfortunately needs to be handled with paste events instead.
1790
        if (
×
1791
            !this.isDOMEventHandled(event, this.paste) &&
×
1792
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1793
            !this.readonly &&
1794
            AngularEditor.hasEditableTarget(this.editor, event.target)
1795
        ) {
1796
            event.preventDefault();
×
1797
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1798
        }
1799
    }
1800

1801
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1802
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1803
        // fall back to React's leaky polyfill instead just for it. It
1804
        // only works for the `insertText` input type.
1805
        if (
×
1806
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1807
            !this.readonly &&
1808
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1809
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1810
        ) {
1811
            event.nativeEvent.preventDefault();
×
1812
            try {
×
1813
                const text = event.data;
×
1814
                if (!Range.isCollapsed(this.editor.selection)) {
×
1815
                    Editor.deleteFragment(this.editor);
×
1816
                }
1817
                // just handle Non-IME input
1818
                if (!this.isComposing) {
×
1819
                    Editor.insertText(this.editor, text);
×
1820
                }
1821
            } catch (error) {
1822
                this.editor.onError({
×
1823
                    code: SlateErrorCode.ToNativeSelectionError,
1824
                    nativeError: error
1825
                });
1826
            }
1827
        }
1828
    }
1829

1830
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1831
        if (!handler) {
3✔
1832
            return false;
3✔
1833
        }
1834
        handler(event);
×
1835
        return event.defaultPrevented;
×
1836
    }
1837
    //#endregion
1838

1839
    ngOnDestroy() {
1840
        this.editorResizeObserver?.disconnect();
23✔
1841
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1842
        this.manualListeners.forEach(manualListener => {
23✔
1843
            manualListener();
483✔
1844
        });
1845
        this.destroy$.complete();
23✔
1846
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1847
    }
1848
}
1849

1850
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1851
    // This was affecting the selection of multiple blocks and dragging behavior,
1852
    // so enabled only if the selection has been collapsed.
1853
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1854
        const leafEl = domRange.startContainer.parentElement!;
×
1855

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

1861
        if (isZeroDimensionRect) {
×
1862
            const leafRect = leafEl.getBoundingClientRect();
×
1863
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1864

1865
            if (leafHasDimensions) {
×
1866
                return;
×
1867
            }
1868
        }
1869

1870
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1871
        scrollIntoView(leafEl, {
×
1872
            scrollMode: 'if-needed'
1873
        });
1874
        delete leafEl.getBoundingClientRect;
×
1875
    }
1876
};
1877

1878
/**
1879
 * Check if the target is inside void and in the editor.
1880
 */
1881

1882
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1883
    let slateNode: Node | null = null;
1✔
1884
    try {
1✔
1885
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1886
    } catch (error) {}
1887
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1888
};
1889

1890
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1891
    return (
2✔
1892
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1893
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1894
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1895
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1896
    );
1897
};
1898

1899
/**
1900
 * remove default insert from composition
1901
 * @param text
1902
 */
1903
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1904
    const types = ['compositionend', 'insertFromComposition'];
×
1905
    if (!types.includes(event.type)) {
×
1906
        return;
×
1907
    }
1908
    const insertText = (event as CompositionEvent).data;
×
1909
    const window = AngularEditor.getWindow(editor);
×
1910
    const domSelection = window.getSelection();
×
1911
    // ensure text node insert composition input text
1912
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1913
        const textNode = domSelection.anchorNode;
×
1914
        textNode.splitText(textNode.length - insertText.length).remove();
×
1915
    }
1916
};
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