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

worktile / slate-angular / d7bf029e-f2e1-4bf1-9b0c-fdf13e281827

23 Dec 2025 03:47AM UTC coverage: 36.577% (-0.3%) from 36.904%
d7bf029e-f2e1-4bf1-9b0c-fdf13e281827

Pull #329

circleci

pubuzhixing8
feat: apply overflow-anchor: none
Pull Request #329: Pre rendering

382 of 1253 branches covered (30.49%)

Branch coverage included in aggregate %.

5 of 56 new or added lines in 2 files covered. (8.93%)

359 existing lines in 3 files now uncovered.

1080 of 2744 relevant lines covered (39.36%)

23.83 hits per line

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

21.79
/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 = `${newHeights.accumulatedHeights[visibleStartIndex]}px`;
×
752
                            const scrollY = window.scrollY;
×
753
                            window.scroll({ top: scrollY - (adjustedTopHeight - virtualView.top) });
×
754
                            this.topHeight = adjustedTopHeight;
×
755
                        }
756
                    }
757
                }
UNCOV
758
                this.tryMeasureInViewportChildrenHeights();
×
759
            } else {
760
                // if (virtualView.top !== this.topHeight) {
761
                //     if (isDebug) {
762
                //         console.log('update top height: ', virtualView.top - this.topHeight, 'start index', this.inViewportIndics[0]);
763
                //     }
764
                //     this.virtualTopHeightElement.style.height = `${virtualView.top}px`;
765
                //     this.topHeight = virtualView.top;
766
                // }
767
            }
768
            if (isDebug) {
×
769
                this.debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
770
            }
771
        });
772
    }
773

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1339
        const window = AngularEditor.getWindow(this.editor);
×
1340

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

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

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

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

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

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

1377
        IS_FOCUSED.delete(this.editor);
×
1378
    }
1379

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

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

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

UNCOV
1403
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1404
                }
1405

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1511
            this.isDraggingInternally = true;
×
1512

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

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

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

UNCOV
1528
            Transforms.select(editor, range);
×
1529

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

1537
                this.isDraggingInternally = false;
×
1538
            }
1539

UNCOV
1540
            AngularEditor.insertData(editor, data);
×
1541

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

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

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

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

1580
            IS_FOCUSED.set(this.editor, true);
2✔
1581
        }
1582
    }
1583

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

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

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

UNCOV
1609
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1610
                        editor.redo();
×
1611
                    }
1612

1613
                    return;
×
1614
                }
1615

1616
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1617
                    event.preventDefault();
×
1618

UNCOV
1619
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1620
                        editor.undo();
×
1621
                    }
1622

UNCOV
1623
                    return;
×
1624
                }
1625

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

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

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

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

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

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

UNCOV
1672
                    return;
×
1673
                }
1674

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

1683
                    return;
×
1684
                }
1685

UNCOV
1686
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1687
                    event.preventDefault();
×
1688

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

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

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

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

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

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

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

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

UNCOV
1731
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1732
                        event.preventDefault();
×
1733

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

UNCOV
1742
                        return;
×
1743
                    }
1744

UNCOV
1745
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1746
                        event.preventDefault();
×
1747

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

UNCOV
1756
                        return;
×
1757
                    }
1758

UNCOV
1759
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1760
                        event.preventDefault();
×
1761

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

UNCOV
1770
                        return;
×
1771
                    }
1772

1773
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1774
                        event.preventDefault();
×
1775

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

UNCOV
1784
                        return;
×
1785
                    }
1786

UNCOV
1787
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1788
                        event.preventDefault();
×
1789

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

UNCOV
1798
                        return;
×
1799
                    }
1800

UNCOV
1801
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1802
                        event.preventDefault();
×
1803

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

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

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

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

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

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

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

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

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

UNCOV
1928
            if (leafHasDimensions) {
×
UNCOV
1929
                return;
×
1930
            }
1931
        }
1932

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

1941
/**
1942
 * Check if the target is inside void and in the editor.
1943
 */
1944

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

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

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