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

worktile / slate-angular / bb06e937-ff48-40e1-adae-a776a777ee33

14 Jan 2026 11:04AM UTC coverage: 36.456% (-0.1%) from 36.593%
bb06e937-ff48-40e1-adae-a776a777ee33

push

circleci

pubuzhixing8
fix(virtual-scroll): support update pre-rendering element width dynamic when editor width changed and use offsetWidth to remove the effect of scale #WIK-19763

402 of 1305 branches covered (30.8%)

Branch coverage included in aggregate %.

2 of 17 new or added lines in 2 files covered. (11.76%)

1 existing line in 1 file now uncovered.

1108 of 2837 relevant lines covered (39.06%)

23.58 hits per line

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

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

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

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

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

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

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

114
    private initialized: boolean;
115

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

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

120
    @Input() editor: AngularEditor;
121

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

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

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

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

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

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

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

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

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

140
    @Input() placeholder: string;
141

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

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

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

200
    listRender: ListRender;
201

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

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

216
    viewportRefresh$ = new Subject<void>();
23✔
217

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

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

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

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

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

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

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

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

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

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

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

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

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

411
            const hasDomSelection = domSelection.type !== 'None';
1✔
412

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

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

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

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

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

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

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

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

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

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

518
    ngAfterViewChecked() {}
519

520
    ngDoCheck() {}
521

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

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

581
    updateListRenderAndRemeasureHeights() {
582
        let virtualView = this.calculateVirtualViewport();
×
583
        let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
584
        if (diff.isDifferent && diff.needRemoveOnTop) {
×
585
            const remeasureIndics = diff.changedIndexesOfTop;
×
586
            const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
587
            if (changed) {
×
588
                virtualView = this.calculateVirtualViewport();
×
589
                diff = this.diffVirtualViewport(virtualView, 'second');
×
590
            }
591
        }
592
        // const oldInViewportChildren = this.inViewportChildren;
593
        this.applyVirtualView(virtualView);
×
594
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
595
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
596
        // 新增或者修改的才需要重算,计算出这个结果
597
        // const remeasureIndics = [];
598
        // this.inViewportChildren.forEach((child, index) => {
599
        //     if (oldInViewportChildren.indexOf(child) === -1) {
600
        //         remeasureIndics.push(this.inViewportIndics[index]);
601
        //     }
602
        // });
603
        this.viewportRefresh$.next();
×
604
    }
605

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

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

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

647
    composePlaceholderDecorate(editor: Editor) {
648
        if (this.placeholderDecorate) {
64!
649
            return this.placeholderDecorate(editor) || [];
×
650
        }
651

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

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

673
    private isEnabledVirtualScroll() {
674
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
675
    }
676

677
    virtualScrollInitialized = false;
23✔
678

679
    virtualTopHeightElement: HTMLElement;
680

681
    virtualBottomHeightElement: HTMLElement;
682

683
    virtualCenterOutlet: HTMLElement;
684

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

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

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

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

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

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

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

929
        const inViewportEndIndex =
930
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
931
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
932
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
933
        return {
×
934
            inViewportChildren: visible.length ? visible : children,
×
935
            inViewportIndics,
936
            top,
937
            bottom,
938
            heights,
939
            accumulatedHeights
940
        };
941
    }
942

943
    private applyVirtualView(virtualView: VirtualViewResult) {
944
        this.inViewportChildren = virtualView.inViewportChildren;
×
945
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
946
        this.inViewportIndics = virtualView.inViewportIndics;
×
947
    }
948

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

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

