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

worktile / slate-angular / f949882c-5928-4a73-8f95-a8eda528e03f

03 Feb 2026 08:59AM UTC coverage: 35.625% (+0.03%) from 35.593%
f949882c-5928-4a73-8f95-a8eda528e03f

push

circleci

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

408 of 1360 branches covered (30.0%)

Branch coverage included in aggregate %.

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

1126 of 2946 relevant lines covered (38.22%)

22.77 hits per line

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

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

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

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

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

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

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

120
    private initialized: boolean;
121

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

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

126
    @Input() editor: AngularEditor;
127

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

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

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

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

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

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

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

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

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

146
    @Input() placeholder: string;
147

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

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

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

206
    listRender: ListRender;
207

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

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

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

223
    virtualScrollInitialized = false;
23✔
224

225
    virtualTopHeightElement: HTMLElement;
226

227
    virtualBottomHeightElement: HTMLElement;
228

229
    virtualCenterOutlet: HTMLElement;
230

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

983
    ngAfterViewChecked() {}
984

985
    ngDoCheck() {}
986

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1604
            this.isDraggingInternally = true;
×
1605

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

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

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

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

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

1630
                this.isDraggingInternally = false;
×
1631
            }
1632

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

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

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

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

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

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

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

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

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

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

1706
                    return;
×
1707
                }
1708

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

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

1716
                    return;
×
1717
                }
1718

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

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

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

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

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

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

1765
                    return;
×
1766
                }
1767

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

1776
                    return;
×
1777
                }
1778

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

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

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

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

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

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

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

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

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

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

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

1835
                        return;
×
1836
                    }
1837

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

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

1849
                        return;
×
1850
                    }
1851

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

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

1863
                        return;
×
1864
                    }
1865

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

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

1877
                        return;
×
1878
                    }
1879

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

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

1891
                        return;
×
1892
                    }
1893

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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