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

worktile / slate-angular / 9cbfe276-6a5c-4ac1-a622-9e7e046f79d4

02 Feb 2026 08:51AM UTC coverage: 35.546% (-0.1%) from 35.651%
9cbfe276-6a5c-4ac1-a622-9e7e046f79d4

push

circleci

pubuzhixing8
fix(virtual-scroll): support calc business top in scrollToElement

405 of 1353 branches covered (29.93%)

Branch coverage included in aggregate %.

6 of 32 new or added lines in 3 files covered. (18.75%)

1 existing line in 1 file now uncovered.

1121 of 2940 relevant lines covered (38.13%)

22.81 hits per line

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

22.0
/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_VIRTUAL_SCROLL_SELECTION,
54
    ELEMENT_KEY_TO_HEIGHTS,
55
    getBusinessTop,
56
    isDebug,
57
    isDebugScrollTop,
58
    isDecoratorRangeListEqual,
59
    measureHeightByIndics,
60
    roundTo
61
} from '../../utils';
62
import { SlatePlaceholder } from '../../types/feature';
63
import { restoreDom } from '../../utils/restore-dom';
64
import { ListRender, updatePreRenderingElementWidth } from '../../view/render/list-render';
65
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
66
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
67
import { isKeyHotkey } from 'is-hotkey';
68
import {
69
    calcBusinessTop,
70
    calculateVirtualTopHeight,
71
    debugLog,
72
    EDITOR_TO_IS_FROM_SCROLL_TO,
73
    EDITOR_TO_ROOT_NODE_WIDTH,
74
    EDITOR_TO_VIEWPORT_HEIGHT,
75
    EDITOR_TO_VIRTUAL_SCROLL_CONFIG,
76
    getCachedHeightByElement,
77
    getViewportHeight,
78
    VIRTUAL_BOTTOM_HEIGHT_CLASS_NAME,
79
    VIRTUAL_CENTER_OUTLET_CLASS_NAME,
80
    VIRTUAL_TOP_HEIGHT_CLASS_NAME
81
} from '../../utils/virtual-scroll';
82

83
// not correctly clipboardData on beforeinput
84
const forceOnDOMPaste = IS_SAFARI;
1✔
85

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

111
    private destroy$ = new Subject();
23✔
112

113
    isComposing = false;
23✔
114
    isDraggingInternally = false;
23✔
115
    isUpdatingSelection = false;
23✔
116
    latestElement = null as DOMElement | null;
23✔
117

118
    protected manualListeners: (() => void)[] = [];
23✔
119

120
    private initialized: boolean;
121

122
    private onTouchedCallback: () => void = () => {};
23✔
123

124
    private onChangeCallback: (_: any) => void = () => {};
23✔
125

126
    @Input() editor: AngularEditor;
127

128
    @Input() renderElement: (element: Element) => ViewType | null;
129

130
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
131

132
    @Input() renderText: (text: SlateText) => ViewType | null;
133

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

136
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
137

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

140
    @Input() isStrictDecorate: boolean = true;
23✔
141

142
    @Input() trackBy: (node: Element) => any = () => null;
206✔
143

144
    @Input() readonly = false;
23✔
145

146
    @Input() placeholder: string;
147

148
    @Input()
149
    set virtualScroll(config: SlateVirtualScrollConfig) {
150
        this.virtualScrollConfig = config;
×
NEW
151
        EDITOR_TO_VIRTUAL_SCROLL_CONFIG.set(this.editor, config);
×
152
        if (isDebugScrollTop) {
×
153
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
154
        }
155
        if (this.isEnabledVirtualScroll()) {
×
156
            this.tryUpdateVirtualViewport();
×
157
        }
158
    }
159

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

178
    //#region DOM attr
179
    @Input() spellCheck = false;
23✔
180
    @Input() autoCorrect = false;
23✔
181
    @Input() autoCapitalize = false;
23✔
182

