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

worktile / slate-angular / 63a9108c-502e-4086-9709-a019cc4d45c3

18 Dec 2025 01:58AM UTC coverage: 36.906% (-0.2%) from 37.107%
63a9108c-502e-4086-9709-a019cc4d45c3

push

circleci

web-flow
feat(virtual-scroll): fix top height when scroll to upward (#327)

380 of 1237 branches covered (30.72%)

Branch coverage included in aggregate %.

2 of 20 new or added lines in 2 files covered. (10.0%)

1 existing line in 1 file now uncovered.

1073 of 2700 relevant lines covered (39.74%)

24.09 hits per line

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

22.24
/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 { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID, SLATE_DEBUG_KEY, SLATE_DEBUG_KEY_SCROLL_TOP } from '../../utils/environment';
43
import Hotkeys from '../../utils/hotkeys';
44
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
45
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
46
import { SlateErrorCode } from '../../types/error';
47
import { NG_VALUE_ACCESSOR } from '@angular/forms';
48
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
49
import { ViewType } from '../../types/view';
50
import { HistoryEditor } from 'slate-history';
51
import {
52
    buildHeightsAndAccumulatedHeights,
53
    EDITOR_TO_BUSINESS_TOP,
54
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
55
    ELEMENT_KEY_TO_HEIGHTS,
56
    ELEMENT_TO_COMPONENT,
57
    getBusinessTop,
58
    getRealHeightByElement,
59
    IS_ENABLED_VIRTUAL_SCROLL,
60
    isDecoratorRangeListEqual
61
} from '../../utils';
62
import { SlatePlaceholder } from '../../types/feature';
63
import { restoreDom } from '../../utils/restore-dom';
64
import { ListRender } from '../../view/render/list-render';
65
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
66
import { BaseElementComponent } from '../../view/base';
67
import { BaseElementFlavour } from '../../view/flavour/element';
68
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
69
import { isKeyHotkey } from 'is-hotkey';
70
import { VirtualScrollDebugOverlay } from './debug';
71

72
// not correctly clipboardData on beforeinput
73
const forceOnDOMPaste = IS_SAFARI;
1✔
74

75
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
76
const isDebugScrollTop = localStorage.getItem(SLATE_DEBUG_KEY_SCROLL_TOP) === 'true';
1✔
77

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

103
    private destroy$ = new Subject();
23✔
104

105
    isComposing = false;
23✔
106
    isDraggingInternally = false;
23✔
107
    isUpdatingSelection = false;
23✔
108
    latestElement = null as DOMElement | null;
23✔
109

110
    protected manualListeners: (() => void)[] = [];
23✔
111

112
    private initialized: boolean;
113

114
    private onTouchedCallback: () => void = () => {};
23✔
115

116
    private onChangeCallback: (_: any) => void = () => {};
23✔
117

118
    @Input() editor: AngularEditor;
119

120
    @Input() renderElement: (element: Element) => ViewType | null;
121

122
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
123

124
    @Input() renderText: (text: SlateText) => ViewType | null;
125

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

128
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
129

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

132
    @Input() isStrictDecorate: boolean = true;
23✔
133

134
    @Input() trackBy: (node: Element) => any = () => null;
206✔
135

136
    @Input() readonly = false;
23✔
137

138
    @Input() placeholder: string;
139

140
    @Input()
141
    set virtualScroll(config: SlateVirtualScrollConfig) {
142
        this.virtualScrollConfig = config;
×
NEW
143
        if (isDebugScrollTop) {
×
NEW
144
            this.debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
145
        }
146
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
147
        if (this.isEnabledVirtualScroll()) {
×
148
            this.tryUpdateVirtualViewport();
×
149
        }
150
    }
151

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

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

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

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

184
    viewContainerRef = inject(ViewContainerRef);
23✔
185

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

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

198
    listRender: ListRender;
199

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

474
    ngAfterViewChecked() {}
475

476
    ngDoCheck() {}
477

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

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

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

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

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

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

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

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

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

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

622
    virtualScrollInitialized = false;
23✔
623

624
    virtualTopHeightElement: HTMLElement;
625

626
    virtualBottomHeightElement: HTMLElement;
627

628
    virtualCenterOutlet: HTMLElement;
629

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

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

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

676
    private tryUpdateVirtualViewport() {
677
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
678
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
679
            let virtualView = this.calculateVirtualViewport();
×
680
            let diff = this.diffVirtualViewport(virtualView);
×
681
            if (!diff.isDiff) {
×
682
                return;
×
683
            }
684
            // diff.isAddedTop
685
            if (diff.isMissingTop) {
×
686
                const remeasureIndics = diff.diffTopRenderedIndexes;
×
687
                const result = this.remeasureHeightByIndics(remeasureIndics);
×
688
                if (result) {
×
689
                    virtualView = this.calculateVirtualViewport();
×
690
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
691
                    if (!diff.isDiff) {
×
692
                        return;
×
693
                    }
694
                }
695
            }
696
            this.applyVirtualView(virtualView);
×
697
            if (this.listRender.initialized) {
×
698
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
699
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
700
                    this.toNativeSelection();
×
701
                }
702
            }
NEW
703
            if (diff.isAddedTop) {
×
NEW
704
                const remeasureAddedIndics = diff.diffTopRenderedIndexes;
×
NEW
705
                if (isDebug) {
×
NEW
706
                    this.debugLog('log', 'isAddedTop to remeasure heights: ', remeasureAddedIndics);
×
707
                }
NEW
708
                const startIndexBeforeAdd = diff.diffTopRenderedIndexes[diff.diffTopRenderedIndexes.length - 1] + 1;
×
NEW
709
                const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
NEW
710
                const result = this.remeasureHeightByIndics(remeasureAddedIndics);
×
NEW
711
                if (result) {
×
NEW
712
                    const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
NEW
713
                    const visibleStartIndex = diff.diffTopRenderedIndexes[0];
×
NEW
714
                    const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
715
                    const adjustedTopHeight =
NEW
716
                        (visibleStartIndex === -1 ? 0 : newHeights.accumulatedHeights[visibleStartIndex]) -
×
717
                        (actualTopHeightAfterAdd - topHeightBeforeAdd);
NEW
718
                    if (adjustedTopHeight !== virtualView.top) {
×
NEW
719
                        if (isDebug) {
×
NEW
720
                            this.debugLog(
×
721
                                'log',
722
                                `update top height cause added element in top: ${adjustedTopHeight}, old height: ${virtualView.top}`
723
                            );
724
                        }
NEW
725
                        this.virtualTopHeightElement.style.height = `${adjustedTopHeight}px`;
×
726
                    }
727
                }
728
            }
UNCOV
729
            this.tryMeasureInViewportChildrenHeights();
×
730
        });
