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

worktile / slate-angular / 4cb1f589-6adf-471f-b778-518472090912

15 Jan 2026 07:27AM UTC coverage: 36.392% (-0.04%) from 36.429%
4cb1f589-6adf-471f-b778-518472090912

push

circleci

pubuzhixing8
fix(virtual-scroll): support get all visible states to performance improvement #WIK-19805

402 of 1307 branches covered (30.76%)

Branch coverage included in aggregate %.

3 of 26 new or added lines in 3 files covered. (11.54%)

3 existing lines in 2 files now uncovered.

1109 of 2845 relevant lines covered (38.98%)

23.54 hits per line

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

22.86
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    HostBinding,
6
    Renderer2,
7
    ElementRef,
8
    ChangeDetectionStrategy,
9
    OnDestroy,
10
    ChangeDetectorRef,
11
    NgZone,
12
    Injector,
13
    forwardRef,
14
    OnChanges,
15
    SimpleChanges,
16
    AfterViewChecked,
17
    DoCheck,
18
    inject,
19
    ViewContainerRef
20
} from '@angular/core';
21
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node, Selection } from 'slate';
22
import { direction } from 'direction';
23
import scrollIntoView from 'scroll-into-view-if-needed';
24
import { AngularEditor } from '../../plugins/angular-editor';
25
import {
26
    DOMElement,
27
    isDOMNode,
28
    DOMStaticRange,
29
    DOMRange,
30
    isDOMElement,
31
    isPlainTextOnlyPaste,
32
    DOMSelection,
33
    getDefaultView,
34
    EDITOR_TO_WINDOW,
35
    EDITOR_TO_ELEMENT,
36
    NODE_TO_ELEMENT,
37
    ELEMENT_TO_NODE,
38
    IS_FOCUSED,
39
    IS_READ_ONLY
40
} from 'slate-dom';
41
import { debounceTime, Subject } 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
    viewportRefresh$ = new Subject<void>();
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!
NEW
286
                const visibleStates = this.editor.getAllVisibleStates();
×
NEW
287
                const virtualView = this.calculateVirtualViewport(visibleStates);
×
288
                this.applyVirtualView(virtualView);
×
289
                const childrenForRender = virtualView.inViewportChildren;
×
290
                if (isDebug) {
×
291
                    debugLog('log', 'writeValue calculate: ', virtualView.inViewportIndics, 'initialized: ', this.listRender.initialized);
×
292
                }
293
                if (!this.listRender.initialized) {
×
294
                    this.listRender.initialize(childrenForRender, this.editor, this.context, 0, virtualView.inViewportIndics);
×
295
                } else {
296
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
NEW
297
                        this.handlePreRendering(visibleStates);
×
UNCOV
298
                    this.listRender.update(
×
299
                        childrenWithPreRendering,
300
                        this.editor,
301
                        this.context,
302
                        preRenderingCount,
303
                        childrenWithPreRenderingIndics
304
                    );
305
                }
306
                this.viewportRefresh$.next();
×
307
            } else {
308
                if (!this.listRender.initialized) {
26✔
309
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
310
                } else {
311
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
312
                }
313
            }
314
            this.cdr.markForCheck();
26✔
315
        }
316
    }
317

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

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

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

397
    toNativeSelection(autoScroll = true) {
15✔
398
        try {
15✔
399
            let { selection } = this.editor;
15✔
400

401
            if (this.isEnabledVirtualScroll()) {
15!
402
                selection = this.calculateVirtualScrollSelection(selection);
×
403
            }
404

405
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
406
            const { activeElement } = root;
15✔
407
            const domSelection = (root as Document).getSelection();
15✔
408

409
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
410
                return;
14✔
411
            }
412

413
            const hasDomSelection = domSelection.type !== 'None';
1✔
414

415
            // If the DOM selection is properly unset, we're done.
416
            if (!selection && !hasDomSelection) {
1!
417
                return;
×
418
            }
419

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

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

439
            // prevent updating native selection when active element is void element
440
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
441
                return;
×
442
            }
443

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

453
            // Otherwise the DOM selection is out of sync, so update it.
454
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
455
            this.isUpdatingSelection = true;
1✔
456

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

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

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

515
    onChange() {
516
        this.forceRender();
13✔
517
        this.onChangeCallback(this.editor.children);
13✔
518
    }