183
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
184
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
185
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
186

187
    get hasBeforeInputSupport() {
188
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
189
    }
190
    //#endregion
191

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

194
    getOutletParent = () => {
23✔
195
        return this.elementRef.nativeElement;
43✔
196
    };
197

198
    getOutletElement = () => {
23✔
199
        if (this.virtualScrollInitialized) {
23!
200
            return this.virtualCenterOutlet;
×
201
        } else {
202
            return null;
23✔
203
        }
204
    };
205

206
    listRender: ListRender;
207

208
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
209
        enabled: false,
210
        scrollTop: 0,
211
        scrollContainer: null
212
    };
213

214
    private inViewportChildren: Element[] = [];
23✔
215
    private inViewportIndics: number[] = [];
23✔
216
    private keyHeightMap = new Map<string, number>();
23✔
217
    private tryUpdateVirtualViewportAnimId: number;
218
    private editorResizeObserver?: ResizeObserver;
219
    private editorScrollContainerResizeObserver?: ResizeObserver;
220

221
    indicsOfNeedBeMeasured$ = new Subject<number[]>();
23✔
222

223
    virtualScrollInitialized = false;
23✔
224

225
    virtualTopHeightElement: HTMLElement;
226

227
    virtualBottomHeightElement: HTMLElement;
228

229
    virtualCenterOutlet: HTMLElement;
230

231
    constructor(
232
        public elementRef: ElementRef,
23✔
233
        public renderer2: Renderer2,
23✔
234
        public cdr: ChangeDetectorRef,
23✔
235
        private ngZone: NgZone,
23✔
236
        private injector: Injector
23✔
237
    ) {}
238

239
    ngOnInit() {
240
        this.editor.injector = this.injector;
23✔
241
        this.editor.children = [];
23✔
242
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
243
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
244
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
245
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
246
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
247
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
248
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
249
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
250
            this.ngZone.run(() => {
13✔
251
                this.onChange();
13✔
252
            });
253
        });
254
        this.ngZone.runOutsideAngular(() => {
23✔
255
            this.initialize();
23✔
256
        });
257
        this.initializeViewContext();
23✔
258
        this.initializeContext();
23✔
259
        // add browser class
260
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
261
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
262
        this.initializeVirtualScroll();
23✔
263
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
264
    }
265

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

286
    registerOnChange(fn: any) {
287
        this.onChangeCallback = fn;
23✔
288
    }
289
    registerOnTouched(fn: any) {
290
        this.onTouchedCallback = fn;
23✔
291
    }
292

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

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

366
    private isEnabledVirtualScroll() {
367
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
368
    }
369

370
    initializeVirtualScroll() {
371
        if (this.virtualScrollInitialized) {
23!
372
            return;
×
373
        }
374
        if (this.isEnabledVirtualScroll()) {
23!
375
            this.virtualScrollInitialized = true;
×
376
            this.virtualTopHeightElement = document.createElement('div');
×
NEW
377
            this.virtualTopHeightElement.classList.add(VIRTUAL_TOP_HEIGHT_CLASS_NAME);
×
378
            this.virtualTopHeightElement.contentEditable = 'false';
×
379
            this.virtualBottomHeightElement = document.createElement('div');
×
NEW
380
            this.virtualBottomHeightElement.classList.add(VIRTUAL_BOTTOM_HEIGHT_CLASS_NAME);
×
381
            this.virtualBottomHeightElement.contentEditable = 'false';
×
382
            this.virtualCenterOutlet = document.createElement('div');
×
NEW
383
            this.virtualCenterOutlet.classList.add(VIRTUAL_CENTER_OUTLET_CLASS_NAME);
×
384
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
385
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
386
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
387
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
388
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.offsetWidth);
×
389
            this.editorResizeObserver = new ResizeObserver(entries => {
×
390
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
391
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
392
                    this.keyHeightMap.clear();
×
393
                    let target = this.virtualTopHeightElement;
×
394
                    if (this.inViewportChildren[0]) {
×
395
                        const firstElement = this.inViewportChildren[0];
×
396
                        const firstDomElement = AngularEditor.toDOMNode(this.editor, firstElement);
×
397
                        target = firstDomElement;
×
398
                    }
399
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, target.offsetWidth);
×
400
                    updatePreRenderingElementWidth(this.editor);
×
401
                    if (isDebug) {
×
402
                        debugLog(
×
403
                            'log',
404
                            'editorResizeObserverRectWidth: ',
405
                            editorResizeObserverRectWidth,
406
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
407
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
408
                        );
409
                    }
410
                }
411
            });
