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

worktile / slate-angular / 51c5c867-52b6-48e3-bd4a-69644250fbff

03 Feb 2026 08:59AM UTC coverage: 35.578% (-0.02%) from 35.593%
51c5c867-52b6-48e3-bd4a-69644250fbff

push

circleci

pubuzhixing8
fix(editable): add isSelectionInsideVoid condition in compositionStart and compositionEnd to avoid impact typing in void node #TINFR-3409

407 of 1360 branches covered (29.93%)

Branch coverage included in aggregate %.

5 of 8 new or added lines in 1 file covered. (62.5%)

1 existing line in 1 file now uncovered.

1125 of 2946 relevant lines covered (38.19%)

22.77 hits per line

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

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

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

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

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

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

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

121
    private initialized: boolean;
122

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

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

127
    @Input() editor: AngularEditor;
128

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

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

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

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

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

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

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

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

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

147
    @Input() placeholder: string;
148

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

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

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

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

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

193
    viewContainerRef = inject(ViewContainerRef);
23✔
194

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

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

207
    listRender: ListRender;
208

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

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

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

224
    virtualScrollInitialized = false;
23✔
225

226
    virtualTopHeightElement: HTMLElement;
227

228
    virtualBottomHeightElement: HTMLElement;
229

230
    virtualCenterOutlet: HTMLElement;
231

232
    elementRef = inject(ElementRef);
23✔
233
    renderer2 = inject(Renderer2);
23✔
234
    cdr = inject(ChangeDetectorRef);
23✔
235
    ngZone = inject(NgZone);
23✔
236
    injector = inject(Injector);
23✔
237

238
    constructor() {}
239

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

984
    ngAfterViewChecked() {}
985

986
    ngDoCheck() {}
987

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1605
            this.isDraggingInternally = true;
×
1606

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

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

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

1622
            Transforms.select(editor, range);
×
1623

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

1631
                this.isDraggingInternally = false;
×
1632
            }
1633

1634
            AngularEditor.insertData(editor, data);
×
1635

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

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

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

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

1674
            IS_FOCUSED.set(this.editor, true);
2✔
1675
        }
1676
    }
1677

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

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

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

1703
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1704
                        editor.redo();
×
1705
                    }
1706

1707
                    return;
×
1708
                }
1709

1710
                if (Hotkeys.isUndo(nativeEvent)) {
×
1711
                    event.preventDefault();
×
1712

1713
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1714
                        editor.undo();
×
1715
                    }
1716

1717
                    return;
×
1718
                }
1719

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

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

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

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

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

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

1766
                    return;
×
1767
                }
1768

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

1777
                    return;
×
1778
                }
1779

1780
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1781
                    event.preventDefault();
×
1782

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

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

1791
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1792
                    event.preventDefault();
×
1793

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

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

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

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

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

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

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

1836
                        return;
×
1837
                    }
1838

1839
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1840
                        event.preventDefault();
×
1841

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

1850
                        return;
×
1851
                    }
1852

1853
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1854
                        event.preventDefault();
×
1855

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

1864
                        return;
×
1865
                    }
1866

1867
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1868
                        event.preventDefault();
×
1869

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

1878
                        return;
×
1879
                    }
1880

1881
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1882
                        event.preventDefault();
×
1883

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

1892
                        return;
×
1893
                    }
1894

1895
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1896
                        event.preventDefault();
×
1897

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

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

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

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

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

1996
    ngOnDestroy() {
1997
        this.editorResizeObserver?.disconnect();
23✔
1998
        this.editorScrollContainerResizeObserver?.disconnect();
23✔
1999
        NODE_TO_ELEMENT.delete(this.editor);
23✔
2000
        this.manualListeners.forEach(manualListener => {
23✔
2001
            manualListener();
483✔
2002
        });
2003
        this.destroy$.complete();
23✔
2004
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
2005
    }
2006
}
2007

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

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

2019
        if (isZeroDimensionRect) {
×
2020
            const leafRect = leafEl.getBoundingClientRect();
×
2021
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2022

2023
            if (leafHasDimensions) {
×
2024
                return;
×
2025
            }
2026
        }
2027

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

2036
/**
2037
 * Check if the target is inside void and in the editor.
2038
 */
2039

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

2048
export const isSelectionInsideVoid = (editor: AngularEditor) => {
1✔
2049
    const selection = editor.selection;
1✔
2050
    if (selection && Range.isCollapsed(selection)) {
1!
NEW
2051
        const currentNode = Node.parent(editor, selection.anchor.path);
×
NEW
2052
        return Element.isElement(currentNode) && Editor.isVoid(editor, currentNode);
×
2053
    }
2054
    return false;
1✔
2055
};
2056

2057
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
2058
    return (
2✔
2059
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
2060
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
2061
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
2062
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
2063
    );
2064
};
2065

2066
/**
2067
 * remove default insert from composition
2068
 * @param text
2069
 */
2070
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2071
    const types = ['compositionend', 'insertFromComposition'];
×
2072
    if (!types.includes(event.type)) {
×
2073
        return;
×
2074
    }
2075
    const insertText = (event as CompositionEvent).data;
×
2076
    const window = AngularEditor.getWindow(editor);
×
2077
    const domSelection = window.getSelection();
×
2078
    // ensure text node insert composition input text
2079
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2080
        const textNode = domSelection.anchorNode;
×
2081
        textNode.splitText(textNode.length - insertText.length).remove();
×
2082
    }
2083
};
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