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

worktile / slate-angular / 35a3ce5b-aada-4a4f-b885-fdc3ea26d53c

24 Dec 2025 02:36AM UTC coverage: 36.769% (-0.1%) from 36.904%
35a3ce5b-aada-4a4f-b885-fdc3ea26d53c

push

circleci

web-flow
feat(virtual-scroll): support pre render top elements (#329)

* chore: remove addedTop recalculate

* feat(virtual-scroll): improve virtual scroll performance and add pre-rendering

add EDITOR_TO_WIDTH weakmap to track editor width
implement pre-rendering of offscreen elements to reduce jank
store huge document value in localStorage for persistence
simplify anchor scroll logic by using fixed index
optimize virtual viewport updates and height measurements

* chore: xx

* fix: list-render error

* feat: apply overflow-anchor: none

* fix: xxx

* chore: remove setting

* chore: remove EDITOR_TO_WIDTH

* feat: revert measure update

* chore: remove

* refactor: xxx

* feat(virtual-scroll): support pre render top elements

* chore: revert header

382 of 1242 branches covered (30.76%)

Branch coverage included in aggregate %.

3 of 59 new or added lines in 2 files covered. (5.08%)

2 existing lines in 1 file now uncovered.

1077 of 2726 relevant lines covered (39.51%)

23.97 hits per line

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

22.09
/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
    ELEMENT_TO_COMPONENT,
65
    getBusinessTop,
66
    getRealHeightByElement,
67
    IS_ENABLED_VIRTUAL_SCROLL,
68
    isDecoratorRangeListEqual
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 { BaseElementComponent } from '../../view/base';
75
import { BaseElementFlavour } from '../../view/flavour/element';
76
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
77
import { isKeyHotkey } from 'is-hotkey';
78
import { VirtualScrollDebugOverlay } from './debug';
79

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

83
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
84
const isDebugScrollTop = localStorage.getItem(SLATE_DEBUG_KEY_SCROLL_TOP) === 'true';
1✔
85

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

111
    private destroy$ = new Subject();
23✔
112

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

118
    protected manualListeners: (() => void)[] = [];
23✔
119

120
    private initialized: boolean;
121

122
    private onTouchedCallback: () => void = () => {};
23✔
123

124
    private onChangeCallback: (_: any) => void = () => {};
23✔
125

126
    @Input() editor: AngularEditor;
127

128
    @Input() renderElement: (element: Element) => ViewType | null;
129

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

132
    @Input() renderText: (text: SlateText) => ViewType | null;
133

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

136
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
137

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

140
    @Input() isStrictDecorate: boolean = true;
23✔
141

142
    @Input() trackBy: (node: Element) => any = () => null;
206✔
143

144
    @Input() readonly = false;
23✔
145

146
    @Input() placeholder: string;
147

148
    @Input()
149
    set virtualScroll(config: SlateVirtualScrollConfig) {
150
        this.virtualScrollConfig = config;
×
151
        if (isDebugScrollTop) {
×
152
            this.debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
153
        }
154
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
155
        if (this.isEnabledVirtualScroll()) {
×
156
            this.tryUpdateVirtualViewport();
×
157
        }
158
    }
159

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

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

206
    listRender: ListRender;
207

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

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

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

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

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

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

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

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

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

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

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

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

386
            const hasDomSelection = domSelection.type !== 'None';
1✔
387

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

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

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

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

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

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

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

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

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

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

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

482
    ngAfterViewChecked() {}
483

484
    ngDoCheck() {}
485

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

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

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

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

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

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

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

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

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

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

629
    virtualScrollInitialized = false;
23✔
630

631
    virtualTopHeightElement: HTMLElement;
632

633
    virtualBottomHeightElement: HTMLElement;
634

635
    virtualCenterOutlet: HTMLElement;
636

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

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

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

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

693
    private tryUpdateVirtualViewport() {
NEW
694
        if (isDebug) {
×
NEW
695
            this.debugLog('log', 'tryUpdateVirtualViewport');
×
696
        }
697
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
698
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
NEW
699
            if (isDebug) {
×
NEW
700
                this.debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
701
            }
702
            let virtualView = this.calculateVirtualViewport();
×
703
            let diff = this.diffVirtualViewport(virtualView);
×
NEW
704
            if (diff.isDiff) {
×
NEW
705
                this.applyVirtualView(virtualView);
×
NEW
706
                if (this.listRender.initialized) {
×
NEW
707
                    let preRenderingCount = 0;
×
NEW
708
                    const childrenWithPreRendering = [...this.inViewportChildren];
×
NEW
709
                    if (this.inViewportIndics[0] !== 0) {
×
NEW
710
                        preRenderingCount = 1;
×
NEW
711
                        childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
712
                    }
NEW
713
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
NEW
714
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
NEW
715
                        this.toNativeSelection();
×
716
                    }
717
                }
NEW
718
                if (diff.isAddedTop) {
×
NEW
719
                    const remeasureAddedIndics = diff.diffTopRenderedIndexes;
×
NEW
720
                    if (isDebug) {
×
NEW
721
                        this.debugLog('log', 'isAddedTop to remeasure heights: ', remeasureAddedIndics);
×
722
                    }
NEW
723
                    const startIndexBeforeAdd = diff.diffTopRenderedIndexes[diff.diffTopRenderedIndexes.length - 1] + 1;
×
NEW
724
                    const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
NEW
725
                    const result = this.remeasureHeightByIndics(remeasureAddedIndics);
×
NEW
726
                    if (result) {
×
NEW
727
                        const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
NEW
728
                        const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
NEW
729
                        const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
NEW
730
                        this.setVirtualSpaceHeight(newTopHeight);
×
NEW
731
                        this.debugLog(
×
732
                            'log',
733
                            `update top height cause added element in top, 减去: ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
734
                        );
735
                    }
736
                }
NEW
737
                this.tryMeasureInViewportChildrenHeights();
×
738
            } else {
NEW
739
                const topHeight = this.getVirtualTopHeight();
×
NEW
740
                if (virtualView.top !== topHeight) {
×
NEW
741
                    this.debugLog('log', 'update top height: ', virtualView.top - topHeight, 'start index', this.inViewportIndics[0]);
×
NEW
742
                    this.setVirtualSpaceHeight(virtualView.top);
×
743
                }
744
            }
NEW
745
            if (isDebug) {
×
NEW
746
                this.debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
747
            }
748
        });
749
    }
750

751
    private calculateVirtualViewport() {
752
        const children = (this.editor.children || []) as Element[];
×
753
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
754
            return {
×
755
                inViewportChildren: children,
756
                visibleIndexes: [],
757
                top: 0,
758
                bottom: 0,
759
                heights: []
760
            };
761
        }
762
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
763
        if (isDebug) {
×
764
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
765
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
766
        }
767
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
768
        if (!viewportHeight) {
×
769
            return {
×
770
                inViewportChildren: [],
771
                visibleIndexes: [],
772
                top: 0,
773
                bottom: 0,
774
                heights: []
775
            };
776
        }
777
        const elementLength = children.length;
×
778
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
779
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
780
            setTimeout(() => {
×
781
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
782
                const businessTop =
783
                    Math.ceil(virtualTopBoundingTop) +
×
784
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
785
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
786
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
787
                if (isDebug) {
×
788
                    this.debugLog('log', 'businessTop', businessTop);
×
789
                }
790
            }, 100);
791
        }
792
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
793
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
794
        const totalHeight = accumulatedHeights[elementLength];
×
795
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
796
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
797
        const viewBottom = limitedScrollTop + viewportHeight;
×
798
        let accumulatedOffset = 0;
×
799
        let visibleStartIndex = -1;
×
800
        const visible: Element[] = [];
×
801
        const visibleIndexes: number[] = [];
×
802

803
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
804
            const currentHeight = heights[i];
×
805
            const nextOffset = accumulatedOffset + currentHeight;
×
806
            // 可视区域有交集,加入渲染
807
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
808
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
809
                visible.push(children[i]);
×
810
                visibleIndexes.push(i);
×
811
            }
812
            accumulatedOffset = nextOffset;
×
813
        }
814

815
        if (visibleStartIndex === -1 && elementLength) {
×
816
            visibleStartIndex = elementLength - 1;
×
817
            visible.push(children[visibleStartIndex]);
×
818
            visibleIndexes.push(visibleStartIndex);
×
819
        }
820

821
        const visibleEndIndex =
822
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
823
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
824
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
UNCOV
825
        return {
×
826
            inViewportChildren: visible.length ? visible : children,
×
827
            visibleIndexes,
828
            top,
829
            bottom,
830
            heights,
831
            accumulatedHeights
832
        };
833
    }
834

835
    private applyVirtualView(virtualView: VirtualViewResult) {
836
        this.inViewportChildren = virtualView.inViewportChildren;
×
837
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
838
        this.inViewportIndics = virtualView.visibleIndexes;
×
839
    }
840

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

955
    private tryMeasureInViewportChildrenHeights() {
956
        if (!this.isEnabledVirtualScroll()) {
×
957
            return;
×
958
        }
959
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
960
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
961
            this.measureVisibleHeights();
×
962
        });
963
    }
964

965
    private measureVisibleHeights() {
966
        const children = (this.editor.children || []) as Element[];
×
NEW
967
        const inViewportIndics = [...this.inViewportIndics];
×
NEW
968
        inViewportIndics.forEach(index => {
×
969
            const node = children[index];
×
970
            if (!node) {
×
971
                return;
×
972
            }
973
            const key = AngularEditor.findKey(this.editor, node);
×
974
            // 跳过已测过的块,除非强制测量
975
            if (this.keyHeightMap.has(key.id)) {
×
976
                return;
×
977
            }
978
            const view = ELEMENT_TO_COMPONENT.get(node);
×
979
            if (!view) {
×
980
                return;
×
981
            }
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
                });
987
            } else {
988
                this.keyHeightMap.set(key.id, ret);
×
989
            }
990
        });
991
    }
992

993
    private remeasureHeightByIndics(indics: number[]): boolean {
994
        const children = (this.editor.children || []) as Element[];
×
995
        let isHeightChanged = false;
×
996
        indics.forEach((index, i) => {
×
997
            const node = children[index];
×
998
            if (!node) {
×
999
                return;
×
1000
            }
1001
            const key = AngularEditor.findKey(this.editor, node);
×
1002
            const view = ELEMENT_TO_COMPONENT.get(node);
×
1003
            if (!view) {
×
1004
                return;
×
1005
            }
1006
            const prevHeight = this.keyHeightMap.get(key.id);
×
1007
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
1008
            if (ret instanceof Promise) {
×
1009
                ret.then(height => {
×
1010
                    this.keyHeightMap.set(key.id, height);
×
1011
                    if (height !== prevHeight) {
×
1012
                        isHeightChanged = true;
×
1013
                        if (isDebug) {
×
1014
                            this.debugLog(
×
1015
                                'log',
1016
                                `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`
1017
                            );
1018
                        }
1019
                    }
1020
                });
1021
            } else {
1022
                this.keyHeightMap.set(key.id, ret);
×
1023
                if (ret !== prevHeight) {
×
1024
                    isHeightChanged = true;
×
1025
                    if (isDebug) {
×
1026
                        this.debugLog('log', `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
1027
                    }
1028
                }
1029
            }
1030
        });