412
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
413
            if (this.virtualScrollConfig.scrollContainer) {
×
414
                this.editorScrollContainerResizeObserver = new ResizeObserver(entries => {
×
415
                    const height = this.virtualScrollConfig.scrollContainer.getBoundingClientRect().height;
×
416
                    EDITOR_TO_VIEWPORT_HEIGHT.set(this.editor, height);
×
417
                    if (isDebug) {
×
418
                        debugLog('log', 'editorScrollContainerResizeObserver calc viewport height: ', height);
×
419
                        this.virtualTopHeightElement.setAttribute('viewport-height', height.toString());
×
420
                    }
421
                });
422
                this.editorScrollContainerResizeObserver.observe(this.virtualScrollConfig.scrollContainer);
×
423
            }
424

425
            let pendingRemeasureIndics: number[] = [];
×
426
            this.indicsOfNeedBeMeasured$
×
427
                .pipe(
428
                    tap((previousValue: number[]) => {
429
                        previousValue.forEach((index: number) => {
×
430
                            if (!pendingRemeasureIndics.includes(index)) {
×
431
                                pendingRemeasureIndics.push(index);
×
432
                            }
433
                        });
434
                    }),
435
                    debounceTime(500),
436
                    filter(() => pendingRemeasureIndics.length > 0)
×
437
                )
438
                .subscribe(() => {
439
                    const changed = measureHeightByIndics(this.editor, pendingRemeasureIndics, true);
×
440
                    if (changed) {
×
441
                        this.tryUpdateVirtualViewport();
×
442
                        if (isDebug) {
×
443
                            debugLog(
×
444
                                'log',
445
                                'exist pendingRemeasureIndics: ',
446
                                pendingRemeasureIndics,
447
                                'will try to update virtual viewport'
448
                            );
449
                        }
450
                    }
451
                    pendingRemeasureIndics = [];
×
452
                });
453
        }
454
    }
455

456
    getChangedIndics(previousValue: Descendant[]) {
457
        const remeasureIndics = [];
×
458
        this.inViewportChildren.forEach((child, index) => {
×
459
            if (previousValue.indexOf(child) === -1) {
×
460
                remeasureIndics.push(this.inViewportIndics[index]);
×
461
            }
462
        });
463
        return remeasureIndics;
×
464
    }
465

466
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
467
        if (!this.virtualScrollInitialized) {
×
468
            return;
×
469
        }
470
        this.virtualTopHeightElement.style.height = `${roundTo(topHeight, 1)}px`;
×
471
        if (bottomHeight !== undefined) {
×
472
            this.virtualBottomHeightElement.style.height = `${roundTo(bottomHeight, 1)}px`;
×
473
        }
474
    }
475

476
    getActualVirtualTopHeight() {
477
        if (!this.virtualScrollInitialized) {
×
478
            return 0;
×
479
        }
480
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
481
    }
482

