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

worktile / slate-angular / 1744f45f-18b4-4122-9fdc-0d5ed9aec40d

22 Jan 2026 10:29AM UTC coverage: 36.14% (-0.03%) from 36.166%
1744f45f-18b4-4122-9fdc-0d5ed9aec40d

push

circleci

pubuzhixing8
refactor(virtual-scroll): improve business logic

402 of 1311 branches covered (30.66%)

Branch coverage included in aggregate %.

0 of 10 new or added lines in 1 file covered. (0.0%)

1109 of 2870 relevant lines covered (38.64%)

23.32 hits per line

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

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

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

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

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

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

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

114
    private initialized: boolean;
115

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

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

120
    @Input() editor: AngularEditor;
121

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

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

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

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

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

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

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

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

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

140
    @Input() placeholder: string;
141

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

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

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

200
    listRender: ListRender;
201

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

524
    ngAfterViewChecked() {}
525

526
    ngDoCheck() {}
527

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

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

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

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

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

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

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

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

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

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

680
    virtualScrollInitialized = false;
23✔
681

682
    virtualTopHeightElement: HTMLElement;
683

684
    virtualBottomHeightElement: HTMLElement;
685

686
    virtualCenterOutlet: HTMLElement;
687

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

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

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

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

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

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

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

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

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

971
    private applyVirtualView(virtualView: VirtualViewResult) {
972
        this.inViewportChildren = virtualView.inViewportChildren;
×
973
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
974
        this.inViewportIndics = virtualView.inViewportIndics;
×
975
    }
976

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

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

1128
    private toSlateSelection() {
1129
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1130
            try {
1✔
1131
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1132
                const { activeElement } = root;
1✔
1133
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1134
                const domSelection = (root as Document).getSelection();
1✔
1135

1136
                if (activeElement === el) {
1!
1137
                    this.latestElement = activeElement;
1✔
1138
                    IS_FOCUSED.set(this.editor, true);
1✔
1139
                } else {
1140
                    IS_FOCUSED.delete(this.editor);
×
1141
                }
1142

1143
                if (!domSelection) {
1!
1144
                    return Transforms.deselect(this.editor);
×
1145
                }
1146

1147
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1148
                const hasDomSelectionInEditor =
1149
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1150
                if (!hasDomSelectionInEditor) {
1!
1151
                    Transforms.deselect(this.editor);
×
1152
                    return;
×
1153
                }
1154

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

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

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

1263
                switch (type) {
×
1264
                    case 'deleteByComposition':
1265
                    case 'deleteByCut':
1266
                    case 'deleteByDrag': {
1267
                        Editor.deleteFragment(editor);
×
1268
                        break;
×
1269
                    }
1270

1271
                    case 'deleteContent':
1272
                    case 'deleteContentForward': {
1273
                        Editor.deleteForward(editor);
×
1274
                        break;
×
1275
                    }
1276

1277
                    case 'deleteContentBackward': {
1278
                        Editor.deleteBackward(editor);
×
1279
                        break;
×
1280
                    }
1281

1282
                    case 'deleteEntireSoftLine': {
1283
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1284
                        Editor.deleteForward(editor, { unit: 'line' });
×
1285
                        break;
×
1286
                    }
1287

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

1293
                    case 'deleteSoftLineBackward': {
1294
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1295
                        break;
×
1296
                    }
1297

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

1303
                    case 'deleteSoftLineForward': {
1304
                        Editor.deleteForward(editor, { unit: 'line' });
×
1305
                        break;
×
1306
                    }
1307

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

1313
                    case 'deleteWordForward': {
1314
                        Editor.deleteForward(editor, { unit: 'word' });
×
1315
                        break;
×
1316
                    }
1317

1318
                    case 'insertLineBreak':
1319
                    case 'insertParagraph': {
1320
                        Editor.insertBreak(editor);
×
1321
                        break;
×
1322
                    }
1323

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

1359
    private onDOMBlur(event: FocusEvent) {
1360
        if (
×
1361
            this.readonly ||
×
1362
            this.isUpdatingSelection ||
1363
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1364
            this.isDOMEventHandled(event, this.blur)
1365
        ) {
1366
            return;
×
1367
        }
1368

1369
        const window = AngularEditor.getWindow(this.editor);
×
1370

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

1380
        const { relatedTarget } = event;
×
1381
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1382

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

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

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

1402
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1403
                return;
×
1404
            }
1405
        }
1406

1407
        IS_FOCUSED.delete(this.editor);
×
1408
    }
1409

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

1422
            const startVoid = Editor.void(this.editor, { at: start });
×
1423
            const endVoid = Editor.void(this.editor, { at: end });
×
1424

1425
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1426
                let blockPath = path;
×
1427
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1428
                    const block = Editor.above(this.editor, {
×
1429
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1430
                        at: path
1431
                    });
1432

1433
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1434
                }
