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

worktile / slate-angular / 354e9f3c-0d8e-4d19-8cc5-5f8e0c3bea1b

05 Feb 2026 03:38AM UTC coverage: 35.352% (+0.006%) from 35.346%
354e9f3c-0d8e-4d19-8cc5-5f8e0c3bea1b

push

circleci

pubuzhixing8
chore: improve calculation logic

409 of 1375 branches covered (29.75%)

Branch coverage included in aggregate %.

1 of 14 new or added lines in 1 file covered. (7.14%)

2 existing lines in 1 file now uncovered.

1126 of 2967 relevant lines covered (37.95%)

22.59 hits per line

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

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

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

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

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

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

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

120
    private initialized: boolean;
121

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

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

126
    @Input() editor: AngularEditor;
127

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

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

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

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

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

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

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

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

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

146
    @Input() placeholder: string;
147

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

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

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

206
    listRender: ListRender;
207

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

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

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

223
    virtualScrollInitialized = false;
23✔
224

225
    virtualTopHeightElement: HTMLElement;
226

227
    virtualBottomHeightElement: HTMLElement;
228

229
    virtualCenterOutlet: HTMLElement;
230

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

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

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

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

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

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

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

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

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

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

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

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

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

509
    calculateInViewportIndicsStartAndEndBySelection() {
510
        if (!this.editor.selection || Range.isCollapsed(this.editor.selection)) {
×
511
            return;
×
512
        }
NEW
513
        const isBackward = Range.isBackward(this.editor.selection);
×
514
        const anchorIndex = this.editor.selection.anchor.path[0];
×
515
        const focusIndex = this.editor.selection.focus.path[0];
×
516
        let minStartIndex = anchorIndex;
×
517
        let minEndIndex = focusIndex;
×
NEW
518
        if (isBackward) {
×
519
            minStartIndex = focusIndex;
×
520
            minEndIndex = anchorIndex;
×
521
        }
522
        if (minStartIndex < this.inViewportIndics[0]) {
×
523
            minStartIndex = this.inViewportIndics[0];
×
524
        }
525
        if (minEndIndex > this.inViewportIndics[this.inViewportIndics.length - 1]) {
×
526
            minEndIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
527
        }
528
        return { minStartIndex, minEndIndex };
×
529
    }
530

531
    private tryUpdateVirtualViewport() {
532
        if (isDebug) {
×
533
            debugLog('log', 'tryUpdateVirtualViewport');
×
534
        }
535
        const isFromScrollTo = EDITOR_TO_IS_FROM_SCROLL_TO.get(this.editor);
×
536
        if (this.inViewportIndics.length > 0 && !isFromScrollTo) {
×
537
            const realTopHeight = this.getActualVirtualTopHeight();
×
538
            const visibleStates = this.editor.getAllVisibleStates();
×
539
            const accumulateTopHeigh = calculateAccumulatedTopHeight(this.editor, this.inViewportIndics[0], visibleStates);
×
540
            if (realTopHeight !== accumulateTopHeigh) {
×
541
                if (isDebug) {
×
542
                    debugLog('log', 'update top height since dirty state,增加高度: ', accumulateTopHeigh - realTopHeight);
×
543
                }
544
                this.setVirtualSpaceHeight(accumulateTopHeigh);
×
545
                return;
×
546
            }
547
        }
548
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
549
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
550
            if (isDebug) {
×
551
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
552
            }
553
            const visibleStates = this.editor.getAllVisibleStates();
×
554
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
555
            let diff = this.diffVirtualViewport(virtualView);
×
556
            if (diff.isDifferent && diff.needRemoveOnTop && !isFromScrollTo) {
×
557
                const remeasureIndics = diff.changedIndexesOfTop;
×
558
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
559
                if (changed) {
×
560
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
561
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
562
                }
563
            }
564
            if (diff.isDifferent) {
×
565
                this.applyVirtualView(virtualView);
×
566
                if (this.listRender.initialized) {
×
567
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
568
                        this.appendPreRenderingToViewport(visibleStates);
×
569
                    this.listRender.update(
×
570
                        childrenWithPreRendering,
571
                        this.editor,
572
                        this.context,
573
                        preRenderingCount,
574
                        childrenWithPreRenderingIndics
575
                    );
576
                    if (diff.needAddOnTop && !isFromScrollTo) {
×
577
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
578
                        if (isDebug) {
×
579
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
580
                        }
581
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
582
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
583
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
584
                        if (changed) {
×
585
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
586
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
587
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
588
                            if (topHeightBeforeAdd !== actualTopHeightAfterAdd) {
×
589
                                this.setVirtualSpaceHeight(newTopHeight);
×
590
                                if (isDebug) {
×
591
                                    debugLog(
×
592
                                        'log',
593
                                        `update top height since will add element in top,减去高度: ${topHeightBeforeAdd - actualTopHeightAfterAdd}`
594
                                    );
595
                                }
596
                            }
597
                        }
598
                    }
599
                    if (this.editor.selection) {
×
600
                        this.toNativeSelection(false);
×
601
                    }
602
                }
603
            }
604
            if (isDebug) {
×
605
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
606
            }
607
        });
608
    }
609

610
    private calculateVirtualViewport(visibleStates: boolean[]) {
611
        const children = (this.editor.children || []) as Element[];
×
612
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
613
            return {
×
614
                inViewportChildren: children,
615
                inViewportIndics: [],
616
                top: 0,
617
                bottom: 0,
618
                heights: []
619
            };
620
        }
621
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
622
        let viewportHeight = getViewportHeight(this.editor);
×
623
        const elementLength = children.length;
×
624
        let businessTop = getBusinessTop(this.editor);
×
625
        if (businessTop === 0 && this.virtualScrollConfig.scrollTop > 0) {
×
626
            businessTop = calcBusinessTop(this.editor);
×
627
        }
628
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
629
        const totalHeight = accumulatedHeights[elementLength] + businessTop;
×
630
        let startPosition = Math.max(scrollTop - businessTop, 0);
×
631
        let endPosition = startPosition + viewportHeight;
×
632
        if (scrollTop < businessTop) {
×
633
            endPosition = startPosition + viewportHeight - (businessTop - scrollTop);
×
634
        }