1100
    private toSlateSelection() {
1101
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1102
            try {
1✔
1103
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1104
                const { activeElement } = root;
1✔
1105
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1106
                const domSelection = (root as Document).getSelection();
1✔
1107

1108
                if (activeElement === el) {
1!
1109
                    this.latestElement = activeElement;
1✔
1110
                    IS_FOCUSED.set(this.editor, true);
1✔
1111
                } else {
1112
                    IS_FOCUSED.delete(this.editor);
×
1113
                }
1114

1115
                if (!domSelection) {
1!
1116
                    return Transforms.deselect(this.editor);
×
1117
                }
1118

1119
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1120
                const hasDomSelectionInEditor =
1121
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1122
                if (!hasDomSelectionInEditor) {
1!
1123
                    Transforms.deselect(this.editor);
×
1124
                    return;
×
1125
                }
1126

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

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

1227
                // COMPAT: If the selection is expanded, even if the command seems like
1228
                // a delete forward/backward command it should delete the selection.
1229
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1230
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1231
                    Editor.deleteFragment(editor, { direction });
×
1232
                    return;
×
1233
                }
1234

1235
                switch (type) {
×
1236
                    case 'deleteByComposition':
1237
                    case 'deleteByCut':
1238
                    case 'deleteByDrag': {
1239
                        Editor.deleteFragment(editor);
×
1240
                        break;
×
1241
                    }
1242

1243
                    case 'deleteContent':
1244
                    case 'deleteContentForward': {
1245
                        Editor.deleteForward(editor);
×
1246
                        break;
×
1247
                    }
1248

1249
                    case 'deleteContentBackward': {
1250
                        Editor.deleteBackward(editor);
×
1251
                        break;
×
1252
                    }
1253

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

1260
                    case 'deleteHardLineBackward': {
1261
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1262
                        break;
×
1263
                    }
1264

1265
                    case 'deleteSoftLineBackward': {
1266
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1267
                        break;
×
1268
                    }
1269

1270
                    case 'deleteHardLineForward': {
1271
                        Editor.deleteForward(editor, { unit: 'block' });
×
1272
                        break;
×
1273
                    }
1274

1275
                    case 'deleteSoftLineForward': {
1276
                        Editor.deleteForward(editor, { unit: 'line' });
×
1277
                        break;
×
1278
                    }
1279

1280
                    case 'deleteWordBackward': {
1281
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1282
                        break;
×
1283
                    }
1284

1285
                    case 'deleteWordForward': {
1286
                        Editor.deleteForward(editor, { unit: 'word' });
×
1287
                        break;
×
1288
                    }
1289

1290
                    case 'insertLineBreak':
1291
                    case 'insertParagraph': {
1292
                        Editor.insertBreak(editor);
×
1293
                        break;
×
1294
                    }
1295

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

1331
    private onDOMBlur(event: FocusEvent) {
1332
        if (
×
1333
            this.readonly ||
×
1334
            this.isUpdatingSelection ||
1335
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1336
            this.isDOMEventHandled(event, this.blur)
1337
        ) {
1338
            return;
×
1339
        }
1340

1341
        const window = AngularEditor.getWindow(this.editor);
×
1342

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

1352
        const { relatedTarget } = event;
×
1353
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1354

1355
        // COMPAT: The event should be ignored if the focus is returning
1356
        // to the editor from an embedded editable element (eg. an <input>
1357
        // element inside a void node).
1358
        if (relatedTarget === el) {
×
1359
            return;
×
1360
        }
1361

1362
        // COMPAT: The event should be ignored if the focus is moving from
1363
        // the editor to inside a void node's spacer element.
1364
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1365
            return;
×
1366
        }
1367

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

1374
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1375
                return;
×
1376
            }
1377
        }
1378

1379
        IS_FOCUSED.delete(this.editor);
×
1380
    }
1381

1382
    private onDOMClick(event: MouseEvent) {
1383
        if (
×
1384
            !this.readonly &&
×
1385
            AngularEditor.hasTarget(this.editor, event.target) &&
1386
            !this.isDOMEventHandled(event, this.click) &&
1387
            isDOMNode(event.target)
1388
        ) {
1389
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1390
            const path = AngularEditor.findPath(this.editor, node);
×
1391
            const start = Editor.start(this.editor, path);
×
1392
            const end = Editor.end(this.editor, path);
×
1393

1394
            const startVoid = Editor.void(this.editor, { at: start });
×
1395
            const endVoid = Editor.void(this.editor, { at: end });
×
1396

1397
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1398
                let blockPath = path;
×
1399
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1400
                    const block = Editor.above(this.editor, {
×
1401
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1402
                        at: path
1403
                    });
1404

1405
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1406
                }
1407

1408
                const range = Editor.range(this.editor, blockPath);
×
1409
                Transforms.select(this.editor, range);
×
1410
                return;
×
1411
            }
1412

1413
            if (
×
1414
                startVoid &&
×
1415
                endVoid &&
1416
                Path.equals(startVoid[1], endVoid[1]) &&
1417
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1418
            ) {
1419
                const range = Editor.range(this.editor, start);
×
1420
                Transforms.select(this.editor, range);
×
1421
            }
1422
        }
1423
    }
1424

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

