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

worktile / slate-angular / b6c00a85-246f-4823-a599-e1a8cb67663e

02 Feb 2026 04:08AM UTC coverage: 35.667% (-0.07%) from 35.734%
b6c00a85-246f-4823-a599-e1a8cb67663e

push

circleci

pubuzhixing8
performance(virtual-scroll): 1. add check condition, 2. check readonly mode in toNativeSelection

405 of 1343 branches covered (30.16%)

Branch coverage included in aggregate %.

1 of 6 new or added lines in 1 file covered. (16.67%)

1 existing line in 1 file now uncovered.

1113 of 2913 relevant lines covered (38.21%)

23.01 hits per line

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

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

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

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

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

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

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

115
    private initialized: boolean;
116

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

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

121
    @Input() editor: AngularEditor;
122

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

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

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

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

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

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

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

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

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

141
    @Input() placeholder: string;
142

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

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

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

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

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

187
    viewContainerRef = inject(ViewContainerRef);
23✔
188

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

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

201
    listRender: ListRender;
202

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

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

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

219
    virtualScrollInitialized = false;
23✔
220

221
    virtualTopHeightElement: HTMLElement;
222

223
    virtualBottomHeightElement: HTMLElement;
224

225
    virtualCenterOutlet: HTMLElement;
226

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

890
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
15✔
891
                return;
14✔
892
            }
893

894
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
NEW
895
                return;
×
896
            }
897

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

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

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

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

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

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

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

985
    onChange() {
986
        this.forceRender();
13✔
987
        this.onChangeCallback(this.editor.children);
13✔
988
    }
989

990
    ngAfterViewChecked() {}
991

992
    ngDoCheck() {}
993

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

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

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

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

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

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

1164
    composePlaceholderDecorate(editor: Editor) {
1165
        if (this.placeholderDecorate) {
64!
1166
            return this.placeholderDecorate(editor) || [];
×
1167
        }
1168

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

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

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

1198
                if (activeElement === el) {
1!
1199
                    this.latestElement = activeElement;
1✔
1200
                    IS_FOCUSED.set(this.editor, true);
1✔
1201
                } else {
1202
                    IS_FOCUSED.delete(this.editor);
×
1203
                }
1204

1205
                if (!domSelection) {
1!
1206
                    return Transforms.deselect(this.editor);
×
1207
                }
1208

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

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

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

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

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

1333
                    case 'deleteContent':
1334
                    case 'deleteContentForward': {
1335
                        Editor.deleteForward(editor);
×
1336
                        break;
×
1337
                    }
1338

1339
                    case 'deleteContentBackward': {
1340
                        Editor.deleteBackward(editor);
×
1341
                        break;
×
1342
                    }
1343

1344
                    case 'deleteEntireSoftLine': {
1345
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1346
                        Editor.deleteForward(editor, { unit: 'line' });
×
1347
                        break;
×
1348
                    }
1349

1350
                    case 'deleteHardLineBackward': {
1351
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1352
                        break;
×
1353
                    }
1354

1355
                    case 'deleteSoftLineBackward': {
1356
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1357
                        break;
×
1358
                    }
1359

1360
                    case 'deleteHardLineForward': {
1361
                        Editor.deleteForward(editor, { unit: 'block' });
×
1362
                        break;
×
1363
                    }
1364

1365
                    case 'deleteSoftLineForward': {
1366
                        Editor.deleteForward(editor, { unit: 'line' });
×
1367
                        break;
×
1368
                    }
1369

1370
                    case 'deleteWordBackward': {
1371
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1372
                        break;
×
1373
                    }
1374

1375
                    case 'deleteWordForward': {
1376
                        Editor.deleteForward(editor, { unit: 'word' });
×
1377
                        break;
×
1378
                    }
1379

1380
                    case 'insertLineBreak':
1381
                    case 'insertParagraph': {
1382
                        Editor.insertBreak(editor);
×
1383
                        break;
×
1384
                    }
1385

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

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

1431
        const window = AngularEditor.getWindow(this.editor);
×
1432

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

1442
        const { relatedTarget } = event;
×
1443
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1444

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

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

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

1464
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1465
                return;
×
1466
            }
1467
        }
1468

1469
        IS_FOCUSED.delete(this.editor);
×
1470
    }
1471

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

1484
            const startVoid = Editor.void(this.editor, { at: start });
×
1485
            const endVoid = Editor.void(this.editor, { at: end });
