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

worktile / slate-angular / ee7b5bb9-0ba9-4db2-a261-36a9f068c827

23 Dec 2025 02:29AM UTC coverage: 36.605% (-0.3%) from 36.904%
ee7b5bb9-0ba9-4db2-a261-36a9f068c827

Pull #329

circleci

pubuzhixing8
fix: list-render error
Pull Request #329: Pre rendering

382 of 1253 branches covered (30.49%)

Branch coverage included in aggregate %.

4 of 55 new or added lines in 2 files covered. (7.27%)

364 existing lines in 3 files now uncovered.

1080 of 2741 relevant lines covered (39.4%)

23.87 hits per line

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

21.82
/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
    EDITOR_TO_WIDTH,
64
    ELEMENT_KEY_TO_HEIGHTS,
65
    ELEMENT_TO_COMPONENT,
66
    getBusinessTop,
67
    getRealHeightByElement,
68
    IS_ENABLED_VIRTUAL_SCROLL,
69
    isDecoratorRangeListEqual
70
} from '../../utils';
71
import { SlatePlaceholder } from '../../types/feature';
72
import { restoreDom } from '../../utils/restore-dom';
73
import { ListRender } from '../../view/render/list-render';
74
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
75
import { BaseElementComponent } from '../../view/base';
76
import { BaseElementFlavour } from '../../view/flavour/element';
77
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
78
import { isKeyHotkey } from 'is-hotkey';
79
import { VirtualScrollDebugOverlay } from './debug';
80

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

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

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

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

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

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

121
    private initialized: boolean;
122

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

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

127
    @Input() editor: AngularEditor;
128

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

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

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

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

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

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

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

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

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

147
    @Input() placeholder: string;
148

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

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

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

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

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

193
    viewContainerRef = inject(ViewContainerRef);
23✔
194

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

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

207
    listRender: ListRender;
208

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

483
    ngAfterViewChecked() {}
484

485
    ngDoCheck() {}
486

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

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

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

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

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

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

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

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

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

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

630
    virtualScrollInitialized = false;
23✔
631

632
    virtualTopHeightElement: HTMLElement;
633

634
    topHeight = 0;
23✔
635

636
    virtualBottomHeightElement: HTMLElement;
637

638
    virtualCenterOutlet: HTMLElement;
639

640
    preRenderingCount = 0;
23✔
641

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

676
    setVirtualSpaceHeight(topHeight: number, bottomHeight: number) {
NEW
677
        if (!this.virtualScrollInitialized) {
×
NEW
678
            return;
×
679
        }
NEW
680
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
NEW
681
        this.topHeight = topHeight;
×
NEW
682
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
683
    }
684

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

690
    private tryUpdateVirtualViewport() {
UNCOV
691
        if (isDebug) {
×
UNCOV
692
            this.debugLog('log', 'tryUpdateVirtualViewport');
×
693
        }
NEW
694
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
NEW
695
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
NEW
696
            if (isDebug) {
×
697
                this.debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
698
            }
NEW
699
            let virtualView = this.calculateVirtualViewport();
×
NEW
700
            let diff = this.diffVirtualViewport(virtualView);
×
NEW
701
            if (diff.isDiff) {
×
702
                // diff.isAddedTop
703
                // if (diff.isMissingTop) {
704
                //     const remeasureIndics = diff.diffTopRenderedIndexes;
705
                //     const result = this.remeasureHeightByIndics(remeasureIndics);
706
                //     if (result) {
707
                //         virtualView = this.calculateVirtualViewport();
708
                //         diff = this.diffVirtualViewport(virtualView, 'second');
709
                //         if (!diff.isDiff) {
710
                //             return;
711
                //         }
712
                //     }
713
                // }
NEW
714
                this.applyVirtualView(virtualView);
×
NEW
715
                if (this.listRender.initialized) {
×
UNCOV
716
                    this.preRenderingCount = 0;
×
UNCOV
717
                    const childrenWithPreRendering = [...this.inViewportChildren];
×
NEW
718
                    if (this.inViewportIndics[0] !== 0) {
×
NEW
719
                        this.preRenderingCount = 1;
×
NEW
720
                        childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
721
                    }
NEW
722
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, this.preRenderingCount);
×
NEW
723
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
NEW
724
                        this.toNativeSelection();
×
725
                    }
726
                }