731
    }
732

733
    private calculateVirtualViewport() {
734
        const children = (this.editor.children || []) as Element[];
×
735
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
736
            return {
×
737
                inViewportChildren: children,
738
                visibleIndexes: new Set<number>(),
739
                top: 0,
740
                bottom: 0,
741
                heights: []
742
            };
743
        }
744
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
745
        if (isDebug) {
×
746
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
747
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
748
        }
749
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
750
        if (!viewportHeight) {
×
751
            return {
×
752
                inViewportChildren: [],
753
                visibleIndexes: new Set<number>(),
754
                top: 0,
755
                bottom: 0,
756
                heights: []
757
            };
758
        }
759
        const elementLength = children.length;
×
760
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
761
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
762
            setTimeout(() => {
×
763
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
764
                const businessTop =
765
                    Math.ceil(virtualTopBoundingTop) +
×
766
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
767
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
768
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
769
                if (isDebug) {
×
770
                    this.debugLog('log', 'businessTop', businessTop);
×
771
                }
772
            }, 100);
773
        }
774
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
775
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
776
        const totalHeight = accumulatedHeights[elementLength];
×
777
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
778
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
779
        const viewBottom = limitedScrollTop + viewportHeight + getBusinessTop(this.editor);
×
780
        let accumulatedOffset = 0;
×
781
        let visibleStartIndex = -1;
×
782
        const visible: Element[] = [];
×
783
        const visibleIndexes: number[] = [];
×
784

785
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
786
            const currentHeight = heights[i];
×
787
            const nextOffset = accumulatedOffset + currentHeight;
×
788
            // 可视区域有交集,加入渲染
789
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
790
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
791
                visible.push(children[i]);
×
792
                visibleIndexes.push(i);
×
793
            }
794
            accumulatedOffset = nextOffset;
×
795
        }
796

797
        if (visibleStartIndex === -1 && elementLength) {
×
798
            visibleStartIndex = elementLength - 1;
×
799
            visible.push(children[visibleStartIndex]);
×
800
            visibleIndexes.push(visibleStartIndex);
×
801
        }
802

803
        const visibleEndIndex =
804
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
805
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
806
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
807

808
        return {
×
809
            inViewportChildren: visible.length ? visible : children,
×
810
            visibleIndexes: new Set(visibleIndexes),
811
            top,
812
            bottom,
813
            heights,
814
            accumulatedHeights
815
        };
816
    }
817