1440
    private onDOMCompositionUpdate(event: CompositionEvent) {
1441
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1442
    }
1443

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

1458
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1459
            // so we need avoid repeat isnertText by isComposing === true,
1460
            this.isComposing = false;
×
1461
        }
1462
        this.render();
×
1463
    }
1464

1465
    private onDOMCopy(event: ClipboardEvent) {
1466
        const window = AngularEditor.getWindow(this.editor);
×
1467
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1468
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1469
            event.preventDefault();
×
1470
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1471
        }
1472
    }
1473

1474
    private onDOMCut(event: ClipboardEvent) {
1475
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1476
            event.preventDefault();
×
1477
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1478
            const { selection } = this.editor;
×
1479

1480
            if (selection) {
×
1481
                AngularEditor.deleteCutData(this.editor);
×
1482
            }
1483
        }
1484
    }
1485

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

1493
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1494
                event.preventDefault();
×
1495
            }
1496
        }
1497
    }
1498

1499
    private onDOMDragStart(event: DragEvent) {
1500
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1501
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1502
            const path = AngularEditor.findPath(this.editor, node);
×
1503
            const voidMatch =
1504
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1505

1506
            // If starting a drag on a void node, make sure it is selected
1507
            // so that it shows up in the selection's fragment.
1508
            if (voidMatch) {
×
1509
                const range = Editor.range(this.editor, path);
×
1510
                Transforms.select(this.editor, range);
×
1511
            }
1512

1513
            this.isDraggingInternally = true;
×
1514

1515
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1516
        }
1517
    }
1518

1519
    private onDOMDrop(event: DragEvent) {
1520
        const editor = this.editor;
×
1521
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1522
            event.preventDefault();
×
1523
            // Keep a reference to the dragged range before updating selection
1524
            const draggedRange = editor.selection;
×
1525

1526
            // Find the range where the drop happened
1527
            const range = AngularEditor.findEventRange(editor, event);
×
1528
            const data = event.dataTransfer;
×
1529

1530
            Transforms.select(editor, range);
×
1531

1532
            if (this.isDraggingInternally) {
×
1533
                if (draggedRange) {
×
1534
                    Transforms.delete(editor, {
×
1535
                        at: draggedRange
1536
                    });
1537
                }
1538

1539
                this.isDraggingInternally = false;
×
1540
            }
1541

1542
            AngularEditor.insertData(editor, data);
×
1543

1544
            // When dragging from another source into the editor, it's possible
1545
            // that the current editor does not have focus.
1546
            if (!AngularEditor.isFocused(editor)) {
×
1547
                AngularEditor.focus(editor);
×
1548
            }
1549
        }
1550
    }
1551

1552
    private onDOMDragEnd(event: DragEvent) {
1553
        if (
×
1554
            !this.readonly &&
×
1555
            this.isDraggingInternally &&
1556
            AngularEditor.hasTarget(this.editor, event.target) &&
1557
            !this.isDOMEventHandled(event, this.dragEnd)
1558
        ) {
1559
            this.isDraggingInternally = false;
×
1560
        }
1561
    }
1562

1563
    private onDOMFocus(event: Event) {
1564
        if (
2✔
1565
            !this.readonly &&
8✔
1566
            !this.isUpdatingSelection &&
1567
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1568
            !this.isDOMEventHandled(event, this.focus)
1569
        ) {
1570
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1571
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1572
            this.latestElement = root.activeElement;
2✔
1573

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

1582
            IS_FOCUSED.set(this.editor, true);
2✔
1583
        }
1584
    }
1585

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

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

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

1611
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1612
                        editor.redo();
×
1613
                    }
1614

1615
                    return;
×
1616
                }
1617

1618
                if (Hotkeys.isUndo(nativeEvent)) {
×
1619
                    event.preventDefault();
×
1620

1621
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1622
                        editor.undo();
×
1623
                    }
1624

1625
                    return;
×
1626
                }
1627

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

1638
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1639
                    event.preventDefault();
×
1640
                    Transforms.move(editor, { unit: 'line' });
×
1641
                    return;
×
1642
                }
1643

1644
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1645
                    event.preventDefault();
×
1646
                    Transforms.move(editor, {
×
1647
                        unit: 'line',
1648
                        edge: 'focus',
1649
                        reverse: true
1650
                    });
1651
                    return;
×
1652
                }
1653

1654
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1655
                    event.preventDefault();
×
1656
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1657
                    return;