1031
        return isHeightChanged;
×
1032
    }
1033

1034
    //#region event proxy
1035
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1036
        this.manualListeners.push(
483✔
1037
            this.renderer2.listen(target, eventName, (event: Event) => {
1038
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1039
                if (beforeInputEvent) {
5!
1040
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1041
                }
1042
                listener(event);
5✔
1043
            })
1044
        );
1045
    }
1046

1047
    private toSlateSelection() {
1048
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1049
            try {
1✔
1050
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1051
                const { activeElement } = root;
1✔
1052
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1053
                const domSelection = (root as Document).getSelection();
1✔
1054

1055
                if (activeElement === el) {
1!
1056
                    this.latestElement = activeElement;
1✔
1057
                    IS_FOCUSED.set(this.editor, true);
1✔
1058
                } else {
1059
                    IS_FOCUSED.delete(this.editor);
×
1060
                }
1061

1062
                if (!domSelection) {
1!
1063
                    return Transforms.deselect(this.editor);
×
1064
                }
1065

1066
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1067
                const hasDomSelectionInEditor =
1068
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1069
                if (!hasDomSelectionInEditor) {
1!
1070
                    Transforms.deselect(this.editor);
×
1071
                    return;
×
1072
                }
1073

1074
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1075
                // for example, double-click the last cell of the table to select a non-editable DOM
1076
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1077
                if (range) {
1✔
1078
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1079
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1080
                            // force adjust DOMSelection
1081
                            this.toNativeSelection();
×
1082
                        }
1083
                    } else {
1084
                        Transforms.select(this.editor, range);
1✔
1085
                    }
1086
                }
