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

worktile / slate-angular / 1a53600f-6474-4078-b417-d4fc01080be8

24 Dec 2025 10:08AM UTC coverage: 37.072% (+0.4%) from 36.686%
1a53600f-6474-4078-b417-d4fc01080be8

push

circleci

pubuzhixing8
feat(virtual-scroll): remove tryMeasureInViewportChildrenHeights logic and revert the handle for needRemoveOnTop

382 of 1233 branches covered (30.98%)

Branch coverage included in aggregate %.

2 of 42 new or added lines in 2 files covered. (4.76%)

1 existing line in 1 file now uncovered.

1079 of 2708 relevant lines covered (39.84%)

24.11 hits per line

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

22.91
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    HostBinding,
6
    Renderer2,
7
    ElementRef,
8
    ChangeDetectionStrategy,
9
    OnDestroy,
10
    ChangeDetectorRef,
11
    NgZone,
12
    Injector,
13
    forwardRef,
14
    OnChanges,
15
    SimpleChanges,
16
    AfterViewChecked,
17
    DoCheck,
18
    inject,
19
    ViewContainerRef
20
} from '@angular/core';
21
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node, Selection } from 'slate';
22
import { direction } from 'direction';
23
import scrollIntoView from 'scroll-into-view-if-needed';
24
import { AngularEditor } from '../../plugins/angular-editor';
25
import {
26
    DOMElement,
27
    isDOMNode,
28
    DOMStaticRange,
29
    DOMRange,
30
    isDOMElement,
31
    isPlainTextOnlyPaste,
32
    DOMSelection,
33
    getDefaultView,
34
    EDITOR_TO_WINDOW,
35
    EDITOR_TO_ELEMENT,
36
    NODE_TO_ELEMENT,
37
    ELEMENT_TO_NODE,
38
    IS_FOCUSED,
39
    IS_READ_ONLY
40
} from 'slate-dom';
41
import { Subject } from 'rxjs';
42
import {
43
    IS_FIREFOX,
44
    IS_SAFARI,
45
    IS_CHROME,
46
    HAS_BEFORE_INPUT_SUPPORT,
47
    IS_ANDROID,
48
    SLATE_DEBUG_KEY,
49
    SLATE_DEBUG_KEY_SCROLL_TOP
50
} from '../../utils/environment';
51
import Hotkeys from '../../utils/hotkeys';
52
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
53
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
54
import { SlateErrorCode } from '../../types/error';
55
import { NG_VALUE_ACCESSOR } from '@angular/forms';
56
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
57
import { ViewType } from '../../types/view';
58
import { HistoryEditor } from 'slate-history';
59
import {
60
    buildHeightsAndAccumulatedHeights,
61
    EDITOR_TO_BUSINESS_TOP,
62
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
63
    ELEMENT_KEY_TO_HEIGHTS,
64
    getBusinessTop,
65
    getRealHeightByElement,
66
    IS_ENABLED_VIRTUAL_SCROLL,
67
    isDecoratorRangeListEqual,
68
    measureHeightByIndics
69
} from '../../utils';
70
import { SlatePlaceholder } from '../../types/feature';
71
import { restoreDom } from '../../utils/restore-dom';
72
import { ListRender } from '../../view/render/list-render';
73
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
74
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
75
import { isKeyHotkey } from 'is-hotkey';
76
import { VirtualScrollDebugOverlay } from './debug';
77

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

81
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
82
const isDebugScrollTop = localStorage.getItem(SLATE_DEBUG_KEY_SCROLL_TOP) === '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
        if (isDebugScrollTop) {
×
150
            this.debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
151
        }
152
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
153
        if (this.isEnabledVirtualScroll()) {
×
154
            this.tryUpdateVirtualViewport();
×
155
        }
156
    }
157

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

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

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

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

190
    viewContainerRef = inject(ViewContainerRef);
23✔
191

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

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

204
    listRender: ListRender;
205

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

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

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

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

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

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

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

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

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

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

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

380
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
381
                return;
14✔
382
            }
383

384
            const hasDomSelection = domSelection.type !== 'None';
1✔
385

386
            // If the DOM selection is properly unset, we're done.
387
            if (!selection && !hasDomSelection) {
1!
388
                return;
×
389
            }
390

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

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

410
            // prevent updating native selection when active element is void element
411
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
412
                return;
×
413
            }
414

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

424
            // Otherwise the DOM selection is out of sync, so update it.
425
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
426
            this.isUpdatingSelection = true;
1✔
427

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

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

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

464
                this.isUpdatingSelection = false;