519

520
    ngAfterViewChecked() {}
521

522
    ngDoCheck() {}
523

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

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

583
    updateListRenderAndRemeasureHeights() {
NEW
584
        const visibleStates = this.editor.getAllVisibleStates();
×
NEW
585
        let virtualView = this.calculateVirtualViewport(visibleStates);
×
586
        let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
587
        if (diff.isDifferent && diff.needRemoveOnTop) {
×
588
            const remeasureIndics = diff.changedIndexesOfTop;
×
589
            const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
590
            if (changed) {
×
NEW
591
                virtualView = this.calculateVirtualViewport(visibleStates);
×
592
                diff = this.diffVirtualViewport(virtualView, 'second');
×
593
            }
594
        }
595
        // const oldInViewportChildren = this.inViewportChildren;
596
        this.applyVirtualView(virtualView);
×
NEW
597
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering(visibleStates);
×
598
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
599
        // 新增或者修改的才需要重算,计算出这个结果
600
        // const remeasureIndics = [];
601
        // this.inViewportChildren.forEach((child, index) => {
602
        //     if (oldInViewportChildren.indexOf(child) === -1) {
603
        //         remeasureIndics.push(this.inViewportIndics[index]);
604
        //     }
605
        // });
606
        this.viewportRefresh$.next();
×
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
                    const firstElement = this.inViewportChildren[0];
×
712
                    const firstDomElement = AngularEditor.toDOMNode(this.editor, firstElement);
×
713
                    const target = firstDomElement || this.virtualTopHeightElement;
×
714
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, target.offsetWidth);
×
715
                    updatePreRenderingElementWidth(this.editor);
×
716
                    this.viewportRefresh$.next();
×
717
                    if (isDebug) {
×
718
                        debugLog(
×
719
                            'log',
720
                            'editorResizeObserverRectWidth: ',
721
                            editorResizeObserverRectWidth,
722
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
723
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
724
                        );
725
                    }
726
                }
727
            });
728
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
729
            this.viewportRefresh$.pipe(debounceTime(1000)).subscribe(() => {
×
730
                // const res = measureHeightByIndics(this.editor, this.inViewportIndics);
731
                // if (isDebug) {
732
                //     debugLog(
733
                //         'log',
734
                //         'viewportRefresh$ debounceTime 1000ms',
735
                //         'inViewportIndics: ',
736
                //         this.inViewportIndics,
737
                //         'measureHeightByIndics height changed: ',
738
                //         res
739
                //     );
740
                // }
741
            });
742
        }
743
    }
744

745
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
746
        if (!this.virtualScrollInitialized) {
×
747
            return;
×
748
        }
749
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
750
        if (bottomHeight !== undefined) {
×
751
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
752
        }
753
    }
754

755
    getActualVirtualTopHeight() {
756
        if (!this.virtualScrollInitialized) {
×
757
            return 0;
×
758
        }
759
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
760
    }
761

762
    handlePreRendering(visibleStates: boolean[]) {
763
        let preRenderingCount = 0;
×
764
        const childrenWithPreRendering = [...this.inViewportChildren];
×
765
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
766
        const firstIndex = this.inViewportIndics[0];
×
767
        for (let index = firstIndex - 1; index >= 0; index--) {
×
768
            const element = this.editor.children[index] as Element;
×
NEW
769
            if (visibleStates[index]) {
×
770
                childrenWithPreRendering.unshift(element);
×
771
                childrenWithPreRenderingIndics.unshift(index);
×
772
                preRenderingCount = 1;
×
773
                break;
×
774
            }
775
        }
776
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
777
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
778
            const element = this.editor.children[index] as Element;
×
NEW
779
            if (visibleStates[index]) {
×
780
                childrenWithPreRendering.push(element);
×
781
                childrenWithPreRenderingIndics.push(index);
×
782
                break;
×
783
            }
784
        }
785
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
786
    }
787