1087
            } catch (error) {
1088
                this.editor.onError({
×
1089
                    code: SlateErrorCode.ToSlateSelectionError,
1090
                    nativeError: error
1091
                });
1092
            }
1093
        }
1094
    }
1095

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

1174
                // COMPAT: If the selection is expanded, even if the command seems like
1175
                // a delete forward/backward command it should delete the selection.
1176
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1177
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1178
                    Editor.deleteFragment(editor, { direction });
×
1179
                    return;
×
1180
                }
1181

1182
                switch (type) {
×
1183
                    case 'deleteByComposition':
1184
                    case 'deleteByCut':
1185
                    case 'deleteByDrag': {
1186
                        Editor.deleteFragment(editor);
×
1187
                        break;
×
1188
                    }
1189

1190
                    case 'deleteContent':
1191
                    case 'deleteContentForward': {
1192
                        Editor.deleteForward(editor);
×
1193
                        break;
×
1194
                    }
1195

1196
                    case 'deleteContentBackward': {
1197
                        Editor.deleteBackward(editor);
×
1198
                        break;
×
1199
                    }
1200

1201
                    case 'deleteEntireSoftLine': {
1202
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1203
                        Editor.deleteForward(editor, { unit: 'line' });
×
1204
                        break;
×
1205
                    }
1206

1207
                    case 'deleteHardLineBackward': {
1208
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1209
                        break;
×
1210
                    }
1211

1212
                    case 'deleteSoftLineBackward': {
1213
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1214
                        break;
×
1215
                    }
1216

1217
                    case 'deleteHardLineForward': {
1218
                        Editor.deleteForward(editor, { unit: 'block' });
×
1219
                        break;
×
1220
                    }
1221

1222
                    case 'deleteSoftLineForward': {
1223
                        Editor.deleteForward(editor, { unit: 'line' });
×
1224
                        break;
×
1225
                    }
1226

1227
                    case 'deleteWordBackward': {
1228
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1229
                        break;
×
1230
                    }
1231

1232
                    case 'deleteWordForward': {
1233
                        Editor.deleteForward(editor, { unit: 'word' });
×
1234
                        break;
×
1235
                    }
1236

1237
                    case 'insertLineBreak':
1238
                    case 'insertParagraph': {
1239
                        Editor.insertBreak(editor);
×
1240
                        break;
×
1241
                    }
1242

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

1278
    private onDOMBlur(event: FocusEvent) {
1279
        if (
×
1280
            this.readonly ||
×
1281
            this.isUpdatingSelection ||
1282
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1283
            this.isDOMEventHandled(event, this.blur)
1284
        ) {
1285
            return;
×
1286
        }
1287

1288
        const window = AngularEditor.getWindow(this.editor);
×
1289

1290
        // COMPAT: If the current `activeElement` is still the previous
1291
        // one, this is due to the window being blurred when the tab
1292
        // itself becomes unfocused, so we want to abort early to allow to
1293
        // editor to stay focused when the tab becomes focused again.
1294
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1295
        if (this.latestElement === root.activeElement) {
×
1296
            return;
×
1297
        }
1298

1299
        const { relatedTarget } = event;
×
1300
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1301

1302
        // COMPAT: The event should be ignored if the focus is returning
1303
        // to the editor from an embedded editable element (eg. an <input>
1304
        // element inside a void node).
1305
        if (relatedTarget === el) {
×
1306
            return;
×
1307
        }
1308

1309
        // COMPAT: The event should be ignored if the focus is moving from
1310
        // the editor to inside a void node's spacer element.
1311
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1312
            return;
×
1313
        }
1314

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

1321
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1322
                return;
×
1323
            }
