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

worktile / slate-angular / d78503c6-987b-4d53-909e-4b19587fce81

16 Jan 2026 05:39AM UTC coverage: 36.157% (-0.2%) from 36.392%
d78503c6-987b-4d53-909e-4b19587fce81

push

circleci

pubuzhixing8
fix(virtual-scroll): support remeasure indics height after data changed and try to update virtual viewport after remeasure #WIK-19811

402 of 1313 branches covered (30.62%)

Branch coverage included in aggregate %.

1 of 28 new or added lines in 2 files covered. (3.57%)

1 existing line in 1 file now uncovered.

1109 of 2866 relevant lines covered (38.7%)

23.33 hits per line

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

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

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

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

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

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

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

114
    private initialized: boolean;
115

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

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

120
    @Input() editor: AngularEditor;
121

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

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

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

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

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

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

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

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

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

140
    @Input() placeholder: string;
141

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

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

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

200
    listRender: ListRender;
201

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

524
    ngAfterViewChecked() {}
525

526
    ngDoCheck() {}
527

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

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

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

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

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

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

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

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

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

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

680
    virtualScrollInitialized = false;
23✔
681

682
    virtualTopHeightElement: HTMLElement;
683

684
    virtualBottomHeightElement: HTMLElement;
685

686
    virtualCenterOutlet: HTMLElement;
687

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

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

753
    getChangedIndics(previousValue: Descendant[]) {
NEW
754
        const remeasureIndics = [];
×
NEW
755
        this.inViewportChildren.forEach((child, index) => {
×
NEW
756
            if (previousValue.indexOf(child) === -1) {
×
NEW
757
                remeasureIndics.push(this.inViewportIndics[index]);
×
758
            }
759
        });
NEW
760
        return remeasureIndics;
×
761
    }
762

763
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
764
        if (!this.virtualScrollInitialized) {
×
765
            return;
×
766
        }
767
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
768
        if (bottomHeight !== undefined) {
×
769
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
770
        }
771
    }
772

773
    getActualVirtualTopHeight() {
774
        if (!this.virtualScrollInitialized) {
×
775
            return 0;
×
776
        }
777
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
778
    }
779

780
    handlePreRendering(visibleStates: boolean[]) {
781
        let preRenderingCount = 0;
×
782
        const childrenWithPreRendering = [...this.inViewportChildren];
×
783
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
784
        const firstIndex = this.inViewportIndics[0];
×
785
        for (let index = firstIndex - 1; index >= 0; index--) {
×
786
            const element = this.editor.children[index] as Element;
×
787
            if (visibleStates[index]) {
×
788
                childrenWithPreRendering.unshift(element);
×
789
                childrenWithPreRenderingIndics.unshift(index);
×
790
                preRenderingCount = 1;
×
791
                break;
×
792
            }
793
        }
794
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
795
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
796
            const element = this.editor.children[index] as Element;
×
797
            if (visibleStates[index]) {
×
798
                childrenWithPreRendering.push(element);
×
799
                childrenWithPreRenderingIndics.push(index);
×
800
                break;
×
801
            }
802
        }
803
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
804
    }
805

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

887
    private calculateVirtualViewport(visibleStates: boolean[]) {
888
        const children = (this.editor.children || []) as Element[];
×
889
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
890
            return {
×
891
                inViewportChildren: children,
892
                inViewportIndics: [],
893
                top: 0,
894
                bottom: 0,
895
                heights: []
896
            };
897
        }
898
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
899
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
900
        if (!viewportHeight) {
×
901
            return {
×
902
                inViewportChildren: [],
903
                inViewportIndics: [],
904
                top: 0,
905
                bottom: 0,
906
                heights: []
907
            };
908
        }
909
        const elementLength = children.length;
×
910
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
911
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
912
            setTimeout(() => {
×
913
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
914
                const businessTop =
915
                    Math.ceil(virtualTopBoundingTop) +
×
916
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
917
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
918
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
919
                if (isDebug) {
×
920
                    debugLog('log', 'businessTop', businessTop);
×
921
                }
922
            }, 100);
923
        }
924
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
925
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
926
        const totalHeight = accumulatedHeights[elementLength];
×
927
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
928
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
929
        const viewBottom = limitedScrollTop + viewportHeight;
×
930
        let accumulatedOffset = 0;
×
931
        let inViewportStartIndex = -1;
×
932
        const visible: Element[] = [];
×
933
        const inViewportIndics: number[] = [];