788
    private tryUpdateVirtualViewport() {
789
        if (isDebug) {
×
790
            debugLog('log', 'tryUpdateVirtualViewport');
×
791
        }
792
        const isFromScrollTo = EDITOR_TO_IS_FROM_SCROLL_TO.get(this.editor);
×
793
        if (this.inViewportIndics.length > 0 && !isFromScrollTo) {
×
794
            const topHeight = this.getActualVirtualTopHeight();
×
NEW
795
            const visibleStates = this.editor.getAllVisibleStates();
×
NEW
796
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0], visibleStates);
×
797
            if (topHeight !== refreshVirtualTopHeight) {
×
798
                if (isDebug) {
×
799
                    debugLog(
×
800
                        'log',
801
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
802
                        topHeight - refreshVirtualTopHeight
803
                    );
804
                }
805
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
806
                return;
×
807
            }
808
        }
809
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
810
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
811
            if (isDebug) {
×
812
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
813
            }
NEW
814
            const visibleStates = this.editor.getAllVisibleStates();
×
NEW
815
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
816
            let diff = this.diffVirtualViewport(virtualView);
×
817
            if (diff.isDifferent && diff.needRemoveOnTop && !isFromScrollTo) {
×
818
                const remeasureIndics = diff.changedIndexesOfTop;
×
819
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
820
                if (changed) {
×
NEW
821
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
822
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
823
                }
824
            }
825
            if (diff.isDifferent) {
×
826
                this.applyVirtualView(virtualView);
×
827
                if (this.listRender.initialized) {
×
828
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
NEW
829
                        this.handlePreRendering(visibleStates);
×
UNCOV
830
                    this.listRender.update(
×
831
                        childrenWithPreRendering,
832
                        this.editor,
833
                        this.context,
834
                        preRenderingCount,
835
                        childrenWithPreRenderingIndics
836
                    );
837
                    if (diff.needAddOnTop && !isFromScrollTo) {
×
838
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
839
                        if (isDebug) {
×
840
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
841
                        }
842
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
843
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
844
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
845
                        if (changed) {
×
NEW
846
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
847
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
848
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
849
                            this.setVirtualSpaceHeight(newTopHeight);
×
850
                            if (isDebug) {
×
851
                                debugLog(
×
852
                                    'log',
853
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
854
                                );
855
                            }
856
                        }
857
                    }
858
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
859
                        this.toNativeSelection(false);
×
860
                    }
861
                    this.viewportRefresh$.next();
×
862
                }
863
            }
864
            if (isDebug) {
×
865
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
866
            }
867
        });
868
    }
869

870
    private calculateVirtualViewport(visibleStates: boolean[]) {
871
        const children = (this.editor.children || []) as Element[];
×
872
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
873
            return {
×
874
                inViewportChildren: children,
875
                inViewportIndics: [],
876
                top: 0,
877
                bottom: 0,
878
                heights: []
879
            };
880
        }
881
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
882
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
883
        if (!viewportHeight) {
×
884
            return {
×
885
                inViewportChildren: [],
886
                inViewportIndics: [],
887
                top: 0,
888
                bottom: 0,
889
                heights: []
890
            };
891
        }
892
        const elementLength = children.length;
×
893
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
894
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
895
            setTimeout(() => {
×
896
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
897
                const businessTop =
898
                    Math.ceil(virtualTopBoundingTop) +
×
899
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
900
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
901
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
902
                if (isDebug) {
×
903
                    debugLog('log', 'businessTop', businessTop);
×
904
                }
905
            }, 100);
906
        }
907
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
NEW
908
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
909
        const totalHeight = accumulatedHeights[elementLength];
×
910
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
911
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
912
        const viewBottom = limitedScrollTop + viewportHeight;
×
913
        let accumulatedOffset = 0;
×
914
        let inViewportStartIndex = -1;
×
915
        const visible: Element[] = [];
×
916
        const inViewportIndics: number[] = [];
×
917

918
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
919
            const currentHeight = heights[i];
×
920
            const nextOffset = accumulatedOffset + currentHeight;
×
NEW
921
            const isVisible = visibleStates[i];
×
922
            if (!isVisible) {
×
923
                accumulatedOffset = nextOffset;
×
924
                continue;
×
925
            }
926
            // 可视区域有交集,加入渲染
927
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
928
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
929
                visible.push(children[i]);
×
930
                inViewportIndics.push(i);
×
931
            }
932
            accumulatedOffset = nextOffset;
×
933
        }
934

935
        const inViewportEndIndex =
936
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
937
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
938
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
939
        return {
×
940
            inViewportChildren: visible.length ? visible : children,
×
941
            inViewportIndics,
942
            top,
943
            bottom,
944
            heights,
945
            accumulatedHeights
946
        };
