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

worktile / slate-angular / 24692129-528d-4f85-a070-27ce06738c46

16 Dec 2025 08:58AM UTC coverage: 37.355% (-0.1%) from 37.461%
24692129-528d-4f85-a070-27ce06738c46

Pull #326

circleci

pubuzhixing8
chore: changeset
Pull Request #326: perf(virtual-scroll): support remeasure height only when element is c…

380 of 1220 branches covered (31.15%)

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.

1069 of 2659 relevant lines covered (40.2%)

24.47 hits per line

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

22.58
/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
        }
NEW
550
        this.remeasureHeightByIndics(remeasureIndics);
×
551
    }
552

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

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

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

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

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

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

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

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

627
    virtualScrollInitialized = false;
23✔
628

629
    virtualTopHeightElement: HTMLElement;
630

631
    virtualBottomHeightElement: HTMLElement;
632

633
    virtualCenterOutlet: HTMLElement;
634

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

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

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

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

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

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

763
        if (visibleStartIndex === -1 && elementLength) {
×
764
            visibleStartIndex = elementLength - 1;
×
765
            visible.push(children[visibleStartIndex]);
×
766
            visibleIndexes.push(visibleStartIndex);
×
767
        }
768

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1432
            this.isDraggingInternally = true;
×
1433

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

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

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

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

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

1458
                this.isDraggingInternally = false;
×
1459
            }
1460

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

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

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

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

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

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

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

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

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

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

1534
                    return;
×
1535
                }
1536

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

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

1544
                    return;
×
1545
                }
1546

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

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

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

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

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

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

1593
                    return;
×
1594
                }
1595

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

1604
                    return;
×
1605
                }
1606

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

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

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

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

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

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

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

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

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

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

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

1663
                        return;
×
1664
                    }
1665

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

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

1677
                        return;
×
1678
                    }
1679

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

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

1691
                        return;
×
1692
                    }
1693

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

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

1705
                        return;
×
1706
                    }
1707

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

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

1719
                        return;
×
1720
                    }
1721

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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