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

worktile / slate-angular / 59321b40-1217-4b12-910a-f7f0a32c1b6d

27 Jan 2026 09:51AM UTC coverage: 35.778% (-0.5%) from 36.293%
59321b40-1217-4b12-910a-f7f0a32c1b6d

push

circleci

pubuzhixing8
fix(virtual-scroll): should prevent execution toNativeSelection when window.getSelection() is not in editor

405 of 1335 branches covered (30.34%)

Branch coverage included in aggregate %.

2 of 2 new or added lines in 1 file covered. (100.0%)

13 existing lines in 2 files now uncovered.

1112 of 2905 relevant lines covered (38.28%)

23.07 hits per line

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

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

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

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

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

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

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

114
    private initialized: boolean;
115

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

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

120
    @Input() editor: AngularEditor;
121

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

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

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

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

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

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

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

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

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

140
    @Input() placeholder: string;
141

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

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

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

200
    listRender: ListRender;
201

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

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

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

218
    virtualScrollInitialized = false;
23✔
219

220
    virtualTopHeightElement: HTMLElement;
221

222
    virtualBottomHeightElement: HTMLElement;
223

224
    virtualCenterOutlet: HTMLElement;
225

226
    constructor(
227
        public elementRef: ElementRef,
23✔
228
        public renderer2: Renderer2,
23✔
229
        public cdr: ChangeDetectorRef,
23✔
230
        private ngZone: NgZone,
23✔
231
        private injector: Injector
23✔
232
    ) {}
233

234
    ngOnInit() {
235
        this.editor.injector = this.injector;
23✔
236
        this.editor.children = [];
23✔
237
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
238
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
239
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
240
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
241
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
242
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
243
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
244
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
245
            this.ngZone.run(() => {
13✔
246
                this.onChange();
13✔
247
            });
248
        });
249
        this.ngZone.runOutsideAngular(() => {
23✔
250
            this.initialize();
23✔
251
        });
252
        this.initializeViewContext();
23✔
253
        this.initializeContext();
23✔
254

255
        // add browser class
256
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
257
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
258
        this.initializeVirtualScroll();
23✔
259
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
260
    }
261

262
    ngOnChanges(simpleChanges: SimpleChanges) {
263
        if (!this.initialized) {
30✔
264
            return;
23✔
265
        }
266
        const decorateChange = simpleChanges['decorate'];
7✔
267
        if (decorateChange) {
7✔
268
            this.forceRender();
2✔
269
        }
270
        const placeholderChange = simpleChanges['placeholder'];
7✔
271
        if (placeholderChange) {
7✔
272
            this.render();
1✔
273
        }
274
        const readonlyChange = simpleChanges['readonly'];
7✔
275
        if (readonlyChange) {
7!
276
            IS_READ_ONLY.set(this.editor, this.readonly);
×
277
            this.render();
×
278
            this.toSlateSelection();
×
279
        }
280
    }
281

282
    registerOnChange(fn: any) {
283
        this.onChangeCallback = fn;
23✔
284
    }
285
    registerOnTouched(fn: any) {
286
        this.onTouchedCallback = fn;
23✔
287
    }
288

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

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

362
    private isEnabledVirtualScroll() {
363
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
364
    }
365

366
    initializeVirtualScroll() {
367
        if (this.virtualScrollInitialized) {
23!
368
            return;
×
369
        }
370
        if (this.isEnabledVirtualScroll()) {
23!
371
            this.virtualScrollInitialized = true;
×
372
            this.virtualTopHeightElement = document.createElement('div');
×
373
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
374
            this.virtualTopHeightElement.contentEditable = 'false';
×
375
            this.virtualBottomHeightElement = document.createElement('div');
×
376
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
377
            this.virtualBottomHeightElement.contentEditable = 'false';
×
378
            this.virtualCenterOutlet = document.createElement('div');
×
379
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
380
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
381
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
382
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
383
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
384
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.offsetWidth);
×
385
            this.editorResizeObserver = new ResizeObserver(entries => {
×
386
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
387
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
388
                    this.keyHeightMap.clear();
×
389
                    let target = this.virtualTopHeightElement;
×
390
                    if (this.inViewportChildren[0]) {
×
391
                        const firstElement = this.inViewportChildren[0];
×
392
                        const firstDomElement = AngularEditor.toDOMNode(this.editor, firstElement);
×
393
                        target = firstDomElement;
×
394
                    }
395
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, target.offsetWidth);
×
396
                    updatePreRenderingElementWidth(this.editor);
×
397
                    if (isDebug) {
×
398
                        debugLog(
×
399
                            'log',
400
                            'editorResizeObserverRectWidth: ',
401
                            editorResizeObserverRectWidth,
402
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
403
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
404
                        );
405
                    }
406
                }
407
            });
408
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
409

410
            let pendingRemeasureIndics: number[] = [];
×
411
            this.indicsOfNeedBeMeasured$
×
412
                .pipe(
413
                    tap((previousValue: number[]) => {
414
                        previousValue.forEach((index: number) => {
×
415
                            if (!pendingRemeasureIndics.includes(index)) {
×
416
                                pendingRemeasureIndics.push(index);
×
417
                            }
418
                        });
419
                    }),
420
                    debounceTime(500),
421
                    filter(() => pendingRemeasureIndics.length > 0)
×
422
                )
423
                .subscribe(() => {
424
                    const changed = measureHeightByIndics(this.editor, pendingRemeasureIndics, true);
×
425
                    if (changed) {
×
426
                        this.tryUpdateVirtualViewport();
×
427
                        if (isDebug) {
×
428
                            debugLog(
×
429
                                'log',
430
                                'exist pendingRemeasureIndics: ',
431
                                pendingRemeasureIndics,
432
                                'will try to update virtual viewport'
433
                            );
434
                        }
435
                    }
436
                    pendingRemeasureIndics = [];
×
437
                });
438
        }
439
    }
440

441
    getChangedIndics(previousValue: Descendant[]) {
442
        const remeasureIndics = [];
×
443
        this.inViewportChildren.forEach((child, index) => {
×
444
            if (previousValue.indexOf(child) === -1) {
×
445
                remeasureIndics.push(this.inViewportIndics[index]);
×
446
            }
447
        });
448
        return remeasureIndics;
×
449
    }
450

451
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
452
        if (!this.virtualScrollInitialized) {
×
453
            return;
×
454
        }
455
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
456
        if (bottomHeight !== undefined) {
×
457
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
458
        }
459
    }
460

461
    getActualVirtualTopHeight() {
462
        if (!this.virtualScrollInitialized) {
×
463
            return 0;
×
464
        }
465
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
466
    }
467

468
    handlePreRendering(visibleStates: boolean[]) {
469
        let preRenderingCount = 0;
×
470
        const childrenWithPreRendering = [...this.inViewportChildren];
×
471
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
472
        const firstIndex = this.inViewportIndics[0];
×
473
        for (let index = firstIndex - 1; index >= 0; index--) {
×
474
            const element = this.editor.children[index] as Element;
×
475
            if (visibleStates[index]) {
×
476
                childrenWithPreRendering.unshift(element);
×
477
                childrenWithPreRenderingIndics.unshift(index);
×
478
                preRenderingCount = 1;
×
479
                break;
×
480
            }
481
        }
482
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
483
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
484
            const element = this.editor.children[index] as Element;
×
485
            if (visibleStates[index]) {
×
486
                childrenWithPreRendering.push(element);
×
487
                childrenWithPreRenderingIndics.push(index);
×
488
                break;
×
489
            }
490
        }