947
    }
948

949
    private applyVirtualView(virtualView: VirtualViewResult) {
950
        this.inViewportChildren = virtualView.inViewportChildren;
×
951
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
952
        this.inViewportIndics = virtualView.inViewportIndics;
×
953
    }
954

955
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
956
        if (!this.inViewportChildren.length) {
×
957
            if (isDebug) {
×
958
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
959
            }
960
            return {
×
961
                isDifferent: true,
962
                changedIndexesOfTop: [],
963
                changedIndexesOfBottom: []
964
            };
965
        }
966
        const oldIndexesInViewport = [...this.inViewportIndics];
×
967
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
968
        const firstNewIndex = newIndexesInViewport[0];
×
969
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
970
        const firstOldIndex = oldIndexesInViewport[0];
×
971
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
972
        const isSameViewport =
973
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
974
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
975
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
976
            return {
×
977
                isDifferent: !isSameViewport,
978
                changedIndexesOfTop: [],
979
                changedIndexesOfBottom: []
980
            };
981
        }
982
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
983
            const changedIndexesOfTop = [];
×
984
            const changedIndexesOfBottom = [];
×
985
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
986
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
987
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
988
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
989
            if (needRemoveOnTop || needAddOnBottom) {
×
990
                // 向下
991
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
992
                    const element = oldIndexesInViewport[index];
×
993
                    if (!newIndexesInViewport.includes(element)) {
×
994
                        changedIndexesOfTop.push(element);
×
995
                    } else {
996
                        break;
×
997
                    }
998
                }
999
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
1000
                    const element = newIndexesInViewport[index];
×
1001
                    if (!oldIndexesInViewport.includes(element)) {
×
1002
                        changedIndexesOfBottom.push(element);
×
1003
                    } else {
1004
                        break;
×
1005
                    }
1006
                }
1007
            } else if (needAddOnTop || needRemoveOnBottom) {
×
1008
                // 向上
1009
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
1010
                    const element = newIndexesInViewport[index];
×
1011
                    if (!oldIndexesInViewport.includes(element)) {
×
1012
                        changedIndexesOfTop.push(element);
×
1013
                    } else {
1014
                        break;
×
1015
                    }
1016
                }
1017
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
1018
                    const element = oldIndexesInViewport[index];
×
1019
                    if (!newIndexesInViewport.includes(element)) {
×
1020
                        changedIndexesOfBottom.push(element);
×
1021
                    } else {
1022
                        break;
×
1023
                    }
1024
                }
1025
            }
1026
            if (isDebug) {
×
1027
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
1028
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
1029
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
1030
                // this.editor.children[index] will be undefined when it is removed
1031
                debugLog(
×
1032
                    'log',
1033
                    'changedIndexesOfTop:',
1034
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
1035
                    changedIndexesOfTop,
1036
                    changedIndexesOfTop.map(
1037
                        index =>
1038
                            (this.editor.children[index] &&
×
1039
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
1040
                            0
1041
                    )
1042
                );
1043
                debugLog(
×
1044
                    'log',
1045
                    'changedIndexesOfBottom:',
1046
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
1047
                    changedIndexesOfBottom,
1048
                    changedIndexesOfBottom.map(
1049
                        index =>
1050
                            (this.editor.children[index] &&
×
1051
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
1052
                            0
1053
                    )
1054
                );
1055
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
1056
                const needBottom = virtualView.heights
×
1057
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
1058
                    .reduce((acc, height) => acc + height, 0);
×
1059
                debugLog(
×
1060
                    'log',
1061
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
1062
                    'newTopHeight:',
1063
                    needTop,
1064
                    'prevTopHeight:',
1065
                    parseFloat(this.virtualTopHeightElement.style.height)
1066
                );
1067
                debugLog(
×
1068
                    'log',
1069
                    'newBottomHeight:',
1070
                    needBottom,
1071
                    'prevBottomHeight:',
1072
                    parseFloat(this.virtualBottomHeightElement.style.height)
1073
                );
1074
                debugLog('warn', '=========== Dividing line ===========');
×
1075
            }
1076
            return {
×
1077
                isDifferent: true,
1078
                needRemoveOnTop,
1079
                needAddOnTop,
1080
                needRemoveOnBottom,
1081
                needAddOnBottom,
1082
                changedIndexesOfTop,
1083
                changedIndexesOfBottom
1084
            };
1085
        }
1086
        return {
×
1087
            isDifferent: false,
1088
            changedIndexesOfTop: [],
1089
            changedIndexesOfBottom: []
1090
        };
1091
    }
