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

worktile / slate-angular / cfbf916f-f18c-48b8-9ff6-c0fb8c432431

23 Dec 2025 07:11AM UTC coverage: 36.623% (-0.3%) from 36.904%
cfbf916f-f18c-48b8-9ff6-c0fb8c432431

Pull #329

circleci

pubuzhixing8
fix: xxx
Pull Request #329: Pre rendering

382 of 1250 branches covered (30.56%)

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 2742 relevant lines covered (39.39%)

23.85 hits per line

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

21.87
/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 actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
NEW
740
                        const scrollY = window.scrollY;
×
NEW
741
                        const newTopHeight = this.topHeight - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
NEW
742
                        this.setVirtualSpaceHeight(newTopHeight, virtualView.bottom);
×
NEW
743
                        this.debugLog(
×
744
                            'log',
745
                            `update top height cause added element in top, 减去: ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
746
                        );
747
                        // this.debugLog(
748
                        //     'log',
749
                        //     `scroll cause added element in top, scroll distance(正数代表滚动条向下): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
750
                        // );
751
                        // window.scroll({ top: scrollY + (actualTopHeightAfterAdd - topHeightBeforeAdd) , behavior: 'instant' });
752
                    }
753
                }
754
                this.tryMeasureInViewportChildrenHeights();
×
755
            } else {
UNCOV
756
                if (virtualView.top !== this.topHeight) {
×
UNCOV
757
                    this.debugLog('log', 'update top height: ', virtualView.top - this.topHeight, 'start index', this.inViewportIndics[0]);
×
UNCOV
758
                    this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
759
                }
760
            }
UNCOV
761
            if (isDebug) {
×
762
                this.debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
763
            }
764
        });
765
    }
766

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

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

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

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

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

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

975
    private tryMeasureInViewportChildrenHeights() {
976
        if (!this.isEnabledVirtualScroll()) {
×
UNCOV
977
            return;
×
978
        }
979
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
980
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
UNCOV
981
            this.measureVisibleHeights();
×
982
        });
983
    }
984

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

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

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

1091
    private toSlateSelection() {
1092
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1093
            try {
1✔
1094
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1095
                const { activeElement } = root;
1✔
1096
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1097
                const domSelection = (root as Document).getSelection();
1✔
1098

1099
                if (activeElement === el) {
1!
1100
                    this.latestElement = activeElement;
1✔
1101
                    IS_FOCUSED.set(this.editor, true);
1✔
1102
                } else {
UNCOV
1103
                    IS_FOCUSED.delete(this.editor);
×
1104
                }
1105

1106
                if (!domSelection) {
1!
1107
                    return Transforms.deselect(this.editor);
×
1108
                }
1109

1110
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1111
                const hasDomSelectionInEditor =
1112
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1113
                if (!hasDomSelectionInEditor) {
1!
1114
                    Transforms.deselect(this.editor);
×
1115
                    return;
×
1116
                }
1117

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

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

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

UNCOV
1226
                switch (type) {
×
1227
                    case 'deleteByComposition':
1228
                    case 'deleteByCut':
1229
                    case 'deleteByDrag': {
UNCOV
1230
                        Editor.deleteFragment(editor);
×
UNCOV
1231
                        break;
×
1232
                    }
1233

1234
                    case 'deleteContent':
1235
                    case 'deleteContentForward': {
UNCOV
1236
                        Editor.deleteForward(editor);
×
UNCOV
1237
                        break;
×
1238
                    }
1239

1240
                    case 'deleteContentBackward': {
UNCOV
1241
                        Editor.deleteBackward(editor);
×
UNCOV
1242
                        break;
×
1243
                    }
1244

1245
                    case 'deleteEntireSoftLine': {
UNCOV
1246
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1247
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1248
                        break;
×
1249
                    }
1250

1251
                    case 'deleteHardLineBackward': {
UNCOV
1252
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
1253
                        break;
×
1254
                    }
1255

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

1261
                    case 'deleteHardLineForward': {
1262
                        Editor.deleteForward(editor, { unit: 'block' });
×
1263
                        break;
×
1264
                    }
1265

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

1271
                    case 'deleteWordBackward': {
UNCOV
1272
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1273
                        break;
×
1274
                    }
1275

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

1281
                    case 'insertLineBreak':
1282
                    case 'insertParagraph': {
UNCOV
1283
                        Editor.insertBreak(editor);
×
UNCOV
1284
                        break;
×
1285
                    }
1286

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

1322
    private onDOMBlur(event: FocusEvent) {
UNCOV
1323
        if (
×
1324
            this.readonly ||
×
1325
            this.isUpdatingSelection ||
1326
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1327
            this.isDOMEventHandled(event, this.blur)
1328
        ) {
UNCOV
1329
            return;
×
1330
        }
1331

UNCOV
1332
        const window = AngularEditor.getWindow(this.editor);
×
1333

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

UNCOV
1343
        const { relatedTarget } = event;
×
1344
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1345

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

1353
        // COMPAT: The event should be ignored if the focus is moving from
1354
        // the editor to inside a void node's spacer element.
1355
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1356
            return;
×
1357
        }
1358

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

UNCOV
1365
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1366
                return;
×
1367
            }
1368
        }
1369

UNCOV
1370
        IS_FOCUSED.delete(this.editor);
×
1371
    }