635
        let accumulatedOffset = 0;
×
636
        const inViewportChildren: Element[] = [];
×
637
        const inViewportIndics: number[] = [];
×
NEW
638
        const startAndEndBySelection = this.calculateInViewportIndicsStartAndEndBySelection();
×
NEW
639
        if (isDebug) {
×
NEW
640
            debugLog('log', 'startAndEndBySelection: ', startAndEndBySelection);
×
641
        }
NEW
642
        for (let i = 0; i < elementLength; i++) {
×
643
            const currentHeight = heights[i];
×
644
            const nextOffset = accumulatedOffset + currentHeight;
×
645
            const isVisible = visibleStates[i];
×
646
            if (!isVisible) {
×
647
                accumulatedOffset = nextOffset;
×
648
                continue;
×
649
            }
NEW
650
            if (
×
651
                (startAndEndBySelection && i > startAndEndBySelection.minEndIndex && accumulatedOffset > endPosition) ||
×
652
                (!startAndEndBySelection && accumulatedOffset > endPosition)
653
            ) {
UNCOV
654
                break;
×
655
            }
NEW
656
            if (
×
657
                (startAndEndBySelection && i < startAndEndBySelection.minStartIndex && accumulatedOffset < startPosition) ||
×
658
                (!startAndEndBySelection && accumulatedOffset < startPosition)
659
            ) {
NEW
660
                accumulatedOffset = nextOffset;
×
NEW
661
                continue;
×
662
            }
NEW
663
            inViewportChildren.push(children[i]);
×
NEW
664
            inViewportIndics.push(i);
×
UNCOV
665
            accumulatedOffset = nextOffset;
×
666
        }
NEW
667
        const inViewportStartIndex = inViewportIndics[0] ?? -1;
×
668
        const inViewportEndIndex =
669
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
670
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
671
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
672
        return {
×
673
            inViewportChildren,
674
            inViewportIndics,
675
            top,
676
            bottom,
677
            heights,
678
            accumulatedHeights
679
        };
680
    }
681

682
    private applyVirtualView(virtualView: VirtualViewResult) {
683
        this.inViewportChildren = virtualView.inViewportChildren;
×
684
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
685
        this.inViewportIndics = virtualView.inViewportIndics;
×
686
    }
687

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

826
    //#region event proxy
827
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
828
        this.manualListeners.push(
483✔
829
            this.renderer2.listen(target, eventName, (event: Event) => {
830
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
831
                if (beforeInputEvent) {
5!
832
                    this.onFallbackBeforeInput(beforeInputEvent);
×
833
                }
834
                listener(event);
5✔
835
            })
836
        );
837
    }
838

