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

worktile / slate-angular / edb6c97b-483e-45e5-b76a-c7dbdd8be06c

22 Jan 2026 10:55AM UTC coverage: 36.06% (-0.08%) from 36.14%
edb6c97b-483e-45e5-b76a-c7dbdd8be06c

push

circleci

pubuzhixing8
fix(virtual-scroll): verify height is NaN to avoid invalid height to cause virtual scroll error #WIK-19823

402 of 1319 branches covered (30.48%)

Branch coverage included in aggregate %.

1 of 12 new or added lines in 2 files covered. (8.33%)

1 existing line in 1 file now uncovered.

1110 of 2874 relevant lines covered (38.62%)

23.3 hits per line

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

22.4
/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, Descendant } 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 { debounceTime, filter, Subject, tap } from 'rxjs';
42
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
43
import Hotkeys from '../../utils/hotkeys';
44
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
45
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
46
import { SlateErrorCode } from '../../types/error';
47
import { NG_VALUE_ACCESSOR } from '@angular/forms';
48
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
49
import { ViewType } from '../../types/view';
50
import { HistoryEditor } from 'slate-history';
51
import {
52
    buildHeightsAndAccumulatedHeights,
53
    EDITOR_TO_BUSINESS_TOP,
54
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
55
    ELEMENT_KEY_TO_HEIGHTS,
56
    getBusinessTop,
57
    IS_ENABLED_VIRTUAL_SCROLL,
58
    isDebug,
59
    isDebugScrollTop,
60
    isDecoratorRangeListEqual,
61
    measureHeightByIndics
62
} from '../../utils';
63
import { SlatePlaceholder } from '../../types/feature';
64
import { restoreDom } from '../../utils/restore-dom';
65
import { ListRender, updatePreRenderingElementWidth } from '../../view/render/list-render';
66
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
67
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
68
import { isKeyHotkey } from 'is-hotkey';
69
import {
70
    calculateVirtualTopHeight,
71
    debugLog,
72
    EDITOR_TO_IS_FROM_SCROLL_TO,
73
    EDITOR_TO_ROOT_NODE_WIDTH,
74
    getCachedHeightByElement
75
} from '../../utils/virtual-scroll';
76

77
// not correctly clipboardData on beforeinput
78
const forceOnDOMPaste = IS_SAFARI;
1✔
79

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

105
    private destroy$ = new Subject();
23✔
106

107
    isComposing = false;
23✔
108
    isDraggingInternally = false;
23✔
109
    isUpdatingSelection = false;
23✔
110
    latestElement = null as DOMElement | null;
23✔
111

112
    protected manualListeners: (() => void)[] = [];
23✔
113

114
    private initialized: boolean;
115

116
    private onTouchedCallback: () => void = () => {};
23✔
117

118
    private onChangeCallback: (_: any) => void = () => {};
23✔
119

120
    @Input() editor: AngularEditor;
121

122
    @Input() renderElement: (element: Element) => ViewType | null;
123

124
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
125

126
    @Input() renderText: (text: SlateText) => ViewType | null;
127

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

130
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
131

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

134
    @Input() isStrictDecorate: boolean = true;
23✔
135

136
    @Input() trackBy: (node: Element) => any = () => null;
206✔
137

138
    @Input() readonly = false;
23✔
139

140
    @Input() placeholder: string;
141

142
    @Input()
143
    set virtualScroll(config: SlateVirtualScrollConfig) {
144
        this.virtualScrollConfig = config;
×
145
        if (isDebugScrollTop) {
×
146
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
147
        }
148
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
149
        if (this.isEnabledVirtualScroll()) {
×
150
            this.tryUpdateVirtualViewport();
×
151
        }
152
    }
153

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

172
    //#region DOM attr
173
    @Input() spellCheck = false;
23✔
174
    @Input() autoCorrect = false;
23✔
175
    @Input() autoCapitalize = false;
23✔
176

177
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
178
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
179
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
180

181
    get hasBeforeInputSupport() {
182
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
183
    }
184
    //#endregion
185

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

188
    getOutletParent = () => {
23✔
189
        return this.elementRef.nativeElement;
43✔
190
    };
191

192
    getOutletElement = () => {
23✔
193
        if (this.virtualScrollInitialized) {
23!
194
            return this.virtualCenterOutlet;
×
195
        } else {
196
            return null;
23✔
197
        }
198
    };
199

200
    listRender: ListRender;
201

202
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
203
        enabled: false,
204
        scrollTop: 0,
205
        viewportHeight: 0,
206
        viewportBoundingTop: 0,
207
        scrollContainer: null
208
    };
209

210
    private inViewportChildren: Element[] = [];
23✔
211
    private inViewportIndics: number[] = [];
23✔
212
    private keyHeightMap = new Map<string, number>();
23✔
213
    private tryUpdateVirtualViewportAnimId: number;
214
    private editorResizeObserver?: ResizeObserver;
215

216
    indicsOfNeedBeMeasured$ = new Subject<number[]>();
23✔
217

218
    constructor(
219
        public elementRef: ElementRef,
23✔
220
        public renderer2: Renderer2,
23✔
221
        public cdr: ChangeDetectorRef,
23✔
222
        private ngZone: NgZone,
23✔
223
        private injector: Injector
23✔
224
    ) {}
225

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

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

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

274
    registerOnChange(fn: any) {
275
        this.onChangeCallback = fn;
23✔
276
    }
277
    registerOnTouched(fn: any) {
278
        this.onTouchedCallback = fn;
23✔
279
    }
280

281
    writeValue(value: Element[]) {
282
        if (value && value.length) {
49✔
283
            this.editor.children = value;
26✔
284
            this.initializeContext();
26✔
285
            if (this.isEnabledVirtualScroll()) {
26!
286
                const previousInViewportChildren = [...this.inViewportChildren];
×
287
                const visibleStates = this.editor.getAllVisibleStates();
×
288
                const virtualView = this.calculateVirtualViewport(visibleStates);
×
289
                this.applyVirtualView(virtualView);
×
290
                const childrenForRender = virtualView.inViewportChildren;
×
291
                if (isDebug) {
×
292
                    debugLog('log', 'writeValue calculate: ', virtualView.inViewportIndics, 'initialized: ', this.listRender.initialized);
×
293
                }
294
                if (!this.listRender.initialized) {
×
295
                    this.listRender.initialize(childrenForRender, this.editor, this.context, 0, virtualView.inViewportIndics);
×
296
                } else {
297
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
298
                        this.handlePreRendering(visibleStates);
×
299
                    this.listRender.update(
×
300
                        childrenWithPreRendering,
301
                        this.editor,
302
                        this.context,
303
                        preRenderingCount,
304
                        childrenWithPreRenderingIndics
305
                    );
306
                }
307
                const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
308
                if (remeasureIndics.length) {
×
309
                    this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
310
                }
311
            } else {
312
                if (!this.listRender.initialized) {
26✔
313
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
314
                } else {
315
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
316
                }
317
            }
318
            this.cdr.markForCheck();
26✔
319
        }
320
    }
321

322
    initialize() {
323
        this.initialized = true;
23✔
324
        const window = AngularEditor.getWindow(this.editor);
23✔
325
        this.addEventListener(
23✔
326
            'selectionchange',
327
            event => {
328
                this.toSlateSelection();
2✔
329
            },
330
            window.document
331
        );
332
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
333
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
334
        }