491
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
492
    }
493

494
    private tryUpdateVirtualViewport() {
495
        if (isDebug) {
×
496
            debugLog('log', 'tryUpdateVirtualViewport');
×
497
        }
498
        const isFromScrollTo = EDITOR_TO_IS_FROM_SCROLL_TO.get(this.editor);
×
499
        if (this.inViewportIndics.length > 0 && !isFromScrollTo) {
×
500
            const topHeight = this.getActualVirtualTopHeight();
×
501
            const visibleStates = this.editor.getAllVisibleStates();
×
502
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0], visibleStates);
×
503
            if (topHeight !== refreshVirtualTopHeight) {
×
504
                if (isDebug) {
×
505
                    debugLog(
×
506
                        'log',
507
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
508
                        topHeight - refreshVirtualTopHeight
509
                    );
510
                }
511
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
512
                return;
×
513
            }
514
        }
515
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
516
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
517
            if (isDebug) {
×
518
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
519
            }
520
            const visibleStates = this.editor.getAllVisibleStates();
×
521
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
522
            let diff = this.diffVirtualViewport(virtualView);
×
523
            if (diff.isDifferent && diff.needRemoveOnTop && !isFromScrollTo) {
×
524
                const remeasureIndics = diff.changedIndexesOfTop;
×
525
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
526
                if (changed) {
×
527
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
528
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
529
                }
530
            }
531
            if (diff.isDifferent) {
×
532
                this.applyVirtualView(virtualView);
×
533
                if (this.listRender.initialized) {
×
534
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
535
                        this.handlePreRendering(visibleStates);
×
536
                    this.listRender.update(
×
537
                        childrenWithPreRendering,
538
                        this.editor,
539
                        this.context,
540
                        preRenderingCount,
541
                        childrenWithPreRenderingIndics
542
                    );
543
                    if (diff.needAddOnTop && !isFromScrollTo) {
×
544
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
545
                        if (isDebug) {
×
546
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
547
                        }
548
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
549
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
550
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
551
                        if (changed) {
×
552
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
553
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
554
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
555
                            this.setVirtualSpaceHeight(newTopHeight);
×
556
                            if (isDebug) {
×
557
                                debugLog(
×
558
                                    'log',
559
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
560
                                );
561
                            }
562
                        }
563
                    }
564
                    if (this.editor.selection) {
×
565
                        this.toNativeSelection(false);
×
566
                    }
567
                }
568
            }
569
            if (isDebug) {
×
570
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
571
            }
572
        });
573
    }
574

575
    private calculateVirtualViewport(visibleStates: boolean[]) {
576
        const children = (this.editor.children || []) as Element[];
×
577
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
578
            return {
×
579
                inViewportChildren: children,
580
                inViewportIndics: [],
581
                top: 0,
582
                bottom: 0,
583
                heights: []
584
            };
585
        }
586
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
587
        let viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
588
        if (!viewportHeight) {
×
589
            return {
×
590
                inViewportChildren: [],
591
                inViewportIndics: [],
592
                top: 0,
593
                bottom: 0,
594
                heights: []
595
            };
596
        }
597
        const elementLength = children.length;
×
598
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
599
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
600
            setTimeout(() => {
×
601
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
602
                const businessTop =
603
                    Math.ceil(virtualTopBoundingTop) +
×
604
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
605
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
606
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
607
                if (isDebug) {
×
608
                    debugLog('log', 'businessTop', businessTop);
×
609
                    this.virtualTopHeightElement.setAttribute('data-business-top', businessTop.toString());
×
610
                }
611
            }, 100);
612
        }
613
        const businessTop = getBusinessTop(this.editor);
×
614
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
615
        const totalHeight = accumulatedHeights[elementLength] + businessTop;
×
616
        let startPosition = Math.max(scrollTop - businessTop, 0);
×
617
        let endPosition = startPosition + viewportHeight;
×
618
        if (scrollTop < businessTop) {
×
619
            endPosition = startPosition + viewportHeight - (businessTop - scrollTop);
×
620
        }
621
        let accumulatedOffset = 0;
×
622
        let inViewportStartIndex = -1;
×
623
        const visible: Element[] = [];
×
624
        const inViewportIndics: number[] = [];
×
625
        for (let i = 0; i < elementLength && accumulatedOffset < endPosition; i++) {
×
626
            const currentHeight = heights[i];
×
627
            const nextOffset = accumulatedOffset + currentHeight;
×
628
            const isVisible = visibleStates[i];
×
629
            if (!isVisible) {
×
630
                accumulatedOffset = nextOffset;
×
631
                continue;
×
632
            }
633
            // 可视区域有交集,加入渲染
634
            if (nextOffset > startPosition && accumulatedOffset < endPosition) {
×
635
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
636
                visible.push(children[i]);
×
637
                inViewportIndics.push(i);
×
638
            }
639
            accumulatedOffset = nextOffset;
×
640
        }
641

642
        const inViewportEndIndex =
643
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
644
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
645
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
646
        return {
×
647
            inViewportChildren: visible.length ? visible : children,
×
648
            inViewportIndics,
649
            top,
650
            bottom,
651
            heights,
652
            accumulatedHeights
653
        };
654
    }
655

656
    private applyVirtualView(virtualView: VirtualViewResult) {
657
        this.inViewportChildren = virtualView.inViewportChildren;
×
658
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
659
        this.inViewportIndics = virtualView.inViewportIndics;
×
660
    }
661

662
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
663
        if (!this.inViewportChildren.length) {
×
664
            if (isDebug) {
×
665
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
666
            }
667
            return {
×
668
                isDifferent: true,
669
                changedIndexesOfTop: [],
670
                changedIndexesOfBottom: []
671
            };
672
        }
673
        const oldIndexesInViewport = [...this.inViewportIndics];
×
674
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
675
        const firstNewIndex = newIndexesInViewport[0];
×
676
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
677
        const firstOldIndex = oldIndexesInViewport[0];
×
678
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
679
        const isSameViewport =
680
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
681
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
682
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
683
            return {
×
684
                isDifferent: !isSameViewport,
685
                changedIndexesOfTop: [],
686
                changedIndexesOfBottom: []
687
            };
688
        }
689
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
690
            const changedIndexesOfTop = [];
×
691
            const changedIndexesOfBottom = [];
×
692
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
693
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
694
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
695
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
696
            if (needRemoveOnTop || needAddOnBottom) {
×
697
                // 向下
698
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
699
                    const element = oldIndexesInViewport[index];
×
700
                    if (!newIndexesInViewport.includes(element)) {
×
701
                        changedIndexesOfTop.push(element);
×
702
                    } else {
703
                        break;
×
704
                    }
705
                }