1092

1093
    //#region event proxy
1094
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1095
        this.manualListeners.push(
483✔
1096
            this.renderer2.listen(target, eventName, (event: Event) => {
1097
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1098
                if (beforeInputEvent) {
5!
1099
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1100
                }
1101
                listener(event);
5✔
1102
            })
1103
        );
1104
    }
1105

1106
    private toSlateSelection() {
1107
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1108
            try {
1✔
1109
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1110
                const { activeElement } = root;
1✔
1111
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1112
                const domSelection = (root as Document).getSelection();
1✔
1113

1114
                if (activeElement === el) {
1!
1115
                    this.latestElement = activeElement;
1✔
1116
                    IS_FOCUSED.set(this.editor, true);
1✔
1117
                } else {
1118
                    IS_FOCUSED.delete(this.editor);
×
1119
                }
1120

1121
                if (!domSelection) {
1!
1122
                    return Transforms.deselect(this.editor);
×
1123
                }
1124

1125
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1126
                const hasDomSelectionInEditor =
1127
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1128
                if (!hasDomSelectionInEditor) {
1!
1129
                    Transforms.deselect(this.editor);
×
1130
                    return;
×
1131
                }
1132

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

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

1233
                // COMPAT: If the selection is expanded, even if the command seems like
1234
                // a delete forward/backward command it should delete the selection.
1235
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1236
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1237
                    Editor.deleteFragment(editor, { direction });
×
1238
                    return;
×
1239
                }
1240

1241
                switch (type) {
×
1242
                    case 'deleteByComposition':
1243
                    case 'deleteByCut':
1244
                    case 'deleteByDrag': {
1245
                        Editor.deleteFragment(editor);
×
1246
                        break;
×
1247
                    }
1248

1249
                    case 'deleteContent':
1250
                    case 'deleteContentForward': {
1251
                        Editor.deleteForward(editor);
×
1252
                        break;
×
1253
                    }
1254

1255
                    case 'deleteContentBackward': {
1256
                        Editor.deleteBackward(editor);
×
1257
                        break;
×
1258
                    }
1259

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

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

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

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

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

1286
                    case 'deleteWordBackward': {
1287
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1288
                        break;
×
1289
                    }
1290

1291
                    case 'deleteWordForward': {
1292
                        Editor.deleteForward(editor, { unit: 'word' });
×
1293
                        break;
×
1294
                    }
1295

1296
                    case 'insertLineBreak':
1297
                    case 'insertParagraph': {
1298
                        Editor.insertBreak(editor);
×
1299
                        break;
×
1300
                    }
1301

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

1337
    private onDOMBlur(event: FocusEvent) {
1338
        if (
×
1339
            this.readonly ||
×
1340
            this.isUpdatingSelection ||
1341
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1342
            this.isDOMEventHandled(event, this.blur)
1343
        ) {
1344
            return;
×
1345
        }
1346

1347
        const window = AngularEditor.getWindow(this.editor);
×
1348

1349
        // COMPAT: If the current `activeElement` is still the previous
1350
        // one, this is due to the window being blurred when the tab
1351
        // itself becomes unfocused, so we want to abort early to allow to
1352
        // editor to stay focused when the tab becomes focused again.
1353
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1354
        if (this.latestElement === root.activeElement) {
×
1355
            return;
×
1356
        }
1357

1358
        const { relatedTarget } = event;
×
1359
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1360

1361
        // COMPAT: The event should be ignored if the focus is returning
1362
        // to the editor from an embedded editable element (eg. an <input>
1363
        // element inside a void node).
1364
        if (relatedTarget === el) {
×
1365
            return;
×
1366
        }
1367

1368
        // COMPAT: The event should be ignored if the focus is moving from
1369
        // the editor to inside a void node's spacer element.
1370
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1371
            return;
×
1372
        }
1373

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

1380
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1381
                return;
×
1382
            }
1383
        }
1384

1385
        IS_FOCUSED.delete(this.editor);
×
1386
    }
1387