1✔
465
            });
466
        } catch (error) {
467
            this.editor.onError({
×
468
                code: SlateErrorCode.ToNativeSelectionError,
469
                nativeError: error
470
            });
471
            this.isUpdatingSelection = false;
×
472
        }
473
    }
474

475
    onChange() {
476
        this.forceRender();
13✔
477
        this.onChangeCallback(this.editor.children);
13✔
478
    }
479

480
    ngAfterViewChecked() {}
481

482
    ngDoCheck() {}
483

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

527
    render() {
528
        const changed = this.updateContext();
2✔
529
        if (changed) {
2✔
530
            if (this.isEnabledVirtualScroll()) {
2!
531
                this.updateListRenderAndRemeasureHeights();
×
532
            } else {
533
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
534
            }
535
        }
536
    }
537

538
    updateListRenderAndRemeasureHeights() {
539
        const virtualView = this.calculateVirtualViewport();
×
540
        const oldInViewportChildren = this.inViewportChildren;
×
541
        this.applyVirtualView(virtualView);
×
542
        const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
543
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
544
        // 新增或者修改的才需要重算,计算出这个结果
545
        const remeasureIndics = [];
×
546
        this.inViewportChildren.forEach((child, index) => {
×
547
            if (oldInViewportChildren.indexOf(child) === -1) {
×
548
                remeasureIndics.push(this.inViewportIndics[index]);
×
549
            }
550
        });
551
        if (isDebug && remeasureIndics.length > 0) {
×
552
            console.log('remeasure height by indics: ', remeasureIndics);
×
553
        }
NEW
554
        measureHeightByIndics(this.editor, remeasureIndics, true);
×
555
    }
556

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

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

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

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

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

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

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

628
    virtualScrollInitialized = false;
23✔
629

630
    virtualTopHeightElement: HTMLElement;
631

632
    virtualBottomHeightElement: HTMLElement;
633

634
    virtualCenterOutlet: HTMLElement;
635

636
    initializeVirtualScroll() {
637
        if (this.virtualScrollInitialized) {
23!
638
            return;
×
639
        }
640
        if (this.isEnabledVirtualScroll()) {
23!
641
            this.virtualScrollInitialized = true;
×
642
            this.virtualTopHeightElement = document.createElement('div');
×
643
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
644
            this.virtualTopHeightElement.contentEditable = 'false';
×
645
            this.virtualBottomHeightElement = document.createElement('div');
×
646
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
647
            this.virtualBottomHeightElement.contentEditable = 'false';
×
648
            this.virtualCenterOutlet = document.createElement('div');
×
649
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
650
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
651
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
652
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
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;
×
657
                    this.keyHeightMap.clear();
×
658
                    const remeasureIndics = this.inViewportIndics;
×
NEW
659
                    measureHeightByIndics(this.editor, remeasureIndics);
×
660
                }
661
            });
662
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
663
            if (isDebug) {
×
664
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
665
                VirtualScrollDebugOverlay.getInstance(doc);
×
666
            }
667
        }
668
    }
669

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

680
    getVirtualTopHeight() {
681
        if (!this.virtualScrollInitialized) {
×
682
            return 0;
×
683
        }
684
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
685
    }
686

687
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
688
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
689
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
690
    }
691

692
    handlePreRendering() {
693
        let preRenderingCount = 1;
×
694
        const childrenWithPreRendering = [...this.inViewportChildren];
×
695
        if (this.inViewportIndics[0] !== 0) {
×
696
            childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
697
        } else {
698
            preRenderingCount = 0;
×
699
        }
700
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
701
        if (lastIndex !== this.editor.children.length - 1) {
×
702
            childrenWithPreRendering.push(this.editor.children[lastIndex + 1] as Element);
×
703
        }
704
        return { preRenderingCount, childrenWithPreRendering };
×
705
    }
706

707
    private tryUpdateVirtualViewport() {
708
        if (isDebug) {
×
709
            this.debugLog('log', 'tryUpdateVirtualViewport');
×
710
        }
711
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
712
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
713
            if (isDebug) {
×
714
                this.debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
715
            }
716
            let virtualView = this.calculateVirtualViewport();
×
717
            let diff = this.diffVirtualViewport(virtualView);
×
NEW
718
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
NEW
719
                const remeasureIndics = diff.changedIndexesOfTop;
×
NEW
720
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
NEW
721
                if (changed) {
×
NEW
722
                    virtualView = this.calculateVirtualViewport();
×
NEW
723
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
724
                }
725
            }