483
    handlePreRendering(visibleStates: boolean[]) {
484
        let preRenderingCount = 0;
×
485
        const childrenWithPreRendering = [...this.inViewportChildren];
×
486
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
487
        const firstIndex = this.inViewportIndics[0];
×
488
        for (let index = firstIndex - 1; index >= 0; index--) {
×
489
            const element = this.editor.children[index] as Element;
×
490
            if (visibleStates[index]) {
×
491
                childrenWithPreRendering.unshift(element);
×
492
                childrenWithPreRenderingIndics.unshift(index);
×
493
                preRenderingCount = 1;
×
494
                break;
×
495
            }
496
        }
497
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
498
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
499
            const element = this.editor.children[index] as Element;
×
500
            if (visibleStates[index]) {
×
501
                childrenWithPreRendering.push(element);
×
502
                childrenWithPreRenderingIndics.push(index);
×
503
                break;
×
504
            }
505
        }
506
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
507
    }
508

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

588
    private calculateVirtualViewport(visibleStates: boolean[]) {
589
        const children = (this.editor.children || []) as Element[];
×
590
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
591
            return {
×
592
                inViewportChildren: children,
593
                inViewportIndics: [],
594
                top: 0,
595
                bottom: 0,
596
                heights: []
597
            };
598
        }
599
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
600
        let viewportHeight = getViewportHeight(this.editor);
×
601
        const elementLength = children.length;
×
602
        let businessTop = getBusinessTop(this.editor);
×
603
        if (businessTop === 0 && this.virtualScrollConfig.scrollTop > 0) {
×
NEW
604
            businessTop = calcBusinessTop(this.editor);
×
605
        }
606
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
607
        const totalHeight = accumulatedHeights[elementLength] + businessTop;
×
608
        let startPosition = Math.max(scrollTop - businessTop, 0);
×
609
        let endPosition = startPosition + viewportHeight;
×
610
        if (scrollTop < businessTop) {
×
611
            endPosition = startPosition + viewportHeight - (businessTop - scrollTop);
×
612
        }
613
        let accumulatedOffset = 0;
×
614
        let inViewportStartIndex = -1;
×
615
        const visible: Element[] = [];
×
616
        const inViewportIndics: number[] = [];
×
617
        for (let i = 0; i < elementLength && accumulatedOffset < endPosition; i++) {
×
618
            const currentHeight = heights[i];
×
619
            const nextOffset = accumulatedOffset + currentHeight;
×
620
            const isVisible = visibleStates[i];
×
621
            if (!isVisible) {
×
622
                accumulatedOffset = nextOffset;
×
623
                continue;
×
624
            }
625
            // 可视区域有交集,加入渲染
626
            if (nextOffset > startPosition && accumulatedOffset < endPosition) {
×
627
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
628
                visible.push(children[i]);
×
629
                inViewportIndics.push(i);
×
630
            }
631
            accumulatedOffset = nextOffset;
×
632
        }
633

634
        const inViewportEndIndex =
635
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
636
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
637
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
638
        return {
×
639
            inViewportChildren: visible.length ? visible : children,
×
640
            inViewportIndics,
641
            top,
642
            bottom,
643
            heights,
644
            accumulatedHeights
645
        };
646
    }
647

648
    private applyVirtualView(virtualView: VirtualViewResult) {
649
        this.inViewportChildren = virtualView.inViewportChildren;
×
650
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
651
        this.inViewportIndics = virtualView.inViewportIndics;
×
652
    }
653

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

792
    //#region event proxy
793
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
794
        this.manualListeners.push(
483✔
795
            this.renderer2.listen(target, eventName, (event: Event) => {
796
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
797
                if (beforeInputEvent) {
5!
798
                    this.onFallbackBeforeInput(beforeInputEvent);
×
799
                }
800
                listener(event);
5✔
801
            })
802
        );
803
    }
804

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

844
    private isSelectionInvisible(selection: Selection) {
845
        const anchorIndex = selection.anchor.path[0];
6✔
846
        const focusIndex = selection.focus.path[0];
6✔
847
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
848
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
849
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
850
    }
851