1324
        }
1325

1326
        IS_FOCUSED.delete(this.editor);
×
1327
    }
1328

1329
    private onDOMClick(event: MouseEvent) {
1330
        if (
×
1331
            !this.readonly &&
×
1332
            AngularEditor.hasTarget(this.editor, event.target) &&
1333
            !this.isDOMEventHandled(event, this.click) &&
1334
            isDOMNode(event.target)
1335
        ) {
1336
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1337
            const path = AngularEditor.findPath(this.editor, node);
×
1338
            const start = Editor.start(this.editor, path);
×
1339
            const end = Editor.end(this.editor, path);
×
1340

1341
            const startVoid = Editor.void(this.editor, { at: start });
×
1342
            const endVoid = Editor.void(this.editor, { at: end });
×
1343

1344
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1345
                let blockPath = path;
×
1346
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1347
                    const block = Editor.above(this.editor, {
×
1348
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1349
                        at: path
1350
                    });
1351

1352
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1353
                }
1354

1355
                const range = Editor.range(this.editor, blockPath);
×
1356
                Transforms.select(this.editor, range);
×
1357
                return;
×
1358
            }
1359

1360
            if (
×
1361
                startVoid &&
×
1362
                endVoid &&
1363
                Path.equals(startVoid[1], endVoid[1]) &&
1364
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1365
            ) {
1366
                const range = Editor.range(this.editor, start);
×
1367
                Transforms.select(this.editor, range);
×
1368
            }