726
            if (diff.isDifferent) {
×
727
                this.applyVirtualView(virtualView);
×
728
                if (this.listRender.initialized) {
×
729
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
730
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
NEW
731
                    if (diff.needAddOnTop) {
×
NEW
732
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
NEW
733
                        if (isDebug) {
×
NEW
734
                            this.debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
735
                        }
NEW
736
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
NEW
737
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
NEW
738
                        const result = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
NEW
739
                        if (result) {
×
NEW
740
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
NEW
741
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
NEW
742
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
NEW
743
                            this.setVirtualSpaceHeight(newTopHeight);
×
NEW
744
                            if (isDebug) {
×
NEW
745
                                this.debugLog(
×
746
                                    'log',
747
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
748
                                );
749
                            }
750
                        }
751
                    }
752
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
753
                        this.toNativeSelection();
×
754
                    }
755
                }
756
            } else {
757
                const topHeight = this.getVirtualTopHeight();
×
758
                if (virtualView.top !== topHeight) {
×
NEW
759
                    this.debugLog(
×
760
                        'log',
761
                        'update top height since invalid status(正数减去高度,负数代表增加高度): ',
762
                        topHeight - virtualView.top
763
                    );
UNCOV
764
                    this.setVirtualSpaceHeight(virtualView.top);
×
765
                }
766
            }
767
            if (isDebug) {
×
768
                this.debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
769
            }
770
        });
771
    }
772

773
    private calculateVirtualViewport() {
774
        const children = (this.editor.children || []) as Element[];
×
775
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
776
            return {
×
777
                inViewportChildren: children,
778
                visibleIndexes: [],
779
                top: 0,
780
                bottom: 0,
781
                heights: []
782
            };
783
        }
784
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
785
        if (isDebug) {
×
786
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
787
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
788
        }
789
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
790
        if (!viewportHeight) {
×
791
            return {
×
792
                inViewportChildren: [],
793
                visibleIndexes: [],
794
                top: 0,
795
                bottom: 0,
796
                heights: []
797
            };
798
        }
799
        const elementLength = children.length;
×
800
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
801
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
802
            setTimeout(() => {
×
803
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
804
                const businessTop =
805
                    Math.ceil(virtualTopBoundingTop) +
×
806
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
807
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
808
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
809
                if (isDebug) {
×
810
                    this.debugLog('log', 'businessTop', businessTop);
×
811
                }
812
            }, 100);
813
        }
814
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
815
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
816
        const totalHeight = accumulatedHeights[elementLength];
×
817
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
818
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
819
        const viewBottom = limitedScrollTop + viewportHeight;
×
820
        let accumulatedOffset = 0;
×
821
        let visibleStartIndex = -1;
×
822
        const visible: Element[] = [];
×
823
        const visibleIndexes: number[] = [];
×
824

825
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
826
            const currentHeight = heights[i];
×
827
            const nextOffset = accumulatedOffset + currentHeight;
×
828
            // 可视区域有交集,加入渲染
829
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
830
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
831
                visible.push(children[i]);
×
832
                visibleIndexes.push(i);
×
833
            }
834
            accumulatedOffset = nextOffset;
×
835
        }
836

837
        if (visibleStartIndex === -1 && elementLength) {
×
838
            visibleStartIndex = elementLength - 1;
×
839
            visible.push(children[visibleStartIndex]);
×
840
            visibleIndexes.push(visibleStartIndex);
×
841
        }
842

843
        const visibleEndIndex =
844
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
845
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
846
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
847
        return {
×
848
            inViewportChildren: visible.length ? visible : children,
×
849
            visibleIndexes,
850
            top,
851
            bottom,
852
            heights,
853
            accumulatedHeights
854
        };
855
    }
856

857
    private applyVirtualView(virtualView: VirtualViewResult) {
858
        this.inViewportChildren = virtualView.inViewportChildren;
×
859
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
860
        this.inViewportIndics = virtualView.visibleIndexes;
×
861
    }
862

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

977
    //#region event proxy
978
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
979
        this.manualListeners.push(
483✔
980
            this.renderer2.listen(target, eventName, (event: Event) => {
981
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
982
                if (beforeInputEvent) {
5!
983
                    this.onFallbackBeforeInput(beforeInputEvent);
×
984
                }
985
                listener(event);
5✔
986
            })
987
        );
988
    }
989