1388
    private onDOMClick(event: MouseEvent) {
1389
        if (
×
1390
            !this.readonly &&
×
1391
            AngularEditor.hasTarget(this.editor, event.target) &&
1392
            !this.isDOMEventHandled(event, this.click) &&
1393
            isDOMNode(event.target)
1394
        ) {
1395
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1396
            const path = AngularEditor.findPath(this.editor, node);
×
1397
            const start = Editor.start(this.editor, path);
×
1398
            const end = Editor.end(this.editor, path);
×
1399

1400
            const startVoid = Editor.void(this.editor, { at: start });
×
1401
            const endVoid = Editor.void(this.editor, { at: end });
×
1402

1403
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1404
                let blockPath = path;
×
1405
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1406
                    const block = Editor.above(this.editor, {
×
1407
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1408
                        at: path
1409
                    });
1410

1411
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1412
                }
1413

1414
                const range = Editor.range(this.editor, blockPath);
×
1415
                Transforms.select(this.editor, range);
×
1416
                return;
×
1417
            }
1418

1419
            if (
×
1420
                startVoid &&
×
1421
                endVoid &&
1422
                Path.equals(startVoid[1], endVoid[1]) &&
1423
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1424
            ) {
1425
                const range = Editor.range(this.editor, start);
×
1426
                Transforms.select(this.editor, range);
×
1427
            }
1428
        }
1429
    }
1430

1431
    private onDOMCompositionStart(event: CompositionEvent) {
1432
        const { selection } = this.editor;
1✔
1433
        if (selection) {
1!
1434
            // solve the problem of cross node Chinese input
1435
            if (Range.isExpanded(selection)) {
×
1436
                Editor.deleteFragment(this.editor);
×
1437
                this.forceRender();
×
1438
            }
1439
        }
1440
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1441
            this.isComposing = true;
1✔
1442
        }
1443
        this.render();
1✔
1444
    }
1445

1446
    private onDOMCompositionUpdate(event: CompositionEvent) {
1447
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1448
    }
1449

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

1464
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1465
            // so we need avoid repeat isnertText by isComposing === true,
1466
            this.isComposing = false;
×
1467
        }
1468
        this.render();
×
1469
    }
1470

1471
    private onDOMCopy(event: ClipboardEvent) {
1472
        const window = AngularEditor.getWindow(this.editor);
×
1473
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1474
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1475
            event.preventDefault();
×
1476
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1477
        }
1478
    }
1479

1480
    private onDOMCut(event: ClipboardEvent) {
1481
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1482
            event.preventDefault();
×
1483
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1484
            const { selection } = this.editor;
×
1485

1486
            if (selection) {
×
1487
                AngularEditor.deleteCutData(this.editor);
×
1488
            }
1489
        }
1490
    }
1491

1492
    private onDOMDragOver(event: DragEvent) {
1493
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1494
            // Only when the target is void, call `preventDefault` to signal
1495
            // that drops are allowed. Editable content is droppable by
1496
            // default, and calling `preventDefault` hides the cursor.
1497
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1498

1499
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1500
                event.preventDefault();
×
1501
            }
1502
        }
1503
    }
1504

1505
    private onDOMDragStart(event: DragEvent) {
1506
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1507
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1508
            const path = AngularEditor.findPath(this.editor, node);
×
1509
            const voidMatch =
1510
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1511

1512
            // If starting a drag on a void node, make sure it is selected
1513
            // so that it shows up in the selection's fragment.
1514
            if (voidMatch) {
×
1515
                const range = Editor.range(this.editor, path);
×
1516
                Transforms.select(this.editor, range);
×
1517
            }
1518

1519
            this.isDraggingInternally = true;
×
1520

1521
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1522
        }
1523
    }
1524

1525
    private onDOMDrop(event: DragEvent) {
1526
        const editor = this.editor;
×
1527
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1528
            event.preventDefault();
×
1529
            // Keep a reference to the dragged range before updating selection
1530
            const draggedRange = editor.selection;
×
1531

1532
            // Find the range where the drop happened
1533
            const range = AngularEditor.findEventRange(editor, event);
×
1534
            const data = event.dataTransfer;
×
1535

1536
            Transforms.select(editor, range);
×
1537

1538
            if (this.isDraggingInternally) {
×
1539
                if (draggedRange) {
×
1540
                    Transforms.delete(editor, {
×
1541
                        at: draggedRange
1542
                    });
1543
                }
1544

1545
                this.isDraggingInternally = false;
×
1546
            }
1547

1548
            AngularEditor.insertData(editor, data);
×
1549

1550
            // When dragging from another source into the editor, it's possible
1551
            // that the current editor does not have focus.
1552
            if (!AngularEditor.isFocused(editor)) {
×
1553
                AngularEditor.focus(editor);
×
1554
            }
1555
        }