706
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
707
                    const element = newIndexesInViewport[index];
×
708
                    if (!oldIndexesInViewport.includes(element)) {
×
709
                        changedIndexesOfBottom.push(element);
×
710
                    } else {
711
                        break;
×
712
                    }
713
                }
714
            } else if (needAddOnTop || needRemoveOnBottom) {
×
715
                // 向上
716
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
717
                    const element = newIndexesInViewport[index];
×
718
                    if (!oldIndexesInViewport.includes(element)) {
×
719
                        changedIndexesOfTop.push(element);
×
720
                    } else {
721
                        break;
×
722
                    }
723
                }
724
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
725
                    const element = oldIndexesInViewport[index];
×
726
                    if (!newIndexesInViewport.includes(element)) {
×
727
                        changedIndexesOfBottom.push(element);
×
728
                    } else {
729
                        break;
×
730
                    }
731
                }
732
            }
733
            if (isDebug) {
×
734
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
735
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
736
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
737
                // this.editor.children[index] will be undefined when it is removed
738
                debugLog(
×
739
                    'log',
740
                    'changedIndexesOfTop:',
741
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
742
                    changedIndexesOfTop,
743
                    changedIndexesOfTop.map(
744
                        index =>
745
                            (this.editor.children[index] &&
×
746
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
747
                            0
748
                    )
749
                );
750
                debugLog(
×
751
                    'log',
752
                    'changedIndexesOfBottom:',
753
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
754
                    changedIndexesOfBottom,
755
                    changedIndexesOfBottom.map(
756
                        index =>
757
                            (this.editor.children[index] &&
×
758
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
759
                            0
760
                    )
761
                );
762
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
763
                const needBottom = virtualView.heights
×
764
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
765
                    .reduce((acc, height) => acc + height, 0);
×
766
                debugLog(
×
767
                    'log',
768
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
769
                    'newTopHeight:',
770
                    needTop,
771
                    'prevTopHeight:',
772
                    parseFloat(this.virtualTopHeightElement.style.height)
773
                );
774
                debugLog(
×
775
                    'log',
776
                    'newBottomHeight:',
777
                    needBottom,
778
                    'prevBottomHeight:',
779
                    parseFloat(this.virtualBottomHeightElement.style.height)
780
                );
781
                debugLog('warn', '=========== Dividing line ===========');
×
782
            }
783
            return {
×
784
                isDifferent: true,
785
                needRemoveOnTop,
786
                needAddOnTop,
787
                needRemoveOnBottom,
788
                needAddOnBottom,
789
                changedIndexesOfTop,
790
                changedIndexesOfBottom
791
            };
792
        }
793
        return {
×
794
            isDifferent: false,
795
            changedIndexesOfTop: [],
796
            changedIndexesOfBottom: []
797
        };
798
    }
799

800
    //#region event proxy
801
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
802
        this.manualListeners.push(
483✔
803
            this.renderer2.listen(target, eventName, (event: Event) => {
804
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
805
                if (beforeInputEvent) {
5!
806
                    this.onFallbackBeforeInput(beforeInputEvent);
×
807
                }
808
                listener(event);
5✔
809
            })
810
        );
811
    }
812