990
    private toSlateSelection() {
991
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
992
            try {
1✔
993
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
994
                const { activeElement } = root;
1✔
995
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
996
                const domSelection = (root as Document).getSelection();
1✔
997

998
                if (activeElement === el) {
1!
999
                    this.latestElement = activeElement;
1✔
1000
                    IS_FOCUSED.set(this.editor, true);
1✔
1001
                } else {
1002
                    IS_FOCUSED.delete(this.editor);
×
1003
                }
1004

1005
                if (!domSelection) {
1!
1006
                    return Transforms.deselect(this.editor);
×
1007
                }
1008

1009
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1010
                const hasDomSelectionInEditor =
1011
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1012
                if (!hasDomSelectionInEditor) {
1!
1013
                    Transforms.deselect(this.editor);
×
1014
                    return;
×
1015
                }
1016

1017
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1018
                // for example, double-click the last cell of the table to select a non-editable DOM
1019
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1020
                if (range) {
1✔
1021
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1022
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1023
                            // force adjust DOMSelection
1024
                            this.toNativeSelection();
×
1025
                        }
1026
                    } else {
1027
                        Transforms.select(this.editor, range);
1✔
1028
                    }
1029
                }
1030
            } catch (error) {
1031
                this.editor.onError({
×
1032
                    code: SlateErrorCode.ToSlateSelectionError,
1033
                    nativeError: error
1034
                });
1035
            }
1036
        }
1037
    }
1038

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

1117
                // COMPAT: If the selection is expanded, even if the command seems like
1118
                // a delete forward/backward command it should delete the selection.
1119
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1120
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1121
                    Editor.deleteFragment(editor, { direction });
×
1122
                    return;
×
1123
                }
1124

1125
                switch (type) {
×
1126
                    case 'deleteByComposition':
1127
                    case 'deleteByCut':
1128
                    case 'deleteByDrag': {
1129
                        Editor.deleteFragment(editor);
×
1130
                        break;
×
1131
                    }
1132

1133
                    case 'deleteContent':
1134
                    case 'deleteContentForward': {
1135
                        Editor.deleteForward(editor);
×
1136
                        break;
×
1137
                    }
1138

1139
                    case 'deleteContentBackward': {
1140
                        Editor.deleteBackward(editor);
×
1141
                        break;
×
1142
                    }
1143

1144
                    case 'deleteEntireSoftLine': {
1145
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1146
                        Editor.deleteForward(editor, { unit: 'line' });
×
1147
                        break;
×
1148
                    }
1149

1150
                    case 'deleteHardLineBackward': {
1151
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1152
                        break;
×
1153
                    }
1154

1155
                    case 'deleteSoftLineBackward': {
1156
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1157
                        break;
×
1158
                    }
1159

1160
                    case 'deleteHardLineForward': {
1161
                        Editor.deleteForward(editor, { unit: 'block' });
×
1162
                        break;
×
1163
                    }
1164

1165
                    case 'deleteSoftLineForward': {
1166
                        Editor.deleteForward(editor, { unit: 'line' });
×
1167
                        break;
×
1168
                    }
1169

1170
                    case 'deleteWordBackward': {
1171
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1172
                        break;
×
1173
                    }
1174

1175
                    case 'deleteWordForward': {
1176
                        Editor.deleteForward(editor, { unit: 'word' });
×
1177
                        break;
×
1178
                    }
1179

1180
                    case 'insertLineBreak':
1181
                    case 'insertParagraph': {
1182
                        Editor.insertBreak(editor);
×
1183
                        break;
×
1184
                    }
1185

1186
                    case 'insertFromComposition': {
1187
                        // COMPAT: in safari, `compositionend` event is dispatched after
1188
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1189
                        // https://www.w3.org/TR/input-events-2/
1190
                        // so the following code is the right logic
1191
                        // because DOM selection in sync will be exec before `compositionend` event
1192
                        // isComposing is true will prevent DOM selection being update correctly.
1193
                        this.isComposing = false;
×
1194
                        preventInsertFromComposition(event, this.editor);
×
1195
                    }
1196
                    case 'insertFromDrop':
1197
                    case 'insertFromPaste':
1198
                    case 'insertFromYank':
1199
                    case 'insertReplacementText':
1200
                    case 'insertText': {
1201
                        // use a weak comparison instead of 'instanceof' to allow
1202
                        // programmatic access of paste events coming from external windows
1203
                        // like cypress where cy.window does not work realibly
1204
                        if (data?.constructor.name === 'DataTransfer') {
×
1205
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1206
                        } else if (typeof data === 'string') {
×
1207
                            Editor.insertText(editor, data);
×
1208
                        }
1209
                        break;
×
1210
                    }
1211
                }