852
    toNativeSelection(autoScroll = true) {
15✔
853
        try {
15✔
854
            let { selection } = this.editor;
15✔
855

856
            if (this.isEnabledVirtualScroll()) {
15!
857
                selection = this.calculateVirtualScrollSelection(selection);
×
858
            }
859

860
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
861
            const { activeElement } = root;
15✔
862
            const domSelection = (root as Document).getSelection();
15✔
863

864
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
865
                return;
×
866
            }
867

868
            const hasDomSelection = domSelection.type !== 'None';
15✔
869

870
            // If the DOM selection is properly unset, we're done.
871
            if (!selection && !hasDomSelection) {
15!
UNCOV
872
                return;
×
873
            }
874

875
            // If the DOM selection is already correct, we're done.
876
            // verify that the dom selection is in the editor
877
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
15✔
878
            let hasDomSelectionInEditor = false;
15✔
879
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
15✔
880
                hasDomSelectionInEditor = true;
1✔
881
            }
882

883
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
15✔
884
                return;
14✔
885
            }
886

887
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
888
                return;
×
889
            }
890

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

902
            // prevent updating native selection when active element is void element
903
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
904
                return;
×
905
            }
906

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

916
            // Otherwise the DOM selection is out of sync, so update it.
917
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
918
            this.isUpdatingSelection = true;
1✔
919

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

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

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

978
    onChange() {
979
        this.forceRender();
13✔
980
        this.onChangeCallback(this.editor.children);
13✔
981
    }
982

983
    ngAfterViewChecked() {}
984

985
    ngDoCheck() {}
986

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

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

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

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

1136
    initializeContext() {
1137
        this.context = {
49✔
1138
            parent: this.editor,
1139
            selection: this.editor.selection,
1140
            decorations: this.generateDecorations(),
1141
            decorate: this.decorate,
1142
            readonly: this.readonly
1143
        };
1144
    }
1145

1146
    initializeViewContext() {
1147
        this.viewContext = {
23✔
1148
            editor: this.editor,
1149
            renderElement: this.renderElement,
1150
            renderLeaf: this.renderLeaf,
1151
            renderText: this.renderText,
1152
            trackBy: this.trackBy,
1153
            isStrictDecorate: this.isStrictDecorate
1154
        };
1155
    }
1156

1157
    composePlaceholderDecorate(editor: Editor) {
1158
        if (this.placeholderDecorate) {
64!
1159
            return this.placeholderDecorate(editor) || [];
×
1160
        }
1161

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

1176
    generateDecorations() {
1177
        const decorations = this.decorate([this.editor, []]);
66✔
1178
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1179
        decorations.push(...placeholderDecorations);
66✔
1180
        return decorations;
66✔
1181
    }
1182

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

1191
                if (activeElement === el) {
1!
1192
                    this.latestElement = activeElement;
1✔
1193
                    IS_FOCUSED.set(this.editor, true);
1✔
1194
                } else {
1195
                    IS_FOCUSED.delete(this.editor);
×
1196
                }
1197

1198
                if (!domSelection) {
1!
1199
                    return Transforms.deselect(this.editor);
×
1200
                }
1201

1202
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1203
                const hasDomSelectionInEditor =
1204
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1205
                if (!hasDomSelectionInEditor) {
1!
1206
                    Transforms.deselect(this.editor);
×
1207
                    return;
×
1208
                }
1209

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

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

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

1318
                switch (type) {
×
1319
                    case 'deleteByComposition':
1320
                    case 'deleteByCut':
1321
                    case 'deleteByDrag': {
1322
                        Editor.deleteFragment(editor);
×
1323
                        break;
×
1324
                    }
1325

1326
                    case 'deleteContent':
1327
                    case 'deleteContentForward': {
1328
                        Editor.deleteForward(editor);
×
1329
                        break;
×
1330
                    }
1331

1332
                    case 'deleteContentBackward': {
1333
                        Editor.deleteBackward(editor);
×
1334
                        break;
×
1335
                    }
1336

1337
                    case 'deleteEntireSoftLine': {
1338
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1339
                        Editor.deleteForward(editor, { unit: 'line' });
×
1340
                        break;
×
1341
                    }
1342

1343
                    case 'deleteHardLineBackward': {
1344
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1345
                        break;
×
1346
                    }
1347

1348
                    case 'deleteSoftLineBackward': {
1349
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1350
                        break;
×
1351
                    }
1352

1353
                    case 'deleteHardLineForward': {
1354
                        Editor.deleteForward(editor, { unit: 'block' });
×
1355
                        break;
×
1356
                    }
1357

1358
                    case 'deleteSoftLineForward': {
1359
                        Editor.deleteForward(editor, { unit: 'line' });
×
1360
                        break;
×
1361
                    }
1362

1363
                    case 'deleteWordBackward': {
1364
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1365
                        break;
×
1366
                    }
1367

1368
                    case 'deleteWordForward': {
1369
                        Editor.deleteForward(editor, { unit: 'word' });
×
1370
                        break;
×
1371
                    }
1372

1373
                    case 'insertLineBreak':
1374
                    case 'insertParagraph': {
1375
                        Editor.insertBreak(editor);
×
1376
                        break;
×
1377
                    }
1378

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

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

1424
        const window = AngularEditor.getWindow(this.editor);
×
1425

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

1435
        const { relatedTarget } = event;
×
1436
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1437

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

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

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

1457
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1458
                return;
×
1459
            }
1460
        }