1435

1436
                const range = Editor.range(this.editor, blockPath);
×
1437
                Transforms.select(this.editor, range);
×
1438
                return;
×
1439
            }
1440

1441
            if (
×
1442
                startVoid &&
×
1443
                endVoid &&
1444
                Path.equals(startVoid[1], endVoid[1]) &&
1445
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1446
            ) {
1447
                const range = Editor.range(this.editor, start);
×
1448
                Transforms.select(this.editor, range);
×
1449
            }
1450
        }
1451
    }
1452

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

1468
    private onDOMCompositionUpdate(event: CompositionEvent) {
1469
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1470
    }
1471

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

1486
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1487
            // so we need avoid repeat isnertText by isComposing === true,
1488
            this.isComposing = false;
×
1489
        }
1490
        this.render();
×
1491
    }
1492

1493
    private onDOMCopy(event: ClipboardEvent) {
1494
        const window = AngularEditor.getWindow(this.editor);
×
1495
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1496
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1497
            event.preventDefault();
×
1498
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1499
        }
1500
    }
1501

1502
    private onDOMCut(event: ClipboardEvent) {
1503
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1504
            event.preventDefault();
×
1505
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1506
            const { selection } = this.editor;
×
1507

1508
            if (selection) {
×
1509
                AngularEditor.deleteCutData(this.editor);
×
1510
            }
1511
        }
1512
    }
1513

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

1521
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1522
                event.preventDefault();
×
1523
            }
1524
        }
1525
    }
1526

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

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

1541
            this.isDraggingInternally = true;
×
1542

1543
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1544
        }
1545
    }
1546

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

1554
            // Find the range where the drop happened
1555
            const range = AngularEditor.findEventRange(editor, event);
×
1556
            const data = event.dataTransfer;
×
1557

1558
            Transforms.select(editor, range);
×
1559

1560
            if (this.isDraggingInternally) {
×
1561
                if (draggedRange) {
×
1562
                    Transforms.delete(editor, {
×
1563
                        at: draggedRange
1564
                    });
1565
                }
1566

1567
                this.isDraggingInternally = false;
×
1568
            }
1569

1570
            AngularEditor.insertData(editor, data);
×
1571

1572
            // When dragging from another source into the editor, it's possible
1573
            // that the current editor does not have focus.
1574
            if (!AngularEditor.isFocused(editor)) {
×
1575
                AngularEditor.focus(editor);
×
1576
            }
1577
        }
1578
    }
1579

1580
    private onDOMDragEnd(event: DragEvent) {
1581
        if (
×
1582
            !this.readonly &&
×
1583
            this.isDraggingInternally &&
1584
            AngularEditor.hasTarget(this.editor, event.target) &&
1585
            !this.isDOMEventHandled(event, this.dragEnd)
1586
        ) {
1587
            this.isDraggingInternally = false;
×
1588
        }
1589
    }
1590

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

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

1610
            IS_FOCUSED.set(this.editor, true);
2✔
1611
        }
1612
    }
1613

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

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

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

1639
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1640
                        editor.redo();
×
1641
                    }
1642

1643
                    return;
×
1644
                }
1645

1646
                if (Hotkeys.isUndo(nativeEvent)) {
×
1647
                    event.preventDefault();
×
1648

1649
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1650
                        editor.undo();
×
1651
                    }
1652

1653
                    return;
×
1654
                }
1655

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

1666
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1667
                    event.preventDefault();
×
1668
                    Transforms.move(editor, { unit: 'line' });
×
1669
                    return;
×
1670
                }
1671

1672
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1673
                    event.preventDefault();
×
1674
                    Transforms.move(editor, {
×
1675
                        unit: 'line',
1676
                        edge: 'focus',
1677
                        reverse: true
1678
                    });
1679
                    return;
×
1680
                }
1681

1682
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1683
                    event.preventDefault();
×
1684
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1685
                    return;
×
1686
                }
1687

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

1696
                    if (selection && Range.isCollapsed(selection)) {
×
1697
                        Transforms.move(editor, { reverse: !isRTL });
×
1698
                    } else {
1699
                        Transforms.collapse(editor, { edge: 'start' });
×
1700
                    }
1701

1702
                    return;
×
1703
                }
1704

1705
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1706
                    event.preventDefault();
×
1707
                    if (selection && Range.isCollapsed(selection)) {
×
1708
                        Transforms.move(editor, { reverse: isRTL });
×
1709
                    } else {
1710
                        Transforms.collapse(editor, { edge: 'end' });
×
1711
                    }