1369
        }
1370
    }
1371

1372
    private onDOMCompositionStart(event: CompositionEvent) {
1373
        const { selection } = this.editor;
1✔
1374
        if (selection) {
1!
1375
            // solve the problem of cross node Chinese input
1376
            if (Range.isExpanded(selection)) {
×
1377
                Editor.deleteFragment(this.editor);
×
1378
                this.forceRender();
×
1379
            }
1380
        }
1381
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1382
            this.isComposing = true;
1✔
1383
        }
1384
        this.render();
1✔
1385
    }
1386

1387
    private onDOMCompositionUpdate(event: CompositionEvent) {
1388
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1389
    }
1390

1391
    private onDOMCompositionEnd(event: CompositionEvent) {
1392
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1393
            Transforms.delete(this.editor);
×
1394
        }
1395
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1396
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1397
            // aren't correct and never fire the "insertFromComposition"
1398
            // type that we need. So instead, insert whenever a composition
1399
            // ends since it will already have been committed to the DOM.
1400
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1401
                preventInsertFromComposition(event, this.editor);
×
1402
                Editor.insertText(this.editor, event.data);
×
1403
            }
1404

1405
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1406
            // so we need avoid repeat isnertText by isComposing === true,
1407
            this.isComposing = false;
×
1408
        }
1409
        this.render();
×
1410
    }
1411