1212
            } catch (error) {
1213
                this.editor.onError({
×
1214
                    code: SlateErrorCode.OnDOMBeforeInputError,
1215
                    nativeError: error
1216
                });
1217
            }
1218
        }
1219
    }
1220

1221
    private onDOMBlur(event: FocusEvent) {
1222
        if (
×
1223
            this.readonly ||
×
1224
            this.isUpdatingSelection ||
1225
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1226
            this.isDOMEventHandled(event, this.blur)
1227
        ) {
1228
            return;
×
1229
        }
1230

1231
        const window = AngularEditor.getWindow(this.editor);
×
1232

1233
        // COMPAT: If the current `activeElement` is still the previous
1234
        // one, this is due to the window being blurred when the tab
1235
        // itself becomes unfocused, so we want to abort early to allow to
1236
        // editor to stay focused when the tab becomes focused again.
1237
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1238
        if (this.latestElement === root.activeElement) {
×
1239
            return;
×
1240
        }
1241

1242
        const { relatedTarget } = event;
×
1243
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1244

1245
        // COMPAT: The event should be ignored if the focus is returning
1246
        // to the editor from an embedded editable element (eg. an <input>
1247
        // element inside a void node).
1248
        if (relatedTarget === el) {
×
1249
            return;
×
1250
        }
1251

1252
        // COMPAT: The event should be ignored if the focus is moving from
1253
        // the editor to inside a void node's spacer element.
1254
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1255
            return;
×
1256
        }
1257

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

1264
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1265
                return;
×
1266
            }
1267
        }
1268

1269
        IS_FOCUSED.delete(this.editor);
×
1270
    }
1271

1272
    private onDOMClick(event: MouseEvent) {
1273
        if (
×
1274
            !this.readonly &&
×
1275
            AngularEditor.hasTarget(this.editor, event.target) &&
1276
            !this.isDOMEventHandled(event, this.click) &&
1277
            isDOMNode(event.target)
1278
        ) {
1279
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1280
            const path = AngularEditor.findPath(this.editor, node);
×
1281
            const start = Editor.start(this.editor, path);
×
1282
            const end = Editor.end(this.editor, path);
×
1283

1284
            const startVoid = Editor.void(this.editor, { at: start });
×
1285
            const endVoid = Editor.void(this.editor, { at: end });
×
1286

1287
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1288
                let blockPath = path;
×
1289
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1290
                    const block = Editor.above(this.editor, {
×
1291
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1292
                        at: path
1293
                    });
1294

1295
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1296
                }
1297

1298
                const range = Editor.range(this.editor, blockPath);
×
1299
                Transforms.select(this.editor, range);
×
1300
                return;
×
1301
            }
1302

1303
            if (
×
1304
                startVoid &&
×
1305
                endVoid &&
1306
                Path.equals(startVoid[1], endVoid[1]) &&
1307
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1308
            ) {
1309
                const range = Editor.range(this.editor, start);
×
1310
                Transforms.select(this.editor, range);
×
1311
            }
1312
        }
1313
    }
1314

1315
    private onDOMCompositionStart(event: CompositionEvent) {
1316
        const { selection } = this.editor;
1✔
1317
        if (selection) {
1!
1318
            // solve the problem of cross node Chinese input
1319
            if (Range.isExpanded(selection)) {
×
1320
                Editor.deleteFragment(this.editor);
×
1321
                this.forceRender();
×
1322
            }
1323
        }
1324
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1325
            this.isComposing = true;
1✔
1326
        }
1327
        this.render();
1✔
1328
    }
1329

1330
    private onDOMCompositionUpdate(event: CompositionEvent) {
1331
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1332
    }
1333

1334
    private onDOMCompositionEnd(event: CompositionEvent) {
1335
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1336
            Transforms.delete(this.editor);
×
1337
        }
1338
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1339
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1340
            // aren't correct and never fire the "insertFromComposition"
1341
            // type that we need. So instead, insert whenever a composition
1342
            // ends since it will already have been committed to the DOM.
1343
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1344
                preventInsertFromComposition(event, this.editor);
×
1345
                Editor.insertText(this.editor, event.data);
×
1346
            }
1347

1348
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1349
            // so we need avoid repeat isnertText by isComposing === true,
1350
            this.isComposing = false;
×
1351
        }
1352
        this.render();
×
1353
    }
1354

1355
    private onDOMCopy(event: ClipboardEvent) {
1356
        const window = AngularEditor.getWindow(this.editor);
×
1357
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1358
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1359
            event.preventDefault();
×
1360
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1361
        }
1362
    }
1363