×
1486

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

1495
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1496
                }
1497

1498
                const range = Editor.range(this.editor, blockPath);
×
1499
                Transforms.select(this.editor, range);
×
1500
                return;
×
1501
            }
1502

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

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

1530
    private onDOMCompositionUpdate(event: CompositionEvent) {
1531
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1532
    }
1533

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

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

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

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

1570
            if (selection) {
×
1571
                AngularEditor.deleteCutData(this.editor);
×
1572
            }
1573
        }
1574
    }
1575

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

1583
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1584
                event.preventDefault();
×
1585
            }
1586
        }
1587
    }
1588

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

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

1603
            this.isDraggingInternally = true;
×
1604

1605
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1606
        }
1607
    }
1608

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

1616
            // Find the range where the drop happened
1617
            const range = AngularEditor.findEventRange(editor, event);
×
1618
            const data = event.dataTransfer;
×
1619

1620
            Transforms.select(editor, range);
×
1621

1622
            if (this.isDraggingInternally) {
×
1623
                if (draggedRange) {
×
1624
                    Transforms.delete(editor, {
×
1625
                        at: draggedRange
1626
                    });
1627
                }
1628

1629
                this.isDraggingInternally = false;
×
1630
            }
1631

1632
            AngularEditor.insertData(editor, data);
×
1633

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

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

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

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

1672
            IS_FOCUSED.set(this.editor, true);
2✔
1673
        }
1674
    }
1675

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

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

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

1701
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1702
                        editor.redo();
×
1703
                    }
1704

1705
                    return;
×
1706
                }
1707

1708
                if (Hotkeys.isUndo(nativeEvent)) {
×
1709
                    event.preventDefault();
×
1710

1711
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1712
                        editor.undo();
×
1713
                    }
1714

1715
                    return;
×
1716
                }
1717

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

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

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

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

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

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

1764
                    return;
×
1765
                }
1766

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

1775
                    return;
×
1776
                }
1777

1778
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1779
                    event.preventDefault();
×
1780

1781
                    if (selection && Range.isExpanded(selection)) {
×
1782
                        Transforms.collapse(editor, { edge: 'focus' });
×
1783
                    }
1784

1785
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1786
                    return;
×
1787
                }
1788

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

1792
                    if (selection && Range.isExpanded(selection)) {
×
1793
                        Transforms.collapse(editor, { edge: 'focus' });
×
1794
                    }
1795

1796
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1797
                    return;
×
1798
                }
1799

1800
                if (isKeyHotkey('mod+a', event)) {
×
1801
                    this.editor.selectAll();
×
1802
                    event.preventDefault();
×
1803
                    return;
×
1804
                }
1805

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

1817
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1818
                        event.preventDefault();
×
1819
                        Editor.insertBreak(editor);
×
1820
                        return;
×
1821
                    }
1822

1823
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1824
                        event.preventDefault();
×
1825

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

1834
                        return;
×
1835
                    }
1836

1837
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1838
                        event.preventDefault();
×
1839

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

1848
                        return;
×
1849
                    }
1850

1851
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1852
                        event.preventDefault();
×
1853

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

1862
                        return;
×
1863
                    }
1864

1865
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1866
                        event.preventDefault();
×
1867

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

1876
                        return;
×
1877
                    }
1878

1879
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1880
                        event.preventDefault();
×
1881

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

1890
                        return;
×
1891
                    }
1892

1893
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1894
                        event.preventDefault();
×
1895

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

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

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

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

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

1994
    ngOnDestroy() {
1995
        this.editorResizeObserver?.disconnect();
22✔
1996
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1997
        this.manualListeners.forEach(manualListener => {
22✔
1998
            manualListener();
462✔
1999
        });
2000
        this.destroy$.complete();
22✔
2001
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
2002
    }
2003
}
2004

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

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

2016
        if (isZeroDimensionRect) {
×
2017
            const leafRect = leafEl.getBoundingClientRect();
×
2018
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2019

2020
            if (leafHasDimensions) {
×
2021
                return;
×
2022
            }
2023
        }
2024

2025
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
2026
        scrollIntoView(leafEl, {
×
2027
            scrollMode: 'if-needed'
2028
        });
2029
        delete leafEl.getBoundingClientRect;
×
2030
    }
2031
};
2032

2033
/**
2034
 * Check if the target is inside void and in the editor.
2035
 */
2036

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

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

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