1412
    private onDOMCopy(event: ClipboardEvent) {
1413
        const window = AngularEditor.getWindow(this.editor);
×
1414
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1415
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1416
            event.preventDefault();
×
1417
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1418
        }
1419
    }
1420

1421
    private onDOMCut(event: ClipboardEvent) {
1422
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1423
            event.preventDefault();
×
1424
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1425
            const { selection } = this.editor;
×
1426

1427
            if (selection) {
×
1428
                AngularEditor.deleteCutData(this.editor);
×
1429
            }
1430
        }
1431
    }
1432

1433
    private onDOMDragOver(event: DragEvent) {
1434
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1435
            // Only when the target is void, call `preventDefault` to signal
1436
            // that drops are allowed. Editable content is droppable by
1437
            // default, and calling `preventDefault` hides the cursor.
1438
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1439

1440
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1441
                event.preventDefault();
×
1442
            }
1443
        }
1444
    }
1445

1446
    private onDOMDragStart(event: DragEvent) {
1447
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1448
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1449
            const path = AngularEditor.findPath(this.editor, node);
×
1450
            const voidMatch =
1451
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1452

1453
            // If starting a drag on a void node, make sure it is selected
1454
            // so that it shows up in the selection's fragment.
1455
            if (voidMatch) {
×
1456
                const range = Editor.range(this.editor, path);
×
1457
                Transforms.select(this.editor, range);
×
1458
            }
1459

1460
            this.isDraggingInternally = true;
×
1461

1462
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1463
        }
1464
    }
1465

1466
    private onDOMDrop(event: DragEvent) {
1467
        const editor = this.editor;
×
1468
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1469
            event.preventDefault();
×
1470
            // Keep a reference to the dragged range before updating selection
1471
            const draggedRange = editor.selection;
×
1472

1473
            // Find the range where the drop happened
1474
            const range = AngularEditor.findEventRange(editor, event);
×
1475
            const data = event.dataTransfer;
×
1476

1477
            Transforms.select(editor, range);
×
1478

1479
            if (this.isDraggingInternally) {
×
1480
                if (draggedRange) {
×
1481
                    Transforms.delete(editor, {
×
1482
                        at: draggedRange
1483
                    });
1484
                }
1485

1486
                this.isDraggingInternally = false;
×
1487
            }
1488

1489
            AngularEditor.insertData(editor, data);
×
1490

1491
            // When dragging from another source into the editor, it's possible
1492
            // that the current editor does not have focus.
1493
            if (!AngularEditor.isFocused(editor)) {
×
1494
                AngularEditor.focus(editor);
×
1495
            }
1496
        }
1497
    }
1498

1499
    private onDOMDragEnd(event: DragEvent) {
1500
        if (
×
1501
            !this.readonly &&
×
1502
            this.isDraggingInternally &&
1503
            AngularEditor.hasTarget(this.editor, event.target) &&
1504
            !this.isDOMEventHandled(event, this.dragEnd)
1505
        ) {
1506
            this.isDraggingInternally = false;
×
1507
        }
1508
    }
1509

1510
    private onDOMFocus(event: Event) {
1511
        if (
2✔
1512
            !this.readonly &&
8✔
1513
            !this.isUpdatingSelection &&
1514
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1515
            !this.isDOMEventHandled(event, this.focus)
1516
        ) {
1517
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1518
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1519
            this.latestElement = root.activeElement;
2✔
1520

1521
            // COMPAT: If the editor has nested editable elements, the focus
1522
            // can go to them. In Firefox, this must be prevented because it
1523
            // results in issues with keyboard navigation. (2017/03/30)
1524
            if (IS_FIREFOX && event.target !== el) {
2!
1525
                el.focus();
×
1526
                return;
×
1527
            }
1528

1529
            IS_FOCUSED.set(this.editor, true);
2✔
1530
        }
1531
    }
1532