1364
    private onDOMCut(event: ClipboardEvent) {
1365
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1366
            event.preventDefault();
×
1367
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1368
            const { selection } = this.editor;
×
1369

1370
            if (selection) {
×
1371
                AngularEditor.deleteCutData(this.editor);
×
1372
            }
1373
        }
1374
    }
1375

1376
    private onDOMDragOver(event: DragEvent) {
1377
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1378
            // Only when the target is void, call `preventDefault` to signal
1379
            // that drops are allowed. Editable content is droppable by
1380
            // default, and calling `preventDefault` hides the cursor.
1381
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1382

1383
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1384
                event.preventDefault();
×
1385
            }
1386
        }
1387
    }
1388

1389
    private onDOMDragStart(event: DragEvent) {
1390
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1391
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1392
            const path = AngularEditor.findPath(this.editor, node);
×
1393
            const voidMatch =
1394
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1395

1396
            // If starting a drag on a void node, make sure it is selected
1397
            // so that it shows up in the selection's fragment.
1398
            if (voidMatch) {
×
1399
                const range = Editor.range(this.editor, path);
×
1400
                Transforms.select(this.editor, range);
×
1401
            }
1402

1403
            this.isDraggingInternally = true;
×
1404

1405
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1406
        }
1407
    }
1408

1409
    private onDOMDrop(event: DragEvent) {
1410
        const editor = this.editor;
×
1411
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1412
            event.preventDefault();
×
1413
            // Keep a reference to the dragged range before updating selection
1414
            const draggedRange = editor.selection;
×
1415

1416
            // Find the range where the drop happened
1417
            const range = AngularEditor.findEventRange(editor, event);
×
1418
            const data = event.dataTransfer;
×
1419

1420
            Transforms.select(editor, range);
×
1421

1422
            if (this.isDraggingInternally) {
×
1423
                if (draggedRange) {
×
1424
                    Transforms.delete(editor, {
×
1425
                        at: draggedRange
1426
                    });
1427
                }
1428

1429
                this.isDraggingInternally = false;
×
1430
            }
1431

1432
            AngularEditor.insertData(editor, data);
×
1433

1434
            // When dragging from another source into the editor, it's possible
1435
            // that the current editor does not have focus.
1436
            if (!AngularEditor.isFocused(editor)) {
×
1437
                AngularEditor.focus(editor);
×
1438
            }
1439
        }
1440
    }
1441

1442
    private onDOMDragEnd(event: DragEvent) {
1443
        if (
×
1444
            !this.readonly &&
×
1445
            this.isDraggingInternally &&
1446
            AngularEditor.hasTarget(this.editor, event.target) &&
1447
            !this.isDOMEventHandled(event, this.dragEnd)
1448
        ) {
1449
            this.isDraggingInternally = false;
×
1450
        }
1451
    }
1452

1453
    private onDOMFocus(event: Event) {
1454
        if (
2✔
1455
            !this.readonly &&
8✔
1456
            !this.isUpdatingSelection &&
1457
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1458
            !this.isDOMEventHandled(event, this.focus)
1459
        ) {
1460
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1461
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1462
            this.latestElement = root.activeElement;
2✔
1463

1464
            // COMPAT: If the editor has nested editable elements, the focus
1465
            // can go to them. In Firefox, this must be prevented because it
1466
            // results in issues with keyboard navigation. (2017/03/30)
1467
            if (IS_FIREFOX && event.target !== el) {
2!
1468
                el.focus();
×
1469
                return;
×
1470
            }
1471

1472
            IS_FOCUSED.set(this.editor, true);
2✔
1473
        }
1474
    }
1475

1476
    private onDOMKeydown(event: KeyboardEvent) {
1477
        const editor = this.editor;
×
1478
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1479
        const { activeElement } = root;
×
1480
        if (
×
1481
            !this.readonly &&
×
1482
            AngularEditor.hasEditableTarget(editor, event.target) &&
1483
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1484
            !this.isComposing &&
1485
            !this.isDOMEventHandled(event, this.keydown)
1486
        ) {
1487
            const nativeEvent = event;
×
1488
            const { selection } = editor;
×
1489

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

1493
            try {
×
1494
                // COMPAT: Since we prevent the default behavior on
1495
                // `beforeinput` events, the browser doesn't think there's ever
1496
                // any history stack to undo or redo, so we have to manage these
1497
                // hotkeys ourselves. (2019/11/06)
1498
                if (Hotkeys.isRedo(nativeEvent)) {
×
1499
                    event.preventDefault();
×
1500

1501
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1502
                        editor.redo();
×
1503
                    }
1504

1505
                    return;
×
1506
                }
1507

1508
                if (Hotkeys.isUndo(nativeEvent)) {
×
1509
                    event.preventDefault();
×
1510

1511
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1512
                        editor.undo();
×
1513
                    }
1514

1515
                    return;
×
1516
                }
1517

1518
                // COMPAT: Certain browsers don't handle the selection updates
1519
                // properly. In Chrome, the selection isn't properly extended.
1520
                // And in Firefox, the selection isn't properly collapsed.
1521
                // (2017/10/17)
1522
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1523
                    event.preventDefault();
×
1524
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1525
                    return;
×
1526
                }