×
934

935
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
936
            const currentHeight = heights[i];
×
937
            const nextOffset = accumulatedOffset + currentHeight;
×
938
            const isVisible = visibleStates[i];
×
939
            if (!isVisible) {
×
940
                accumulatedOffset = nextOffset;
×
941
                continue;
×
942
            }
943
            // 可视区域有交集,加入渲染
944
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
945
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
946
                visible.push(children[i]);
×
947
                inViewportIndics.push(i);
×
948
            }
949
            accumulatedOffset = nextOffset;
×
950
        }
951

952
        const inViewportEndIndex =
953
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
954
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
955
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
956
        return {
×
957
            inViewportChildren: visible.length ? visible : children,
×
958
            inViewportIndics,
959
            top,
960
            bottom,
961
            heights,
962
            accumulatedHeights
963
        };
964
    }
965

966
    private applyVirtualView(virtualView: VirtualViewResult) {
967
        this.inViewportChildren = virtualView.inViewportChildren;
×
968
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
969
        this.inViewportIndics = virtualView.inViewportIndics;
×
970
    }
971

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

1110
    //#region event proxy
1111
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1112
        this.manualListeners.push(
483✔
1113
            this.renderer2.listen(target, eventName, (event: Event) => {
1114
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1115
                if (beforeInputEvent) {
5!
1116
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1117
                }
1118
                listener(event);
5✔
1119
            })
1120
        );
1121
    }
1122

1123
    private toSlateSelection() {
1124
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1125
            try {
1✔
1126
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1127
                const { activeElement } = root;
1✔
1128
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1129
                const domSelection = (root as Document).getSelection();
1✔
1130

1131
                if (activeElement === el) {
1!
1132
                    this.latestElement = activeElement;
1✔
1133
                    IS_FOCUSED.set(this.editor, true);
1✔
1134
                } else {
1135
                    IS_FOCUSED.delete(this.editor);
×
1136
                }
1137

1138
                if (!domSelection) {
1!
1139
                    return Transforms.deselect(this.editor);
×
1140
                }
1141

1142
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1143
                const hasDomSelectionInEditor =
1144
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1145
                if (!hasDomSelectionInEditor) {
1!
1146
                    Transforms.deselect(this.editor);
×
1147
                    return;
×
1148
                }
1149

1150
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1151
                // for example, double-click the last cell of the table to select a non-editable DOM
1152
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1153
                if (range) {
1✔
1154
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1155
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1156
                            // force adjust DOMSelection
1157
                            this.toNativeSelection(false);
×
1158
                        }
1159
                    } else {
1160
                        Transforms.select(this.editor, range);
1✔
1161
                    }
1162
                }
1163
            } catch (error) {
1164
                this.editor.onError({
×
1165
                    code: SlateErrorCode.ToSlateSelectionError,
1166
                    nativeError: error
1167
                });
1168
            }
1169
        }
1170
    }
1171

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

1250
                // COMPAT: If the selection is expanded, even if the command seems like
1251
                // a delete forward/backward command it should delete the selection.
1252
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1253
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1254
                    Editor.deleteFragment(editor, { direction });
×
1255
                    return;
×
1256
                }
1257