1533
    private onDOMKeydown(event: KeyboardEvent) {
1534
        const editor = this.editor;
×
1535
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1536
        const { activeElement } = root;
×
1537
        if (
×
1538
            !this.readonly &&
×
1539
            AngularEditor.hasEditableTarget(editor, event.target) &&
1540
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1541
            !this.isComposing &&
1542
            !this.isDOMEventHandled(event, this.keydown)
1543
        ) {
1544
            const nativeEvent = event;
×
1545
            const { selection } = editor;
×
1546

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

1550
            try {
×
1551
                // COMPAT: Since we prevent the default behavior on
1552
                // `beforeinput` events, the browser doesn't think there's ever
1553
                // any history stack to undo or redo, so we have to manage these
1554
                // hotkeys ourselves. (2019/11/06)
1555
                if (Hotkeys.isRedo(nativeEvent)) {
×
1556
                    event.preventDefault();
×
1557

1558
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1559
                        editor.redo();
×
1560
                    }
1561

1562
                    return;
×
1563
                }
1564

1565
                if (Hotkeys.isUndo(nativeEvent)) {
×
1566
                    event.preventDefault();
×
1567

1568
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1569
                        editor.undo();
×
1570
                    }
1571

1572
                    return;
×
1573
                }
1574

1575
                // COMPAT: Certain browsers don't handle the selection updates
1576
                // properly. In Chrome, the selection isn't properly extended.
1577
                // And in Firefox, the selection isn't properly collapsed.
1578
                // (2017/10/17)
1579
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1580
                    event.preventDefault();
×
1581
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1582
                    return;
×
1583
                }
1584

1585
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1586
                    event.preventDefault();
×
1587
                    Transforms.move(editor, { unit: 'line' });
×
1588
                    return;
×
1589
                }
1590

1591
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1592
                    event.preventDefault();
×
1593
                    Transforms.move(editor, {
×
1594
                        unit: 'line',
1595
                        edge: 'focus',
1596
                        reverse: true
1597
                    });
1598
                    return;
×
1599
                }
1600

1601
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1602
                    event.preventDefault();
×
1603
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1604
                    return;
×
1605
                }
1606

1607
                // COMPAT: If a void node is selected, or a zero-width text node
1608
                // adjacent to an inline is selected, we need to handle these
1609
                // hotkeys manually because browsers won't be able to skip over
1610
                // the void node with the zero-width space not being an empty
1611
                // string.
1612
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1613
                    event.preventDefault();
×
1614

1615
                    if (selection && Range.isCollapsed(selection)) {
×
1616
                        Transforms.move(editor, { reverse: !isRTL });
×
1617
                    } else {
1618
                        Transforms.collapse(editor, { edge: 'start' });
×
1619
                    }
1620

1621
                    return;
×
1622
                }
1623

1624
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1625
                    event.preventDefault();
×
1626
                    if (selection && Range.isCollapsed(selection)) {
×
1627
                        Transforms.move(editor, { reverse: isRTL });
×
1628
                    } else {
1629
                        Transforms.collapse(editor, { edge: 'end' });
×
1630
                    }
1631

1632
                    return;
×
1633
                }
1634

1635
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1636
                    event.preventDefault();
×
1637

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

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

1646
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1647
                    event.preventDefault();
×
1648

1649
                    if (selection && Range.isExpanded(selection)) {
×
1650
                        Transforms.collapse(editor, { edge: 'focus' });
×
1651
                    }
1652

1653
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1654
                    return;
×
1655
                }
1656

1657
                if (isKeyHotkey('mod+a', event)) {
×
1658
                    this.editor.selectAll();
×
1659
                    event.preventDefault();
×
1660
                    return;
×
1661
                }
1662

1663
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1664
                // fall back to guessing at the input intention for hotkeys.
1665
                // COMPAT: In iOS, some of these hotkeys are handled in the
1666
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1667
                    // We don't have a core behavior for these, but they change the
1668
                    // DOM if we don't prevent them, so we have to.
1669
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1670
                        event.preventDefault();
×
1671
                        return;
×
1672
                    }
1673

1674
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1675
                        event.preventDefault();