NEW
727
                if (diff.isAddedTop) {
×
NEW
728
                    const remeasureAddedIndics = diff.diffTopRenderedIndexes;
×
NEW
729
                    if (isDebug) {
×
NEW
730
                        this.debugLog('log', 'isAddedTop to remeasure heights: ', remeasureAddedIndics);
×
731
                    }
NEW
732
                    const startIndexBeforeAdd = diff.diffTopRenderedIndexes[diff.diffTopRenderedIndexes.length - 1] + 1;
×
NEW
733
                    const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
NEW
734
                    const result = this.remeasureHeightByIndics(remeasureAddedIndics);
×
735
                    // 补偿添加元素导致的高度变化,但是可能出现负数
736
                    // 会造成 topHeight 整体是增加的,下次滚动计算时会补偿上
NEW
737
                    if (result) {
×
NEW
738
                        const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
NEW
739
                        const visibleStartIndex = diff.diffTopRenderedIndexes[0];
×
NEW
740
                        const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
741
                        const adjustedTopHeight =
NEW
742
                            (visibleStartIndex === -1 ? 0 : newHeights.accumulatedHeights[visibleStartIndex]) -
×
743
                            (actualTopHeightAfterAdd - topHeightBeforeAdd);
NEW
744
                        if (adjustedTopHeight !== virtualView.top) {
×
NEW
745
                            if (isDebug) {
×
NEW
746
                                this.debugLog(
×
747
                                    'log',
748
                                    `update top height cause added element in top: ${adjustedTopHeight}, old height: ${virtualView.top}`
749
                                );
750
                            }
UNCOV
751
                            this.virtualTopHeightElement.style.height = `${adjustedTopHeight}px`;
×
752
                            this.topHeight = adjustedTopHeight;
×
753
                        }
754
                    }
755
                }
UNCOV
756
                this.tryMeasureInViewportChildrenHeights();
×
757
            } else {
758
                // if (virtualView.top !== this.topHeight) {
759
                //     if (isDebug) {
760
                //         console.log('update top height: ', virtualView.top - this.topHeight, 'start index', this.inViewportIndics[0]);
761
                //     }
762
                //     this.virtualTopHeightElement.style.height = `${virtualView.top}px`;
763
                //     this.topHeight = virtualView.top;
764
                // }
765
            }
UNCOV
766
            if (isDebug) {
×
767
                this.debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
768
            }
769
        });
770
    }
771

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

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

UNCOV
840
        if (visibleStartIndex === -1 && elementLength) {
×
UNCOV
841
            visibleStartIndex = elementLength - 1;
×
842
            visible.push(children[visibleStartIndex]);
×
843
            visibleIndexes.push(visibleStartIndex);
×
844
        }
845

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

860
    private applyVirtualView(virtualView: VirtualViewResult) {
861
        this.inViewportChildren = virtualView.inViewportChildren;
×
862
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
UNCOV
863
        this.inViewportIndics = virtualView.visibleIndexes;
×
864
    }
865

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

980
    private tryMeasureInViewportChildrenHeights() {
UNCOV
981
        if (!this.isEnabledVirtualScroll()) {
×
982
            return;
×
983
        }
984
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
985
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
UNCOV
986
            this.measureVisibleHeights();
×
987
        });
988
    }
989

990
    private measureVisibleHeights() {
UNCOV
991
        const children = (this.editor.children || []) as Element[];
×
UNCOV
992
        const xxx = [...this.inViewportIndics];
×
UNCOV
993
        let preRendingIndex = -1;
×
994
        // if (this.preRenderingCount) {
995
        //     preRendingIndex = this.inViewportIndics[0] - 1;
996
        //     xxx.unshift(preRendingIndex);
997
        // }
998
        xxx.forEach(index => {
×
999
            const node = children[index];
×
UNCOV
1000
            if (!node) {
×
1001
                return;
×
1002
            }
1003
            const key = AngularEditor.findKey(this.editor, node);
×
1004
            // 跳过已测过的块,除非强制测量
UNCOV
1005
            if (this.keyHeightMap.has(key.id)) {
×
1006
                return;
×
1007
            }
1008
            const view = ELEMENT_TO_COMPONENT.get(node);
×
1009
            if (!view) {
×
1010
                return;
×
1011
            }
1012
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
1013
            if (ret instanceof Promise) {
×
1014
                ret.then(height => {
×
UNCOV
1015
                    this.keyHeightMap.set(key.id, height);
×
1016
                });
1017
            } else {
UNCOV
1018
                this.keyHeightMap.set(key.id, ret);
×
1019
            }
UNCOV
1020
            if (preRendingIndex === index) {
×
UNCOV
1021
                if (isDebug) {
×
1022
                    console.log('pre height', ret);
×
1023
                }
1024
                const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
1025
                const startIndex = preRendingIndex === -1 ? 0 : preRendingIndex + 1;
×
1026
                const top = accumulatedHeights[startIndex];
×
UNCOV
1027
                if (top !== this.topHeight) {
×
UNCOV
1028
                    const res = top - this.topHeight;
×
UNCOV
1029
                    if (isDebug) {
×
UNCOV
1030
                        console.log('update top height and sub scroll y: ', res, 'start index', startIndex);
×
1031
                    }
UNCOV
1032
                    this.topHeight = top;
×
UNCOV
1033
                    this.virtualTopHeightElement.style.height = `${top}px`;
×
1034
                    // const scrollTop = window.scrollY;
1035
                    // window.scrollTo(0, scrollTop + res);
UNCOV
1036
                    this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
1037
                }
1038
            }
1039
        });
1040
    }
1041