1712

1713
                    return;
×
1714
                }
1715

1716
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1717
                    event.preventDefault();
×
1718

1719
                    if (selection && Range.isExpanded(selection)) {
×
1720
                        Transforms.collapse(editor, { edge: 'focus' });
×
1721
                    }
1722

1723
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1724
                    return;
×
1725
                }
1726

1727
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1728
                    event.preventDefault();
×
1729

1730
                    if (selection && Range.isExpanded(selection)) {
×
1731
                        Transforms.collapse(editor, { edge: 'focus' });
×
1732
                    }
1733

1734
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1735
                    return;
×
1736
                }
1737

1738
                if (isKeyHotkey('mod+a', event)) {
×
1739
                    this.editor.selectAll();
×
1740
                    event.preventDefault();
×
1741
                    return;
×
1742
                }
1743

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

1755
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1756
                        event.preventDefault();
×
1757
                        Editor.insertBreak(editor);
×
1758
                        return;
×
1759
                    }
1760

1761
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1762
                        event.preventDefault();
×
1763

1764
                        if (selection && Range.isExpanded(selection)) {
×
1765
                            Editor.deleteFragment(editor, {
×
1766
                                direction: 'backward'
1767
                            });
1768
                        } else {
1769
                            Editor.deleteBackward(editor);
×
1770
                        }
1771

1772
                        return;
×
1773
                    }
1774

1775
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1776
                        event.preventDefault();
×
1777

1778
                        if (selection && Range.isExpanded(selection)) {
×
1779
                            Editor.deleteFragment(editor, {
×
1780
                                direction: 'forward'
1781
                            });
1782
                        } else {
1783
                            Editor.deleteForward(editor);
×
1784
                        }
1785

1786
                        return;
×
1787
                    }
1788

1789
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1790
                        event.preventDefault();
×
1791

1792
                        if (selection && Range.isExpanded(selection)) {
×
1793
                            Editor.deleteFragment(editor, {
×
1794
                                direction: 'backward'
1795
                            });
1796
                        } else {
1797
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1798
                        }
1799

1800
                        return;
×
1801
                    }
1802

1803
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1804
                        event.preventDefault();
×
1805

1806
                        if (selection && Range.isExpanded(selection)) {
×
1807
                            Editor.deleteFragment(editor, {
×
1808
                                direction: 'forward'
1809
                            });
1810
                        } else {
1811
                            Editor.deleteForward(editor, { unit: 'line' });
×
1812
                        }
1813

1814
                        return;
×
1815
                    }
1816

1817
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1818
                        event.preventDefault();
×
1819

1820
                        if (selection && Range.isExpanded(selection)) {
×
1821
                            Editor.deleteFragment(editor, {
×
1822
                                direction: 'backward'
1823
                            });
1824
                        } else {
1825
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1826
                        }
1827

1828
                        return;
×
1829
                    }
1830

1831
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1832
                        event.preventDefault();
×
1833

1834
                        if (selection && Range.isExpanded(selection)) {
×
1835
                            Editor.deleteFragment(editor, {
×
1836
                                direction: 'forward'
1837
                            });
1838
                        } else {
1839
                            Editor.deleteForward(editor, { unit: 'word' });
×
1840
                        }
1841

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

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

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

1923
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1924
        if (!handler) {
3✔
1925
            return false;
3✔
1926
        }
1927
        handler(event);
×
1928
        return event.defaultPrevented;
×
1929
    }
1930
    //#endregion
1931

1932
    ngOnDestroy() {
1933
        this.editorResizeObserver?.disconnect();
22✔
1934
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1935
        this.manualListeners.forEach(manualListener => {
22✔
1936
            manualListener();
462✔
1937
        });
1938
        this.destroy$.complete();
22✔
1939
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1940
    }
1941
}
1942

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

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

1954
        if (isZeroDimensionRect) {
×
1955
            const leafRect = leafEl.getBoundingClientRect();
×
1956
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1957

1958
            if (leafHasDimensions) {
×
1959
                return;
×
1960
            }
1961
        }
1962

1963
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1964
        scrollIntoView(leafEl, {
×
1965
            scrollMode: 'if-needed'
1966
        });
1967
        delete leafEl.getBoundingClientRect;
×
1968
    }
1969
};
1970

1971
/**
1972
 * Check if the target is inside void and in the editor.
1973
 */
1974

1975
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1976
    let slateNode: Node | null = null;
1✔
1977
    try {
1✔
1978
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1979
    } catch (error) {}
1980
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1981
};
1982

1983
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1984
    return (
2✔
1985
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1986
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1987
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1988
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1989
    );
1990
};
1991

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