1258
                switch (type) {
×
1259
                    case 'deleteByComposition':
1260
                    case 'deleteByCut':
1261
                    case 'deleteByDrag': {
1262
                        Editor.deleteFragment(editor);
×
1263
                        break;
×
1264
                    }
1265

1266
                    case 'deleteContent':
1267
                    case 'deleteContentForward': {
1268
                        Editor.deleteForward(editor);
×
1269
                        break;
×
1270
                    }
1271

1272
                    case 'deleteContentBackward': {
1273
                        Editor.deleteBackward(editor);
×
1274
                        break;
×
1275
                    }
1276

1277
                    case 'deleteEntireSoftLine': {
1278
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1279
                        Editor.deleteForward(editor, { unit: 'line' });
×
1280
                        break;
×
1281
                    }
1282

1283
                    case 'deleteHardLineBackward': {
1284
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1285
                        break;
×
1286
                    }
1287

1288
                    case 'deleteSoftLineBackward': {
1289
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1290
                        break;
×
1291
                    }
1292

1293
                    case 'deleteHardLineForward': {
1294
                        Editor.deleteForward(editor, { unit: 'block' });
×
1295
                        break;
×
1296
                    }
1297

1298
                    case 'deleteSoftLineForward': {
1299
                        Editor.deleteForward(editor, { unit: 'line' });
×
1300
                        break;
×
1301
                    }
1302

1303
                    case 'deleteWordBackward': {
1304
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1305
                        break;
×
1306
                    }
1307

1308
                    case 'deleteWordForward': {
1309
                        Editor.deleteForward(editor, { unit: 'word' });
×
1310
                        break;
×
1311
                    }
1312

1313
                    case 'insertLineBreak':
1314
                    case 'insertParagraph': {
1315
                        Editor.insertBreak(editor);
×
1316
                        break;
×
1317
                    }
1318

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

1354
    private onDOMBlur(event: FocusEvent) {
1355
        if (
×
1356
            this.readonly ||
×
1357
            this.isUpdatingSelection ||
1358
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1359
            this.isDOMEventHandled(event, this.blur)
1360
        ) {
1361
            return;
×
1362
        }
1363

1364
        const window = AngularEditor.getWindow(this.editor);
×
1365

1366
        // COMPAT: If the current `activeElement` is still the previous
1367
        // one, this is due to the window being blurred when the tab
1368
        // itself becomes unfocused, so we want to abort early to allow to
1369
        // editor to stay focused when the tab becomes focused again.
1370
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1371
        if (this.latestElement === root.activeElement) {
×
1372
            return;
×
1373
        }
1374

1375
        const { relatedTarget } = event;
×
1376
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1377

1378
        // COMPAT: The event should be ignored if the focus is returning
1379
        // to the editor from an embedded editable element (eg. an <input>
1380
        // element inside a void node).
1381
        if (relatedTarget === el) {
×
1382
            return;
×
1383
        }
1384

1385
        // COMPAT: The event should be ignored if the focus is moving from
1386
        // the editor to inside a void node's spacer element.
1387
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1388
            return;
×
1389
        }
1390

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

1397
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1398
                return;
×
1399
            }
1400
        }
1401

1402
        IS_FOCUSED.delete(this.editor);
×
1403
    }
1404

1405
    private onDOMClick(event: MouseEvent) {
1406
        if (
×
1407
            !this.readonly &&
×
1408
            AngularEditor.hasTarget(this.editor, event.target) &&
1409
            !this.isDOMEventHandled(event, this.click) &&
1410
            isDOMNode(event.target)
1411
        ) {
1412
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1413
            const path = AngularEditor.findPath(this.editor, node);
×
1414
            const start = Editor.start(this.editor, path);
×
1415
            const end = Editor.end(this.editor, path);
×
1416

1417
            const startVoid = Editor.void(this.editor, { at: start });
×
1418
            const endVoid = Editor.void(this.editor, { at: end });
×
1419

1420
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1421
                let blockPath = path;
×
1422
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1423
                    const block = Editor.above(this.editor, {
×
1424
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1425
                        at: path
1426
                    });
1427

1428
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1429
                }
1430

1431
                const range = Editor.range(this.editor, blockPath);
×
1432
                Transforms.select(this.editor, range);
×
1433
                return;
×
1434
            }
1435

1436
            if (
×
1437
                startVoid &&
×
1438
                endVoid &&
1439
                Path.equals(startVoid[1], endVoid[1]) &&
1440
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1441
            ) {
1442
                const range = Editor.range(this.editor, start);
×
1443
                Transforms.select(this.editor, range);
×
1444
            }
1445
        }
1446
    }
1447

1448
    private onDOMCompositionStart(event: CompositionEvent) {
1449
        const { selection } = this.editor;
1✔
1450
        if (selection) {
1!
1451
            // solve the problem of cross node Chinese input
1452
            if (Range.isExpanded(selection)) {
×
1453
                Editor.deleteFragment(this.editor);
×
1454
                this.forceRender();
×
1455
            }
1456
        }
1457
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1458
            this.isComposing = true;
1✔
1459
        }
1460
        this.render();
1✔
1461
    }
1462

1463
    private onDOMCompositionUpdate(event: CompositionEvent) {
1464
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1465
    }
1466

1467
    private onDOMCompositionEnd(event: CompositionEvent) {
1468
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1469
            Transforms.delete(this.editor);
×
1470
        }
1471
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1472
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1473
            // aren't correct and never fire the "insertFromComposition"
1474
            // type that we need. So instead, insert whenever a composition
1475
            // ends since it will already have been committed to the DOM.
1476
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1477
                preventInsertFromComposition(event, this.editor);