×
1658
                }
1659

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

1668
                    if (selection && Range.isCollapsed(selection)) {
×
1669
                        Transforms.move(editor, { reverse: !isRTL });
×
1670
                    } else {
1671
                        Transforms.collapse(editor, { edge: 'start' });
×
1672
                    }
1673

1674
                    return;
×
1675
                }
1676

1677
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1678
                    event.preventDefault();
×
1679
                    if (selection && Range.isCollapsed(selection)) {
×
1680
                        Transforms.move(editor, { reverse: isRTL });
×
1681
                    } else {
1682
                        Transforms.collapse(editor, { edge: 'end' });
×
1683
                    }
1684

1685
                    return;
×
1686
                }
1687

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

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

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

1699
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1700
                    event.preventDefault();
×
1701

1702
                    if (selection && Range.isExpanded(selection)) {
×
1703
                        Transforms.collapse(editor, { edge: 'focus' });
×
1704
                    }
1705

1706
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1707
                    return;
×
1708
                }
1709

1710
                if (isKeyHotkey('mod+a', event)) {
×
1711
                    this.editor.selectAll();
×
1712
                    event.preventDefault();
×
1713
                    return;
×
1714
                }
1715

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

1727
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1728
                        event.preventDefault();
×
1729
                        Editor.insertBreak(editor);
×
1730
                        return;
×
1731
                    }
1732

1733
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1734
                        event.preventDefault();
×
1735

1736
                        if (selection && Range.isExpanded(selection)) {
×
1737
                            Editor.deleteFragment(editor, {
×
1738
                                direction: 'backward'
1739
                            });
1740
                        } else {
1741
                            Editor.deleteBackward(editor);
×
1742
                        }
1743

1744
                        return;
×
1745
                    }
1746

1747
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1748
                        event.preventDefault();
×
1749

1750
                        if (selection && Range.isExpanded(selection)) {
×
1751
                            Editor.deleteFragment(editor, {
×
1752
                                direction: 'forward'
1753
                            });
1754
                        } else {
1755
                            Editor.deleteForward(editor);
×
1756
                        }
1757

1758
                        return;
×
1759
                    }
1760

1761
                    if (Hotkeys.isDeleteLineBackward(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, { unit: 'line' });
×
1770
                        }
1771

1772
                        return;
×
1773
                    }
1774

1775
                    if (Hotkeys.isDeleteLineForward(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, { unit: 'line' });
×
1784
                        }
1785

1786
                        return;
×
1787
                    }
1788

1789
                    if (Hotkeys.isDeleteWordBackward(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: 'word' });
×
1798
                        }
1799

1800
                        return;
×
1801
                    }
1802

1803
                    if (Hotkeys.isDeleteWordForward(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: 'word' });
×
1812
                        }
1813

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

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

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

1895
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1896
        if (!handler) {
3✔
1897
            return false;
3✔
1898
        }
1899
        handler(event);
×
1900
        return event.defaultPrevented;
×
1901
    }
1902
    //#endregion
1903

1904
    ngOnDestroy() {
1905
        this.editorResizeObserver?.disconnect();
22✔
1906
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1907
        this.manualListeners.forEach(manualListener => {
22✔
1908
            manualListener();
462✔
1909
        });
1910
        this.destroy$.complete();
22✔
1911
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1912
    }
1913
}
1914

1915
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1916
    // This was affecting the selection of multiple blocks and dragging behavior,
1917
    // so enabled only if the selection has been collapsed.
1918
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1919
        const leafEl = domRange.startContainer.parentElement!;
×
1920

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

1926
        if (isZeroDimensionRect) {
×
1927
            const leafRect = leafEl.getBoundingClientRect();
×
1928
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1929

1930
            if (leafHasDimensions) {
×
1931
                return;
×
1932
            }
1933
        }
1934

1935
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1936
        scrollIntoView(leafEl, {
×
1937
            scrollMode: 'if-needed'
1938
        });
1939
        delete leafEl.getBoundingClientRect;
×
1940
    }
1941
};
1942

1943
/**
1944
 * Check if the target is inside void and in the editor.
1945
 */
1946

1947
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1948
    let slateNode: Node | null = null;
1✔
1949
    try {
1✔
1950
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1951
    } catch (error) {}
1952
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1953
};
1954

1955
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1956
    return (
2✔
1957
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1958
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1959
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1960
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1961
    );
1962
};
1963

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