818
    private applyVirtualView(virtualView: VirtualViewResult) {
819
        this.inViewportChildren = virtualView.inViewportChildren;
×
820
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
821
        this.inViewportIndics = virtualView.visibleIndexes;
×
822
    }
823

824
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
825
        if (!this.inViewportChildren.length) {
×
826
            return {
×
827
                isDiff: true,
828
                diffTopRenderedIndexes: [],
829
                diffBottomRenderedIndexes: []
830
            };
831
        }
832
        const oldVisibleIndexes = [...this.inViewportIndics];
×
833
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
834
        const firstNewIndex = newVisibleIndexes[0];
×
835
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
836
        const firstOldIndex = oldVisibleIndexes[0];
×
837
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
838
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
839
            const diffTopRenderedIndexes = [];
×
840
            const diffBottomRenderedIndexes = [];
×
841
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
842
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
843
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
844
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
845
            if (isMissingTop || isAddedBottom) {
×
846
                // 向下
847
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
848
                    const element = oldVisibleIndexes[index];
×
849
                    if (!newVisibleIndexes.includes(element)) {
×
850
                        diffTopRenderedIndexes.push(element);
×
851
                    } else {
852
                        break;
×
853
                    }
854
                }
855
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
856
                    const element = newVisibleIndexes[index];
×
857
                    if (!oldVisibleIndexes.includes(element)) {
×
858
                        diffBottomRenderedIndexes.push(element);
×
859
                    } else {
860
                        break;
×
861
                    }
862
                }
863
            } else if (isAddedTop || isMissingBottom) {
×
864
                // 向上
865
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
866
                    const element = newVisibleIndexes[index];
×
867
                    if (!oldVisibleIndexes.includes(element)) {
×
868
                        diffTopRenderedIndexes.push(element);
×
869
                    } else {
870
                        break;
×
871
                    }
872
                }
873
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
874
                    const element = oldVisibleIndexes[index];
×
875
                    if (!newVisibleIndexes.includes(element)) {
×
876
                        diffBottomRenderedIndexes.push(element);
×
877
                    } else {
878
                        break;
×
879
                    }
880
                }
881
            }
882
            if (isDebug) {
×
883
                this.debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
884
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
885
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
886
                this.debugLog(
×
887
                    'log',
888
                    'diffTopRenderedIndexes:',
889
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
890
                    diffTopRenderedIndexes,
891
                    diffTopRenderedIndexes.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
892
                );
893
                this.debugLog(
×
894
                    'log',
895
                    'diffBottomRenderedIndexes:',
896
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
897
                    diffBottomRenderedIndexes,
898
                    diffBottomRenderedIndexes.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
899
                );
900
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
901
                const needBottom = virtualView.heights
×
902
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
903
                    .reduce((acc, height) => acc + height, 0);
×
904
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
905
                this.debugLog(
×
906
                    'log',
907
                    'newBottomHeight:',
908
                    needBottom,
909
                    'prevBottomHeight:',
910
                    parseFloat(this.virtualBottomHeightElement.style.height)
911
                );
912
                this.debugLog('warn', '=========== Dividing line ===========');
×
913
            }
914
            return {
×
915
                isDiff: true,
916
                isMissingTop,
917
                isAddedTop,
918
                isMissingBottom,
919
                isAddedBottom,
920
                diffTopRenderedIndexes,
921
                diffBottomRenderedIndexes
922
            };
923
        }
924
        return {
×
925
            isDiff: false,
926
            diffTopRenderedIndexes: [],
927
            diffBottomRenderedIndexes: []
928
        };
929
    }
930

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

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

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

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

1022
    private toSlateSelection() {
1023
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1024
            try {
1✔
1025
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1026
                const { activeElement } = root;
1✔
1027
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1028
                const domSelection = (root as Document).getSelection();
1✔
1029

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

1037
                if (!domSelection) {
1!
1038
                    return Transforms.deselect(this.editor);
×
1039
                }
1040

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

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

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

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

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

1165
                    case 'deleteContent':
1166
                    case 'deleteContentForward': {
1167
                        Editor.deleteForward(editor);
×
1168
                        break;
×
1169
                    }
1170

1171
                    case 'deleteContentBackward': {
1172
                        Editor.deleteBackward(editor);
×
1173
                        break;
×
1174
                    }
1175

1176
                    case 'deleteEntireSoftLine': {
1177
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1178
                        Editor.deleteForward(editor, { unit: 'line' });
×
1179
                        break;
×
1180
                    }
1181

1182
                    case 'deleteHardLineBackward': {
1183
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1184
                        break;
×
1185
                    }
1186

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

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

1197
                    case 'deleteSoftLineForward': {
1198
                        Editor.deleteForward(editor, { unit: 'line' });
×
1199
                        break;
×
1200
                    }
1201

1202
                    case 'deleteWordBackward': {
1203
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1204
                        break;
×
1205
                    }
1206

1207
                    case 'deleteWordForward': {
1208
                        Editor.deleteForward(editor, { unit: 'word' });
×
1209
                        break;
×
1210
                    }
1211

1212
                    case 'insertLineBreak':
1213
                    case 'insertParagraph': {
1214
                        Editor.insertBreak(editor);
×
1215
                        break;
×
1216
                    }
1217

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

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

1263
        const window = AngularEditor.getWindow(this.editor);
×
1264

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

1274
        const { relatedTarget } = event;
×
1275
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1276

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

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

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

1296
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1297
                return;
×
1298
            }
1299
        }