×
1478
                Editor.insertText(this.editor, event.data);
×
1479
            }
1480

1481
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1482
            // so we need avoid repeat isnertText by isComposing === true,
1483
            this.isComposing = false;
×
1484
        }
1485
        this.render();
×
1486
    }
1487

1488
    private onDOMCopy(event: ClipboardEvent) {
1489
        const window = AngularEditor.getWindow(this.editor);
×
1490
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1491
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1492
            event.preventDefault();
×
1493
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1494
        }
1495
    }
1496

1497
    private onDOMCut(event: ClipboardEvent) {
1498
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1499
            event.preventDefault();
×
1500
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1501
            const { selection } = this.editor;
×
1502

1503
            if (selection) {
×
1504
                AngularEditor.deleteCutData(this.editor);
×
1505
            }
1506
        }
1507
    }
1508

1509
    private onDOMDragOver(event: DragEvent) {
1510
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1511
            // Only when the target is void, call `preventDefault` to signal
1512
            // that drops are allowed. Editable content is droppable by
1513
            // default, and calling `preventDefault` hides the cursor.
1514
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1515

1516
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1517
                event.preventDefault();
×
1518
            }
1519
        }
1520
    }
1521

1522
    private onDOMDragStart(event: DragEvent) {
1523
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1524
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1525
            const path = AngularEditor.findPath(this.editor, node);
×
1526
            const voidMatch =
1527
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1528

1529
            // If starting a drag on a void node, make sure it is selected
1530
            // so that it shows up in the selection's fragment.
1531
            if (voidMatch) {
×
1532
                const range = Editor.range(this.editor, path);
×
1533
                Transforms.select(this.editor, range);
×
1534
            }
1535

1536
            this.isDraggingInternally = true;
×
1537

1538
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1539
        }
1540
    }
1541

1542
    private onDOMDrop(event: DragEvent) {
1543
        const editor = this.editor;
×
1544
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1545
            event.preventDefault();
×
1546
            // Keep a reference to the dragged range before updating selection
1547
            const draggedRange = editor.selection;
×
1548

1549
            // Find the range where the drop happened
1550
            const range = AngularEditor.findEventRange(editor, event);
×
1551
            const data = event.dataTransfer;
×
1552

1553
            Transforms.select(editor, range);
×
1554

1555
            if (this.isDraggingInternally) {
×
1556
                if (draggedRange) {
×
1557
                    Transforms.delete(editor, {
×
1558
                        at: draggedRange
1559
                    });
1560
                }
1561

1562
                this.isDraggingInternally = false;
×
1563
            }
1564

1565
            AngularEditor.insertData(editor, data);
×
1566

1567
            // When dragging from another source into the editor, it's possible
1568
            // that the current editor does not have focus.
1569
            if (!AngularEditor.isFocused(editor)) {
×
1570
                AngularEditor.focus(editor);
×
1571
            }
1572
        }
1573
    }
1574

1575
    private onDOMDragEnd(event: DragEvent) {
1576
        if (
×
1577
            !this.readonly &&
×
1578
            this.isDraggingInternally &&
1579
            AngularEditor.hasTarget(this.editor, event.target) &&
1580
            !this.isDOMEventHandled(event, this.dragEnd)
1581
        ) {
1582
            this.isDraggingInternally = false;
×
1583
        }
1584
    }
1585

1586
    private onDOMFocus(event: Event) {
1587
        if (
2✔
1588
            !this.readonly &&
8✔
1589
            !this.isUpdatingSelection &&
1590
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1591
            !this.isDOMEventHandled(event, this.focus)
1592
        ) {
1593
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1594
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1595
            this.latestElement = root.activeElement;
2✔
1596

1597
            // COMPAT: If the editor has nested editable elements, the focus
1598
            // can go to them. In Firefox, this must be prevented because it
1599
            // results in issues with keyboard navigation. (2017/03/30)
1600
            if (IS_FIREFOX && event.target !== el) {
2!
1601
                el.focus();
×
1602
                return;
×
1603
            }
1604

1605
            IS_FOCUSED.set(this.editor, true);
2✔
1606
        }
1607
    }
1608