1556
    }
1557

1558
    private onDOMDragEnd(event: DragEvent) {
1559
        if (
×
1560
            !this.readonly &&
×
1561
            this.isDraggingInternally &&
1562
            AngularEditor.hasTarget(this.editor, event.target) &&
1563
            !this.isDOMEventHandled(event, this.dragEnd)
1564
        ) {
1565
            this.isDraggingInternally = false;
×
1566
        }
1567
    }
1568

1569
    private onDOMFocus(event: Event) {
1570
        if (
2✔
1571
            !this.readonly &&
8✔
1572
            !this.isUpdatingSelection &&
1573
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1574
            !this.isDOMEventHandled(event, this.focus)
1575
        ) {
1576
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1577
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1578
            this.latestElement = root.activeElement;
2✔
1579

1580
            // COMPAT: If the editor has nested editable elements, the focus
1581
            // can go to them. In Firefox, this must be prevented because it
1582
            // results in issues with keyboard navigation. (2017/03/30)
1583
            if (IS_FIREFOX && event.target !== el) {
2!
1584
                el.focus();
×
1585
                return;
×
1586
            }
1587

1588
            IS_FOCUSED.set(this.editor, true);
2✔
1589
        }
1590
    }
1591

1592
    private onDOMKeydown(event: KeyboardEvent) {
1593
        const editor = this.editor;
×
1594
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1595
        const { activeElement } = root;
×
1596
        if (
×
1597
            !this.readonly &&
×
1598
            AngularEditor.hasEditableTarget(editor, event.target) &&
1599
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1600
            !this.isComposing &&
1601
            !this.isDOMEventHandled(event, this.keydown)
1602
        ) {
1603
            const nativeEvent = event;
×
1604
            const { selection } = editor;
×
1605

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

1609
            try {
×
1610
                // COMPAT: Since we prevent the default behavior on
1611
                // `beforeinput` events, the browser doesn't think there's ever
1612
                // any history stack to undo or redo, so we have to manage these
1613
                // hotkeys ourselves. (2019/11/06)
1614
                if (Hotkeys.isRedo(nativeEvent)) {
×
1615
                    event.preventDefault();
×
1616

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

1621
                    return;
×
1622
                }
1623

1624
                if (Hotkeys.isUndo(nativeEvent)) {
×
1625
                    event.preventDefault();
×
1626

1627
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1628
                        editor.undo();
×
1629
                    }
1630

1631
                    return;
×
1632
                }
1633

1634
                // COMPAT: Certain browsers don't handle the selection updates
1635
                // properly. In Chrome, the selection isn't properly extended.
1636
                // And in Firefox, the selection isn't properly collapsed.
1637
                // (2017/10/17)
1638
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1639
                    event.preventDefault();
×
1640
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1641
                    return;
×
1642
                }
1643

1644
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1645
                    event.preventDefault();
×
1646
                    Transforms.move(editor, { unit: 'line' });
×
1647
                    return;
×
1648
                }
1649

1650
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1651
                    event.preventDefault();
×
1652
                    Transforms.move(editor, {
×
1653
                        unit: 'line',
1654
                        edge: 'focus',
1655
                        reverse: true
1656
                    });
1657
                    return;
×
1658
                }
1659

1660
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1661
                    event.preventDefault();
×
1662
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1663
                    return;
×
1664
                }
1665

1666
                // COMPAT: If a void node is selected, or a zero-width text node
1667
                // adjacent to an inline is selected, we need to handle these
1668
                // hotkeys manually because browsers won't be able to skip over
1669
                // the void node with the zero-width space not being an empty
1670
                // string.
1671
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1672
                    event.preventDefault();
×
1673

1674
                    if (selection && Range.isCollapsed(selection)) {
×
1675
                        Transforms.move(editor, { reverse: !isRTL });
×
1676
                    } else {
1677
                        Transforms.collapse(editor, { edge: 'start' });
×
1678
                    }