1527

1528
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1529
                    event.preventDefault();
×
1530
                    Transforms.move(editor, { unit: 'line' });
×
1531
                    return;
×
1532
                }
1533

1534
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1535
                    event.preventDefault();
×
1536
                    Transforms.move(editor, {
×
1537
                        unit: 'line',
1538
                        edge: 'focus',
1539
                        reverse: true
1540
                    });
1541
                    return;
×
1542
                }
1543

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

1550
                // COMPAT: If a void node is selected, or a zero-width text node
1551
                // adjacent to an inline is selected, we need to handle these
1552
                // hotkeys manually because browsers won't be able to skip over
1553
                // the void node with the zero-width space not being an empty
1554
                // string.
1555
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1556
                    event.preventDefault();
×
1557

1558
                    if (selection && Range.isCollapsed(selection)) {
×
1559
                        Transforms.move(editor, { reverse: !isRTL });
×
1560
                    } else {
1561
                        Transforms.collapse(editor, { edge: 'start' });
×
1562
                    }
1563

1564
                    return;
×
1565
                }
1566

1567
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1568
                    event.preventDefault();
×
1569
                    if (selection && Range.isCollapsed(selection)) {
×
1570
                        Transforms.move(editor, { reverse: isRTL });
×
1571
                    } else {
1572
                        Transforms.collapse(editor, { edge: 'end' });
×
1573
                    }
1574

1575
                    return;
×
1576
                }
1577

1578
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1579
                    event.preventDefault();
×
1580

1581
                    if (selection && Range.isExpanded(selection)) {
×
1582
                        Transforms.collapse(editor, { edge: 'focus' });
×
1583
                    }
1584

1585
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1586
                    return;
×
1587
                }
1588

1589
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1590
                    event.preventDefault();
×
1591

1592
                    if (selection && Range.isExpanded(selection)) {
×
1593
                        Transforms.collapse(editor, { edge: 'focus' });
×
1594
                    }
1595

1596
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1597
                    return;
×
1598
                }
1599

1600
                if (isKeyHotkey('mod+a', event)) {
×
1601
                    this.editor.selectAll();
×
1602
                    event.preventDefault();
×
1603
                    return;
×
1604
                }
1605

1606
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1607
                // fall back to guessing at the input intention for hotkeys.
1608
                // COMPAT: In iOS, some of these hotkeys are handled in the
1609
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1610
                    // We don't have a core behavior for these, but they change the
1611
                    // DOM if we don't prevent them, so we have to.
1612
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1613
                        event.preventDefault();
×
1614
                        return;
×
1615
                    }
1616

1617
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1618
                        event.preventDefault();
×
1619
                        Editor.insertBreak(editor);
×
1620
                        return;
×
1621
                    }
1622

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

1626
                        if (selection && Range.isExpanded(selection)) {
×
1627
                            Editor.deleteFragment(editor, {
×
1628
                                direction: 'backward'
1629
                            });
1630
                        } else {
1631
                            Editor.deleteBackward(editor);
×
1632
                        }
1633

1634
                        return;
×
1635
                    }
1636

1637
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1638
                        event.preventDefault();
×
1639

1640
                        if (selection && Range.isExpanded(selection)) {
×
1641
                            Editor.deleteFragment(editor, {
×
1642
                                direction: 'forward'
1643
                            });
1644
                        } else {
1645
                            Editor.deleteForward(editor);
×
1646
                        }
1647

1648
                        return;
×
1649
                    }
1650

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

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

1662
                        return;
×
1663
                    }
1664

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

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

1676
                        return;
×
1677
                    }
1678

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

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

1690
                        return;
×
1691
                    }
1692

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

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

1704
                        return;
×
1705
                    }