839
    calculateVirtualScrollSelection(selection: Selection) {
840
        if (selection) {
×
841
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
842
            const indics = this.inViewportIndics;
×
843
            if (indics.length > 0) {
×
844
                const currentVisibleRange: Range = {
×
845
                    anchor: Editor.start(this.editor, [indics[0]]),
846
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
847
                };
848
                const [start, end] = Range.edges(selection);
×
849
                let forwardSelection = { anchor: start, focus: end };
×
850
                if (!isBlockCardCursor) {
×
851
                    forwardSelection = { anchor: start, focus: end };
×
852
                } else {
853
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
854
                }
855
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
856
                if (intersectedSelection && isBlockCardCursor) {
×
857
                    return selection;
×
858
                }
859
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
860
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
861
                    if (isDebug) {
×
862
                        debugLog(
×
863
                            'log',
864
                            `selection is not in visible range, selection: ${JSON.stringify(
865
                                selection
866
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
867
                        );
868
                    }
869
                    return intersectedSelection;
×
870
                }
871
                return selection;
×
872
            }
873
        }
874
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
875
        return selection;
×
876
    }
877

878
    private isSelectionInvisible(selection: Selection) {
879
        const anchorIndex = selection.anchor.path[0];
6✔
880
        const focusIndex = selection.focus.path[0];
6✔
881
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
882
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
883
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
884
    }
885

886
    toNativeSelection(autoScroll = true) {
15✔
887
        try {
15✔
888
            let { selection } = this.editor;
15✔
889

890
            if (this.isEnabledVirtualScroll() && Range.isCollapsed(selection)) {
15!
891
                selection = this.calculateVirtualScrollSelection(selection);
×
892
            }
893

894
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
895
            const { activeElement } = root;
15✔
896
            const domSelection = (root as Document).getSelection();
15✔
897

898
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
899
                return;
×
900
            }
901

902
            const hasDomSelection = domSelection.type !== 'None';
15✔
903

904
            // If the DOM selection is properly unset, we're done.
905
            if (!selection && !hasDomSelection) {
15✔
906
                return;
9✔
907
            }
908

909
            // If the DOM selection is already correct, we're done.
910
            // verify that the dom selection is in the editor
911
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
6✔
912
            let hasDomSelectionInEditor = false;
6✔
913
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
6✔
914
                hasDomSelectionInEditor = true;
1✔
915
            }
916

917
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
6✔
918
                return;
5✔
919
            }
920

921
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
922
                return;
×
923
            }
924

925
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
926
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
927
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
928
                    exactMatch: false,
929
                    suppressThrow: true
930
                });
931
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
932
                    return;
×
933
                }
934
            }
935

936
            // prevent updating native selection when active element is void element
937
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
938
                return;
×
939
            }
940

941
            // when <Editable/> is being controlled through external value
942
            // then its children might just change - DOM responds to it on its own
943
            // but Slate's value is not being updated through any operation
944
            // and thus it doesn't transform selection on its own
945
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
946
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
947
                return;
×
948
            }
949

950
            // Otherwise the DOM selection is out of sync, so update it.
951
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
952
            this.isUpdatingSelection = true;
1✔
953

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

956
            if (newDomRange) {
1!
957
                // COMPAT: Since the DOM range has no concept of backwards/forwards
958
                // we need to check and do the right thing here.
959
                if (Range.isBackward(selection)) {
1!
960
                    // eslint-disable-next-line max-len
961
                    domSelection.setBaseAndExtent(
×
962
                        newDomRange.endContainer,
963
                        newDomRange.endOffset,
964
                        newDomRange.startContainer,
965
                        newDomRange.startOffset
966
                    );
967
                } else {
968
                    // eslint-disable-next-line max-len
969
                    domSelection.setBaseAndExtent(
1✔
970
                        newDomRange.startContainer,
971
                        newDomRange.startOffset,
972
                        newDomRange.endContainer,
973
                        newDomRange.endOffset
974
                    );
975
                }
976
            } else {
977
                domSelection.removeAllRanges();
×
978
            }
979

980
            setTimeout(() => {
1✔
981
                if (
1!
982
                    this.isEnabledVirtualScroll() &&
1!
983
                    !selection &&
984
                    this.editor.selection &&
985
                    autoScroll &&
986
                    this.virtualScrollConfig.scrollContainer
987
                ) {
988
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
989
                    this.isUpdatingSelection = false;
×
990
                    return;
×
991
                } else {
992
                    // handle scrolling in setTimeout because of
993
                    // dom should not have updated immediately after listRender's updating
994
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
995
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
996
                    // to focus the contenteditable element too. (2016/11/16)
997
                    if (newDomRange && IS_FIREFOX) {
1!
998
                        el.focus();
×
999
                    }
1000
                }
1001
                this.isUpdatingSelection = false;
1✔
1002
            });
1003
        } catch (error) {
1004
            this.editor.onError({
×
1005
                code: SlateErrorCode.ToNativeSelectionError,
1006
                nativeError: error
1007
            });
1008
            this.isUpdatingSelection = false;
×
1009
        }
1010
    }
1011

1012
    onChange() {
1013
        this.forceRender();
13✔
1014
        this.onChangeCallback(this.editor.children);
13✔
1015
    }
1016

1017
    ngAfterViewChecked() {}
1018

1019
    ngDoCheck() {}
1020

1021
    forceRender() {
1022
        this.updateContext();
15✔
1023
        if (this.isEnabledVirtualScroll()) {
15!
1024
            this.updateListRenderAndRemeasureHeights();
×
1025
        } else {
1026
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
1027
        }
1028
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
1029
        // when the DOMElement where the selection is located is removed
1030
        // the compositionupdate and compositionend events will no longer be fired
1031
        // so isComposing needs to be corrected
1032
        // need exec after this.cdr.detectChanges() to render HTML
1033
        // need exec before this.toNativeSelection() to correct native selection
1034
        if (this.isComposing) {
15!
1035
            // Composition input text be not rendered when user composition input with selection is expanded
1036
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
1037
            // this time condition is true and isComposing is assigned false
1038
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
1039
            setTimeout(() => {
×
1040
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
1041
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
1042
                let textContent = '';
×
1043
                // skip decorate text
1044
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
1045
                    let text = stringDOMNode.textContent;
×
1046
                    const zeroChar = '\uFEFF';
×
1047
                    // remove zero with char
1048
                    if (text.startsWith(zeroChar)) {
×
1049
                        text = text.slice(1);
×
1050
                    }
1051
                    if (text.endsWith(zeroChar)) {
×
1052
                        text = text.slice(0, text.length - 1);
×
1053
                    }
1054
                    textContent += text;
×
1055
                });
1056
                if (Node.string(textNode).endsWith(textContent)) {
×
1057
                    this.isComposing = false;
×
1058
                }
1059
            }, 0);
1060
        }
1061
        if (this.editor.selection && this.isSelectionInvisible(this.editor.selection)) {
15!
1062
            Transforms.deselect(this.editor);
×
1063
            return;
×
1064
        } else {
1065
            this.toNativeSelection();
15✔
1066
        }
1067
    }
1068

1069
    render() {
1070
        const changed = this.updateContext();
2✔
1071
        if (changed) {
2✔
1072
            if (this.isEnabledVirtualScroll()) {
2!
1073
                this.updateListRenderAndRemeasureHeights();
×
1074
            } else {
1075
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
1076
            }
1077
        }
1078
    }
1079

1080
    updateListRenderAndRemeasureHeights() {
1081
        const operations = this.editor.operations;
×
1082
        const firstIndex = this.inViewportIndics[0];
×
1083
        const operationsOfFirstElementMerged = operations.filter(
×
1084
            op => op.type === 'merge_node' && op.path.length === 1 && firstIndex === op.path[0] - 1
×
1085
        );
1086
        const operationsOfFirstElementSplitted = operations.filter(
×
1087
            op => op.type === 'split_node' && op.path.length === 1 && firstIndex === op.path[0]
×
1088
        );
1089
        const mutationOfFirstElementHeight = operationsOfFirstElementSplitted.length > 0 || operationsOfFirstElementMerged.length > 0;
×
1090
        const visibleStates = this.editor.getAllVisibleStates();
×
1091
        const previousInViewportChildren = [...this.inViewportChildren];
×
1092
        // the first element height will reset to default height when split or merge
1093
        // if the most top content of the first element is not in viewport, the change of height will cause the viewport to scroll
1094
        // to keep viewport stable, we need to use the current inViewportIndics temporarily
1095
        if (mutationOfFirstElementHeight) {
×
1096
            const newInViewportIndics = [];
×
1097
            const newInViewportChildren = [];
×
1098
            this.inViewportIndics.forEach(index => {
×
1099
                const element = this.editor.children[index] as Element;
×
1100
                const isVisible = visibleStates[index];
×
1101
                if (isVisible) {
×
1102
                    newInViewportIndics.push(index);
×
1103
                    newInViewportChildren.push(element);
×
1104
                }
1105
            });
1106
            if (operationsOfFirstElementSplitted.length > 0) {
×
1107
                const lastIndex = newInViewportIndics[newInViewportIndics.length - 1];
×
1108
                for (let i = lastIndex + 1; i < this.editor.children.length; i++) {
×
1109
                    const element = this.editor.children[i] as Element;
×
1110
                    const isVisible = visibleStates[i];
×
1111
                    if (isVisible) {
×
1112
                        newInViewportIndics.push(i);
×
1113
                        newInViewportChildren.push(element);
×
1114
                        break;
×
1115
                    }
1116
                }
1117
            }
1118
            this.inViewportIndics = newInViewportIndics;
×
1119
            this.inViewportChildren = newInViewportChildren;
×
1120
            if (isDebug) {
×
1121
                debugLog(
×
1122
                    'log',
1123
                    'updateListRenderAndRemeasureHeights',
1124
                    'mutationOfFirstElementHeight',
1125
                    'newInViewportIndics',
1126
                    newInViewportIndics
1127
                );
1128
            }
1129
        } else {
1130
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
1131
            let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
1132
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
1133
                const remeasureIndics = diff.changedIndexesOfTop;
×
1134
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
1135
                if (changed) {
×
1136
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
1137
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
1138
                }
1139
            }
1140
            this.applyVirtualView(virtualView);
×
1141
        }
1142
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
1143
            this.appendPreRenderingToViewport(visibleStates);
×
1144
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
1145
        const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
1146
        if (remeasureIndics.length) {
×
1147
            this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
1148
        }
1149
    }
1150

1151
    updateContext() {
1152
        const decorations = this.generateDecorations();
17✔
1153
        if (
17✔
1154
            this.context.selection !== this.editor.selection ||
46✔
1155
            this.context.decorate !== this.decorate ||
1156
            this.context.readonly !== this.readonly ||
1157
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
1158
        ) {
1159
            this.context = {
10✔
1160
                parent: this.editor,
1161
                selection: this.editor.selection,
1162
                decorations: decorations,
1163
                decorate: this.decorate,
1164
                readonly: this.readonly
1165
            };
1166
            return true;
10✔
1167
        }
1168
        return false;
7✔
1169
    }
1170

1171
    initializeContext() {
1172
        this.context = {
49✔
1173
            parent: this.editor,
1174
            selection: this.editor.selection,
1175
            decorations: this.generateDecorations(),
1176
            decorate: this.decorate,
1177
            readonly: this.readonly
1178
        };
1179
    }
1180

1181
    initializeViewContext() {
1182
        this.viewContext = {
23✔
1183
            editor: this.editor,
1184
            renderElement: this.renderElement,
1185
            renderLeaf: this.renderLeaf,
1186
            renderText: this.renderText,
1187
            trackBy: this.trackBy,
1188
            isStrictDecorate: this.isStrictDecorate
1189
        };
1190
    }
1191

1192
    composePlaceholderDecorate(editor: Editor) {
1193
        if (this.placeholderDecorate) {
64!
1194
            return this.placeholderDecorate(editor) || [];
×
1195
        }
1196

1197
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
1198
            const start = Editor.start(editor, []);
3✔
1199
            return [
3✔
1200
                {
1201
                    placeholder: this.placeholder,
1202
                    anchor: start,
1203
                    focus: start
1204
                }
1205
            ];
1206
        } else {
1207
            return [];
61✔
1208
        }
1209
    }
1210

1211
    generateDecorations() {
1212
        const decorations = this.decorate([this.editor, []]);
66✔
1213
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1214
        decorations.push(...placeholderDecorations);
66✔
1215
        return decorations;
66✔
1216
    }
1217

1218
    private toSlateSelection() {
1219
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1220
            try {
1✔
1221
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1222
                const { activeElement } = root;
1✔
1223
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1224
                const domSelection = (root as Document).getSelection();
1✔
1225

1226
                if (activeElement === el) {
1!
1227
                    this.latestElement = activeElement;
1✔
1228
                    IS_FOCUSED.set(this.editor, true);
1✔
1229
                } else {
1230
                    IS_FOCUSED.delete(this.editor);
×
1231
                }
1232

1233
                if (!domSelection) {
1!
1234
                    return Transforms.deselect(this.editor);
×
1235
                }
1236

1237
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1238
                const hasDomSelectionInEditor =
1239
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1240
                if (!hasDomSelectionInEditor) {
1!
1241
                    Transforms.deselect(this.editor);
×
1242
                    return;
×
1243
                }
1244

1245
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1246
                // for example, double-click the last cell of the table to select a non-editable DOM
1247
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1248
                if (range) {
1✔
1249
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1250
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1251
                            // force adjust DOMSelection
1252
                            this.toNativeSelection(false);
×
1253
                        }
1254
                    } else {
1255
                        Transforms.select(this.editor, range);
1✔
1256
                    }
1257
                }
1258
            } catch (error) {
1259
                this.editor.onError({
×
1260
                    code: SlateErrorCode.ToSlateSelectionError,
1261
                    nativeError: error
1262
                });
1263
            }
1264
        }
1265
    }
1266

1267
    private onDOMBeforeInput(
1268
        event: Event & {
1269
            inputType: string;
1270
            isComposing: boolean;
1271
            data: string | null;
1272
            dataTransfer: DataTransfer | null;
1273
            getTargetRanges(): DOMStaticRange[];
1274
        }
1275
    ) {
1276
        const editor = this.editor;
×
1277
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1278
        const { activeElement } = root;
×
1279
        const { selection } = editor;
×
1280
        const { inputType: type } = event;
×
1281
        const data = event.dataTransfer || event.data || undefined;
×
1282
        if (IS_ANDROID) {
×
1283
            let targetRange: Range | null = null;
×
1284
            let [nativeTargetRange] = event.getTargetRanges();
×
1285
            if (nativeTargetRange) {
×
1286
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1287
            }
1288
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1289
            // have to manually get the selection here to ensure it's up-to-date.
1290
            const window = AngularEditor.getWindow(editor);
×
1291
            const domSelection = window.getSelection();
×
1292
            if (!targetRange && domSelection) {
×
1293
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1294
            }
1295
            targetRange = targetRange ?? editor.selection;
×
1296
            if (type === 'insertCompositionText') {
×
1297
                if (data && data.toString().includes('\n')) {
×
1298
                    restoreDom(editor, () => {
×
1299
                        Editor.insertBreak(editor);
×
1300
                    });
1301
                } else {
1302
                    if (targetRange) {
×
1303
                        if (data) {
×
1304
                            restoreDom(editor, () => {
×
1305
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1306
                            });
1307
                        } else {
1308
                            restoreDom(editor, () => {
×
1309
                                Transforms.delete(editor, { at: targetRange });
×
1310
                            });
1311
                        }
1312
                    }
1313
                }
1314
                return;
×
1315
            }
1316
            if (type === 'deleteContentBackward') {
×
1317
                // gboard can not prevent default action, so must use restoreDom,
1318
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1319
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1320
                if (!Range.isCollapsed(targetRange)) {
×
1321
                    restoreDom(editor, () => {
×
1322
                        Transforms.delete(editor, { at: targetRange });
×
1323
                    });
1324
                    return;
×
1325
                }
1326
            }
1327
            if (type === 'insertText') {
×
1328
                restoreDom(editor, () => {
×
1329
                    if (typeof data === 'string') {
×
1330
                        Editor.insertText(editor, data);
×
1331
                    }
1332
                });
1333
                return;
×
1334
            }
1335
        }
1336
        if (
×
1337
            !this.readonly &&
×
1338
            AngularEditor.hasEditableTarget(editor, event.target) &&
1339
            !isTargetInsideVoid(editor, activeElement) &&
1340
            !this.isDOMEventHandled(event, this.beforeInput)
1341
        ) {
1342
            try {
×
1343
                event.preventDefault();
×
1344

1345
                // COMPAT: If the selection is expanded, even if the command seems like
1346
                // a delete forward/backward command it should delete the selection.
1347
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1348
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1349
                    Editor.deleteFragment(editor, { direction });
×
1350
                    return;
×
1351
                }
1352

1353
                switch (type) {
×
1354
                    case 'deleteByComposition':
1355
                    case 'deleteByCut':
1356
                    case 'deleteByDrag': {
1357
                        Editor.deleteFragment(editor);
×
1358
                        break;
×
1359
                    }
1360

1361
                    case 'deleteContent':
1362
                    case 'deleteContentForward': {
1363
                        Editor.deleteForward(editor);
×
1364
                        break;
×
1365
                    }
1366

1367
                    case 'deleteContentBackward': {
1368
                        Editor.deleteBackward(editor);
×
1369
                        break;
×
1370
                    }
1371

1372
                    case 'deleteEntireSoftLine': {
1373
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1374
                        Editor.deleteForward(editor, { unit: 'line' });
×
1375
                        break;
×
1376
                    }
1377

1378
                    case 'deleteHardLineBackward': {
1379
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1380
                        break;
×
1381
                    }
1382

1383
                    case 'deleteSoftLineBackward': {
1384
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1385
                        break;
×
1386
                    }
1387

1388
                    case 'deleteHardLineForward': {
1389
                        Editor.deleteForward(editor, { unit: 'block' });
×
1390
                        break;
×
1391
                    }
1392

1393
                    case 'deleteSoftLineForward': {
1394
                        Editor.deleteForward(editor, { unit: 'line' });
×
1395
                        break;
×
1396
                    }
1397

1398
                    case 'deleteWordBackward': {
1399
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1400
                        break;
×
1401
                    }
1402

1403
                    case 'deleteWordForward': {
1404
                        Editor.deleteForward(editor, { unit: 'word' });
×
1405
                        break;
×
1406
                    }
1407

1408
                    case 'insertLineBreak':
1409
                    case 'insertParagraph': {
1410
                        Editor.insertBreak(editor);
×
1411
                        break;
×
1412
                    }
1413

1414
                    case 'insertFromComposition': {
1415
                        // COMPAT: in safari, `compositionend` event is dispatched after
1416
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1417
                        // https://www.w3.org/TR/input-events-2/
1418
                        // so the following code is the right logic
1419
                        // because DOM selection in sync will be exec before `compositionend` event
1420
                        // isComposing is true will prevent DOM selection being update correctly.
1421
                        this.isComposing = false;
×
1422
                        preventInsertFromComposition(event, this.editor);
×
1423
                    }
1424
                    case 'insertFromDrop':
1425
                    case 'insertFromPaste':
1426
                    case 'insertFromYank':
1427
                    case 'insertReplacementText':
1428
                    case 'insertText': {
1429
                        // use a weak comparison instead of 'instanceof' to allow
1430
                        // programmatic access of paste events coming from external windows
1431
                        // like cypress where cy.window does not work realibly
1432
                        if (data?.constructor.name === 'DataTransfer') {
×
1433
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1434
                        } else if (typeof data === 'string') {
×
1435
                            Editor.insertText(editor, data);
×
1436
                        }
1437
                        break;
×
1438
                    }
1439
                }
1440
            } catch (error) {
1441
                this.editor.onError({
×
1442
                    code: SlateErrorCode.OnDOMBeforeInputError,
1443
                    nativeError: error
1444
                });
1445
            }
1446
        }
1447
    }
1448

1449
    private onDOMBlur(event: FocusEvent) {
1450
        if (
×
1451
            this.readonly ||
×
1452
            this.isUpdatingSelection ||
1453
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1454
            this.isDOMEventHandled(event, this.blur)
1455
        ) {
1456
            return;
×
1457
        }
1458

1459
        const window = AngularEditor.getWindow(this.editor);
×
1460

1461
        // COMPAT: If the current `activeElement` is still the previous
1462
        // one, this is due to the window being blurred when the tab
1463
        // itself becomes unfocused, so we want to abort early to allow to
1464
        // editor to stay focused when the tab becomes focused again.
1465
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1466
        if (this.latestElement === root.activeElement) {
×
1467
            return;
×
1468
        }
1469

1470
        const { relatedTarget } = event;
×
1471
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1472

1473
        // COMPAT: The event should be ignored if the focus is returning
1474
        // to the editor from an embedded editable element (eg. an <input>
1475
        // element inside a void node).
1476
        if (relatedTarget === el) {
×
1477
            return;
×
1478
        }
1479

1480
        // COMPAT: The event should be ignored if the focus is moving from
1481
        // the editor to inside a void node's spacer element.
1482
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1483
            return;
×
1484
        }
1485

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

1492
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1493
                return;
×
1494
            }
1495
        }
1496

1497
        IS_FOCUSED.delete(this.editor);
×
1498
    }
1499

1500
    private onDOMClick(event: MouseEvent) {
1501
        if (
×
1502
            !this.readonly &&
×
1503
            AngularEditor.hasTarget(this.editor, event.target) &&
1504
            !this.isDOMEventHandled(event, this.click) &&
1505
            isDOMNode(event.target)
1506
        ) {
1507
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1508
            const path = AngularEditor.findPath(this.editor, node);
×
1509
            const start = Editor.start(this.editor, path);
×
1510
            const end = Editor.end(this.editor, path);
×
1511

1512
            const startVoid = Editor.void(this.editor, { at: start });
×
1513
            const endVoid = Editor.void(this.editor, { at: end });
×
1514

1515
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1516
                let blockPath = path;
×
1517
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1518
                    const block = Editor.above(this.editor, {
×
1519
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1520
                        at: path
1521
                    });
1522

1523
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1524
                }
1525

1526
                const range = Editor.range(this.editor, blockPath);
×
1527
                Transforms.select(this.editor, range);
×
1528
                return;
×
1529
            }
1530

1531
            if (
×
1532
                startVoid &&
×
1533
                endVoid &&
1534
                Path.equals(startVoid[1], endVoid[1]) &&
1535
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1536
            ) {
1537
                const range = Editor.range(this.editor, start);
×
1538
                Transforms.select(this.editor, range);
×
1539
            }
1540
        }
1541
    }
1542

1543
    private onDOMCompositionStart(event: CompositionEvent) {
1544
        const { selection } = this.editor;
1✔
1545
        if (selection) {
1!
1546
            // solve the problem of cross node Chinese input
1547
            if (Range.isExpanded(selection)) {
×
1548
                Editor.deleteFragment(this.editor);
×
1549
                this.forceRender();
×
1550
            }
1551
        }
1552
        if (
1✔
1553
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
3✔
1554
            !isSelectionInsideVoid(this.editor) &&
1555
            !this.isDOMEventHandled(event, this.compositionStart)
1556
        ) {
1557
            this.isComposing = true;
1✔
1558
        }
1559
        this.render();
1✔
1560
    }
1561

1562
    private onDOMCompositionUpdate(event: CompositionEvent) {
1563
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1564
    }
1565

1566
    private onDOMCompositionEnd(event: CompositionEvent) {
1567
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1568
            Transforms.delete(this.editor);
×
1569
        }
1570
        if (
×
1571
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
×
1572
            !isSelectionInsideVoid(this.editor) &&
1573
            !this.isDOMEventHandled(event, this.compositionEnd)
1574
        ) {
1575
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1576
            // aren't correct and never fire the "insertFromComposition"
1577
            // type that we need. So instead, insert whenever a composition
1578
            // ends since it will already have been committed to the DOM.
1579
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1580
                preventInsertFromComposition(event, this.editor);
×
1581
                Editor.insertText(this.editor, event.data);
×
1582
            }
1583

1584
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1585
            // so we need avoid repeat insertText by isComposing === true,
1586
            this.isComposing = false;
×
1587
        }
1588
        this.render();
×
1589
    }
1590

1591
    private onDOMCopy(event: ClipboardEvent) {
1592
        const window = AngularEditor.getWindow(this.editor);
×
1593
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1594
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1595
            event.preventDefault();
×
1596
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1597
        }
1598
    }
1599

1600
    private onDOMCut(event: ClipboardEvent) {
1601
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1602
            event.preventDefault();
×
1603
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1604
            const { selection } = this.editor;
×
1605

1606
            if (selection) {
×
1607
                AngularEditor.deleteCutData(this.editor);
×
1608
            }
1609
        }
1610
    }
1611

1612
    private onDOMDragOver(event: DragEvent) {
1613
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1614
            // Only when the target is void, call `preventDefault` to signal
1615
            // that drops are allowed. Editable content is droppable by
1616
            // default, and calling `preventDefault` hides the cursor.
1617
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1618

1619
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1620
                event.preventDefault();
×
1621
            }
1622
        }
1623
    }
1624

1625
    private onDOMDragStart(event: DragEvent) {
1626
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1627
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1628
            const path = AngularEditor.findPath(this.editor, node);
×
1629
            const voidMatch =
1630
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1631

1632
            // If starting a drag on a void node, make sure it is selected
1633
            // so that it shows up in the selection's fragment.
1634
            if (voidMatch) {
×
1635
                const range = Editor.range(this.editor, path);
×
1636
                Transforms.select(this.editor, range);
×
1637
            }
1638

1639
            this.isDraggingInternally = true;
×
1640

1641
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1642
        }
1643
    }
1644

1645
    private onDOMDrop(event: DragEvent) {
1646
        const editor = this.editor;
×
1647
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1648
            event.preventDefault();
×
1649
            // Keep a reference to the dragged range before updating selection
1650
            const draggedRange = editor.selection;
×
1651

1652
            // Find the range where the drop happened
1653
            const range = AngularEditor.findEventRange(editor, event);
×
1654
            const data = event.dataTransfer;
×
1655

1656
            Transforms.select(editor, range);
×
1657

1658
            if (this.isDraggingInternally) {
×
1659
                if (draggedRange) {
×
1660
                    Transforms.delete(editor, {
×
1661
                        at: draggedRange
1662
                    });
1663
                }
1664

1665
                this.isDraggingInternally = false;
×
1666
            }
1667

1668
            AngularEditor.insertData(editor, data);
×
1669

1670
            // When dragging from another source into the editor, it's possible
1671
            // that the current editor does not have focus.
1672
            if (!AngularEditor.isFocused(editor)) {
×
1673
                AngularEditor.focus(editor);
×
1674
            }
1675
        }
1676
    }
1677

1678
    private onDOMDragEnd(event: DragEvent) {
1679
        if (
×
1680
            !this.readonly &&
×
1681
            this.isDraggingInternally &&
1682
            AngularEditor.hasTarget(this.editor, event.target) &&
1683
            !this.isDOMEventHandled(event, this.dragEnd)
1684
        ) {
1685
            this.isDraggingInternally = false;
×
1686
        }
1687
    }
1688

1689
    private onDOMFocus(event: Event) {
1690
        if (
2✔
1691
            !this.readonly &&
8✔
1692
            !this.isUpdatingSelection &&
1693
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1694
            !this.isDOMEventHandled(event, this.focus)
1695
        ) {
1696
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1697
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1698
            this.latestElement = root.activeElement;
2✔
1699

1700
            // COMPAT: If the editor has nested editable elements, the focus
1701
            // can go to them. In Firefox, this must be prevented because it
1702
            // results in issues with keyboard navigation. (2017/03/30)
1703
            if (IS_FIREFOX && event.target !== el) {
2!
1704
                el.focus();
×
1705
                return;
×
1706
            }
1707

1708
            IS_FOCUSED.set(this.editor, true);
2✔
1709
        }
1710
    }
1711

1712
    private onDOMKeydown(event: KeyboardEvent) {
1713
        const editor = this.editor;
×
1714
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1715
        const { activeElement } = root;
×
1716
        if (
×
1717
            !this.readonly &&
×
1718
            AngularEditor.hasEditableTarget(editor, event.target) &&
1719
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1720
            !this.isComposing &&
1721
            !this.isDOMEventHandled(event, this.keydown)
1722
        ) {
1723
            const nativeEvent = event;
×
1724
            const { selection } = editor;
×
1725

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

1729
            try {
×
1730
                // COMPAT: Since we prevent the default behavior on
1731
                // `beforeinput` events, the browser doesn't think there's ever
1732
                // any history stack to undo or redo, so we have to manage these
1733
                // hotkeys ourselves. (2019/11/06)
1734
                if (Hotkeys.isRedo(nativeEvent)) {
×
1735
                    event.preventDefault();
×
1736

1737
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1738
                        editor.redo();
×
1739
                    }
1740

1741
                    return;
×
1742
                }
1743

1744
                if (Hotkeys.isUndo(nativeEvent)) {
×
1745
                    event.preventDefault();
×
1746

1747
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1748
                        editor.undo();
×
1749
                    }
1750

1751
                    return;
×
1752
                }
1753

1754
                // COMPAT: Certain browsers don't handle the selection updates
1755
                // properly. In Chrome, the selection isn't properly extended.
1756
                // And in Firefox, the selection isn't properly collapsed.
1757
                // (2017/10/17)
1758
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1759
                    event.preventDefault();
×
1760
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1761
                    return;
×
1762
                }
1763

1764
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1765
                    event.preventDefault();
×
1766
                    Transforms.move(editor, { unit: 'line' });
×
1767
                    return;
×
1768
                }
1769

1770
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1771
                    event.preventDefault();
×
1772
                    Transforms.move(editor, {
×
1773
                        unit: 'line',
1774
                        edge: 'focus',
1775
                        reverse: true
1776
                    });
1777
                    return;
×
1778
                }
1779

1780
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1781
                    event.preventDefault();
×
1782
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1783
                    return;
×
1784
                }
1785

1786
                // COMPAT: If a void node is selected, or a zero-width text node
1787
                // adjacent to an inline is selected, we need to handle these
1788
                // hotkeys manually because browsers won't be able to skip over
1789
                // the void node with the zero-width space not being an empty
1790
                // string.
1791
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1792
                    event.preventDefault();
×
1793

1794
                    if (selection && Range.isCollapsed(selection)) {
×
1795
                        Transforms.move(editor, { reverse: !isRTL });
×
1796
                    } else {
1797
                        Transforms.collapse(editor, { edge: 'start' });
×
1798
                    }
1799

1800
                    return;
×
1801
                }
1802

1803
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1804
                    event.preventDefault();
×
1805
                    if (selection && Range.isCollapsed(selection)) {
×
1806
                        Transforms.move(editor, { reverse: isRTL });
×
1807
                    } else {
1808
                        Transforms.collapse(editor, { edge: 'end' });
×
1809
                    }
1810

1811
                    return;
×
1812
                }
1813

1814
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1815
                    event.preventDefault();
×
1816

1817
                    if (selection && Range.isExpanded(selection)) {
×
1818
                        Transforms.collapse(editor, { edge: 'focus' });
×
1819
                    }
1820

1821
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1822
                    return;
×
1823
                }
1824

1825
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1826
                    event.preventDefault();
×
1827

1828
                    if (selection && Range.isExpanded(selection)) {
×
1829
                        Transforms.collapse(editor, { edge: 'focus' });
×
1830
                    }
1831

1832
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1833
                    return;
×
1834
                }
1835

1836
                if (isKeyHotkey('mod+a', event)) {
×
1837
                    this.editor.selectAll();
×
1838
                    event.preventDefault();
×
1839
                    return;
×
1840
                }
1841

1842
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1843
                // fall back to guessing at the input intention for hotkeys.
1844
                // COMPAT: In iOS, some of these hotkeys are handled in the
1845
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1846
                    // We don't have a core behavior for these, but they change the
1847
                    // DOM if we don't prevent them, so we have to.
1848
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1849
                        event.preventDefault();
×
1850
                        return;
×
1851
                    }
1852

1853
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1854
                        event.preventDefault();
×
1855
                        Editor.insertBreak(editor);
×
1856
                        return;
×
1857
                    }
1858

1859
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1860
                        event.preventDefault();
×
1861

1862
                        if (selection && Range.isExpanded(selection)) {
×
1863
                            Editor.deleteFragment(editor, {
×
1864
                                direction: 'backward'
1865
                            });
1866
                        } else {
1867
                            Editor.deleteBackward(editor);
×
1868
                        }
1869

1870
                        return;
×
1871
                    }
1872

1873
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1874
                        event.preventDefault();
×
1875

1876
                        if (selection && Range.isExpanded(selection)) {
×
1877
                            Editor.deleteFragment(editor, {
×
1878
                                direction: 'forward'
1879
                            });
1880
                        } else {
1881
                            Editor.deleteForward(editor);
×
1882
                        }
1883

1884
                        return;
×
1885
                    }
1886

1887
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1888
                        event.preventDefault();
×
1889

1890
                        if (selection && Range.isExpanded(selection)) {
×
1891
                            Editor.deleteFragment(editor, {
×
1892
                                direction: 'backward'
1893
                            });
1894
                        } else {
1895
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1896
                        }
1897

1898
                        return;
×
1899
                    }
1900

1901
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1902
                        event.preventDefault();
×
1903

1904
                        if (selection && Range.isExpanded(selection)) {
×
1905
                            Editor.deleteFragment(editor, {
×
1906
                                direction: 'forward'
1907
                            });
1908
                        } else {
1909
                            Editor.deleteForward(editor, { unit: 'line' });
×
1910
                        }
1911

1912
                        return;
×
1913
                    }
1914

1915
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1916
                        event.preventDefault();
×
1917

1918
                        if (selection && Range.isExpanded(selection)) {
×
1919
                            Editor.deleteFragment(editor, {
×
1920
                                direction: 'backward'
1921
                            });
1922
                        } else {
1923
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1924
                        }
1925

1926
                        return;
×
1927
                    }
1928

1929
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1930
                        event.preventDefault();
×
1931

1932
                        if (selection && Range.isExpanded(selection)) {
×
1933
                            Editor.deleteFragment(editor, {
×
1934
                                direction: 'forward'
1935
                            });
1936
                        } else {
1937
                            Editor.deleteForward(editor, { unit: 'word' });
×
1938
                        }
1939

1940
                        return;
×
1941
                    }
1942
                } else {
1943
                    if (IS_CHROME || IS_SAFARI) {
×
1944
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1945
                        // an event when deleting backwards in a selected void inline node
1946
                        if (
×
1947
                            selection &&
×
1948
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1949
                            Range.isCollapsed(selection)
1950
                        ) {
1951
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1952
                            if (
×
1953
                                Element.isElement(currentNode) &&
×
1954
                                Editor.isVoid(editor, currentNode) &&
1955
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1956
                            ) {
1957
                                event.preventDefault();
×
1958
                                Editor.deleteBackward(editor, {
×
1959
                                    unit: 'block'
1960
                                });
1961
                                return;
×
1962
                            }
1963
                        }
1964
                    }
1965
                }
1966
            } catch (error) {
1967
                this.editor.onError({
×
1968
                    code: SlateErrorCode.OnDOMKeydownError,
1969
                    nativeError: error
1970
                });
1971
            }
1972
        }
1973
    }
1974

1975
    private onDOMPaste(event: ClipboardEvent) {
1976
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1977
        // fall back to React's `onPaste` here instead.
1978
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1979
        // when "paste without formatting" option is used.
1980
        // This unfortunately needs to be handled with paste events instead.
1981
        if (
×
1982
            !this.isDOMEventHandled(event, this.paste) &&
×
1983
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1984
            !this.readonly &&
1985
            AngularEditor.hasEditableTarget(this.editor, event.target)
1986
        ) {
1987
            event.preventDefault();
×
1988
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1989
        }
1990
    }
1991

1992
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1993
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1994
        // fall back to React's leaky polyfill instead just for it. It
1995
        // only works for the `insertText` input type.
1996
        if (
×
1997
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1998
            !this.readonly &&
1999
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
2000
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
2001
        ) {
2002
            event.nativeEvent.preventDefault();
×
2003
            try {
×
2004
                const text = event.data;
×
2005
                if (!Range.isCollapsed(this.editor.selection)) {
×
2006
                    Editor.deleteFragment(this.editor);
×
2007
                }
2008
                // just handle Non-IME input
2009
                if (!this.isComposing) {
×
2010
                    Editor.insertText(this.editor, text);
×
2011
                }
2012
            } catch (error) {
2013
                this.editor.onError({
×
2014
                    code: SlateErrorCode.ToNativeSelectionError,
2015
                    nativeError: error
2016
                });
2017
            }
2018
        }
2019
    }
2020

2021
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
2022
        if (!handler) {
3✔
2023
            return false;
3✔
2024
        }
2025
        handler(event);
×
2026
        return event.defaultPrevented;
×
2027
    }
2028
    //#endregion
2029

2030
    ngOnDestroy() {
2031
        this.editorResizeObserver?.disconnect();
22✔
2032
        this.editorScrollContainerResizeObserver?.disconnect();
22✔
2033
        NODE_TO_ELEMENT.delete(this.editor);
22✔
2034
        this.manualListeners.forEach(manualListener => {
22✔
2035
            manualListener();
462✔
2036
        });
2037
        this.destroy$.complete();
22✔
2038
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
2039
    }
2040
}
2041

2042
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
2043
    // This was affecting the selection of multiple blocks and dragging behavior,
2044
    // so enabled only if the selection has been collapsed.
2045
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
2046
        const leafEl = domRange.startContainer.parentElement!;
×
2047

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

2053
        if (isZeroDimensionRect) {
×
2054
            const leafRect = leafEl.getBoundingClientRect();
×
2055
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2056

2057
            if (leafHasDimensions) {
×
2058
                return;
×
2059
            }
2060
        }
2061

2062
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
2063
        scrollIntoView(leafEl, {
×
2064
            scrollMode: 'if-needed'
2065
        });
2066
        delete leafEl.getBoundingClientRect;
×
2067
    }
2068
};
2069

2070
/**
2071
 * Check if the target is inside void and in the editor.
2072
 */
2073

2074
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
2075
    let slateNode: Node | null = null;
1✔
2076
    try {
1✔
2077
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
2078
    } catch (error) {}
2079
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
2080
};
2081

2082
export const isSelectionInsideVoid = (editor: AngularEditor) => {
1✔
2083
    const selection = editor.selection;
1✔
2084
    if (selection && Range.isCollapsed(selection)) {
1!
2085
        const currentNode = Node.parent(editor, selection.anchor.path);
×
2086
        return Element.isElement(currentNode) && Editor.isVoid(editor, currentNode);
×
2087
    }
2088
    return false;
1✔
2089
};
2090

2091
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
2092
    return (
2✔
2093
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
2094
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
2095
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
2096
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
2097
    );
2098
};
2099

2100
/**
2101
 * remove default insert from composition
2102
 * @param text
2103
 */
2104
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2105
    const types = ['compositionend', 'insertFromComposition'];
×
2106
    if (!types.includes(event.type)) {
×
2107
        return;
×
2108
    }
2109
    const insertText = (event as CompositionEvent).data;
×
2110
    const window = AngularEditor.getWindow(editor);
×
2111
    const domSelection = window.getSelection();
×
2112
    // ensure text node insert composition input text
2113
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2114
        const textNode = domSelection.anchorNode;
×
2115
        textNode.splitText(textNode.length - insertText.length).remove();
×
2116
    }
2117
};
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