1300

1301
        IS_FOCUSED.delete(this.editor);
×
1302
    }
1303

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

1316
            const startVoid = Editor.void(this.editor, { at: start });
×
1317
            const endVoid = Editor.void(this.editor, { at: end });
×
1318

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

1327
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1328
                }
1329

1330
                const range = Editor.range(this.editor, blockPath);
×
1331
                Transforms.select(this.editor, range);
×
1332
                return;
×
1333
            }
1334

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

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

1362
    private onDOMCompositionUpdate(event: CompositionEvent) {
1363
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1364
    }
1365

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

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

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

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

1402
            if (selection) {
×
1403
                AngularEditor.deleteCutData(this.editor);
×
1404
            }
1405
        }
1406
    }
1407

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

1415
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1416
                event.preventDefault();
×
1417
            }
1418
        }
1419
    }
1420

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

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

1435
            this.isDraggingInternally = true;
×
1436

1437
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1438
        }
1439
    }
1440

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

1448
            // Find the range where the drop happened
1449
            const range = AngularEditor.findEventRange(editor, event);
×
1450
            const data = event.dataTransfer;
×
1451

1452
            Transforms.select(editor, range);
×
1453

1454
            if (this.isDraggingInternally) {
×
1455
                if (draggedRange) {
×
1456
                    Transforms.delete(editor, {
×
1457
                        at: draggedRange
1458
                    });
1459
                }
1460

1461
                this.isDraggingInternally = false;
×
1462
            }
1463

1464
            AngularEditor.insertData(editor, data);
×
1465

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

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

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

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

1504
            IS_FOCUSED.set(this.editor, true);
2✔
1505
        }
1506
    }
1507

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

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

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

1533
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1534
                        editor.redo();
×
1535
                    }
1536

1537
                    return;
×
1538
                }
1539

1540
                if (Hotkeys.isUndo(nativeEvent)) {
×
1541
                    event.preventDefault();
×
1542

1543
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1544
                        editor.undo();
×
1545
                    }
1546

1547
                    return;
×
1548
                }
1549

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

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

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

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

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

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

1596
                    return;
×
1597
                }
1598

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

1607
                    return;
×
1608
                }
1609

1610
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1611
                    event.preventDefault();
×
1612

1613
                    if (selection && Range.isExpanded(selection)) {
×
1614
                        Transforms.collapse(editor, { edge: 'focus' });
×
1615
                    }
1616

1617
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1618
                    return;
×
1619
                }
1620

1621
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1622
                    event.preventDefault();
×
1623

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

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

1632
                if (isKeyHotkey('mod+a', event)) {
×
1633
                    this.editor.selectAll();
×
1634
                    event.preventDefault();
×
1635
                    return;
×
1636
                }
1637

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

1649
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1650
                        event.preventDefault();
×
1651
                        Editor.insertBreak(editor);
×
1652
                        return;
×
1653
                    }
1654

1655
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1656
                        event.preventDefault();
×
1657

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

1666
                        return;
×
1667
                    }
1668

1669
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1670
                        event.preventDefault();
×
1671

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

1680
                        return;
×
1681
                    }
1682

1683
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1684
                        event.preventDefault();
×
1685

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

1694
                        return;
×
1695
                    }
1696

1697
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1698
                        event.preventDefault();
×
1699

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

1708
                        return;
×
1709
                    }
1710

1711
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1712
                        event.preventDefault();
×
1713

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

1722
                        return;
×
1723
                    }
1724

1725
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1726
                        event.preventDefault();
×
1727

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

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

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

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

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

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

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

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

1848
        if (isZeroDimensionRect) {
×
1849
            const leafRect = leafEl.getBoundingClientRect();
×
1850
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1851

1852
            if (leafHasDimensions) {
×
1853
                return;
×
1854
            }
1855
        }
1856

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

1865
/**
1866
 * Check if the target is inside void and in the editor.
1867
 */
1868

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

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

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