1706
                } else {
1707
                    if (IS_CHROME || IS_SAFARI) {
×
1708
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1709
                        // an event when deleting backwards in a selected void inline node
1710
                        if (
×
1711
                            selection &&
×
1712
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1713
                            Range.isCollapsed(selection)
1714
                        ) {
1715
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1716
                            if (
×
1717
                                Element.isElement(currentNode) &&
×
1718
                                Editor.isVoid(editor, currentNode) &&
1719
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1720
                            ) {
1721
                                event.preventDefault();
×
1722
                                Editor.deleteBackward(editor, {
×
1723
                                    unit: 'block'
1724
                                });
1725
                                return;
×
1726
                            }
1727
                        }
1728
                    }
1729
                }
1730
            } catch (error) {
1731
                this.editor.onError({
×
1732
                    code: SlateErrorCode.OnDOMKeydownError,
1733
                    nativeError: error
1734
                });
1735
            }
1736
        }
1737
    }
1738

1739
    private onDOMPaste(event: ClipboardEvent) {
1740
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1741
        // fall back to React's `onPaste` here instead.
1742
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1743
        // when "paste without formatting" option is used.
1744
        // This unfortunately needs to be handled with paste events instead.
1745
        if (
×
1746
            !this.isDOMEventHandled(event, this.paste) &&
×
1747
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1748
            !this.readonly &&
1749
            AngularEditor.hasEditableTarget(this.editor, event.target)
1750
        ) {
1751
            event.preventDefault();
×
1752
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1753
        }
1754
    }
1755

1756
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1757
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1758
        // fall back to React's leaky polyfill instead just for it. It
1759
        // only works for the `insertText` input type.
1760
        if (
×
1761
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1762
            !this.readonly &&
1763
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1764
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1765
        ) {
1766
            event.nativeEvent.preventDefault();
×
1767
            try {
×
1768
                const text = event.data;
×
1769
                if (!Range.isCollapsed(this.editor.selection)) {
×
1770
                    Editor.deleteFragment(this.editor);
×
1771
                }
1772
                // just handle Non-IME input
1773
                if (!this.isComposing) {
×
1774
                    Editor.insertText(this.editor, text);
×
1775
                }
1776
            } catch (error) {
1777
                this.editor.onError({
×
1778
                    code: SlateErrorCode.ToNativeSelectionError,
1779
                    nativeError: error
1780
                });
1781
            }
1782
        }
1783
    }
1784

1785
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1786
        if (!handler) {
3✔
1787
            return false;
3✔
1788
        }
1789
        handler(event);
×
1790
        return event.defaultPrevented;
×
1791
    }
1792
    //#endregion
1793

1794
    ngOnDestroy() {
1795
        this.editorResizeObserver?.disconnect();
22✔
1796
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1797
        this.manualListeners.forEach(manualListener => {
22✔
1798
            manualListener();
462✔
1799
        });
1800
        this.destroy$.complete();
22✔
1801
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1802
    }
1803
}
1804

1805
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1806
    // This was affecting the selection of multiple blocks and dragging behavior,
1807
    // so enabled only if the selection has been collapsed.
1808
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1809
        const leafEl = domRange.startContainer.parentElement!;
×
1810

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

1816
        if (isZeroDimensionRect) {
×
1817
            const leafRect = leafEl.getBoundingClientRect();
×
1818
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1819

1820
            if (leafHasDimensions) {
×
1821
                return;
×
1822
            }
1823
        }
1824

1825
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1826
        scrollIntoView(leafEl, {
×
1827
            scrollMode: 'if-needed'
1828
        });
1829
        delete leafEl.getBoundingClientRect;
×
1830
    }
1831
};
1832

1833
/**
1834
 * Check if the target is inside void and in the editor.
1835
 */
1836

1837
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1838
    let slateNode: Node | null = null;
1✔
1839
    try {
1✔
1840
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1841
    } catch (error) {}
1842
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1843
};
1844

1845
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1846
    return (
2✔
1847
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1848
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1849
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1850
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1851
    );
1852
};
1853

1854
/**
1855
 * remove default insert from composition
1856
 * @param text
1857
 */
1858
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1859
    const types = ['compositionend', 'insertFromComposition'];
×
1860
    if (!types.includes(event.type)) {
×
1861
        return;
×
1862
    }
1863
    const insertText = (event as CompositionEvent).data;
×
1864
    const window = AngularEditor.getWindow(editor);
×
1865
    const domSelection = window.getSelection();
×
1866
    // ensure text node insert composition input text
1867
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1868
        const textNode = domSelection.anchorNode;
×
1869
        textNode.splitText(textNode.length - insertText.length).remove();
×
1870
    }
1871
};
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