1461

1462
        IS_FOCUSED.delete(this.editor);
×
1463
    }
1464

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

1477
            const startVoid = Editor.void(this.editor, { at: start });
×
1478
            const endVoid = Editor.void(this.editor, { at: end });
×
1479

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

1488
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1489
                }
1490

1491
                const range = Editor.range(this.editor, blockPath);
×
1492
                Transforms.select(this.editor, range);
×
1493
                return;
×
1494
            }
1495

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

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

1523
    private onDOMCompositionUpdate(event: CompositionEvent) {
1524
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1525
    }
1526

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

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

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

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

1563
            if (selection) {
×
1564
                AngularEditor.deleteCutData(this.editor);
×
1565
            }
1566
        }
1567
    }
1568

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

1576
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1577
                event.preventDefault();
×
1578
            }
1579
        }
1580
    }
1581

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

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

1596
            this.isDraggingInternally = true;
×
1597

1598
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1599
        }
1600
    }
1601

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

1609
            // Find the range where the drop happened
1610
            const range = AngularEditor.findEventRange(editor, event);
×
1611
            const data = event.dataTransfer;
×
1612

1613
            Transforms.select(editor, range);
×
1614

1615
            if (this.isDraggingInternally) {
×
1616
                if (draggedRange) {
×
1617
                    Transforms.delete(editor, {
×
1618
                        at: draggedRange
1619
                    });
1620
                }
1621

1622
                this.isDraggingInternally = false;
×
1623
            }
1624

1625
            AngularEditor.insertData(editor, data);
×
1626

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

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

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

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

1665
            IS_FOCUSED.set(this.editor, true);
2✔
1666
        }
1667
    }
1668

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

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

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

1694
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1695
                        editor.redo();
×
1696
                    }
1697

1698
                    return;
×
1699
                }
1700

1701
                if (Hotkeys.isUndo(nativeEvent)) {
×
1702
                    event.preventDefault();
×
1703

1704
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1705
                        editor.undo();
×
1706
                    }
1707

1708
                    return;
×
1709
                }
1710

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

1721
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1722
                    event.preventDefault();
×
1723
                    Transforms.move(editor, { unit: 'line' });
×
1724
                    return;
×
1725
                }
1726

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

1737
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1738
                    event.preventDefault();
×
1739
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1740
                    return;
×
1741
                }
1742

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