1679

1680
                    return;
×
1681
                }
1682

1683
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1684
                    event.preventDefault();
×
1685
                    if (selection && Range.isCollapsed(selection)) {
×
1686
                        Transforms.move(editor, { reverse: isRTL });
×
1687
                    } else {
1688
                        Transforms.collapse(editor, { edge: 'end' });
×
1689
                    }
1690

1691
                    return;
×
1692
                }
1693

1694
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1695
                    event.preventDefault();
×
1696

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

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

1705
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1706
                    event.preventDefault();
×
1707

1708
                    if (selection && Range.isExpanded(selection)) {
×
1709
                        Transforms.collapse(editor, { edge: 'focus' });
×
1710
                    }
1711

1712
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1713
                    return;
×
1714
                }
1715

1716
                if (isKeyHotkey('mod+a', event)) {
×
1717
                    this.editor.selectAll();
×
1718
                    event.preventDefault();
×
1719
                    return;
×
1720
                }
1721

1722
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1723
                // fall back to guessing at the input intention for hotkeys.
1724
                // COMPAT: In iOS, some of these hotkeys are handled in the
1725
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1726
                    // We don't have a core behavior for these, but they change the
1727
                    // DOM if we don't prevent them, so we have to.
1728
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1729
                        event.preventDefault();
×
1730
                        return;
×
1731
                    }
1732

1733
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1734
                        event.preventDefault();
×
1735
                        Editor.insertBreak(editor);
×
1736
                        return;
×
1737
                    }
1738

1739
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1740
                        event.preventDefault();
×
1741

1742
                        if (selection && Range.isExpanded(selection)) {
×
1743
                            Editor.deleteFragment(editor, {
×
1744
                                direction: 'backward'
1745
                            });
1746
                        } else {
1747
                            Editor.deleteBackward(editor);
×
1748
                        }
1749

1750
                        return;
×
1751
                    }
1752

1753
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1754
                        event.preventDefault();
×
1755

1756
                        if (selection && Range.isExpanded(selection)) {
×
1757
                            Editor.deleteFragment(editor, {
×
1758
                                direction: 'forward'
1759
                            });
1760
                        } else {
1761
                            Editor.deleteForward(editor);
×
1762
                        }
1763

1764
                        return;
×
1765
                    }
1766

1767
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1768
                        event.preventDefault();
×
1769

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

1778
                        return;
×
1779
                    }
1780

1781
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1782
                        event.preventDefault();
×
1783

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

1792
                        return;
×
1793
                    }
1794

1795
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1796
                        event.preventDefault();
×
1797

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

1806
                        return;
×
1807
                    }
1808

1809
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1810
                        event.preventDefault();
×
1811

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

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

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

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

1901
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1902
        if (!handler) {
3✔
1903
            return false;
3✔
1904
        }
1905
        handler(event);
×
1906
        return event.defaultPrevented;
×
1907
    }
1908
    //#endregion
1909

1910
    ngOnDestroy() {
1911
        this.editorResizeObserver?.disconnect();
23✔
1912
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1913
        this.manualListeners.forEach(manualListener => {
23✔
1914
            manualListener();
483✔
1915
        });
1916
        this.destroy$.complete();
23✔
1917
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1918
    }
1919
}
1920

1921
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1922
    // This was affecting the selection of multiple blocks and dragging behavior,
1923
    // so enabled only if the selection has been collapsed.
1924
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1925
        const leafEl = domRange.startContainer.parentElement!;
×
1926

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

1932
        if (isZeroDimensionRect) {
×
1933
            const leafRect = leafEl.getBoundingClientRect();
×
1934
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1935

1936
            if (leafHasDimensions) {
×
1937
                return;
×
1938
            }
1939
        }
1940

1941
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1942
        scrollIntoView(leafEl, {
×
1943
            scrollMode: 'if-needed'
1944
        });
1945
        delete leafEl.getBoundingClientRect;
×
1946
    }
1947
};
1948

1949
/**
1950
 * Check if the target is inside void and in the editor.
1951
 */
1952

1953
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1954
    let slateNode: Node | null = null;
1✔
1955
    try {
1✔
1956
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1957
    } catch (error) {}
1958
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1959
};
1960

1961
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1962
    return (
2✔
1963
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1964
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1965
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1966
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1967
    );
1968
};
1969

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