×
1676
                        Editor.insertBreak(editor);
×
1677
                        return;
×
1678
                    }
1679

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

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

1691
                        return;
×
1692
                    }
1693

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

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

1705
                        return;
×
1706
                    }
1707

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

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

1719
                        return;
×
1720
                    }
1721

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

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

1733
                        return;
×
1734
                    }
1735

1736
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1737
                        event.preventDefault();
×
1738

1739
                        if (selection && Range.isExpanded(selection)) {
×
1740
                            Editor.deleteFragment(editor, {
×
1741
                                direction: 'backward'
1742
                            });
1743
                        } else {
1744
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1745
                        }
1746

1747
                        return;
×
1748
                    }
1749

1750
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1751
                        event.preventDefault();
×
1752

1753
                        if (selection && Range.isExpanded(selection)) {
×
1754
                            Editor.deleteFragment(editor, {
×
1755
                                direction: 'forward'
1756
                            });
1757
                        } else {
1758
                            Editor.deleteForward(editor, { unit: 'word' });
×
1759
                        }
1760

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

1796
    private onDOMPaste(event: ClipboardEvent) {
1797
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1798
        // fall back to React's `onPaste` here instead.
1799
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1800
        // when "paste without formatting" option is used.
1801
        // This unfortunately needs to be handled with paste events instead.
1802
        if (
×
1803
            !this.isDOMEventHandled(event, this.paste) &&
×
1804
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1805
            !this.readonly &&
1806
            AngularEditor.hasEditableTarget(this.editor, event.target)
1807
        ) {
1808
            event.preventDefault();
×
1809
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1810
        }
1811
    }
1812

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

1842
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1843
        if (!handler) {
3✔
1844
            return false;
3✔
1845
        }
1846
        handler(event);
×
1847
        return event.defaultPrevented;
×
1848
    }
1849
    //#endregion
1850

1851
    ngOnDestroy() {
1852
        this.editorResizeObserver?.disconnect();
22✔
1853
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1854
        this.manualListeners.forEach(manualListener => {
22✔
1855
            manualListener();
462✔
1856
        });
1857
        this.destroy$.complete();
22✔
1858
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1859
    }
1860
}
1861

1862
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1863
    // This was affecting the selection of multiple blocks and dragging behavior,
1864
    // so enabled only if the selection has been collapsed.
1865
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1866
        const leafEl = domRange.startContainer.parentElement!;
×
1867

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

1873
        if (isZeroDimensionRect) {
×
1874
            const leafRect = leafEl.getBoundingClientRect();
×
1875
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1876

1877
            if (leafHasDimensions) {
×
1878
                return;
×
1879
            }
1880
        }
1881

1882
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1883
        scrollIntoView(leafEl, {
×
1884
            scrollMode: 'if-needed'
1885
        });
1886
        delete leafEl.getBoundingClientRect;
×
1887
    }
1888
};
1889

1890
/**
1891
 * Check if the target is inside void and in the editor.
1892
 */
1893

1894
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1895
    let slateNode: Node | null = null;
1✔
1896
    try {
1✔
1897
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1898
    } catch (error) {}
1899
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1900
};
1901

1902
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1903
    return (
2✔
1904
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1905
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1906
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1907
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1908
    );
1909
};
1910

1911
/**
1912
 * remove default insert from composition
1913
 * @param text
1914
 */
1915
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1916
    const types = ['compositionend', 'insertFromComposition'];
×
1917
    if (!types.includes(event.type)) {
×
1918
        return;
×
1919
    }
1920
    const insertText = (event as CompositionEvent).data;
×
1921
    const window = AngularEditor.getWindow(editor);
×
1922
    const domSelection = window.getSelection();
×
1923
    // ensure text node insert composition input text
1924
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1925
        const textNode = domSelection.anchorNode;
×
1926
        textNode.splitText(textNode.length - insertText.length).remove();
×
1927
    }
1928
};
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

© 2025 Coveralls, Inc