1751
                    if (selection && Range.isCollapsed(selection)) {
×
1752
                        Transforms.move(editor, { reverse: !isRTL });
×
1753
                    } else {
1754
                        Transforms.collapse(editor, { edge: 'start' });
×
1755
                    }
1756

1757
                    return;
×
1758
                }
1759

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

1768
                    return;
×
1769
                }
1770

1771
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1772
                    event.preventDefault();
×
1773

1774
                    if (selection && Range.isExpanded(selection)) {
×
1775
                        Transforms.collapse(editor, { edge: 'focus' });
×
1776
                    }
1777

1778
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1779
                    return;
×
1780
                }
1781

1782
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1783
                    event.preventDefault();
×
1784

1785
                    if (selection && Range.isExpanded(selection)) {
×
1786
                        Transforms.collapse(editor, { edge: 'focus' });
×
1787
                    }
1788

1789
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1790
                    return;
×
1791
                }
1792

1793
                if (isKeyHotkey('mod+a', event)) {
×
1794
                    this.editor.selectAll();
×
1795
                    event.preventDefault();
×
1796
                    return;
×
1797
                }
1798

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

1810
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1811
                        event.preventDefault();
×
1812
                        Editor.insertBreak(editor);
×
1813
                        return;
×
1814
                    }
1815

1816
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1817
                        event.preventDefault();
×
1818

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

1827
                        return;
×
1828
                    }
1829

1830
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1831
                        event.preventDefault();
×
1832

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

1841
                        return;
×
1842
                    }
1843

1844
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1845
                        event.preventDefault();
×
1846

1847
                        if (selection && Range.isExpanded(selection)) {
×
1848
                            Editor.deleteFragment(editor, {
×
1849
                                direction: 'backward'
1850
                            });
1851
                        } else {
1852
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1853
                        }
1854

1855
                        return;
×
1856
                    }
1857

1858
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1859
                        event.preventDefault();
×
1860

1861
                        if (selection && Range.isExpanded(selection)) {
×
1862
                            Editor.deleteFragment(editor, {
×
1863
                                direction: 'forward'
1864
                            });
1865
                        } else {
1866
                            Editor.deleteForward(editor, { unit: 'line' });
×
1867
                        }
1868

1869
                        return;
×
1870
                    }
1871

1872
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1873
                        event.preventDefault();
×
1874

1875
                        if (selection && Range.isExpanded(selection)) {
×
1876
                            Editor.deleteFragment(editor, {
×
1877
                                direction: 'backward'
1878
                            });
1879
                        } else {
1880
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1881
                        }
1882

1883
                        return;
×
1884
                    }
1885

1886
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1887
                        event.preventDefault();
×
1888

1889
                        if (selection && Range.isExpanded(selection)) {
×
1890
                            Editor.deleteFragment(editor, {
×
1891
                                direction: 'forward'
1892
                            });
1893
                        } else {
1894
                            Editor.deleteForward(editor, { unit: 'word' });
×
1895
                        }
1896

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

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

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

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

1987
    ngOnDestroy() {
1988
        this.editorResizeObserver?.disconnect();
22✔
1989
        this.editorScrollContainerResizeObserver?.disconnect();
22✔
1990
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1991
        this.manualListeners.forEach(manualListener => {
22✔
1992
            manualListener();
462✔
1993
        });
1994
        this.destroy$.complete();
22✔
1995
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1996
    }
1997
}
1998

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

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

2010
        if (isZeroDimensionRect) {
×
2011
            const leafRect = leafEl.getBoundingClientRect();
×
2012
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2013

2014
            if (leafHasDimensions) {
×
2015
                return;
×
2016
            }
2017
        }
2018

2019
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
2020
        scrollIntoView(leafEl, {
×
2021
            scrollMode: 'if-needed'
2022
        });
2023
        delete leafEl.getBoundingClientRect;
×
2024
    }
2025
};
2026

2027
/**
2028
 * Check if the target is inside void and in the editor.
2029
 */
2030

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

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

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