335
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
336
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
337
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
338
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
339
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
340
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
341
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
342
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
343
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
344
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
345
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
346
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
347
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
348
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
349
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
350
            this.addEventListener(event.name, () => {});
115✔
351
        });
352
    }
353

354
    calculateVirtualScrollSelection(selection: Selection) {
355
        if (selection) {
×
356
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
357
            const indics = this.inViewportIndics;
×
358
            if (indics.length > 0) {
×
359
                const currentVisibleRange: Range = {
×
360
                    anchor: Editor.start(this.editor, [indics[0]]),
361
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
362
                };
363
                const [start, end] = Range.edges(selection);
×
364
                let forwardSelection = { anchor: start, focus: end };
×
365
                if (!isBlockCardCursor) {
×
366
                    forwardSelection = { anchor: start, focus: end };
×
367
                } else {
368
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
369
                }
370
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
371
                if (intersectedSelection && isBlockCardCursor) {
×
372
                    return selection;
×
373
                }
374
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
375
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
376
                    if (isDebug) {
×
377
                        debugLog(
×
378
                            'log',
379
                            `selection is not in visible range, selection: ${JSON.stringify(
380
                                selection
381
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
382
                        );
383
                    }
384
                    return intersectedSelection;
×
385
                }
386
                return selection;
×
387
            }
388
        }
389
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
390
        return selection;
×
391
    }
392

393
    private isSelectionInvisible(selection: Selection) {
394
        const anchorIndex = selection.anchor.path[0];
6✔
395
        const focusIndex = selection.focus.path[0];
6✔
396
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
397
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
398
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
399
    }
400

401
    toNativeSelection(autoScroll = true) {
15✔
402
        try {
15✔
403
            let { selection } = this.editor;
15✔
404

405
            if (this.isEnabledVirtualScroll()) {
15!
406
                selection = this.calculateVirtualScrollSelection(selection);
×
407
            }
408

409
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
410
            const { activeElement } = root;
15✔
411
            const domSelection = (root as Document).getSelection();
15✔
412

413
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
414
                return;
14✔
415
            }
416

417
            const hasDomSelection = domSelection.type !== 'None';
1✔
418

419
            // If the DOM selection is properly unset, we're done.
420
            if (!selection && !hasDomSelection) {
1!
421
                return;
×
422
            }
423

424
            // If the DOM selection is already correct, we're done.
425
            // verify that the dom selection is in the editor
426
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
427
            let hasDomSelectionInEditor = false;
1✔
428
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
429
                hasDomSelectionInEditor = true;
1✔
430
            }
431

432
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
433
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
434
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
435
                    exactMatch: false,
436
                    suppressThrow: true
437
                });
438
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
439
                    return;
×
440
                }
441
            }
442

443
            // prevent updating native selection when active element is void element
444
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
445
                return;
×
446
            }
447

448
            // when <Editable/> is being controlled through external value
449
            // then its children might just change - DOM responds to it on its own
450
            // but Slate's value is not being updated through any operation
451
            // and thus it doesn't transform selection on its own
452
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
453
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
454
                return;
×
455
            }
456

457
            // Otherwise the DOM selection is out of sync, so update it.
458
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
459
            this.isUpdatingSelection = true;
1✔
460

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

463
            if (newDomRange) {
1!
464
                // COMPAT: Since the DOM range has no concept of backwards/forwards
465
                // we need to check and do the right thing here.
466
                if (Range.isBackward(selection)) {
1!
467
                    // eslint-disable-next-line max-len
468
                    domSelection.setBaseAndExtent(
×
469
                        newDomRange.endContainer,
470
                        newDomRange.endOffset,
471
                        newDomRange.startContainer,
472
                        newDomRange.startOffset
473
                    );
474
                } else {
475
                    // eslint-disable-next-line max-len
476
                    domSelection.setBaseAndExtent(
1✔
477
                        newDomRange.startContainer,
478
                        newDomRange.startOffset,
479
                        newDomRange.endContainer,
480
                        newDomRange.endOffset
481
                    );
482
                }
483
            } else {
484
                domSelection.removeAllRanges();
×
485
            }
486

487
            setTimeout(() => {
1✔
488
                if (
1!
489
                    this.isEnabledVirtualScroll() &&
1!
490
                    !selection &&
491
                    this.editor.selection &&
492
                    autoScroll &&
493
                    this.virtualScrollConfig.scrollContainer
494
                ) {
495
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
496
                    this.isUpdatingSelection = false;
×
497
                    return;
×
498
                } else {
499
                    // handle scrolling in setTimeout because of
500
                    // dom should not have updated immediately after listRender's updating
501
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
502
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
503
                    // to focus the contenteditable element too. (2016/11/16)
504
                    if (newDomRange && IS_FIREFOX) {
1!
505
                        el.focus();
×
506
                    }
507
                }
508
                this.isUpdatingSelection = false;
1✔
509
            });
510
        } catch (error) {
511
            this.editor.onError({
×
512
                code: SlateErrorCode.ToNativeSelectionError,
513
                nativeError: error
514
            });
515
            this.isUpdatingSelection = false;
×
516
        }
517
    }
518

519
    onChange() {
520
        this.forceRender();
13✔
521
        this.onChangeCallback(this.editor.children);
13✔
522
    }
523

524
    ngAfterViewChecked() {}
525

526
    ngDoCheck() {}
527

528
    forceRender() {
529
        this.updateContext();
15✔
530
        if (this.isEnabledVirtualScroll()) {
15!
531
            this.updateListRenderAndRemeasureHeights();
×
532
        } else {
533
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
534
        }
535
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
536
        // when the DOMElement where the selection is located is removed
537
        // the compositionupdate and compositionend events will no longer be fired
538
        // so isComposing needs to be corrected
539
        // need exec after this.cdr.detectChanges() to render HTML
540
        // need exec before this.toNativeSelection() to correct native selection
541
        if (this.isComposing) {
15!
542
            // Composition input text be not rendered when user composition input with selection is expanded
543
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
544
            // this time condition is true and isComposing is assigned false
545
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
546
            setTimeout(() => {
×
547
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
548
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
549
                let textContent = '';
×
550
                // skip decorate text
551
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
552
                    let text = stringDOMNode.textContent;
×
553
                    const zeroChar = '\uFEFF';
×
554
                    // remove zero with char
555
                    if (text.startsWith(zeroChar)) {
×
556
                        text = text.slice(1);
×
557
                    }
558
                    if (text.endsWith(zeroChar)) {
×
559
                        text = text.slice(0, text.length - 1);
×
560
                    }
561
                    textContent += text;
×
562
                });
563
                if (Node.string(textNode).endsWith(textContent)) {
×
564
                    this.isComposing = false;
×
565
                }
566
            }, 0);
567
        }
568
        if (this.editor.selection && this.isSelectionInvisible(this.editor.selection)) {
15!
569
            Transforms.deselect(this.editor);
×
570
            return;
×
571
        } else {
572
            this.toNativeSelection();
15✔
573
        }
574
    }
575

576
    render() {
577
        const changed = this.updateContext();
2✔
578
        if (changed) {
2✔
579
            if (this.isEnabledVirtualScroll()) {
2!
580
                this.updateListRenderAndRemeasureHeights();
×
581
            } else {
582
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
583
            }
584
        }
585
    }
586

587
    updateListRenderAndRemeasureHeights() {
588
        const visibleStates = this.editor.getAllVisibleStates();
×
589
        const previousInViewportChildren = [...this.inViewportChildren];
×
590
        let virtualView = this.calculateVirtualViewport(visibleStates);
×
591
        let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
592
        if (diff.isDifferent && diff.needRemoveOnTop) {
×
593
            const remeasureIndics = diff.changedIndexesOfTop;
×
594
            const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
595
            if (changed) {
×
596
                virtualView = this.calculateVirtualViewport(visibleStates);
×
597
                diff = this.diffVirtualViewport(virtualView, 'second');
×
598
            }
599
        }
600
        this.applyVirtualView(virtualView);
×
601
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering(visibleStates);
×
602
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
603
        const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
604
        if (remeasureIndics.length) {
×
605
            this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
606
        }
607
    }
608

609
    updateContext() {
610
        const decorations = this.generateDecorations();
17✔
611
        if (
17✔
612
            this.context.selection !== this.editor.selection ||
46✔
613
            this.context.decorate !== this.decorate ||
614
            this.context.readonly !== this.readonly ||
615
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
616
        ) {
617
            this.context = {
10✔
618
                parent: this.editor,
619
                selection: this.editor.selection,
620
                decorations: decorations,
621
                decorate: this.decorate,
622
                readonly: this.readonly
623
            };
624
            return true;
10✔
625
        }
626
        return false;
7✔
627
    }
628

629
    initializeContext() {
630
        this.context = {
49✔
631
            parent: this.editor,
632
            selection: this.editor.selection,
633
            decorations: this.generateDecorations(),
634
            decorate: this.decorate,
635
            readonly: this.readonly
636
        };
637
    }
638

639
    initializeViewContext() {
640
        this.viewContext = {
23✔
641
            editor: this.editor,
642
            renderElement: this.renderElement,
643
            renderLeaf: this.renderLeaf,
644
            renderText: this.renderText,
645
            trackBy: this.trackBy,
646
            isStrictDecorate: this.isStrictDecorate
647
        };
648
    }
649

650
    composePlaceholderDecorate(editor: Editor) {
651
        if (this.placeholderDecorate) {
64!
652
            return this.placeholderDecorate(editor) || [];
×
653
        }
654

655
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
656
            const start = Editor.start(editor, []);
3✔
657
            return [
3✔
658
                {
659
                    placeholder: this.placeholder,
660
                    anchor: start,
661
                    focus: start
662
                }
663
            ];
664
        } else {
665
            return [];
61✔
666
        }
667
    }
668

669
    generateDecorations() {
670
        const decorations = this.decorate([this.editor, []]);
66✔
671
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
672
        decorations.push(...placeholderDecorations);
66✔
673
        return decorations;
66✔
674
    }
675

676
    private isEnabledVirtualScroll() {
677
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
678
    }
679

680
    virtualScrollInitialized = false;
23✔
681

682
    virtualTopHeightElement: HTMLElement;
683

684
    virtualBottomHeightElement: HTMLElement;
685

686
    virtualCenterOutlet: HTMLElement;
687

688
    initializeVirtualScroll() {
689
        if (this.virtualScrollInitialized) {
23!
690
            return;
×
691
        }
692
        if (this.isEnabledVirtualScroll()) {
23!
693
            this.virtualScrollInitialized = true;
×
694
            this.virtualTopHeightElement = document.createElement('div');
×
695
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
696
            this.virtualTopHeightElement.contentEditable = 'false';
×
697
            this.virtualBottomHeightElement = document.createElement('div');
×
698
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
699
            this.virtualBottomHeightElement.contentEditable = 'false';
×
700
            this.virtualCenterOutlet = document.createElement('div');
×
701
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
702
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
703
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
704
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
705
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
706
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.offsetWidth);
×
707
            this.editorResizeObserver = new ResizeObserver(entries => {
×
708
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
709
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
710
                    this.keyHeightMap.clear();
×
711
                    let target = this.virtualTopHeightElement;
×
712
                    if (this.inViewportChildren[0]) {
×
713
                        const firstElement = this.inViewportChildren[0];
×
714
                        const firstDomElement = AngularEditor.toDOMNode(this.editor, firstElement);
×
715
                        target = firstDomElement;
×
716
                    }
717
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, target.offsetWidth);
×
718
                    updatePreRenderingElementWidth(this.editor);
×
719
                    if (isDebug) {
×
720
                        debugLog(
×
721
                            'log',
722
                            'editorResizeObserverRectWidth: ',
723
                            editorResizeObserverRectWidth,
724
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
725
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
726
                        );
727
                    }
728
                }
729
            });
730
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
731

732
            let pendingRemeasureIndics: number[] = [];
×
733
            this.indicsOfNeedBeMeasured$
×
734
                .pipe(
735
                    tap((previousValue: number[]) => {
736
                        previousValue.forEach((index: number) => {
×
737
                            if (!pendingRemeasureIndics.includes(index)) {
×
738
                                pendingRemeasureIndics.push(index);
×
739
                            }
740
                        });
741
                    }),
742
                    debounceTime(500),
743
                    filter(() => pendingRemeasureIndics.length > 0)
×
744
                )
745
                .subscribe(() => {
NEW
746
                    const changed = measureHeightByIndics(this.editor, pendingRemeasureIndics, true);
×
NEW
747
                    if (changed) {
×
NEW
748
                        this.tryUpdateVirtualViewport();
×
NEW
749
                        if (isDebug) {
×
NEW
750
                            debugLog(
×
751
                                'log',
752
                                'exist pendingRemeasureIndics: ',
753
                                pendingRemeasureIndics,
754
                                'will try to update virtual viewport'
755
                            );
756
                        }
757
                    }
NEW
758
                    pendingRemeasureIndics = [];
×
759
                });
760
        }
761
    }
762

763
    getChangedIndics(previousValue: Descendant[]) {
764
        const remeasureIndics = [];
×
765
        this.inViewportChildren.forEach((child, index) => {
×
766
            if (previousValue.indexOf(child) === -1) {
×
767
                remeasureIndics.push(this.inViewportIndics[index]);
×
768
            }
769
        });
770
        return remeasureIndics;
×
771
    }
772

773
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
774
        if (!this.virtualScrollInitialized) {
×
775
            return;
×
776
        }
777
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
778
        if (bottomHeight !== undefined) {
×
779
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
780
        }
781
    }
782

783
    getActualVirtualTopHeight() {
784
        if (!this.virtualScrollInitialized) {
×
785
            return 0;
×
786
        }
787
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
788
    }
789

790
    handlePreRendering(visibleStates: boolean[]) {
791
        let preRenderingCount = 0;
×
792
        const childrenWithPreRendering = [...this.inViewportChildren];
×
793
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
794
        const firstIndex = this.inViewportIndics[0];
×
795
        for (let index = firstIndex - 1; index >= 0; index--) {
×
796
            const element = this.editor.children[index] as Element;
×
797
            if (visibleStates[index]) {
×
798
                childrenWithPreRendering.unshift(element);
×
799
                childrenWithPreRenderingIndics.unshift(index);
×
800
                preRenderingCount = 1;
×
801
                break;
×
802
            }
803
        }
804
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
805
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
806
            const element = this.editor.children[index] as Element;
×
807
            if (visibleStates[index]) {
×
808
                childrenWithPreRendering.push(element);
×
809
                childrenWithPreRenderingIndics.push(index);
×
810
                break;
×
811
            }
812
        }
813
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
814
    }
815

816
    private tryUpdateVirtualViewport() {
817
        if (isDebug) {
×
818
            debugLog('log', 'tryUpdateVirtualViewport');
×
819
        }
820
        const isFromScrollTo = EDITOR_TO_IS_FROM_SCROLL_TO.get(this.editor);
×
821
        if (this.inViewportIndics.length > 0 && !isFromScrollTo) {
×
822
            const topHeight = this.getActualVirtualTopHeight();
×
823
            const visibleStates = this.editor.getAllVisibleStates();
×
824
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0], visibleStates);
×
825
            if (topHeight !== refreshVirtualTopHeight) {
×
826
                if (isDebug) {
×
827
                    debugLog(
×
828
                        'log',
829
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
830
                        topHeight - refreshVirtualTopHeight
831
                    );
832
                }
833
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
834
                return;
×
835
            }
836
        }
837
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
838
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
839
            if (isDebug) {
×
840
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
841
            }
842
            const visibleStates = this.editor.getAllVisibleStates();
×
843
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
844
            let diff = this.diffVirtualViewport(virtualView);
×
845
            if (diff.isDifferent && diff.needRemoveOnTop && !isFromScrollTo) {
×
846
                const remeasureIndics = diff.changedIndexesOfTop;
×
847
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
848
                if (changed) {
×
849
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
850
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
851
                }
852
            }
853
            if (diff.isDifferent) {
×
854
                this.applyVirtualView(virtualView);
×
855
                if (this.listRender.initialized) {
×
856
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
857
                        this.handlePreRendering(visibleStates);
×
858
                    this.listRender.update(
×
859
                        childrenWithPreRendering,
860
                        this.editor,
861
                        this.context,
862
                        preRenderingCount,
863
                        childrenWithPreRenderingIndics
864
                    );
865
                    if (diff.needAddOnTop && !isFromScrollTo) {
×
866
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
867
                        if (isDebug) {
×
868
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
869
                        }
870
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
871
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
872
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
873
                        if (changed) {
×
874
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
875
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
876
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
877
                            this.setVirtualSpaceHeight(newTopHeight);
×
878
                            if (isDebug) {
×
879
                                debugLog(
×
880
                                    'log',
881
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
882
                                );
883
                            }
884
                        }
885
                    }
886
                    if (this.editor.selection) {
×
887
                        this.toNativeSelection(false);
×
888
                    }
889
                }
890
            }
891
            if (isDebug) {
×
892
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
893
            }
894
        });
895
    }
896

897
    private calculateVirtualViewport(visibleStates: boolean[]) {
898
        const children = (this.editor.children || []) as Element[];
×
899
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
900
            return {
×
901
                inViewportChildren: children,
902
                inViewportIndics: [],
903
                top: 0,
904
                bottom: 0,
905
                heights: []
906
            };
907
        }
908
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
909
        let viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
910
        if (!viewportHeight) {
×
911
            return {
×
912
                inViewportChildren: [],
913
                inViewportIndics: [],
914
                top: 0,
915
                bottom: 0,
916
                heights: []
917
            };
918
        }
919
        const elementLength = children.length;
×
920
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
921
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
922
            setTimeout(() => {
×
923
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
924
                const businessTop =
925
                    Math.ceil(virtualTopBoundingTop) +
×
926
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
927
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
928
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
929
                if (isDebug) {
×
930
                    debugLog('log', 'businessTop', businessTop);
×
931
                    this.virtualTopHeightElement.setAttribute('data-business-top', businessTop.toString());
×
932
                }
933
            }, 100);
934
        }
935
        const businessTop = getBusinessTop(this.editor);
×
936
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
937
        const totalHeight = accumulatedHeights[elementLength] + businessTop;
×
938
        let startPosition = Math.max(scrollTop - businessTop, 0);
×
939
        let endPosition = startPosition + viewportHeight;
×
940
        if (scrollTop < businessTop) {
×
941
            endPosition = startPosition + viewportHeight - (businessTop - scrollTop);
×
942
        }
943
        let accumulatedOffset = 0;
×
944
        let inViewportStartIndex = -1;
×
945
        const visible: Element[] = [];
×
946
        const inViewportIndics: number[] = [];
×
947
        for (let i = 0; i < elementLength && accumulatedOffset < endPosition; i++) {
×
948
            const currentHeight = heights[i];
×
949
            const nextOffset = accumulatedOffset + currentHeight;
×
950
            const isVisible = visibleStates[i];
×
951
            if (!isVisible) {
×
952
                accumulatedOffset = nextOffset;
×
953
                continue;
×
954
            }
955
            // 可视区域有交集,加入渲染
956
            if (nextOffset > startPosition && accumulatedOffset < endPosition) {
×
957
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
958
                visible.push(children[i]);
×
959
                inViewportIndics.push(i);
×
960
            }
961
            accumulatedOffset = nextOffset;
×
962
        }
963

964
        const inViewportEndIndex =
965
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
966
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
967
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
968
        return {
×
969
            inViewportChildren: visible.length ? visible : children,
×
970
            inViewportIndics,
971
            top,
972
            bottom,
973
            heights,
974
            accumulatedHeights
975
        };
976
    }
977

978
    private applyVirtualView(virtualView: VirtualViewResult) {
979
        this.inViewportChildren = virtualView.inViewportChildren;
×
980
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
981
        this.inViewportIndics = virtualView.inViewportIndics;
×
982
    }
983

984
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
985
        if (!this.inViewportChildren.length) {
×
986
            if (isDebug) {
×
987
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
988
            }
989
            return {
×
990
                isDifferent: true,
991
                changedIndexesOfTop: [],
992
                changedIndexesOfBottom: []
993
            };
994
        }
995
        const oldIndexesInViewport = [...this.inViewportIndics];
×
996
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
997
        const firstNewIndex = newIndexesInViewport[0];
×
998
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
999
        const firstOldIndex = oldIndexesInViewport[0];
×
1000
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
1001
        const isSameViewport =
1002
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
1003
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
1004
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
1005
            return {
×
1006
                isDifferent: !isSameViewport,
1007
                changedIndexesOfTop: [],
1008
                changedIndexesOfBottom: []
1009
            };
1010
        }
1011
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
1012
            const changedIndexesOfTop = [];
×
1013
            const changedIndexesOfBottom = [];
×
1014
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
1015
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
1016
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
1017
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
1018
            if (needRemoveOnTop || needAddOnBottom) {
×
1019
                // 向下
1020
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
1021
                    const element = oldIndexesInViewport[index];
×
1022
                    if (!newIndexesInViewport.includes(element)) {
×
1023
                        changedIndexesOfTop.push(element);
×
1024
                    } else {
1025
                        break;
×
1026
                    }
1027
                }
1028
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
1029
                    const element = newIndexesInViewport[index];
×
1030
                    if (!oldIndexesInViewport.includes(element)) {
×
1031
                        changedIndexesOfBottom.push(element);
×
1032
                    } else {
1033
                        break;
×
1034
                    }
1035
                }
1036
            } else if (needAddOnTop || needRemoveOnBottom) {
×
1037
                // 向上
1038
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
1039
                    const element = newIndexesInViewport[index];
×
1040
                    if (!oldIndexesInViewport.includes(element)) {
×
1041
                        changedIndexesOfTop.push(element);
×
1042
                    } else {
1043
                        break;
×
1044
                    }
1045
                }
1046
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
1047
                    const element = oldIndexesInViewport[index];
×
1048
                    if (!newIndexesInViewport.includes(element)) {
×
1049
                        changedIndexesOfBottom.push(element);
×
1050
                    } else {
1051
                        break;
×
1052
                    }
1053
                }
1054
            }
1055
            if (isDebug) {
×
1056
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
1057
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
1058
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
1059
                // this.editor.children[index] will be undefined when it is removed
1060
                debugLog(
×
1061
                    'log',
1062
                    'changedIndexesOfTop:',
1063
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
1064
                    changedIndexesOfTop,
1065
                    changedIndexesOfTop.map(
1066
                        index =>
1067
                            (this.editor.children[index] &&
×
1068
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
1069
                            0
1070
                    )
1071
                );
1072
                debugLog(
×
1073
                    'log',
1074
                    'changedIndexesOfBottom:',
1075
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
1076
                    changedIndexesOfBottom,
1077
                    changedIndexesOfBottom.map(
1078
                        index =>
1079
                            (this.editor.children[index] &&
×
1080
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
1081
                            0
1082
                    )
1083
                );
1084
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
1085
                const needBottom = virtualView.heights
×
1086
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
1087
                    .reduce((acc, height) => acc + height, 0);
×
1088
                debugLog(
×
1089
                    'log',
1090
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
1091
                    'newTopHeight:',
1092
                    needTop,
1093
                    'prevTopHeight:',
1094
                    parseFloat(this.virtualTopHeightElement.style.height)
1095
                );
1096
                debugLog(
×
1097
                    'log',
1098
                    'newBottomHeight:',
1099
                    needBottom,
1100
                    'prevBottomHeight:',
1101
                    parseFloat(this.virtualBottomHeightElement.style.height)
1102
                );
1103
                debugLog('warn', '=========== Dividing line ===========');
×
1104
            }
1105
            return {
×
1106
                isDifferent: true,
1107
                needRemoveOnTop,
1108
                needAddOnTop,
1109
                needRemoveOnBottom,
1110
                needAddOnBottom,
1111
                changedIndexesOfTop,
1112
                changedIndexesOfBottom
1113
            };
1114
        }
1115
        return {
×
1116
            isDifferent: false,
1117
            changedIndexesOfTop: [],
1118
            changedIndexesOfBottom: []
1119
        };
1120
    }
1121

1122
    //#region event proxy
1123
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1124
        this.manualListeners.push(
483✔
1125
            this.renderer2.listen(target, eventName, (event: Event) => {
1126
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1127
                if (beforeInputEvent) {
5!
1128
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1129
                }
1130
                listener(event);
5✔
1131
            })
1132
        );
1133
    }
1134

1135
    private toSlateSelection() {
1136
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1137
            try {
1✔
1138
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1139
                const { activeElement } = root;
1✔
1140
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1141
                const domSelection = (root as Document).getSelection();
1✔
1142

1143
                if (activeElement === el) {
1!
1144
                    this.latestElement = activeElement;
1✔
1145
                    IS_FOCUSED.set(this.editor, true);
1✔
1146
                } else {
1147
                    IS_FOCUSED.delete(this.editor);
×
1148
                }
1149

1150
                if (!domSelection) {
1!
1151
                    return Transforms.deselect(this.editor);
×
1152
                }
1153

1154
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1155
                const hasDomSelectionInEditor =
1156
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1157
                if (!hasDomSelectionInEditor) {
1!
1158
                    Transforms.deselect(this.editor);
×
1159
                    return;
×
1160
                }
1161

1162
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1163
                // for example, double-click the last cell of the table to select a non-editable DOM
1164
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1165
                if (range) {
1✔
1166
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1167
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1168
                            // force adjust DOMSelection
1169
                            this.toNativeSelection(false);
×
1170
                        }
1171
                    } else {
1172
                        Transforms.select(this.editor, range);
1✔
1173
                    }
1174
                }
1175
            } catch (error) {
1176
                this.editor.onError({
×
1177
                    code: SlateErrorCode.ToSlateSelectionError,
1178
                    nativeError: error
1179
                });
1180
            }
1181
        }
1182
    }
1183

1184
    private onDOMBeforeInput(
1185
        event: Event & {
1186
            inputType: string;
1187
            isComposing: boolean;
1188
            data: string | null;
1189
            dataTransfer: DataTransfer | null;
1190
            getTargetRanges(): DOMStaticRange[];
1191
        }
1192
    ) {
1193
        const editor = this.editor;
×
1194
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1195
        const { activeElement } = root;
×
1196
        const { selection } = editor;
×
1197
        const { inputType: type } = event;
×
1198
        const data = event.dataTransfer || event.data || undefined;
×
1199
        if (IS_ANDROID) {
×
1200
            let targetRange: Range | null = null;
×
1201
            let [nativeTargetRange] = event.getTargetRanges();
×
1202
            if (nativeTargetRange) {
×
1203
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1204
            }
1205
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1206
            // have to manually get the selection here to ensure it's up-to-date.
1207
            const window = AngularEditor.getWindow(editor);
×
1208
            const domSelection = window.getSelection();
×
1209
            if (!targetRange && domSelection) {
×
1210
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1211
            }
1212
            targetRange = targetRange ?? editor.selection;
×
1213
            if (type === 'insertCompositionText') {
×
1214
                if (data && data.toString().includes('\n')) {
×
1215
                    restoreDom(editor, () => {
×
1216
                        Editor.insertBreak(editor);
×
1217
                    });
1218
                } else {
1219
                    if (targetRange) {
×
1220
                        if (data) {
×
1221
                            restoreDom(editor, () => {
×
1222
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1223
                            });
1224
                        } else {
1225
                            restoreDom(editor, () => {
×
1226
                                Transforms.delete(editor, { at: targetRange });
×
1227
                            });
1228
                        }
1229
                    }
1230
                }
1231
                return;
×
1232
            }
1233
            if (type === 'deleteContentBackward') {
×
1234
                // gboard can not prevent default action, so must use restoreDom,
1235
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1236
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1237
                if (!Range.isCollapsed(targetRange)) {
×
1238
                    restoreDom(editor, () => {
×
1239
                        Transforms.delete(editor, { at: targetRange });
×
1240
                    });
1241
                    return;
×
1242
                }
1243
            }
1244
            if (type === 'insertText') {
×
1245
                restoreDom(editor, () => {
×
1246
                    if (typeof data === 'string') {
×
1247
                        Editor.insertText(editor, data);
×
1248
                    }
1249
                });
1250
                return;
×
1251
            }
1252
        }
1253
        if (
×
1254
            !this.readonly &&
×
1255
            AngularEditor.hasEditableTarget(editor, event.target) &&
1256
            !isTargetInsideVoid(editor, activeElement) &&
1257
            !this.isDOMEventHandled(event, this.beforeInput)
1258
        ) {
1259
            try {
×
1260
                event.preventDefault();
×
1261

1262
                // COMPAT: If the selection is expanded, even if the command seems like
1263
                // a delete forward/backward command it should delete the selection.
1264
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1265
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1266
                    Editor.deleteFragment(editor, { direction });
×
1267
                    return;
×
1268
                }
1269

1270
                switch (type) {
×
1271
                    case 'deleteByComposition':
1272
                    case 'deleteByCut':
1273
                    case 'deleteByDrag': {
1274
                        Editor.deleteFragment(editor);
×
1275
                        break;
×
1276
                    }
1277

1278
                    case 'deleteContent':
1279
                    case 'deleteContentForward': {
1280
                        Editor.deleteForward(editor);
×
1281
                        break;
×
1282
                    }
1283

1284
                    case 'deleteContentBackward': {
1285
                        Editor.deleteBackward(editor);
×
1286
                        break;
×
1287
                    }
1288

1289
                    case 'deleteEntireSoftLine': {
1290
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1291
                        Editor.deleteForward(editor, { unit: 'line' });
×
1292
                        break;
×
1293
                    }
1294

1295
                    case 'deleteHardLineBackward': {
1296
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1297
                        break;
×
1298
                    }
1299

1300
                    case 'deleteSoftLineBackward': {
1301
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1302
                        break;
×
1303
                    }
1304

1305
                    case 'deleteHardLineForward': {
1306
                        Editor.deleteForward(editor, { unit: 'block' });
×
1307
                        break;
×
1308
                    }
1309

1310
                    case 'deleteSoftLineForward': {
1311
                        Editor.deleteForward(editor, { unit: 'line' });
×
1312
                        break;
×
1313
                    }
1314

1315
                    case 'deleteWordBackward': {
1316
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1317
                        break;
×
1318
                    }
1319

1320
                    case 'deleteWordForward': {
1321
                        Editor.deleteForward(editor, { unit: 'word' });
×
1322
                        break;
×
1323
                    }
1324

1325
                    case 'insertLineBreak':
1326
                    case 'insertParagraph': {
1327
                        Editor.insertBreak(editor);
×
1328
                        break;
×
1329
                    }
1330

1331
                    case 'insertFromComposition': {
1332
                        // COMPAT: in safari, `compositionend` event is dispatched after
1333
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1334
                        // https://www.w3.org/TR/input-events-2/
1335
                        // so the following code is the right logic
1336
                        // because DOM selection in sync will be exec before `compositionend` event
1337
                        // isComposing is true will prevent DOM selection being update correctly.
1338
                        this.isComposing = false;
×
1339
                        preventInsertFromComposition(event, this.editor);
×
1340
                    }
1341
                    case 'insertFromDrop':
1342
                    case 'insertFromPaste':
1343
                    case 'insertFromYank':
1344
                    case 'insertReplacementText':
1345
                    case 'insertText': {
1346
                        // use a weak comparison instead of 'instanceof' to allow
1347
                        // programmatic access of paste events coming from external windows
1348
                        // like cypress where cy.window does not work realibly
1349
                        if (data?.constructor.name === 'DataTransfer') {
×
1350
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1351
                        } else if (typeof data === 'string') {
×
1352
                            Editor.insertText(editor, data);
×
1353
                        }
1354
                        break;
×
1355
                    }
1356
                }
1357
            } catch (error) {
1358
                this.editor.onError({
×
1359
                    code: SlateErrorCode.OnDOMBeforeInputError,
1360
                    nativeError: error
1361
                });
1362
            }
1363
        }
1364
    }
1365

1366
    private onDOMBlur(event: FocusEvent) {
1367
        if (
×
1368
            this.readonly ||
×
1369
            this.isUpdatingSelection ||
1370
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1371
            this.isDOMEventHandled(event, this.blur)
1372
        ) {
1373
            return;
×
1374
        }
1375

1376
        const window = AngularEditor.getWindow(this.editor);
×
1377

1378
        // COMPAT: If the current `activeElement` is still the previous
1379
        // one, this is due to the window being blurred when the tab
1380
        // itself becomes unfocused, so we want to abort early to allow to
1381
        // editor to stay focused when the tab becomes focused again.
1382
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1383
        if (this.latestElement === root.activeElement) {
×
1384
            return;
×
1385
        }
1386

1387
        const { relatedTarget } = event;
×
1388
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1389

1390
        // COMPAT: The event should be ignored if the focus is returning
1391
        // to the editor from an embedded editable element (eg. an <input>
1392
        // element inside a void node).
1393
        if (relatedTarget === el) {
×
1394
            return;
×
1395
        }
1396

1397
        // COMPAT: The event should be ignored if the focus is moving from
1398
        // the editor to inside a void node's spacer element.
1399
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1400
            return;
×
1401
        }
1402

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

1409
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1410
                return;
×
1411
            }
1412
        }
1413

1414
        IS_FOCUSED.delete(this.editor);
×
1415
    }
1416

1417
    private onDOMClick(event: MouseEvent) {
1418
        if (
×
1419
            !this.readonly &&
×
1420
            AngularEditor.hasTarget(this.editor, event.target) &&
1421
            !this.isDOMEventHandled(event, this.click) &&
1422
            isDOMNode(event.target)
1423
        ) {
1424
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1425
            const path = AngularEditor.findPath(this.editor, node);
×
1426
            const start = Editor.start(this.editor, path);
×
1427
            const end = Editor.end(this.editor, path);
×
1428

1429
            const startVoid = Editor.void(this.editor, { at: start });
×
1430
            const endVoid = Editor.void(this.editor, { at: end });
×
1431

1432
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1433
                let blockPath = path;
×
1434
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1435
                    const block = Editor.above(this.editor, {
×
1436
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1437
                        at: path
1438
                    });
1439

1440
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1441
                }
1442

1443
                const range = Editor.range(this.editor, blockPath);
×
1444
                Transforms.select(this.editor, range);
×
1445
                return;
×
1446
            }
1447

1448
            if (
×
1449
                startVoid &&
×
1450
                endVoid &&
1451
                Path.equals(startVoid[1], endVoid[1]) &&
1452
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1453
            ) {
1454
                const range = Editor.range(this.editor, start);
×
1455
                Transforms.select(this.editor, range);
×
1456
            }
1457
        }
1458
    }
1459

1460
    private onDOMCompositionStart(event: CompositionEvent) {
1461
        const { selection } = this.editor;
1✔
1462
        if (selection) {
1!
1463
            // solve the problem of cross node Chinese input
1464
            if (Range.isExpanded(selection)) {
×
1465
                Editor.deleteFragment(this.editor);
×
1466
                this.forceRender();
×
1467
            }
1468
        }
1469
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1470
            this.isComposing = true;
1✔
1471
        }
1472
        this.render();
1✔
1473
    }
1474

1475
    private onDOMCompositionUpdate(event: CompositionEvent) {
1476
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1477
    }
1478

1479
    private onDOMCompositionEnd(event: CompositionEvent) {
1480
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1481
            Transforms.delete(this.editor);
×
1482
        }
1483
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1484
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1485
            // aren't correct and never fire the "insertFromComposition"
1486
            // type that we need. So instead, insert whenever a composition
1487
            // ends since it will already have been committed to the DOM.
1488
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1489
                preventInsertFromComposition(event, this.editor);
×
1490
                Editor.insertText(this.editor, event.data);
×
1491
            }
1492

1493
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1494
            // so we need avoid repeat isnertText by isComposing === true,
1495
            this.isComposing = false;
×
1496
        }
1497
        this.render();
×
1498
    }
1499

1500
    private onDOMCopy(event: ClipboardEvent) {
1501
        const window = AngularEditor.getWindow(this.editor);
×
1502
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1503
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1504
            event.preventDefault();
×
1505
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1506
        }
1507
    }
1508

1509
    private onDOMCut(event: ClipboardEvent) {
1510
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1511
            event.preventDefault();
×
1512
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1513
            const { selection } = this.editor;
×
1514

1515
            if (selection) {
×
1516
                AngularEditor.deleteCutData(this.editor);
×
1517
            }
1518
        }
1519
    }
1520

1521
    private onDOMDragOver(event: DragEvent) {
1522
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1523
            // Only when the target is void, call `preventDefault` to signal
1524
            // that drops are allowed. Editable content is droppable by
1525
            // default, and calling `preventDefault` hides the cursor.
1526
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1527

1528
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1529
                event.preventDefault();
×
1530
            }
1531
        }
1532
    }
1533

1534
    private onDOMDragStart(event: DragEvent) {
1535
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1536
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1537
            const path = AngularEditor.findPath(this.editor, node);
×
1538
            const voidMatch =
1539
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1540

1541
            // If starting a drag on a void node, make sure it is selected
1542
            // so that it shows up in the selection's fragment.
1543
            if (voidMatch) {
×
1544
                const range = Editor.range(this.editor, path);
×
1545
                Transforms.select(this.editor, range);
×
1546
            }
1547

1548
            this.isDraggingInternally = true;
×
1549

1550
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1551
        }
1552
    }
1553

1554
    private onDOMDrop(event: DragEvent) {
1555
        const editor = this.editor;
×
1556
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1557
            event.preventDefault();
×
1558
            // Keep a reference to the dragged range before updating selection
1559
            const draggedRange = editor.selection;
×
1560

1561
            // Find the range where the drop happened
1562
            const range = AngularEditor.findEventRange(editor, event);
×
1563
            const data = event.dataTransfer;
×
1564

1565
            Transforms.select(editor, range);
×
1566

1567
            if (this.isDraggingInternally) {
×
1568
                if (draggedRange) {
×
1569
                    Transforms.delete(editor, {
×
1570
                        at: draggedRange
1571
                    });
1572
                }
1573

1574
                this.isDraggingInternally = false;
×
1575
            }
1576

1577
            AngularEditor.insertData(editor, data);
×
1578

1579
            // When dragging from another source into the editor, it's possible
1580
            // that the current editor does not have focus.
1581
            if (!AngularEditor.isFocused(editor)) {
×
1582
                AngularEditor.focus(editor);
×
1583
            }
1584
        }
1585
    }
1586

1587
    private onDOMDragEnd(event: DragEvent) {
1588
        if (
×
1589
            !this.readonly &&
×
1590
            this.isDraggingInternally &&
1591
            AngularEditor.hasTarget(this.editor, event.target) &&
1592
            !this.isDOMEventHandled(event, this.dragEnd)
1593
        ) {
1594
            this.isDraggingInternally = false;
×
1595
        }
1596
    }
1597

1598
    private onDOMFocus(event: Event) {
1599
        if (
2✔
1600
            !this.readonly &&
8✔
1601
            !this.isUpdatingSelection &&
1602
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1603
            !this.isDOMEventHandled(event, this.focus)
1604
        ) {
1605
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1606
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1607
            this.latestElement = root.activeElement;
2✔
1608

1609
            // COMPAT: If the editor has nested editable elements, the focus
1610
            // can go to them. In Firefox, this must be prevented because it
1611
            // results in issues with keyboard navigation. (2017/03/30)
1612
            if (IS_FIREFOX && event.target !== el) {
2!
1613
                el.focus();
×
1614
                return;
×
1615
            }
1616

1617
            IS_FOCUSED.set(this.editor, true);
2✔
1618
        }
1619
    }
1620

1621
    private onDOMKeydown(event: KeyboardEvent) {
1622
        const editor = this.editor;
×
1623
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1624
        const { activeElement } = root;
×
1625
        if (
×
1626
            !this.readonly &&
×
1627
            AngularEditor.hasEditableTarget(editor, event.target) &&
1628
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1629
            !this.isComposing &&
1630
            !this.isDOMEventHandled(event, this.keydown)
1631
        ) {
1632
            const nativeEvent = event;
×
1633
            const { selection } = editor;
×
1634

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

1638
            try {
×
1639
                // COMPAT: Since we prevent the default behavior on
1640
                // `beforeinput` events, the browser doesn't think there's ever
1641
                // any history stack to undo or redo, so we have to manage these
1642
                // hotkeys ourselves. (2019/11/06)
1643
                if (Hotkeys.isRedo(nativeEvent)) {
×
1644
                    event.preventDefault();
×
1645

1646
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1647
                        editor.redo();
×
1648
                    }
1649

1650
                    return;
×
1651
                }
1652

1653
                if (Hotkeys.isUndo(nativeEvent)) {
×
1654
                    event.preventDefault();
×
1655

1656
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1657
                        editor.undo();
×
1658
                    }
1659

1660
                    return;
×
1661
                }
1662

1663
                // COMPAT: Certain browsers don't handle the selection updates
1664
                // properly. In Chrome, the selection isn't properly extended.
1665
                // And in Firefox, the selection isn't properly collapsed.
1666
                // (2017/10/17)
1667
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1668
                    event.preventDefault();
×
1669
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1670
                    return;
×
1671
                }
1672

1673
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1674
                    event.preventDefault();
×
1675
                    Transforms.move(editor, { unit: 'line' });
×
1676
                    return;
×
1677
                }
1678

1679
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1680
                    event.preventDefault();
×
1681
                    Transforms.move(editor, {
×
1682
                        unit: 'line',
1683
                        edge: 'focus',
1684
                        reverse: true
1685
                    });
1686
                    return;
×
1687
                }
1688

1689
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1690
                    event.preventDefault();
×
1691
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1692
                    return;
×
1693
                }
1694

1695
                // COMPAT: If a void node is selected, or a zero-width text node
1696
                // adjacent to an inline is selected, we need to handle these
1697
                // hotkeys manually because browsers won't be able to skip over
1698
                // the void node with the zero-width space not being an empty
1699
                // string.
1700
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1701
                    event.preventDefault();
×
1702

1703
                    if (selection && Range.isCollapsed(selection)) {
×
1704
                        Transforms.move(editor, { reverse: !isRTL });
×
1705
                    } else {
1706
                        Transforms.collapse(editor, { edge: 'start' });
×
1707
                    }
1708

1709
                    return;
×
1710
                }
1711

1712
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1713
                    event.preventDefault();
×
1714
                    if (selection && Range.isCollapsed(selection)) {
×
1715
                        Transforms.move(editor, { reverse: isRTL });
×
1716
                    } else {
1717
                        Transforms.collapse(editor, { edge: 'end' });
×
1718
                    }
1719

1720
                    return;
×
1721
                }
1722

1723
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1724
                    event.preventDefault();
×
1725

1726
                    if (selection && Range.isExpanded(selection)) {
×
1727
                        Transforms.collapse(editor, { edge: 'focus' });
×
1728
                    }
1729

1730
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1731
                    return;
×
1732
                }
1733

1734
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1735
                    event.preventDefault();
×
1736

1737
                    if (selection && Range.isExpanded(selection)) {
×
1738
                        Transforms.collapse(editor, { edge: 'focus' });
×
1739
                    }
1740

1741
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1742
                    return;
×
1743
                }
1744

1745
                if (isKeyHotkey('mod+a', event)) {
×
1746
                    this.editor.selectAll();
×
1747
                    event.preventDefault();
×
1748
                    return;
×
1749
                }
1750

1751
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1752
                // fall back to guessing at the input intention for hotkeys.
1753
                // COMPAT: In iOS, some of these hotkeys are handled in the
1754
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1755
                    // We don't have a core behavior for these, but they change the
1756
                    // DOM if we don't prevent them, so we have to.
1757
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1758
                        event.preventDefault();
×
1759
                        return;
×
1760
                    }
1761

1762
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1763
                        event.preventDefault();
×
1764
                        Editor.insertBreak(editor);
×
1765
                        return;
×
1766
                    }
1767

1768
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1769
                        event.preventDefault();
×
1770

1771
                        if (selection && Range.isExpanded(selection)) {
×
1772
                            Editor.deleteFragment(editor, {
×
1773
                                direction: 'backward'
1774
                            });
1775
                        } else {
1776
                            Editor.deleteBackward(editor);
×
1777
                        }
1778

1779
                        return;
×
1780
                    }
1781

1782
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1783
                        event.preventDefault();
×
1784

1785
                        if (selection && Range.isExpanded(selection)) {
×
1786
                            Editor.deleteFragment(editor, {
×
1787
                                direction: 'forward'
1788
                            });
1789
                        } else {
1790
                            Editor.deleteForward(editor);
×
1791
                        }
1792

1793
                        return;
×
1794
                    }
1795

1796
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1797
                        event.preventDefault();
×
1798

1799
                        if (selection && Range.isExpanded(selection)) {
×
1800
                            Editor.deleteFragment(editor, {
×
1801
                                direction: 'backward'
1802
                            });
1803
                        } else {
1804
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1805
                        }
1806

1807
                        return;
×
1808
                    }
1809

1810
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1811
                        event.preventDefault();
×
1812

1813
                        if (selection && Range.isExpanded(selection)) {
×
1814
                            Editor.deleteFragment(editor, {
×
1815
                                direction: 'forward'
1816
                            });
1817
                        } else {
1818
                            Editor.deleteForward(editor, { unit: 'line' });
×
1819
                        }
1820

1821
                        return;
×
1822
                    }
1823

1824
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1825
                        event.preventDefault();
×
1826

1827
                        if (selection && Range.isExpanded(selection)) {
×
1828
                            Editor.deleteFragment(editor, {
×
1829
                                direction: 'backward'
1830
                            });
1831
                        } else {
1832
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1833
                        }
1834

1835
                        return;
×
1836
                    }
1837

1838
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1839
                        event.preventDefault();
×
1840

1841
                        if (selection && Range.isExpanded(selection)) {
×
1842
                            Editor.deleteFragment(editor, {
×
1843
                                direction: 'forward'
1844
                            });
1845
                        } else {
1846
                            Editor.deleteForward(editor, { unit: 'word' });
×
1847
                        }
1848

1849
                        return;
×
1850
                    }
1851
                } else {
1852
                    if (IS_CHROME || IS_SAFARI) {
×
1853
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1854
                        // an event when deleting backwards in a selected void inline node
1855
                        if (
×
1856
                            selection &&
×
1857
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1858
                            Range.isCollapsed(selection)
1859
                        ) {
1860
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1861
                            if (
×
1862
                                Element.isElement(currentNode) &&
×
1863
                                Editor.isVoid(editor, currentNode) &&
1864
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1865
                            ) {
1866
                                event.preventDefault();
×
1867
                                Editor.deleteBackward(editor, {
×
1868
                                    unit: 'block'
1869
                                });
1870
                                return;
×
1871
                            }
1872
                        }
1873
                    }
1874
                }
1875
            } catch (error) {
1876
                this.editor.onError({
×
1877
                    code: SlateErrorCode.OnDOMKeydownError,
1878
                    nativeError: error
1879
                });
1880
            }
1881
        }
1882
    }
1883

1884
    private onDOMPaste(event: ClipboardEvent) {
1885
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1886
        // fall back to React's `onPaste` here instead.
1887
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1888
        // when "paste without formatting" option is used.
1889
        // This unfortunately needs to be handled with paste events instead.
1890
        if (
×
1891
            !this.isDOMEventHandled(event, this.paste) &&
×
1892
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1893
            !this.readonly &&
1894
            AngularEditor.hasEditableTarget(this.editor, event.target)
1895
        ) {
1896
            event.preventDefault();
×
1897
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1898
        }
1899
    }
1900

1901
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1902
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1903
        // fall back to React's leaky polyfill instead just for it. It
1904
        // only works for the `insertText` input type.
1905
        if (
×
1906
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1907
            !this.readonly &&
1908
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1909
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1910
        ) {
1911
            event.nativeEvent.preventDefault();
×
1912
            try {
×
1913
                const text = event.data;
×
1914
                if (!Range.isCollapsed(this.editor.selection)) {
×
1915
                    Editor.deleteFragment(this.editor);
×
1916
                }
1917
                // just handle Non-IME input
1918
                if (!this.isComposing) {
×
1919
                    Editor.insertText(this.editor, text);
×
1920
                }
1921
            } catch (error) {
1922
                this.editor.onError({
×
1923
                    code: SlateErrorCode.ToNativeSelectionError,
1924
                    nativeError: error
1925
                });
1926
            }
1927
        }
1928
    }
1929

1930
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1931
        if (!handler) {
3✔
1932
            return false;
3✔
1933
        }
1934
        handler(event);
×
1935
        return event.defaultPrevented;
×
1936
    }
1937
    //#endregion
1938

1939
    ngOnDestroy() {
1940
        this.editorResizeObserver?.disconnect();
23✔
1941
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1942
        this.manualListeners.forEach(manualListener => {
23✔
1943
            manualListener();
483✔
1944
        });
1945
        this.destroy$.complete();
23✔
1946
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1947
    }
1948
}
1949

1950
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1951
    // This was affecting the selection of multiple blocks and dragging behavior,
1952
    // so enabled only if the selection has been collapsed.
1953
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1954
        const leafEl = domRange.startContainer.parentElement!;
×
1955

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

1961
        if (isZeroDimensionRect) {
×
1962
            const leafRect = leafEl.getBoundingClientRect();
×
1963
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1964

1965
            if (leafHasDimensions) {
×
1966
                return;
×
1967
            }
1968
        }
1969

1970
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1971
        scrollIntoView(leafEl, {
×
1972
            scrollMode: 'if-needed'
1973
        });
1974
        delete leafEl.getBoundingClientRect;
×
1975
    }
1976
};
1977

1978
/**
1979
 * Check if the target is inside void and in the editor.
1980
 */
1981

1982
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1983
    let slateNode: Node | null = null;
1✔
1984
    try {
1✔
1985
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1986
    } catch (error) {}
1987
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1988
};
1989

1990
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1991
    return (
2✔
1992
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1993
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1994
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1995
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1996
    );
1997
};
1998

1999
/**
2000
 * remove default insert from composition
2001
 * @param text
2002
 */
2003
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2004
    const types = ['compositionend', 'insertFromComposition'];
×
2005
    if (!types.includes(event.type)) {
×
2006
        return;
×
2007
    }
2008
    const insertText = (event as CompositionEvent).data;
×
2009
    const window = AngularEditor.getWindow(editor);
×
2010
    const domSelection = window.getSelection();
×
2011
    // ensure text node insert composition input text
2012
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2013
        const textNode = domSelection.anchorNode;
×
2014
        textNode.splitText(textNode.length - insertText.length).remove();
×
2015
    }
2016
};
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