1609
    private onDOMKeydown(event: KeyboardEvent) {
1610
        const editor = this.editor;
×
1611
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1612
        const { activeElement } = root;
×
1613
        if (
×
1614
            !this.readonly &&
×
1615
            AngularEditor.hasEditableTarget(editor, event.target) &&
1616
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1617
            !this.isComposing &&
1618
            !this.isDOMEventHandled(event, this.keydown)
1619
        ) {
1620
            const nativeEvent = event;
×
1621
            const { selection } = editor;
×
1622

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

1626
            try {
×
1627
                // COMPAT: Since we prevent the default behavior on
1628
                // `beforeinput` events, the browser doesn't think there's ever
1629
                // any history stack to undo or redo, so we have to manage these
1630
                // hotkeys ourselves. (2019/11/06)
1631
                if (Hotkeys.isRedo(nativeEvent)) {
×
1632
                    event.preventDefault();
×
1633

1634
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1635
                        editor.redo();
×
1636
                    }
1637

1638
                    return;
×
1639
                }
1640

1641
                if (Hotkeys.isUndo(nativeEvent)) {
×
1642
                    event.preventDefault();
×
1643

1644
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1645
                        editor.undo();
×
1646
                    }
1647

1648
                    return;
×
1649
                }
1650

1651
                // COMPAT: Certain browsers don't handle the selection updates
1652
                // properly. In Chrome, the selection isn't properly extended.
1653
                // And in Firefox, the selection isn't properly collapsed.
1654
                // (2017/10/17)
1655
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1656
                    event.preventDefault();
×
1657
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1658
                    return;
×
1659
                }
1660

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

1667
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1668
                    event.preventDefault();
×
1669
                    Transforms.move(editor, {
×
1670
                        unit: 'line',
1671
                        edge: 'focus',
1672
                        reverse: true
1673
                    });
1674
                    return;
×
1675
                }
1676

1677
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1678
                    event.preventDefault();
×
1679
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1680
                    return;
×
1681
                }
1682

1683
                // COMPAT: If a void node is selected, or a zero-width text node
1684
                // adjacent to an inline is selected, we need to handle these
1685
                // hotkeys manually because browsers won't be able to skip over
1686
                // the void node with the zero-width space not being an empty
1687
                // string.
1688
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1689
                    event.preventDefault();
×
1690

1691
                    if (selection && Range.isCollapsed(selection)) {
×
1692
                        Transforms.move(editor, { reverse: !isRTL });
×
1693
                    } else {
1694
                        Transforms.collapse(editor, { edge: 'start' });
×
1695
                    }
1696

1697
                    return;
×
1698
                }
1699

1700
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1701
                    event.preventDefault();
×
1702
                    if (selection && Range.isCollapsed(selection)) {
×
1703
                        Transforms.move(editor, { reverse: isRTL });
×
1704
                    } else {
1705
                        Transforms.collapse(editor, { edge: 'end' });
×
1706
                    }
1707

1708
                    return;
×
1709
                }
1710

1711
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1712
                    event.preventDefault();
×
1713

1714
                    if (selection && Range.isExpanded(selection)) {
×
1715
                        Transforms.collapse(editor, { edge: 'focus' });
×
1716
                    }
1717

1718
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1719
                    return;
×
1720
                }
1721

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

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

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

1733
                if (isKeyHotkey('mod+a', event)) {
×
1734
                    this.editor.selectAll();
×
1735
                    event.preventDefault();
×
1736
                    return;
×
1737
                }
1738

1739
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1740
                // fall back to guessing at the input intention for hotkeys.
1741
                // COMPAT: In iOS, some of these hotkeys are handled in the
1742
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1743
                    // We don't have a core behavior for these, but they change the
1744
                    // DOM if we don't prevent them, so we have to.
1745
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1746
                        event.preventDefault();
×
1747
                        return;
×
1748
                    }
1749

1750
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1751
                        event.preventDefault();
×
1752
                        Editor.insertBreak(editor);
×
1753
                        return;
×
1754
                    }
1755

1756
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1757
                        event.preventDefault();
×
1758

1759
                        if (selection && Range.isExpanded(selection)) {
×
1760
                            Editor.deleteFragment(editor, {
×
1761
                                direction: 'backward'
1762
                            });
1763
                        } else {
1764
                            Editor.deleteBackward(editor);
×
1765
                        }
1766

1767
                        return;
×
1768
                    }
1769

1770
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1771
                        event.preventDefault();
×
1772

1773
                        if (selection && Range.isExpanded(selection)) {
×
1774
                            Editor.deleteFragment(editor, {
×
1775
                                direction: 'forward'
1776
                            });
1777
                        } else {
1778
                            Editor.deleteForward(editor);
×
1779
                        }