1372

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

UNCOV
1385
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
1386
            const endVoid = Editor.void(this.editor, { at: end });
×
1387

1388
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
UNCOV
1389
                let blockPath = path;
×
UNCOV
1390
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
UNCOV
1391
                    const block = Editor.above(this.editor, {
×
1392
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1393
                        at: path
1394
                    });
1395

UNCOV
1396
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1397
                }
1398

UNCOV
1399
                const range = Editor.range(this.editor, blockPath);
×
1400
                Transforms.select(this.editor, range);
×
1401
                return;
×
1402
            }
1403

UNCOV
1404
            if (
×
1405
                startVoid &&
×
1406
                endVoid &&
1407
                Path.equals(startVoid[1], endVoid[1]) &&
1408
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1409
            ) {
UNCOV
1410
                const range = Editor.range(this.editor, start);
×
UNCOV
1411
                Transforms.select(this.editor, range);
×
1412
            }
1413
        }
1414
    }
1415

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

1431
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1432
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1433
    }
1434

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

1449
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1450
            // so we need avoid repeat isnertText by isComposing === true,
1451
            this.isComposing = false;
×
1452
        }
UNCOV
1453
        this.render();
×
1454
    }
1455

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

1465
    private onDOMCut(event: ClipboardEvent) {
UNCOV
1466
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1467
            event.preventDefault();
×
1468
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1469
            const { selection } = this.editor;
×
1470

1471
            if (selection) {
×
UNCOV
1472
                AngularEditor.deleteCutData(this.editor);
×
1473
            }
1474
        }
1475
    }
1476

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

UNCOV
1484
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1485
                event.preventDefault();
×
1486
            }
1487
        }
1488
    }
1489

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

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

UNCOV
1504
            this.isDraggingInternally = true;
×
1505

1506
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1507
        }
1508
    }
1509

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

1517
            // Find the range where the drop happened
UNCOV
1518
            const range = AngularEditor.findEventRange(editor, event);
×
UNCOV
1519
            const data = event.dataTransfer;
×
1520

UNCOV
1521
            Transforms.select(editor, range);
×
1522

UNCOV
1523
            if (this.isDraggingInternally) {
×
UNCOV
1524
                if (draggedRange) {
×
1525
                    Transforms.delete(editor, {
×
1526
                        at: draggedRange
1527
                    });
1528
                }
1529

UNCOV
1530
                this.isDraggingInternally = false;
×
1531
            }
1532

UNCOV
1533
            AngularEditor.insertData(editor, data);
×
1534

1535
            // When dragging from another source into the editor, it's possible
1536
            // that the current editor does not have focus.
1537
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1538
                AngularEditor.focus(editor);
×
1539
            }
1540
        }
1541
    }
1542

1543
    private onDOMDragEnd(event: DragEvent) {
1544
        if (
×
1545
            !this.readonly &&
×
1546
            this.isDraggingInternally &&
1547
            AngularEditor.hasTarget(this.editor, event.target) &&
1548
            !this.isDOMEventHandled(event, this.dragEnd)
1549
        ) {
1550
            this.isDraggingInternally = false;
×
1551
        }
1552
    }
1553

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

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

1573
            IS_FOCUSED.set(this.editor, true);
2✔
1574
        }
1575
    }
1576

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

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

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

1602
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1603
                        editor.redo();
×
1604
                    }
1605

UNCOV
1606
                    return;
×
1607
                }
1608

UNCOV
1609
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1610
                    event.preventDefault();
×
1611

1612
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1613
                        editor.undo();
×
1614
                    }
1615

1616
                    return;
×
1617
                }
1618

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

1629
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
UNCOV
1630
                    event.preventDefault();
×
UNCOV
1631
                    Transforms.move(editor, { unit: 'line' });
×
1632
                    return;
×
1633
                }
1634

1635
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1636
                    event.preventDefault();
×
UNCOV
1637
                    Transforms.move(editor, {
×
1638
                        unit: 'line',
1639
                        edge: 'focus',
1640
                        reverse: true
1641
                    });
1642
                    return;
×
1643
                }
1644

UNCOV
1645
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1646
                    event.preventDefault();
×
1647
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
UNCOV
1648
                    return;
×
1649
                }
1650

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

1659
                    if (selection && Range.isCollapsed(selection)) {
×
1660
                        Transforms.move(editor, { reverse: !isRTL });
×
1661
                    } else {
UNCOV
1662
                        Transforms.collapse(editor, { edge: 'start' });
×
1663
                    }
1664

UNCOV
1665
                    return;
×
1666
                }
1667

UNCOV
1668
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1669
                    event.preventDefault();