813
    calculateVirtualScrollSelection(selection: Selection) {
814
        if (selection) {
×
815
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
816
            const indics = this.inViewportIndics;
×
817
            if (indics.length > 0) {
×
818
                const currentVisibleRange: Range = {
×
819
                    anchor: Editor.start(this.editor, [indics[0]]),
820
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
821
                };
822
                const [start, end] = Range.edges(selection);
×
823
                let forwardSelection = { anchor: start, focus: end };
×
824
                if (!isBlockCardCursor) {
×
825
                    forwardSelection = { anchor: start, focus: end };
×
826
                } else {
827
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
828
                }
829
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
830
                if (intersectedSelection && isBlockCardCursor) {
×
831
                    return selection;
×
832
                }
833
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
834
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
835
                    if (isDebug) {
×
836
                        debugLog(
×
837
                            'log',
838
                            `selection is not in visible range, selection: ${JSON.stringify(
839
                                selection
840
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
841
                        );
842
                    }
843
                    return intersectedSelection;
×
844
                }
845
                return selection;
×
846
            }
847
        }
848
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
849
        return selection;
×
850
    }
851

852
    private isSelectionInvisible(selection: Selection) {
853
        const anchorIndex = selection.anchor.path[0];
6✔
854
        const focusIndex = selection.focus.path[0];
6✔
855
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
856
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
857
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
858
    }
859

860
    toNativeSelection(autoScroll = true) {
15✔
861
        try {
15✔
862
            let { selection } = this.editor;
15✔
863

864
            if (this.isEnabledVirtualScroll()) {
15!
865
                selection = this.calculateVirtualScrollSelection(selection);
×
866
            }
867

868
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
869
            const { activeElement } = root;
15✔
870
            const domSelection = (root as Document).getSelection();
15✔
871

872
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
873
                return;
×
874
            }
875

876
            const hasDomSelection = domSelection.type !== 'None';
15✔
877

878
            // If the DOM selection is properly unset, we're done.
879
            if (!selection && !hasDomSelection) {
15✔
880
                return;
9✔
881
            }
882

883
            // If the DOM selection is already correct, we're done.
884
            // verify that the dom selection is in the editor
885
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
6✔
886
            let hasDomSelectionInEditor = false;
6✔
887
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
6✔
888
                hasDomSelectionInEditor = true;
1✔
889
            }
890

891
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
6✔
892
                return;
5✔
893
            }
894

895
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
896
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
897
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
898
                    exactMatch: false,
899
                    suppressThrow: true
900
                });
901
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
902
                    return;
×
903
                }
904
            }
905

906
            // prevent updating native selection when active element is void element
907
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
908
                return;
×
909
            }
910

911
            // when <Editable/> is being controlled through external value
912
            // then its children might just change - DOM responds to it on its own
913
            // but Slate's value is not being updated through any operation
914
            // and thus it doesn't transform selection on its own
915
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
916
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
917
                return;
×
918
            }
919

920
            // Otherwise the DOM selection is out of sync, so update it.
921
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
922
            this.isUpdatingSelection = true;
1✔
923

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

926
            if (newDomRange) {
1!
927
                // COMPAT: Since the DOM range has no concept of backwards/forwards
928
                // we need to check and do the right thing here.
929
                if (Range.isBackward(selection)) {
1!
930
                    // eslint-disable-next-line max-len
931
                    domSelection.setBaseAndExtent(
×
932
                        newDomRange.endContainer,
933
                        newDomRange.endOffset,
934
                        newDomRange.startContainer,
935
                        newDomRange.startOffset
936
                    );
937
                } else {
938
                    // eslint-disable-next-line max-len
939
                    domSelection.setBaseAndExtent(
1✔
940
                        newDomRange.startContainer,
941
                        newDomRange.startOffset,
942
                        newDomRange.endContainer,
943
                        newDomRange.endOffset
944
                    );
945
                }
946
            } else {
UNCOV
947
                domSelection.removeAllRanges();
×
948
            }
949

950
            setTimeout(() => {
1✔
951
                if (
1!
952
                    this.isEnabledVirtualScroll() &&
1!
953
                    !selection &&
954
                    this.editor.selection &&
955
                    autoScroll &&
956
                    this.virtualScrollConfig.scrollContainer
957
                ) {
958
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
959
                    this.isUpdatingSelection = false;
×
960
                    return;
×
961
                } else {
962
                    // handle scrolling in setTimeout because of
963
                    // dom should not have updated immediately after listRender's updating
964
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
965
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
966
                    // to focus the contenteditable element too. (2016/11/16)
967
                    if (newDomRange && IS_FIREFOX) {
1!
968
                        el.focus();
×
969
                    }
970
                }
971
                this.isUpdatingSelection = false;
1✔
972
            });
973
        } catch (error) {
974
            this.editor.onError({
×
975
                code: SlateErrorCode.ToNativeSelectionError,
976
                nativeError: error
977
            });
978
            this.isUpdatingSelection = false;
×
979
        }
980
    }
981

982
    onChange() {
983
        this.forceRender();
13✔
984
        this.onChangeCallback(this.editor.children);
13✔
985
    }
986

987
    ngAfterViewChecked() {}
988

989
    ngDoCheck() {}
990

991
    forceRender() {
992
        this.updateContext();
15✔
993
        if (this.isEnabledVirtualScroll()) {
15!
994
            this.updateListRenderAndRemeasureHeights();
×
995
        } else {
996
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
997
        }
998
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
999
        // when the DOMElement where the selection is located is removed
1000
        // the compositionupdate and compositionend events will no longer be fired
1001
        // so isComposing needs to be corrected
1002
        // need exec after this.cdr.detectChanges() to render HTML
1003
        // need exec before this.toNativeSelection() to correct native selection
1004
        if (this.isComposing) {
15!
1005
            // Composition input text be not rendered when user composition input with selection is expanded
1006
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
1007
            // this time condition is true and isComposing is assigned false
1008
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
1009
            setTimeout(() => {
×
1010
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
1011
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
1012
                let textContent = '';
×
1013
                // skip decorate text
1014
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
1015
                    let text = stringDOMNode.textContent;
×
1016
                    const zeroChar = '\uFEFF';
×
1017
                    // remove zero with char
1018
                    if (text.startsWith(zeroChar)) {
×
1019
                        text = text.slice(1);
×
1020
                    }
1021
                    if (text.endsWith(zeroChar)) {
×
1022
                        text = text.slice(0, text.length - 1);
×
1023
                    }
1024
                    textContent += text;
×
1025
                });
1026
                if (Node.string(textNode).endsWith(textContent)) {
×
1027
                    this.isComposing = false;
×
1028
                }
1029
            }, 0);
1030
        }
1031
        if (this.editor.selection && this.isSelectionInvisible(this.editor.selection)) {
15!
1032
            Transforms.deselect(this.editor);
×
1033
            return;
×
1034
        } else {
1035
            this.toNativeSelection();
15✔
1036
        }
1037
    }
1038

1039
    render() {
1040
        const changed = this.updateContext();
2✔
1041
        if (changed) {
2✔
1042
            if (this.isEnabledVirtualScroll()) {
2!
1043
                this.updateListRenderAndRemeasureHeights();
×
1044
            } else {
1045
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
1046
            }
1047
        }
1048
    }
1049

1050
    updateListRenderAndRemeasureHeights() {
1051
        const operations = this.editor.operations;
×
1052
        const firstIndex = this.inViewportIndics[0];
×
1053
        const operationsOfFirstElementMerged = operations.filter(
×
1054
            op => op.type === 'merge_node' && op.path.length === 1 && firstIndex === op.path[0] - 1
×
1055
        );
1056
        const operationsOfFirstElementSplitted = operations.filter(
×
1057
            op => op.type === 'split_node' && op.path.length === 1 && firstIndex === op.path[0]
×
1058
        );
1059
        const mutationOfFirstElementHeight = operationsOfFirstElementSplitted.length > 0 || operationsOfFirstElementMerged.length > 0;
×
1060
        const visibleStates = this.editor.getAllVisibleStates();
×
1061
        const previousInViewportChildren = [...this.inViewportChildren];
×
1062
        // the first element height will reset to default height when split or merge
1063
        // if the most top content of the first element is not in viewport, the change of height will cause the viewport to scroll
1064
        // to keep viewport stable, we need to use the current inViewportIndics temporarily
1065
        if (mutationOfFirstElementHeight) {
×
1066
            const newInViewportIndics = [];
×
1067
            const newInViewportChildren = [];
×
1068
            this.inViewportIndics.forEach(index => {
×
1069
                const element = this.editor.children[index] as Element;
×
1070
                const isVisible = visibleStates[index];
×
1071
                if (isVisible) {
×
1072
                    newInViewportIndics.push(index);
×
1073
                    newInViewportChildren.push(element);
×
1074
                }
1075
            });
1076
            if (operationsOfFirstElementSplitted.length > 0) {
×
1077
                const lastIndex = newInViewportIndics[newInViewportIndics.length - 1];
×
1078
                for (let i = lastIndex + 1; i < this.editor.children.length; i++) {
×
1079
                    const element = this.editor.children[i] as Element;
×
1080
                    const isVisible = visibleStates[i];
×
1081
                    if (isVisible) {
×
1082
                        newInViewportIndics.push(i);
×
1083
                        newInViewportChildren.push(element);
×
1084
                        break;
×
1085
                    }
1086
                }
1087
            }
1088
            this.inViewportIndics = newInViewportIndics;
×
1089
            this.inViewportChildren = newInViewportChildren;
×
1090
            if (isDebug) {
×
1091
                debugLog(
×
1092
                    'log',
1093
                    'updateListRenderAndRemeasureHeights',
1094
                    'mutationOfFirstElementHeight',
1095
                    'newInViewportIndics',
1096
                    newInViewportIndics
1097
                );
1098
            }
1099
        } else {
1100
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
1101
            let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
1102
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
1103
                const remeasureIndics = diff.changedIndexesOfTop;
×
1104
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
1105
                if (changed) {
×
1106
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
1107
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
1108
                }
1109
            }
1110
            this.applyVirtualView(virtualView);
×
1111
        }
1112
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering(visibleStates);
×
1113
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
1114
        const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
1115
        if (remeasureIndics.length) {
×
1116
            this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
1117
        }
1118
    }
1119

1120
    updateContext() {
1121
        const decorations = this.generateDecorations();
17✔
1122
        if (
17✔
1123
            this.context.selection !== this.editor.selection ||
46✔
1124
            this.context.decorate !== this.decorate ||
1125
            this.context.readonly !== this.readonly ||
1126
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
1127
        ) {
1128
            this.context = {
10✔
1129
                parent: this.editor,
1130
                selection: this.editor.selection,
1131
                decorations: decorations,
1132
                decorate: this.decorate,
1133
                readonly: this.readonly
1134
            };
1135
            return true;
10✔
1136
        }
1137
        return false;
7✔
1138
    }
1139

1140
    initializeContext() {
1141
        this.context = {
49✔
1142
            parent: this.editor,
1143
            selection: this.editor.selection,
1144
            decorations: this.generateDecorations(),
1145
            decorate: this.decorate,
1146
            readonly: this.readonly
1147
        };
1148
    }
1149

1150
    initializeViewContext() {
1151
        this.viewContext = {
23✔
1152
            editor: this.editor,
1153
            renderElement: this.renderElement,
1154
            renderLeaf: this.renderLeaf,
1155
            renderText: this.renderText,
1156
            trackBy: this.trackBy,
1157
            isStrictDecorate: this.isStrictDecorate
1158
        };
1159
    }
1160

1161
    composePlaceholderDecorate(editor: Editor) {
1162
        if (this.placeholderDecorate) {
64!
1163
            return this.placeholderDecorate(editor) || [];
×
1164
        }
1165

1166
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
1167
            const start = Editor.start(editor, []);
3✔
1168
            return [
3✔
1169
                {
1170
                    placeholder: this.placeholder,
1171
                    anchor: start,
1172
                    focus: start
1173
                }
1174
            ];
1175
        } else {
1176
            return [];
61✔
1177
        }
1178
    }
1179

1180
    generateDecorations() {
1181
        const decorations = this.decorate([this.editor, []]);
66✔
1182
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1183
        decorations.push(...placeholderDecorations);
66✔
1184
        return decorations;
66✔
1185
    }
1186

1187
    private toSlateSelection() {
1188
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1189
            try {
1✔
1190
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1191
                const { activeElement } = root;
1✔
1192
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1193
                const domSelection = (root as Document).getSelection();
1✔
1194

1195
                if (activeElement === el) {
1!
1196
                    this.latestElement = activeElement;
1✔
1197
                    IS_FOCUSED.set(this.editor, true);
1✔
1198
                } else {
UNCOV
1199
                    IS_FOCUSED.delete(this.editor);
×
1200
                }
1201

1202
                if (!domSelection) {
1!
1203
                    return Transforms.deselect(this.editor);
×
1204
                }
1205

1206
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1207
                const hasDomSelectionInEditor =
1208
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1209
                if (!hasDomSelectionInEditor) {
1!
UNCOV
1210
                    Transforms.deselect(this.editor);
×
UNCOV
1211
                    return;
×
1212
                }
1213

1214
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1215
                // for example, double-click the last cell of the table to select a non-editable DOM
1216
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1217
                if (range) {
1✔
1218
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1219
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1220
                            // force adjust DOMSelection
1221
                            this.toNativeSelection(false);
×
1222
                        }
1223
                    } else {
1224
                        Transforms.select(this.editor, range);
1✔
1225
                    }
1226
                }
1227
            } catch (error) {
1228
                this.editor.onError({
×
1229
                    code: SlateErrorCode.ToSlateSelectionError,
1230
                    nativeError: error
1231
                });
1232
            }
1233
        }
1234
    }
1235

1236
    private onDOMBeforeInput(
1237
        event: Event & {
1238
            inputType: string;
1239
            isComposing: boolean;
1240
            data: string | null;
1241
            dataTransfer: DataTransfer | null;
1242
            getTargetRanges(): DOMStaticRange[];
1243
        }
1244
    ) {
1245
        const editor = this.editor;
×
1246
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1247
        const { activeElement } = root;
×
1248
        const { selection } = editor;
×
1249
        const { inputType: type } = event;
×
1250
        const data = event.dataTransfer || event.data || undefined;
×
1251
        if (IS_ANDROID) {
×
1252
            let targetRange: Range | null = null;
×
1253
            let [nativeTargetRange] = event.getTargetRanges();
×
1254
            if (nativeTargetRange) {
×
1255
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1256
            }
1257
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1258
            // have to manually get the selection here to ensure it's up-to-date.
1259
            const window = AngularEditor.getWindow(editor);
×
1260
            const domSelection = window.getSelection();
×
1261
            if (!targetRange && domSelection) {
×
1262
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1263
            }
1264
            targetRange = targetRange ?? editor.selection;
×
1265
            if (type === 'insertCompositionText') {
×
1266
                if (data && data.toString().includes('\n')) {
×
1267
                    restoreDom(editor, () => {
×
1268
                        Editor.insertBreak(editor);
×
1269
                    });
1270
                } else {
1271
                    if (targetRange) {
×
1272
                        if (data) {
×
1273
                            restoreDom(editor, () => {
×
1274
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1275
                            });
1276
                        } else {
1277
                            restoreDom(editor, () => {
×
1278
                                Transforms.delete(editor, { at: targetRange });
×
1279
                            });
1280
                        }
1281
                    }
1282
                }
1283
                return;
×
1284
            }
1285
            if (type === 'deleteContentBackward') {
×
1286
                // gboard can not prevent default action, so must use restoreDom,
1287
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1288
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1289
                if (!Range.isCollapsed(targetRange)) {
×
1290
                    restoreDom(editor, () => {
×
1291
                        Transforms.delete(editor, { at: targetRange });
×
1292
                    });
1293
                    return;
×
1294
                }
1295
            }
1296
            if (type === 'insertText') {
×
1297
                restoreDom(editor, () => {
×
1298
                    if (typeof data === 'string') {
×
1299
                        Editor.insertText(editor, data);
×
1300
                    }
1301
                });
1302
                return;
×
1303
            }
1304
        }
1305
        if (
×
1306
            !this.readonly &&
×
1307
            AngularEditor.hasEditableTarget(editor, event.target) &&
1308
            !isTargetInsideVoid(editor, activeElement) &&
1309
            !this.isDOMEventHandled(event, this.beforeInput)
1310
        ) {
1311
            try {
×
1312
                event.preventDefault();
×
1313

1314
                // COMPAT: If the selection is expanded, even if the command seems like
1315
                // a delete forward/backward command it should delete the selection.
1316
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1317
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1318
                    Editor.deleteFragment(editor, { direction });
×
1319
                    return;
×
1320
                }
1321

1322
                switch (type) {
×
1323
                    case 'deleteByComposition':
1324
                    case 'deleteByCut':
1325
                    case 'deleteByDrag': {
1326
                        Editor.deleteFragment(editor);
×
1327
                        break;
×
1328
                    }
1329

1330
                    case 'deleteContent':
1331
                    case 'deleteContentForward': {
1332
                        Editor.deleteForward(editor);
×
1333
                        break;
×
1334
                    }
1335

1336
                    case 'deleteContentBackward': {
1337
                        Editor.deleteBackward(editor);
×
1338
                        break;
×
1339
                    }
1340

1341
                    case 'deleteEntireSoftLine': {
1342
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1343
                        Editor.deleteForward(editor, { unit: 'line' });
×
1344
                        break;
×
1345
                    }
1346

1347
                    case 'deleteHardLineBackward': {
1348
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1349
                        break;
×
1350
                    }
1351

1352
                    case 'deleteSoftLineBackward': {
1353
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1354
                        break;
×
1355
                    }
1356

1357
                    case 'deleteHardLineForward': {
1358
                        Editor.deleteForward(editor, { unit: 'block' });
×
1359
                        break;
×
1360
                    }
1361

1362
                    case 'deleteSoftLineForward': {
1363
                        Editor.deleteForward(editor, { unit: 'line' });
×
1364
                        break;
×
1365
                    }
1366

1367
                    case 'deleteWordBackward': {
1368
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1369
                        break;
×
1370
                    }
1371

1372
                    case 'deleteWordForward': {
1373
                        Editor.deleteForward(editor, { unit: 'word' });
×
1374
                        break;
×
1375
                    }
1376

1377
                    case 'insertLineBreak':
1378
                    case 'insertParagraph': {
1379
                        Editor.insertBreak(editor);
×
1380
                        break;
×
1381
                    }
1382

1383
                    case 'insertFromComposition': {
1384
                        // COMPAT: in safari, `compositionend` event is dispatched after
1385
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1386
                        // https://www.w3.org/TR/input-events-2/
1387
                        // so the following code is the right logic
1388
                        // because DOM selection in sync will be exec before `compositionend` event
1389
                        // isComposing is true will prevent DOM selection being update correctly.
1390
                        this.isComposing = false;
×
1391
                        preventInsertFromComposition(event, this.editor);
×
1392
                    }
1393
                    case 'insertFromDrop':
1394
                    case 'insertFromPaste':
1395
                    case 'insertFromYank':
1396
                    case 'insertReplacementText':
1397
                    case 'insertText': {
1398
                        // use a weak comparison instead of 'instanceof' to allow
1399
                        // programmatic access of paste events coming from external windows
1400
                        // like cypress where cy.window does not work realibly
1401
                        if (data?.constructor.name === 'DataTransfer') {
×
1402
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1403
                        } else if (typeof data === 'string') {
×
1404
                            Editor.insertText(editor, data);
×
1405
                        }
1406
                        break;
×
1407
                    }
1408
                }
1409
            } catch (error) {
1410
                this.editor.onError({
×
1411
                    code: SlateErrorCode.OnDOMBeforeInputError,
1412
                    nativeError: error
1413
                });
1414
            }
1415
        }
1416
    }
1417

1418
    private onDOMBlur(event: FocusEvent) {
1419
        if (
×
1420
            this.readonly ||
×
1421
            this.isUpdatingSelection ||
1422
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1423
            this.isDOMEventHandled(event, this.blur)
1424
        ) {
1425
            return;
×
1426
        }
1427

1428
        const window = AngularEditor.getWindow(this.editor);
×
1429

1430
        // COMPAT: If the current `activeElement` is still the previous
1431
        // one, this is due to the window being blurred when the tab
1432
        // itself becomes unfocused, so we want to abort early to allow to
1433
        // editor to stay focused when the tab becomes focused again.
1434
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1435
        if (this.latestElement === root.activeElement) {
×
1436
            return;
×
1437
        }
1438

1439
        const { relatedTarget } = event;
×
1440
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1441

1442
        // COMPAT: The event should be ignored if the focus is returning
1443
        // to the editor from an embedded editable element (eg. an <input>
1444
        // element inside a void node).
1445
        if (relatedTarget === el) {
×
1446
            return;
×
1447
        }
1448

1449
        // COMPAT: The event should be ignored if the focus is moving from
1450
        // the editor to inside a void node's spacer element.
1451
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1452
            return;
×
1453
        }
1454

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

1461
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1462
                return;
×
1463
            }
1464
        }
1465

1466
        IS_FOCUSED.delete(this.editor);
×
1467
    }
1468

1469
    private onDOMClick(event: MouseEvent) {
1470
        if (
×
1471
            !this.readonly &&
×
1472
            AngularEditor.hasTarget(this.editor, event.target) &&
1473
            !this.isDOMEventHandled(event, this.click) &&
1474
            isDOMNode(event.target)
1475
        ) {
1476
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1477
            const path = AngularEditor.findPath(this.editor, node);
×
1478
            const start = Editor.start(this.editor, path);
×
1479
            const end = Editor.end(this.editor, path);
×
1480

1481
            const startVoid = Editor.void(this.editor, { at: start });
×
1482
            const endVoid = Editor.void(this.editor, { at: end });
×
1483

1484
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1485
                let blockPath = path;
×
1486
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1487
                    const block = Editor.above(this.editor, {
×
1488
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1489
                        at: path
1490
                    });
1491

1492
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1493
                }
1494

1495
                const range = Editor.range(this.editor, blockPath);
×
1496
                Transforms.select(this.editor, range);
×
1497
                return;
×
1498
            }
1499

1500
            if (
×
1501
                startVoid &&
×
1502
                endVoid &&
1503
                Path.equals(startVoid[1], endVoid[1]) &&
1504
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1505
            ) {
1506
                const range = Editor.range(this.editor, start);
×
1507
                Transforms.select(this.editor, range);
×
1508
            }
1509
        }
1510
    }
1511

1512
    private onDOMCompositionStart(event: CompositionEvent) {
1513
        const { selection } = this.editor;
1✔
1514
        if (selection) {
1!
1515
            // solve the problem of cross node Chinese input
1516
            if (Range.isExpanded(selection)) {
×
1517
                Editor.deleteFragment(this.editor);
×
1518
                this.forceRender();
×
1519
            }
1520
        }
1521
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1522
            this.isComposing = true;
1✔
1523
        }
1524
        this.render();
1✔
1525
    }
1526

1527
    private onDOMCompositionUpdate(event: CompositionEvent) {
1528
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1529
    }
1530

1531
    private onDOMCompositionEnd(event: CompositionEvent) {
1532
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1533
            Transforms.delete(this.editor);
×
1534
        }
1535
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1536
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1537
            // aren't correct and never fire the "insertFromComposition"
1538
            // type that we need. So instead, insert whenever a composition
1539
            // ends since it will already have been committed to the DOM.
1540
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1541
                preventInsertFromComposition(event, this.editor);
×
1542
                Editor.insertText(this.editor, event.data);
×
1543
            }
1544

1545
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1546
            // so we need avoid repeat isnertText by isComposing === true,
1547
            this.isComposing = false;
×
1548
        }
1549
        this.render();
×
1550
    }
1551

1552
    private onDOMCopy(event: ClipboardEvent) {
1553
        const window = AngularEditor.getWindow(this.editor);
×
1554
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1555
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1556
            event.preventDefault();
×
1557
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1558
        }
1559
    }
1560

1561
    private onDOMCut(event: ClipboardEvent) {
1562
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1563
            event.preventDefault();
×
1564
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1565
            const { selection } = this.editor;
×
1566

1567
            if (selection) {
×
1568
                AngularEditor.deleteCutData(this.editor);
×
1569
            }
1570
        }
1571
    }
1572

1573
    private onDOMDragOver(event: DragEvent) {
1574
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1575
            // Only when the target is void, call `preventDefault` to signal
1576
            // that drops are allowed. Editable content is droppable by
1577
            // default, and calling `preventDefault` hides the cursor.
1578
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1579

1580
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1581
                event.preventDefault();
×
1582
            }
1583
        }
1584
    }
1585

1586
    private onDOMDragStart(event: DragEvent) {
1587
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1588
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1589
            const path = AngularEditor.findPath(this.editor, node);
×
1590
            const voidMatch =
1591
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1592

1593
            // If starting a drag on a void node, make sure it is selected
1594
            // so that it shows up in the selection's fragment.
1595
            if (voidMatch) {
×
1596
                const range = Editor.range(this.editor, path);
×
1597
                Transforms.select(this.editor, range);
×
1598
            }
1599

1600
            this.isDraggingInternally = true;
×
1601

1602
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1603
        }
1604
    }
1605

1606
    private onDOMDrop(event: DragEvent) {
1607
        const editor = this.editor;
×
1608
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1609
            event.preventDefault();
×
1610
            // Keep a reference to the dragged range before updating selection
1611
            const draggedRange = editor.selection;
×
1612

1613
            // Find the range where the drop happened
1614
            const range = AngularEditor.findEventRange(editor, event);
×
1615
            const data = event.dataTransfer;
×
1616

1617
            Transforms.select(editor, range);
×
1618

1619
            if (this.isDraggingInternally) {
×
1620
                if (draggedRange) {
×
1621
                    Transforms.delete(editor, {
×
1622
                        at: draggedRange
1623
                    });
1624
                }
1625

1626
                this.isDraggingInternally = false;
×
1627
            }
1628

1629
            AngularEditor.insertData(editor, data);
×
1630

1631
            // When dragging from another source into the editor, it's possible
1632
            // that the current editor does not have focus.
1633
            if (!AngularEditor.isFocused(editor)) {
×
1634
                AngularEditor.focus(editor);
×
1635
            }
1636
        }
1637
    }
1638

1639
    private onDOMDragEnd(event: DragEvent) {
1640
        if (
×
1641
            !this.readonly &&
×
1642
            this.isDraggingInternally &&
1643
            AngularEditor.hasTarget(this.editor, event.target) &&
1644
            !this.isDOMEventHandled(event, this.dragEnd)
1645
        ) {
1646
            this.isDraggingInternally = false;
×
1647
        }
1648
    }
1649

1650
    private onDOMFocus(event: Event) {
1651
        if (
2✔
1652
            !this.readonly &&
8✔
1653
            !this.isUpdatingSelection &&
1654
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1655
            !this.isDOMEventHandled(event, this.focus)
1656
        ) {
1657
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1658
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1659
            this.latestElement = root.activeElement;
2✔
1660

1661
            // COMPAT: If the editor has nested editable elements, the focus
1662
            // can go to them. In Firefox, this must be prevented because it
1663
            // results in issues with keyboard navigation. (2017/03/30)
1664
            if (IS_FIREFOX && event.target !== el) {
2!
1665
                el.focus();
×
1666
                return;
×
1667
            }
1668

1669
            IS_FOCUSED.set(this.editor, true);
2✔
1670
        }
1671
    }
1672

1673
    private onDOMKeydown(event: KeyboardEvent) {
1674
        const editor = this.editor;
×
1675
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1676
        const { activeElement } = root;
×
1677
        if (
×
1678
            !this.readonly &&
×
1679
            AngularEditor.hasEditableTarget(editor, event.target) &&
1680
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1681
            !this.isComposing &&
1682
            !this.isDOMEventHandled(event, this.keydown)
1683
        ) {
1684
            const nativeEvent = event;
×
1685
            const { selection } = editor;
×
1686

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

1690
            try {
×
1691
                // COMPAT: Since we prevent the default behavior on
1692
                // `beforeinput` events, the browser doesn't think there's ever
1693
                // any history stack to undo or redo, so we have to manage these
1694
                // hotkeys ourselves. (2019/11/06)
1695
                if (Hotkeys.isRedo(nativeEvent)) {
×
1696
                    event.preventDefault();
×
1697

1698
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1699
                        editor.redo();
×
1700
                    }
1701

1702
                    return;
×
1703
                }
1704

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

1708
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1709
                        editor.undo();
×
1710
                    }
1711

1712
                    return;
×
1713
                }
1714

1715
                // COMPAT: Certain browsers don't handle the selection updates
1716
                // properly. In Chrome, the selection isn't properly extended.
1717
                // And in Firefox, the selection isn't properly collapsed.
1718
                // (2017/10/17)
1719
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1720
                    event.preventDefault();
×
1721
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1722
                    return;
×
1723
                }
1724

1725
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1726
                    event.preventDefault();
×
1727
                    Transforms.move(editor, { unit: 'line' });
×
1728
                    return;
×
1729
                }
1730

1731
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1732
                    event.preventDefault();
×
1733
                    Transforms.move(editor, {
×
1734
                        unit: 'line',
1735
                        edge: 'focus',
1736
                        reverse: true
1737
                    });
1738
                    return;
×
1739
                }
1740

1741
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1742
                    event.preventDefault();
×
1743
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1744
                    return;
×
1745
                }
1746

1747
                // COMPAT: If a void node is selected, or a zero-width text node
1748
                // adjacent to an inline is selected, we need to handle these
1749
                // hotkeys manually because browsers won't be able to skip over
1750
                // the void node with the zero-width space not being an empty
1751
                // string.
1752
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1753
                    event.preventDefault();
×
1754

1755
                    if (selection && Range.isCollapsed(selection)) {
×
1756
                        Transforms.move(editor, { reverse: !isRTL });
×
1757
                    } else {
1758
                        Transforms.collapse(editor, { edge: 'start' });
×
1759
                    }
1760

1761
                    return;
×
1762
                }
1763

1764
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1765
                    event.preventDefault();
×
1766
                    if (selection && Range.isCollapsed(selection)) {
×
1767
                        Transforms.move(editor, { reverse: isRTL });
×
1768
                    } else {
1769
                        Transforms.collapse(editor, { edge: 'end' });
×
1770
                    }
1771

1772
                    return;
×
1773
                }
1774

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

1778
                    if (selection && Range.isExpanded(selection)) {
×
1779
                        Transforms.collapse(editor, { edge: 'focus' });
×
1780
                    }
1781

1782
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1783
                    return;
×
1784
                }
1785

1786
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1787
                    event.preventDefault();
×
1788

1789
                    if (selection && Range.isExpanded(selection)) {
×
1790
                        Transforms.collapse(editor, { edge: 'focus' });
×
1791
                    }
1792

1793
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1794
                    return;
×
1795
                }
1796

1797
                if (isKeyHotkey('mod+a', event)) {
×
1798
                    this.editor.selectAll();
×
1799
                    event.preventDefault();
×
1800
                    return;
×
1801
                }
1802

1803
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1804
                // fall back to guessing at the input intention for hotkeys.
1805
                // COMPAT: In iOS, some of these hotkeys are handled in the
1806
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1807
                    // We don't have a core behavior for these, but they change the
1808
                    // DOM if we don't prevent them, so we have to.
1809
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1810
                        event.preventDefault();
×
1811
                        return;
×
1812
                    }
1813

1814
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1815
                        event.preventDefault();
×
1816
                        Editor.insertBreak(editor);
×
1817
                        return;
×
1818
                    }
1819

1820
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1821
                        event.preventDefault();
×
1822

1823
                        if (selection && Range.isExpanded(selection)) {
×
1824
                            Editor.deleteFragment(editor, {
×
1825
                                direction: 'backward'
1826
                            });
1827
                        } else {
1828
                            Editor.deleteBackward(editor);
×
1829
                        }
1830

1831
                        return;
×
1832
                    }
1833

1834
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1835
                        event.preventDefault();
×
1836

1837
                        if (selection && Range.isExpanded(selection)) {
×
1838
                            Editor.deleteFragment(editor, {
×
1839
                                direction: 'forward'
1840
                            });
1841
                        } else {
1842
                            Editor.deleteForward(editor);
×
1843
                        }
1844

1845
                        return;
×
1846
                    }
1847

1848
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1849
                        event.preventDefault();
×
1850

1851
                        if (selection && Range.isExpanded(selection)) {
×
1852
                            Editor.deleteFragment(editor, {
×
1853
                                direction: 'backward'
1854
                            });
1855
                        } else {
1856
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1857
                        }
1858

1859
                        return;
×
1860
                    }
1861

1862
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1863
                        event.preventDefault();
×
1864

1865
                        if (selection && Range.isExpanded(selection)) {
×
1866
                            Editor.deleteFragment(editor, {
×
1867
                                direction: 'forward'
1868
                            });
1869
                        } else {
1870
                            Editor.deleteForward(editor, { unit: 'line' });
×
1871
                        }
1872

1873
                        return;
×
1874
                    }
1875

1876
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1877
                        event.preventDefault();
×
1878

1879
                        if (selection && Range.isExpanded(selection)) {
×
1880
                            Editor.deleteFragment(editor, {
×
1881
                                direction: 'backward'
1882
                            });
1883
                        } else {
1884
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1885
                        }
1886

1887
                        return;
×
1888
                    }
1889

1890
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1891
                        event.preventDefault();
×
1892

1893
                        if (selection && Range.isExpanded(selection)) {
×
1894
                            Editor.deleteFragment(editor, {
×
1895
                                direction: 'forward'
1896
                            });
1897
                        } else {
1898
                            Editor.deleteForward(editor, { unit: 'word' });
×
1899
                        }
1900

1901
                        return;
×
1902
                    }
1903
                } else {
1904
                    if (IS_CHROME || IS_SAFARI) {
×
1905
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1906
                        // an event when deleting backwards in a selected void inline node
1907
                        if (
×
1908
                            selection &&
×
1909
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1910
                            Range.isCollapsed(selection)
1911
                        ) {
1912
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1913
                            if (
×
1914
                                Element.isElement(currentNode) &&
×
1915
                                Editor.isVoid(editor, currentNode) &&
1916
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1917
                            ) {
1918
                                event.preventDefault();
×
1919
                                Editor.deleteBackward(editor, {
×
1920
                                    unit: 'block'
1921
                                });
1922
                                return;
×
1923
                            }
1924
                        }
1925
                    }
1926
                }
1927
            } catch (error) {
1928
                this.editor.onError({
×
1929
                    code: SlateErrorCode.OnDOMKeydownError,
1930
                    nativeError: error
1931
                });
1932
            }
1933
        }
1934
    }
1935

1936
    private onDOMPaste(event: ClipboardEvent) {
1937
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1938
        // fall back to React's `onPaste` here instead.
1939
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1940
        // when "paste without formatting" option is used.
1941
        // This unfortunately needs to be handled with paste events instead.
1942
        if (
×
1943
            !this.isDOMEventHandled(event, this.paste) &&
×
1944
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1945
            !this.readonly &&
1946
            AngularEditor.hasEditableTarget(this.editor, event.target)
1947
        ) {
1948
            event.preventDefault();
×
1949
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1950
        }
1951
    }
1952

1953
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1954
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1955
        // fall back to React's leaky polyfill instead just for it. It
1956
        // only works for the `insertText` input type.
1957
        if (
×
1958
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1959
            !this.readonly &&
1960
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1961
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1962
        ) {
1963
            event.nativeEvent.preventDefault();
×
1964
            try {
×
1965
                const text = event.data;
×
1966
                if (!Range.isCollapsed(this.editor.selection)) {
×
1967
                    Editor.deleteFragment(this.editor);
×
1968
                }
1969
                // just handle Non-IME input
1970
                if (!this.isComposing) {
×
1971
                    Editor.insertText(this.editor, text);
×
1972
                }
1973
            } catch (error) {
1974
                this.editor.onError({
×
1975
                    code: SlateErrorCode.ToNativeSelectionError,
1976
                    nativeError: error
1977
                });
1978
            }
1979
        }
1980
    }
1981

1982
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1983
        if (!handler) {
3✔
1984
            return false;
3✔
1985
        }
1986
        handler(event);
×
1987
        return event.defaultPrevented;
×
1988
    }
1989
    //#endregion
1990

1991
    ngOnDestroy() {
1992
        this.editorResizeObserver?.disconnect();
23✔
1993
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1994
        this.manualListeners.forEach(manualListener => {
23✔
1995
            manualListener();
483✔
1996
        });
1997
        this.destroy$.complete();
23✔
1998
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1999
    }
2000
}
2001

2002
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
2003
    // This was affecting the selection of multiple blocks and dragging behavior,
2004
    // so enabled only if the selection has been collapsed.
UNCOV
2005
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
UNCOV
2006
        const leafEl = domRange.startContainer.parentElement!;
×
2007

2008
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
2009
        // When this happens, do not scroll like most editors do.
UNCOV
2010
        const domRect = domRange.getBoundingClientRect();
×
UNCOV
2011
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
2012

UNCOV
2013
        if (isZeroDimensionRect) {
×
2014
            const leafRect = leafEl.getBoundingClientRect();
×
2015
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2016

2017
            if (leafHasDimensions) {
×
2018
                return;
×
2019
            }
2020
        }
2021

UNCOV
2022
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
2023
        scrollIntoView(leafEl, {
×
2024
            scrollMode: 'if-needed'
2025
        });
UNCOV
2026
        delete leafEl.getBoundingClientRect;
×
2027
    }
2028
};
2029

2030
/**
2031
 * Check if the target is inside void and in the editor.
2032
 */
2033

2034
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
2035
    let slateNode: Node | null = null;
1✔
2036
    try {
1✔
2037
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
2038
    } catch (error) {}
2039
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
2040
};
2041

2042
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
2043
    return (
2✔
2044
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
2045
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
2046
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
2047
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
2048
    );
2049
};
2050

2051
/**
2052
 * remove default insert from composition
2053
 * @param text
2054
 */
2055
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2056
    const types = ['compositionend', 'insertFromComposition'];
×
2057
    if (!types.includes(event.type)) {
×
2058
        return;
×
2059
    }
2060
    const insertText = (event as CompositionEvent).data;
×
2061
    const window = AngularEditor.getWindow(editor);
×
2062
    const domSelection = window.getSelection();
×
2063
    // ensure text node insert composition input text
2064
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2065
        const textNode = domSelection.anchorNode;
×
2066
        textNode.splitText(textNode.length - insertText.length).remove();
×
2067
    }
2068
};
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