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

worktile / slate-angular / e833a566-4345-4ffa-ba65-16af56ff5177

23 Dec 2025 12:42PM UTC coverage: 36.617% (-0.3%) from 36.904%
e833a566-4345-4ffa-ba65-16af56ff5177

Pull #329

circleci

pubuzhixing8
chore: remove EDITOR_TO_WIDTH
Pull Request #329: Pre rendering

382 of 1250 branches covered (30.56%)

Branch coverage included in aggregate %.

3 of 51 new or added lines in 2 files covered. (5.88%)

278 existing lines in 1 file now uncovered.

1079 of 2740 relevant lines covered (39.38%)

23.87 hits per line

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

21.88
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    HostBinding,
6
    Renderer2,
7
    ElementRef,
8
    ChangeDetectionStrategy,
9
    OnDestroy,
10
    ChangeDetectorRef,
11
    NgZone,
12
    Injector,
13
    forwardRef,
14
    OnChanges,
15
    SimpleChanges,
16
    AfterViewChecked,
17
    DoCheck,
18
    inject,
19
    ViewContainerRef
20
} from '@angular/core';
21
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node, Selection } from 'slate';
22
import { direction } from 'direction';
23
import scrollIntoView from 'scroll-into-view-if-needed';
24
import { AngularEditor } from '../../plugins/angular-editor';
25
import {
26
    DOMElement,
27
    isDOMNode,
28
    DOMStaticRange,
29
    DOMRange,
30
    isDOMElement,
31
    isPlainTextOnlyPaste,
32
    DOMSelection,
33
    getDefaultView,
34
    EDITOR_TO_WINDOW,
35
    EDITOR_TO_ELEMENT,
36
    NODE_TO_ELEMENT,
37
    ELEMENT_TO_NODE,
38
    IS_FOCUSED,
39
    IS_READ_ONLY
40
} from 'slate-dom';
41
import { Subject } from 'rxjs';
42
import {
43
    IS_FIREFOX,
44
    IS_SAFARI,
45
    IS_CHROME,
46
    HAS_BEFORE_INPUT_SUPPORT,
47
    IS_ANDROID,
48
    SLATE_DEBUG_KEY,
49
    SLATE_DEBUG_KEY_SCROLL_TOP
50
} from '../../utils/environment';
51
import Hotkeys from '../../utils/hotkeys';
52
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
53
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
54
import { SlateErrorCode } from '../../types/error';
55
import { NG_VALUE_ACCESSOR } from '@angular/forms';
56
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
57
import { ViewType } from '../../types/view';
58
import { HistoryEditor } from 'slate-history';
59
import {
60
    buildHeightsAndAccumulatedHeights,
61
    EDITOR_TO_BUSINESS_TOP,
62
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
63
    ELEMENT_KEY_TO_HEIGHTS,
64
    ELEMENT_TO_COMPONENT,
65
    getBusinessTop,
66
    getRealHeightByElement,
67
    IS_ENABLED_VIRTUAL_SCROLL,
68
    isDecoratorRangeListEqual
69
} from '../../utils';
70
import { SlatePlaceholder } from '../../types/feature';
71
import { restoreDom } from '../../utils/restore-dom';
72
import { ListRender } from '../../view/render/list-render';
73
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
74
import { BaseElementComponent } from '../../view/base';
75
import { BaseElementFlavour } from '../../view/flavour/element';
76
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
77
import { isKeyHotkey } from 'is-hotkey';
78
import { VirtualScrollDebugOverlay } from './debug';
79

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

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

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

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

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

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

120
    private initialized: boolean;
121

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

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

126
    @Input() editor: AngularEditor;
127

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

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

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

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

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

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

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

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

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

146
    @Input() placeholder: string;
147

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

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

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

206
    listRender: ListRender;
207

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

482
    ngAfterViewChecked() {}
483

484
    ngDoCheck() {}
485

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

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

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

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

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

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

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

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

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

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

629
    virtualScrollInitialized = false;
23✔
630

631
    virtualTopHeightElement: HTMLElement;
632

633
    topHeight = 0;
23✔
634

635
    virtualBottomHeightElement: HTMLElement;
636

637
    virtualCenterOutlet: HTMLElement;
638

639
    preRenderingCount = 0;
23✔
640

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1238
                    case 'deleteContentBackward': {
1239
                        Editor.deleteBackward(editor);
×
1240
                        break;
×
1241
                    }
1242

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

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

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

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

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

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

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

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

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

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

1330
        const window = AngularEditor.getWindow(this.editor);
×
1331

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

1341
        const { relatedTarget } = event;
×
1342
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1343

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

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

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

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

UNCOV
1368
        IS_FOCUSED.delete(this.editor);
×
1369
    }
1370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1502
            this.isDraggingInternally = true;
×
1503

UNCOV
1504
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1505
        }
1506
    }
1507

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

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

UNCOV
1519
            Transforms.select(editor, range);
×
1520

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

UNCOV
1528
                this.isDraggingInternally = false;
×
1529
            }
1530

UNCOV
1531
            AngularEditor.insertData(editor, data);
×
1532

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

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

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

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

1571
            IS_FOCUSED.set(this.editor, true);
2✔
1572
        }
1573
    }
1574

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

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

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

UNCOV
1600
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1601
                        editor.redo();
×
1602
                    }
1603

1604
                    return;
×
1605
                }
1606

UNCOV
1607
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1608
                    event.preventDefault();
×
1609

UNCOV
1610
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1611
                        editor.undo();
×
1612
                    }
1613

UNCOV
1614
                    return;
×
1615
                }
1616

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

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

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

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

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

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

UNCOV
1663
                    return;
×
1664
                }
1665

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

1674
                    return;
×
1675
                }
1676

1677
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1678
                    event.preventDefault();
×
1679

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

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

1688
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1689
                    event.preventDefault();
×
1690

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

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

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

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

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

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

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

1733
                        return;
×
1734
                    }
1735

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

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

1747
                        return;
×
1748
                    }
1749

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

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

1761
                        return;
×
1762
                    }
1763

1764
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1765
                        event.preventDefault();
×
1766

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

UNCOV
1775
                        return;
×
1776
                    }
1777

1778
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1779
                        event.preventDefault();
×
1780

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

UNCOV
1789
                        return;
×
1790
                    }
1791

UNCOV
1792
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1793
                        event.preventDefault();
×
1794

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

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

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

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

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

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

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

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

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

UNCOV
1919
            if (leafHasDimensions) {
×
1920
                return;
×
1921
            }
1922
        }
1923

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

1932
/**
1933
 * Check if the target is inside void and in the editor.
1934
 */
1935

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

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

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