1780

1781
                        return;
×
1782
                    }
1783

1784
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1785
                        event.preventDefault();
×
1786

1787
                        if (selection && Range.isExpanded(selection)) {
×
1788
                            Editor.deleteFragment(editor, {
×
1789
                                direction: 'backward'
1790
                            });
1791
                        } else {
1792
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1793
                        }
1794

1795
                        return;
×
1796
                    }
1797

1798
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1799
                        event.preventDefault();
×
1800

1801
                        if (selection && Range.isExpanded(selection)) {
×
1802
                            Editor.deleteFragment(editor, {
×
1803
                                direction: 'forward'
1804
                            });
1805
                        } else {
1806
                            Editor.deleteForward(editor, { unit: 'line' });
×
1807
                        }
1808

1809
                        return;
×
1810
                    }
1811

1812
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1813
                        event.preventDefault();
×
1814

1815
                        if (selection && Range.isExpanded(selection)) {
×
1816
                            Editor.deleteFragment(editor, {
×
1817
                                direction: 'backward'
1818
                            });
1819
                        } else {
1820
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1821
                        }
1822

1823
                        return;
×
1824
                    }
1825

1826
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1827
                        event.preventDefault();
×
1828

1829
                        if (selection && Range.isExpanded(selection)) {
×
1830
                            Editor.deleteFragment(editor, {
×
1831
                                direction: 'forward'
1832
                            });
1833
                        } else {
1834
                            Editor.deleteForward(editor, { unit: 'word' });
×
1835
                        }
1836

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

1872
    private onDOMPaste(event: ClipboardEvent) {
1873
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1874
        // fall back to React's `onPaste` here instead.
1875
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1876
        // when "paste without formatting" option is used.
1877
        // This unfortunately needs to be handled with paste events instead.
1878
        if (
×
1879
            !this.isDOMEventHandled(event, this.paste) &&
×
1880
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1881
            !this.readonly &&
1882
            AngularEditor.hasEditableTarget(this.editor, event.target)
1883
        ) {
1884
            event.preventDefault();
×
1885
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1886
        }
1887
    }
1888

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

1918
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1919
        if (!handler) {
3✔
1920
            return false;
3✔
1921
        }
1922
        handler(event);
×
1923
        return event.defaultPrevented;
×
1924
    }
1925
    //#endregion
1926

1927
    ngOnDestroy() {
1928
        this.editorResizeObserver?.disconnect();
22✔
1929
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1930
        this.manualListeners.forEach(manualListener => {
22✔
1931
            manualListener();
462✔
1932
        });
1933
        this.destroy$.complete();
22✔
1934
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1935
    }
1936
}
1937

1938
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1939
    // This was affecting the selection of multiple blocks and dragging behavior,
1940
    // so enabled only if the selection has been collapsed.
1941
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1942
        const leafEl = domRange.startContainer.parentElement!;
×
1943

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

1949
        if (isZeroDimensionRect) {
×
1950
            const leafRect = leafEl.getBoundingClientRect();
×
1951
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1952

1953
            if (leafHasDimensions) {
×
1954
                return;
×
1955
            }
1956
        }
1957

1958
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1959
        scrollIntoView(leafEl, {
×
1960
            scrollMode: 'if-needed'
1961
        });
1962
        delete leafEl.getBoundingClientRect;
×
1963
    }
1964
};
1965

1966
/**
1967
 * Check if the target is inside void and in the editor.
1968
 */
1969

1970
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1971
    let slateNode: Node | null = null;
1✔
1972
    try {
1✔
1973
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1974
    } catch (error) {}
1975
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1976
};
1977

1978
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1979
    return (
2✔
1980
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1981
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1982
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1983
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1984
    );
1985
};
1986

1987
/**
1988
 * remove default insert from composition
1989
 * @param text
1990
 */
1991
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1992
    const types = ['compositionend', 'insertFromComposition'];
×
1993
    if (!types.includes(event.type)) {
×
1994
        return;
×
1995
    }
1996
    const insertText = (event as CompositionEvent).data;
×
1997
    const window = AngularEditor.getWindow(editor);
×
1998
    const domSelection = window.getSelection();
×
1999
    // ensure text node insert composition input text
2000
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2001
        const textNode = domSelection.anchorNode;
×
2002
        textNode.splitText(textNode.length - insertText.length).remove();
×
2003
    }
2004
};
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