×
1670
                    if (selection && Range.isCollapsed(selection)) {
×
1671
                        Transforms.move(editor, { reverse: isRTL });
×
1672
                    } else {
UNCOV
1673
                        Transforms.collapse(editor, { edge: 'end' });
×
1674
                    }
1675

1676
                    return;
×
1677
                }
1678

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

UNCOV
1682
                    if (selection && Range.isExpanded(selection)) {
×
1683
                        Transforms.collapse(editor, { edge: 'focus' });
×
1684
                    }
1685

UNCOV
1686
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1687
                    return;
×
1688
                }
1689

UNCOV
1690
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1691
                    event.preventDefault();
×
1692

UNCOV
1693
                    if (selection && Range.isExpanded(selection)) {
×
1694
                        Transforms.collapse(editor, { edge: 'focus' });
×
1695
                    }
1696

1697
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1698
                    return;
×
1699
                }
1700

UNCOV
1701
                if (isKeyHotkey('mod+a', event)) {
×
1702
                    this.editor.selectAll();
×
UNCOV
1703
                    event.preventDefault();
×
UNCOV
1704
                    return;
×
1705
                }
1706

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

UNCOV
1718
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1719
                        event.preventDefault();
×
UNCOV
1720
                        Editor.insertBreak(editor);
×
UNCOV
1721
                        return;
×
1722
                    }
1723

UNCOV
1724
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1725
                        event.preventDefault();
×
1726

UNCOV
1727
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1728
                            Editor.deleteFragment(editor, {
×
1729
                                direction: 'backward'
1730
                            });
1731
                        } else {
UNCOV
1732
                            Editor.deleteBackward(editor);
×
1733
                        }
1734

UNCOV
1735
                        return;
×
1736
                    }
1737

UNCOV
1738
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1739
                        event.preventDefault();
×
1740

UNCOV
1741
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1742
                            Editor.deleteFragment(editor, {
×
1743
                                direction: 'forward'
1744
                            });
1745
                        } else {
UNCOV
1746
                            Editor.deleteForward(editor);
×
1747
                        }
1748

UNCOV
1749
                        return;
×
1750
                    }
1751

UNCOV
1752
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1753
                        event.preventDefault();
×
1754

UNCOV
1755
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1756
                            Editor.deleteFragment(editor, {
×
1757
                                direction: 'backward'
1758
                            });
1759
                        } else {
UNCOV
1760
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1761
                        }
1762

UNCOV
1763
                        return;
×
1764
                    }
1765

UNCOV
1766
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1767
                        event.preventDefault();
×
1768

UNCOV
1769
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1770
                            Editor.deleteFragment(editor, {
×
1771
                                direction: 'forward'
1772
                            });
1773
                        } else {
UNCOV
1774
                            Editor.deleteForward(editor, { unit: 'line' });
×
1775
                        }
1776

UNCOV
1777
                        return;
×
1778
                    }
1779

UNCOV
1780
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1781
                        event.preventDefault();
×
1782

UNCOV
1783
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1784
                            Editor.deleteFragment(editor, {
×
1785
                                direction: 'backward'
1786
                            });
1787
                        } else {
1788
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1789
                        }
1790

UNCOV
1791
                        return;
×
1792
                    }
1793

UNCOV
1794
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1795
                        event.preventDefault();
×
1796

UNCOV
1797
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1798
                            Editor.deleteFragment(editor, {
×
1799
                                direction: 'forward'
1800
                            });
1801
                        } else {
1802
                            Editor.deleteForward(editor, { unit: 'word' });
×
1803
                        }
1804

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

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

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

1886
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1887
        if (!handler) {
3✔
1888
            return false;
3✔
1889
        }
UNCOV
1890
        handler(event);
×
UNCOV
1891
        return event.defaultPrevented;
×
1892
    }
1893
    //#endregion
1894

1895
    ngOnDestroy() {
1896
        this.editorResizeObserver?.disconnect();
22✔
1897
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1898
        this.manualListeners.forEach(manualListener => {
22✔
1899
            manualListener();
462✔
1900
        });
1901
        this.destroy$.complete();
22✔
1902
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1903
    }
1904
}
1905

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

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

1917
        if (isZeroDimensionRect) {
×
1918
            const leafRect = leafEl.getBoundingClientRect();
×
UNCOV
1919
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1920

1921
            if (leafHasDimensions) {
×
1922
                return;
×
1923
            }
1924
        }
1925

1926
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1927
        scrollIntoView(leafEl, {
×
1928
            scrollMode: 'if-needed'
1929
        });
UNCOV
1930
        delete leafEl.getBoundingClientRect;
×
1931
    }
1932
};
1933

1934
/**
1935
 * Check if the target is inside void and in the editor.
1936
 */
1937

1938
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1939
    let slateNode: Node | null = null;
1✔
1940
    try {
1✔
1941
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1942
    } catch (error) {}
1943
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1944
};
1945

1946
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1947
    return (
2✔
1948
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1949
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1950
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1951
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1952
    );
1953
};
1954

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