1042
    private remeasureHeightByIndics(indics: number[]): boolean {
UNCOV
1043
        const children = (this.editor.children || []) as Element[];
×
UNCOV
1044
        let isHeightChanged = false;
×
UNCOV
1045
        indics.forEach((index, i) => {
×
UNCOV
1046
            const node = children[index];
×
UNCOV
1047
            if (!node) {
×
UNCOV
1048
                return;
×
1049
            }
UNCOV
1050
            const key = AngularEditor.findKey(this.editor, node);
×
UNCOV
1051
            const view = ELEMENT_TO_COMPONENT.get(node);
×
UNCOV
1052
            if (!view) {
×
UNCOV
1053
                return;
×
1054
            }
UNCOV
1055
            const prevHeight = this.keyHeightMap.get(key.id);
×
UNCOV
1056
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
UNCOV
1057
            if (ret instanceof Promise) {
×
UNCOV
1058
                ret.then(height => {
×
1059
                    this.keyHeightMap.set(key.id, height);
×
UNCOV
1060
                    if (height !== prevHeight) {
×
UNCOV
1061
                        isHeightChanged = true;
×
UNCOV
1062
                        if (isDebug) {
×
1063
                            this.debugLog(
×
1064
                                'log',
1065
                                `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`
1066
                            );
1067
                        }
1068
                    }
1069
                });
1070
            } else {
1071
                this.keyHeightMap.set(key.id, ret);
×
UNCOV
1072
                if (ret !== prevHeight) {
×
UNCOV
1073
                    isHeightChanged = true;
×
UNCOV
1074
                    if (isDebug) {
×
UNCOV
1075
                        this.debugLog('log', `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
1076
                    }
1077
                }
1078
            }
1079
        });
UNCOV
1080
        return isHeightChanged;
×
1081
    }
1082

1083
    //#region event proxy
1084
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1085
        this.manualListeners.push(
483✔
1086
            this.renderer2.listen(target, eventName, (event: Event) => {
1087
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1088
                if (beforeInputEvent) {
5!
UNCOV
1089
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1090
                }
1091
                listener(event);
5✔
1092
            })
1093
        );
1094
    }
1095

1096
    private toSlateSelection() {
1097
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1098
            try {
1✔
1099
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1100
                const { activeElement } = root;
1✔
1101
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1102
                const domSelection = (root as Document).getSelection();
1✔
1103

1104
                if (activeElement === el) {
1!
1105
                    this.latestElement = activeElement;
1✔
1106
                    IS_FOCUSED.set(this.editor, true);
1✔
1107
                } else {
1108
                    IS_FOCUSED.delete(this.editor);
×
1109
                }
1110

1111
                if (!domSelection) {
1!
1112
                    return Transforms.deselect(this.editor);
×
1113
                }
1114

1115
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1116
                const hasDomSelectionInEditor =
1117
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1118
                if (!hasDomSelectionInEditor) {
1!
1119
                    Transforms.deselect(this.editor);
×
1120
                    return;
×
1121
                }
1122

1123
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1124
                // for example, double-click the last cell of the table to select a non-editable DOM
1125
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1126
                if (range) {
1✔
1127
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1128
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1129
                            // force adjust DOMSelection
UNCOV
1130
                            this.toNativeSelection();
×
1131
                        }
1132
                    } else {
1133
                        Transforms.select(this.editor, range);
1✔
1134
                    }
1135
                }
1136
            } catch (error) {
1137
                this.editor.onError({
×
1138
                    code: SlateErrorCode.ToSlateSelectionError,
1139
                    nativeError: error
1140
                });
1141
            }
1142
        }
1143
    }
1144

1145
    private onDOMBeforeInput(
1146
        event: Event & {
1147
            inputType: string;
1148
            isComposing: boolean;
1149
            data: string | null;
1150
            dataTransfer: DataTransfer | null;
1151
            getTargetRanges(): DOMStaticRange[];
1152
        }
1153
    ) {
UNCOV
1154
        const editor = this.editor;
×
UNCOV
1155
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1156
        const { activeElement } = root;
×
1157
        const { selection } = editor;
×
1158
        const { inputType: type } = event;
×
1159
        const data = event.dataTransfer || event.data || undefined;
×
UNCOV
1160
        if (IS_ANDROID) {
×
UNCOV
1161
            let targetRange: Range | null = null;
×
1162
            let [nativeTargetRange] = event.getTargetRanges();
×
UNCOV
1163
            if (nativeTargetRange) {
×
UNCOV
1164
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1165
            }
1166
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1167
            // have to manually get the selection here to ensure it's up-to-date.
UNCOV
1168
            const window = AngularEditor.getWindow(editor);
×
UNCOV
1169
            const domSelection = window.getSelection();
×
UNCOV
1170
            if (!targetRange && domSelection) {
×
1171
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1172
            }
UNCOV
1173
            targetRange = targetRange ?? editor.selection;
×
UNCOV
1174
            if (type === 'insertCompositionText') {
×
UNCOV
1175
                if (data && data.toString().includes('\n')) {
×
1176
                    restoreDom(editor, () => {
×
1177
                        Editor.insertBreak(editor);
×
1178
                    });
1179
                } else {
UNCOV
1180
                    if (targetRange) {
×
UNCOV
1181
                        if (data) {
×
1182
                            restoreDom(editor, () => {
×
UNCOV
1183
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1184
                            });
1185
                        } else {
1186
                            restoreDom(editor, () => {
×
1187
                                Transforms.delete(editor, { at: targetRange });
×
1188
                            });
1189
                        }
1190
                    }
1191
                }
1192
                return;
×
1193
            }
UNCOV
1194
            if (type === 'deleteContentBackward') {
×
1195
                // gboard can not prevent default action, so must use restoreDom,
1196
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1197
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1198
                if (!Range.isCollapsed(targetRange)) {
×
UNCOV
1199
                    restoreDom(editor, () => {
×
UNCOV
1200
                        Transforms.delete(editor, { at: targetRange });
×
1201
                    });
1202
                    return;
×
1203
                }
1204
            }
UNCOV
1205
            if (type === 'insertText') {
×
UNCOV
1206
                restoreDom(editor, () => {
×
UNCOV
1207
                    if (typeof data === 'string') {
×
1208
                        Editor.insertText(editor, data);
×
1209
                    }
1210
                });
UNCOV
1211
                return;
×
1212
            }
1213
        }
1214
        if (
×
1215
            !this.readonly &&
×
1216
            AngularEditor.hasEditableTarget(editor, event.target) &&
1217
            !isTargetInsideVoid(editor, activeElement) &&
1218
            !this.isDOMEventHandled(event, this.beforeInput)
1219
        ) {
UNCOV
1220
            try {
×
UNCOV
1221
                event.preventDefault();
×
1222

1223
                // COMPAT: If the selection is expanded, even if the command seems like
1224
                // a delete forward/backward command it should delete the selection.
UNCOV
1225
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
UNCOV
1226
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
UNCOV
1227
                    Editor.deleteFragment(editor, { direction });
×
1228
                    return;
×
1229
                }
1230

UNCOV
1231
                switch (type) {
×
1232
                    case 'deleteByComposition':
1233
                    case 'deleteByCut':
1234
                    case 'deleteByDrag': {
UNCOV
1235
                        Editor.deleteFragment(editor);
×
UNCOV
1236
                        break;
×
1237
                    }
1238

1239
                    case 'deleteContent':
1240
                    case 'deleteContentForward': {
UNCOV
1241
                        Editor.deleteForward(editor);
×
UNCOV
1242
                        break;
×
1243
                    }
1244

1245
                    case 'deleteContentBackward': {
UNCOV
1246
                        Editor.deleteBackward(editor);
×
UNCOV
1247
                        break;
×
1248
                    }
1249

1250
                    case 'deleteEntireSoftLine': {
1251
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1252
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1253
                        break;
×
1254
                    }
1255

1256
                    case 'deleteHardLineBackward': {
UNCOV
1257
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
1258
                        break;
×
1259
                    }
1260

1261
                    case 'deleteSoftLineBackward': {
1262
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1263
                        break;
×
1264
                    }
1265

1266
                    case 'deleteHardLineForward': {
UNCOV
1267
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
1268
                        break;
×
1269
                    }
1270

1271
                    case 'deleteSoftLineForward': {
UNCOV
1272
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1273
                        break;
×
1274
                    }
1275

1276
                    case 'deleteWordBackward': {
UNCOV
1277
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1278
                        break;
×
1279
                    }
1280

1281
                    case 'deleteWordForward': {
UNCOV
1282
                        Editor.deleteForward(editor, { unit: 'word' });
×
UNCOV
1283
                        break;
×
1284
                    }
1285

1286
                    case 'insertLineBreak':
1287
                    case 'insertParagraph': {
1288
                        Editor.insertBreak(editor);
×
UNCOV
1289
                        break;
×
1290
                    }
1291

1292
                    case 'insertFromComposition': {
1293
                        // COMPAT: in safari, `compositionend` event is dispatched after
1294
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1295
                        // https://www.w3.org/TR/input-events-2/
1296
                        // so the following code is the right logic
1297
                        // because DOM selection in sync will be exec before `compositionend` event
1298
                        // isComposing is true will prevent DOM selection being update correctly.
1299
                        this.isComposing = false;
×
1300
                        preventInsertFromComposition(event, this.editor);
×
1301
                    }
1302
                    case 'insertFromDrop':
1303
                    case 'insertFromPaste':
1304
                    case 'insertFromYank':
1305
                    case 'insertReplacementText':
1306
                    case 'insertText': {
1307
                        // use a weak comparison instead of 'instanceof' to allow
1308
                        // programmatic access of paste events coming from external windows
1309
                        // like cypress where cy.window does not work realibly
UNCOV
1310
                        if (data?.constructor.name === 'DataTransfer') {
×
1311
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1312
                        } else if (typeof data === 'string') {
×
UNCOV
1313
                            Editor.insertText(editor, data);
×
1314
                        }
UNCOV
1315
                        break;
×
1316
                    }
1317
                }
1318
            } catch (error) {
1319
                this.editor.onError({
×
1320
                    code: SlateErrorCode.OnDOMBeforeInputError,
1321
                    nativeError: error
1322
                });
1323
            }
1324
        }
1325
    }
1326

1327
    private onDOMBlur(event: FocusEvent) {
UNCOV
1328
        if (
×
1329
            this.readonly ||
×
1330
            this.isUpdatingSelection ||
1331
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1332
            this.isDOMEventHandled(event, this.blur)
1333
        ) {
UNCOV
1334
            return;
×
1335
        }
1336

1337
        const window = AngularEditor.getWindow(this.editor);
×
1338

1339
        // COMPAT: If the current `activeElement` is still the previous
1340
        // one, this is due to the window being blurred when the tab
1341
        // itself becomes unfocused, so we want to abort early to allow to
1342
        // editor to stay focused when the tab becomes focused again.
UNCOV
1343
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1344
        if (this.latestElement === root.activeElement) {
×
1345
            return;
×
1346
        }
1347

1348
        const { relatedTarget } = event;
×
UNCOV
1349
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1350

1351
        // COMPAT: The event should be ignored if the focus is returning
1352
        // to the editor from an embedded editable element (eg. an <input>
1353
        // element inside a void node).
UNCOV
1354
        if (relatedTarget === el) {
×
1355
            return;
×
1356
        }
1357

1358
        // COMPAT: The event should be ignored if the focus is moving from
1359
        // the editor to inside a void node's spacer element.
1360
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
UNCOV
1361
            return;
×
1362
        }
1363

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

UNCOV
1370
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
UNCOV
1371
                return;
×
1372
            }
1373
        }
1374

UNCOV
1375
        IS_FOCUSED.delete(this.editor);
×
1376
    }
1377

1378
    private onDOMClick(event: MouseEvent) {
UNCOV
1379
        if (
×
1380
            !this.readonly &&
×
1381
            AngularEditor.hasTarget(this.editor, event.target) &&
1382
            !this.isDOMEventHandled(event, this.click) &&
1383
            isDOMNode(event.target)
1384
        ) {
UNCOV
1385
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1386
            const path = AngularEditor.findPath(this.editor, node);
×
UNCOV
1387
            const start = Editor.start(this.editor, path);
×
1388
            const end = Editor.end(this.editor, path);
×
1389

UNCOV
1390
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
1391
            const endVoid = Editor.void(this.editor, { at: end });
×
1392

1393
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
UNCOV
1394
                let blockPath = path;
×
1395
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
UNCOV
1396
                    const block = Editor.above(this.editor, {
×
UNCOV
1397
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1398
                        at: path
1399
                    });
1400

1401
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1402
                }
1403

UNCOV
1404
                const range = Editor.range(this.editor, blockPath);
×
UNCOV
1405
                Transforms.select(this.editor, range);
×
UNCOV
1406
                return;
×
1407
            }
1408

1409
            if (
×
1410
                startVoid &&
×
1411
                endVoid &&
1412
                Path.equals(startVoid[1], endVoid[1]) &&
1413
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1414
            ) {
1415
                const range = Editor.range(this.editor, start);
×
1416
                Transforms.select(this.editor, range);
×
1417
            }
1418
        }
1419
    }
1420

1421
    private onDOMCompositionStart(event: CompositionEvent) {
1422
        const { selection } = this.editor;
1✔
1423
        if (selection) {
1!
1424
            // solve the problem of cross node Chinese input
1425
            if (Range.isExpanded(selection)) {
×
UNCOV
1426
                Editor.deleteFragment(this.editor);
×
1427
                this.forceRender();
×
1428
            }
1429
        }
1430
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1431
            this.isComposing = true;
1✔
1432
        }
1433
        this.render();
1✔
1434
    }
1435

1436
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1437
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1438
    }
1439

1440
    private onDOMCompositionEnd(event: CompositionEvent) {
1441
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1442
            Transforms.delete(this.editor);
×
1443
        }
UNCOV
1444
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1445
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1446
            // aren't correct and never fire the "insertFromComposition"
1447
            // type that we need. So instead, insert whenever a composition
1448
            // ends since it will already have been committed to the DOM.
1449
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
UNCOV
1450
                preventInsertFromComposition(event, this.editor);
×
1451
                Editor.insertText(this.editor, event.data);
×
1452
            }
1453

1454
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1455
            // so we need avoid repeat isnertText by isComposing === true,
1456
            this.isComposing = false;
×
1457
        }
UNCOV
1458
        this.render();
×
1459
    }
1460

1461
    private onDOMCopy(event: ClipboardEvent) {
1462
        const window = AngularEditor.getWindow(this.editor);
×
UNCOV
1463
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
UNCOV
1464
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
UNCOV
1465
            event.preventDefault();
×
UNCOV
1466
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1467
        }
1468
    }
1469

1470
    private onDOMCut(event: ClipboardEvent) {
1471
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
UNCOV
1472
            event.preventDefault();
×
UNCOV
1473
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1474
            const { selection } = this.editor;
×
1475

UNCOV
1476
            if (selection) {
×
1477
                AngularEditor.deleteCutData(this.editor);
×
1478
            }
1479
        }
1480
    }
1481

1482
    private onDOMDragOver(event: DragEvent) {
UNCOV
1483
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1484
            // Only when the target is void, call `preventDefault` to signal
1485
            // that drops are allowed. Editable content is droppable by
1486
            // default, and calling `preventDefault` hides the cursor.
UNCOV
1487
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1488

1489
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1490
                event.preventDefault();
×
1491
            }
1492
        }
1493
    }
1494

1495
    private onDOMDragStart(event: DragEvent) {
UNCOV
1496
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
UNCOV
1497
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1498
            const path = AngularEditor.findPath(this.editor, node);
×
1499
            const voidMatch =
1500
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1501

1502
            // If starting a drag on a void node, make sure it is selected
1503
            // so that it shows up in the selection's fragment.
UNCOV
1504
            if (voidMatch) {
×
UNCOV
1505
                const range = Editor.range(this.editor, path);
×
1506
                Transforms.select(this.editor, range);
×
1507
            }
1508

UNCOV
1509
            this.isDraggingInternally = true;
×
1510

UNCOV
1511
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1512
        }
1513
    }
1514

1515
    private onDOMDrop(event: DragEvent) {
UNCOV
1516
        const editor = this.editor;
×
UNCOV
1517
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
UNCOV
1518
            event.preventDefault();
×
1519
            // Keep a reference to the dragged range before updating selection
UNCOV
1520
            const draggedRange = editor.selection;
×
1521

1522
            // Find the range where the drop happened
UNCOV
1523
            const range = AngularEditor.findEventRange(editor, event);
×
UNCOV
1524
            const data = event.dataTransfer;
×
1525

1526
            Transforms.select(editor, range);
×
1527

UNCOV
1528
            if (this.isDraggingInternally) {
×
UNCOV
1529
                if (draggedRange) {
×
UNCOV
1530
                    Transforms.delete(editor, {
×
1531
                        at: draggedRange
1532
                    });
1533
                }
1534

1535
                this.isDraggingInternally = false;
×
1536
            }
1537

UNCOV
1538
            AngularEditor.insertData(editor, data);
×
1539

1540
            // When dragging from another source into the editor, it's possible
1541
            // that the current editor does not have focus.
UNCOV
1542
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1543
                AngularEditor.focus(editor);
×
1544
            }
1545
        }
1546
    }
1547

1548
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1549
        if (
×
1550
            !this.readonly &&
×
1551
            this.isDraggingInternally &&
1552
            AngularEditor.hasTarget(this.editor, event.target) &&
1553
            !this.isDOMEventHandled(event, this.dragEnd)
1554
        ) {
1555
            this.isDraggingInternally = false;
×
1556
        }
1557
    }
1558

1559
    private onDOMFocus(event: Event) {
1560
        if (
2✔
1561
            !this.readonly &&
8✔
1562
            !this.isUpdatingSelection &&
1563
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1564
            !this.isDOMEventHandled(event, this.focus)
1565
        ) {
1566
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1567
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1568
            this.latestElement = root.activeElement;
2✔
1569

1570
            // COMPAT: If the editor has nested editable elements, the focus
1571
            // can go to them. In Firefox, this must be prevented because it
1572
            // results in issues with keyboard navigation. (2017/03/30)
1573
            if (IS_FIREFOX && event.target !== el) {
2!
UNCOV
1574
                el.focus();
×
UNCOV
1575
                return;
×
1576
            }
1577

1578
            IS_FOCUSED.set(this.editor, true);
2✔
1579
        }
1580
    }
1581

1582
    private onDOMKeydown(event: KeyboardEvent) {
UNCOV
1583
        const editor = this.editor;
×
UNCOV
1584
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1585
        const { activeElement } = root;
×
1586
        if (
×
1587
            !this.readonly &&
×
1588
            AngularEditor.hasEditableTarget(editor, event.target) &&
1589
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1590
            !this.isComposing &&
1591
            !this.isDOMEventHandled(event, this.keydown)
1592
        ) {
1593
            const nativeEvent = event;
×
UNCOV
1594
            const { selection } = editor;
×
1595

UNCOV
1596
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
UNCOV
1597
            const isRTL = direction(Node.string(element)) === 'rtl';
×
1598

UNCOV
1599
            try {
×
1600
                // COMPAT: Since we prevent the default behavior on
1601
                // `beforeinput` events, the browser doesn't think there's ever
1602
                // any history stack to undo or redo, so we have to manage these
1603
                // hotkeys ourselves. (2019/11/06)
1604
                if (Hotkeys.isRedo(nativeEvent)) {
×
UNCOV
1605
                    event.preventDefault();
×
1606

UNCOV
1607
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1608
                        editor.redo();
×
1609
                    }
1610

UNCOV
1611
                    return;
×
1612
                }
1613

UNCOV
1614
                if (Hotkeys.isUndo(nativeEvent)) {
×
1615
                    event.preventDefault();
×
1616

UNCOV
1617
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1618
                        editor.undo();
×
1619
                    }
1620

1621
                    return;
×
1622
                }
1623

1624
                // COMPAT: Certain browsers don't handle the selection updates
1625
                // properly. In Chrome, the selection isn't properly extended.
1626
                // And in Firefox, the selection isn't properly collapsed.
1627
                // (2017/10/17)
UNCOV
1628
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1629
                    event.preventDefault();
×
UNCOV
1630
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
UNCOV
1631
                    return;
×
1632
                }
1633

UNCOV
1634
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1635
                    event.preventDefault();
×
1636
                    Transforms.move(editor, { unit: 'line' });
×
UNCOV
1637
                    return;
×
1638
                }
1639

UNCOV
1640
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
UNCOV
1641
                    event.preventDefault();
×
1642
                    Transforms.move(editor, {
×
1643
                        unit: 'line',
1644
                        edge: 'focus',
1645
                        reverse: true
1646
                    });
1647
                    return;
×
1648
                }
1649

1650
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
UNCOV
1651
                    event.preventDefault();
×
UNCOV
1652
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1653
                    return;
×
1654
                }
1655

1656
                // COMPAT: If a void node is selected, or a zero-width text node
1657
                // adjacent to an inline is selected, we need to handle these
1658
                // hotkeys manually because browsers won't be able to skip over
1659
                // the void node with the zero-width space not being an empty
1660
                // string.
UNCOV
1661
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
UNCOV
1662
                    event.preventDefault();
×
1663

UNCOV
1664
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1665
                        Transforms.move(editor, { reverse: !isRTL });
×
1666
                    } else {
UNCOV
1667
                        Transforms.collapse(editor, { edge: 'start' });
×
1668
                    }
1669

1670
                    return;
×
1671
                }
1672

UNCOV
1673
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1674
                    event.preventDefault();
×
1675
                    if (selection && Range.isCollapsed(selection)) {
×
1676
                        Transforms.move(editor, { reverse: isRTL });
×
1677
                    } else {
UNCOV
1678
                        Transforms.collapse(editor, { edge: 'end' });
×
1679
                    }
1680

1681
                    return;
×
1682
                }
1683

1684
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1685
                    event.preventDefault();
×
1686

UNCOV
1687
                    if (selection && Range.isExpanded(selection)) {
×
1688
                        Transforms.collapse(editor, { edge: 'focus' });
×
1689
                    }
1690

1691
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1692
                    return;
×
1693
                }
1694

1695
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1696
                    event.preventDefault();
×
1697

1698
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1699
                        Transforms.collapse(editor, { edge: 'focus' });
×
1700
                    }
1701

1702
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
UNCOV
1703
                    return;
×
1704
                }
1705

UNCOV
1706
                if (isKeyHotkey('mod+a', event)) {
×
UNCOV
1707
                    this.editor.selectAll();
×
1708
                    event.preventDefault();
×
1709
                    return;
×
1710
                }
1711

1712
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1713
                // fall back to guessing at the input intention for hotkeys.
1714
                // COMPAT: In iOS, some of these hotkeys are handled in the
UNCOV
1715
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1716
                    // We don't have a core behavior for these, but they change the
1717
                    // DOM if we don't prevent them, so we have to.
UNCOV
1718
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1719
                        event.preventDefault();
×
UNCOV
1720
                        return;
×
1721
                    }
1722

1723
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
UNCOV
1724
                        event.preventDefault();
×
1725
                        Editor.insertBreak(editor);
×
1726
                        return;
×
1727
                    }
1728

UNCOV
1729
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1730
                        event.preventDefault();
×
1731

UNCOV
1732
                        if (selection && Range.isExpanded(selection)) {
×
1733
                            Editor.deleteFragment(editor, {
×
1734
                                direction: 'backward'
1735
                            });
1736
                        } else {
1737
                            Editor.deleteBackward(editor);
×
1738
                        }
1739

1740
                        return;
×
1741
                    }
1742

UNCOV
1743
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1744
                        event.preventDefault();
×
1745

UNCOV
1746
                        if (selection && Range.isExpanded(selection)) {
×
1747
                            Editor.deleteFragment(editor, {
×
1748
                                direction: 'forward'
1749
                            });
1750
                        } else {
1751
                            Editor.deleteForward(editor);
×
1752
                        }
1753

1754
                        return;
×
1755
                    }
1756

UNCOV
1757
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1758
                        event.preventDefault();
×
1759

UNCOV
1760
                        if (selection && Range.isExpanded(selection)) {
×
1761
                            Editor.deleteFragment(editor, {
×
1762
                                direction: 'backward'
1763
                            });
1764
                        } else {
UNCOV
1765
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1766
                        }
1767

UNCOV
1768
                        return;
×
1769
                    }
1770

UNCOV
1771
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1772
                        event.preventDefault();
×
1773

UNCOV
1774
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1775
                            Editor.deleteFragment(editor, {
×
1776
                                direction: 'forward'
1777
                            });
1778
                        } else {
1779
                            Editor.deleteForward(editor, { unit: 'line' });
×
1780
                        }
1781

1782
                        return;
×
1783
                    }
1784

UNCOV
1785
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1786
                        event.preventDefault();
×
1787

1788
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1789
                            Editor.deleteFragment(editor, {
×
1790
                                direction: 'backward'
1791
                            });
1792
                        } else {
UNCOV
1793
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1794
                        }
1795

UNCOV
1796
                        return;
×
1797
                    }
1798

UNCOV
1799
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1800
                        event.preventDefault();
×
1801

1802
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1803
                            Editor.deleteFragment(editor, {
×
1804
                                direction: 'forward'
1805
                            });
1806
                        } else {
UNCOV
1807
                            Editor.deleteForward(editor, { unit: 'word' });
×
1808
                        }
1809

UNCOV
1810
                        return;
×
1811
                    }
1812
                } else {
UNCOV
1813
                    if (IS_CHROME || IS_SAFARI) {
×
1814
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1815
                        // an event when deleting backwards in a selected void inline node
UNCOV
1816
                        if (
×
1817
                            selection &&
×
1818
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1819
                            Range.isCollapsed(selection)
1820
                        ) {
UNCOV
1821
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
UNCOV
1822
                            if (
×
1823
                                Element.isElement(currentNode) &&
×
1824
                                Editor.isVoid(editor, currentNode) &&
1825
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1826
                            ) {
1827
                                event.preventDefault();
×
UNCOV
1828
                                Editor.deleteBackward(editor, {
×
1829
                                    unit: 'block'
1830
                                });
1831
                                return;
×
1832
                            }
1833
                        }
1834
                    }
1835
                }
1836
            } catch (error) {
UNCOV
1837
                this.editor.onError({
×
1838
                    code: SlateErrorCode.OnDOMKeydownError,
1839
                    nativeError: error
1840
                });
1841
            }
1842
        }
1843
    }
1844

1845
    private onDOMPaste(event: ClipboardEvent) {
1846
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1847
        // fall back to React's `onPaste` here instead.
1848
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1849
        // when "paste without formatting" option is used.
1850
        // This unfortunately needs to be handled with paste events instead.
UNCOV
1851
        if (
×
1852
            !this.isDOMEventHandled(event, this.paste) &&
×
1853
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1854
            !this.readonly &&
1855
            AngularEditor.hasEditableTarget(this.editor, event.target)
1856
        ) {
UNCOV
1857
            event.preventDefault();
×
UNCOV
1858
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1859
        }
1860
    }
1861

1862
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1863
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1864
        // fall back to React's leaky polyfill instead just for it. It
1865
        // only works for the `insertText` input type.
1866
        if (
×
1867
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1868
            !this.readonly &&
1869
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1870
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1871
        ) {
UNCOV
1872
            event.nativeEvent.preventDefault();
×
1873
            try {
×
1874
                const text = event.data;
×
1875
                if (!Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1876
                    Editor.deleteFragment(this.editor);
×
1877
                }
1878
                // just handle Non-IME input
UNCOV
1879
                if (!this.isComposing) {
×
UNCOV
1880
                    Editor.insertText(this.editor, text);
×
1881
                }
1882
            } catch (error) {
1883
                this.editor.onError({
×
1884
                    code: SlateErrorCode.ToNativeSelectionError,
1885
                    nativeError: error
1886
                });
1887
            }
1888
        }
1889
    }
1890

1891
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1892
        if (!handler) {
3✔
1893
            return false;
3✔
1894
        }
UNCOV
1895
        handler(event);
×
UNCOV
1896
        return event.defaultPrevented;
×
1897
    }
1898
    //#endregion
1899

1900
    ngOnDestroy() {
1901
        this.editorResizeObserver?.disconnect();
23✔
1902
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1903
        this.manualListeners.forEach(manualListener => {
23✔
1904
            manualListener();
483✔
1905
        });
1906
        this.destroy$.complete();
23✔
1907
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1908
    }
1909
}
1910

1911
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1912
    // This was affecting the selection of multiple blocks and dragging behavior,
1913
    // so enabled only if the selection has been collapsed.
UNCOV
1914
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
UNCOV
1915
        const leafEl = domRange.startContainer.parentElement!;
×
1916

1917
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1918
        // When this happens, do not scroll like most editors do.
UNCOV
1919
        const domRect = domRange.getBoundingClientRect();
×
1920
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1921

1922
        if (isZeroDimensionRect) {
×
UNCOV
1923
            const leafRect = leafEl.getBoundingClientRect();
×
1924
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1925

1926
            if (leafHasDimensions) {
×
UNCOV
1927
                return;
×
1928
            }
1929
        }
1930

UNCOV
1931
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1932
        scrollIntoView(leafEl, {
×
1933
            scrollMode: 'if-needed'
1934
        });
UNCOV
1935
        delete leafEl.getBoundingClientRect;
×
1936
    }
1937
};
1938

1939
/**
1940
 * Check if the target is inside void and in the editor.
1941
 */
1942

1943
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1944
    let slateNode: Node | null = null;
1✔
1945
    try {
1✔
1946
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1947
    } catch (error) {}
1948
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1949
};
1950

1951
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1952
    return (
2✔
1953
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1954
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1955
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1956
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1957
    );
1958
};
1959

1960
/**
1961
 * remove default insert from composition
1962
 * @param text
1963
 */
1964
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
UNCOV
1965
    const types = ['compositionend', 'insertFromComposition'];
×
UNCOV
1966
    if (!types.includes(event.type)) {
×
UNCOV
1967
        return;
×
1968
    }
UNCOV
1969
    const insertText = (event as CompositionEvent).data;
×
UNCOV
1970
    const window = AngularEditor.getWindow(editor);
×
UNCOV
1971
    const domSelection = window.getSelection();
×
1972
    // ensure text node insert composition input text
UNCOV
1973
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
UNCOV
1974
        const textNode = domSelection.anchorNode;
×
UNCOV
1975
        textNode.splitText(textNode.length - insertText.length).remove();
×
1976
    }
1977
};
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