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

worktile / slate-angular / db63a883-a433-4641-9b57-859a1fb80ba2

05 Feb 2026 04:43AM UTC coverage: 35.336% (-0.3%) from 35.625%
db63a883-a433-4641-9b57-859a1fb80ba2

Pull #337

circleci

pubuzhixing8
chore: improve code segments
Pull Request #337: Do not remove selected elements in virtual scroll

409 of 1376 branches covered (29.72%)

Branch coverage included in aggregate %.

2 of 41 new or added lines in 1 file covered. (4.88%)

1 existing line in 1 file now uncovered.

1126 of 2968 relevant lines covered (37.94%)

22.58 hits per line

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

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

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

86
class RemeasureConfig {
87
    indics: number[];
88
    tryUpdateViewport: boolean;
89
}
90

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

116
    private destroy$ = new Subject();
23✔
117

118
    isComposing = false;
23✔
119
    isDraggingInternally = false;
23✔
120
    isUpdatingSelection = false;
23✔
121
    latestElement = null as DOMElement | null;
23✔
122

123
    protected manualListeners: (() => void)[] = [];
23✔
124

125
    private initialized: boolean;
126

127
    private onTouchedCallback: () => void = () => {};
23✔
128

129
    private onChangeCallback: (_: any) => void = () => {};
23✔
130

131
    @Input() editor: AngularEditor;
132

133
    @Input() renderElement: (element: Element) => ViewType | null;
134

135
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
136

137
    @Input() renderText: (text: SlateText) => ViewType | null;
138

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

141
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
142

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

145
    @Input() isStrictDecorate: boolean = true;
23✔
146

147
    @Input() trackBy: (node: Element) => any = () => null;
206✔
148

149
    @Input() readonly = false;
23✔
150

151
    @Input() placeholder: string;
152

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

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

183
    //#region DOM attr
184
    @Input() spellCheck = false;
23✔
185
    @Input() autoCorrect = false;
23✔
186
    @Input() autoCapitalize = false;
23✔
187

188
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
189
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
190
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
191

192
    get hasBeforeInputSupport() {
193
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
194
    }
195
    //#endregion
196

197
    viewContainerRef = inject(ViewContainerRef);
23✔
198

199
    getOutletParent = () => {
23✔
200
        return this.elementRef.nativeElement;
43✔
201
    };
202

203
    getOutletElement = () => {
23✔
204
        if (this.virtualScrollInitialized) {
23!
205
            return this.virtualCenterOutlet;
×
206
        } else {
207
            return null;
23✔
208
        }
209
    };
210

211
    listRender: ListRender;
212

213
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
214
        enabled: false,
215
        scrollTop: 0,
216
        scrollContainer: null
217
    };
218

219
    private inViewportChildren: Element[] = [];
23✔
220
    private inViewportIndics: number[] = [];
23✔
221
    private keyHeightMap = new Map<string, number>();
23✔
222
    private tryUpdateVirtualViewportAnimId: number;
223
    private editorResizeObserver?: ResizeObserver;
224
    private editorScrollContainerResizeObserver?: ResizeObserver;
225

226
    indicsOfNeedRemeasured$ = new Subject<RemeasureConfig>();
23✔
227

228
    virtualScrollInitialized = false;
23✔
229

230
    virtualTopHeightElement: HTMLElement;
231

232
    virtualBottomHeightElement: HTMLElement;
233

234
    virtualCenterOutlet: HTMLElement;
235

236
    constructor(
237
        public elementRef: ElementRef,
23✔
238
        public renderer2: Renderer2,
23✔
239
        public cdr: ChangeDetectorRef,
23✔
240
        private ngZone: NgZone,
23✔
241
        private injector: Injector
23✔
242
    ) {}
243

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

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

291
    registerOnChange(fn: any) {
292
        this.onChangeCallback = fn;
23✔
293
    }
294
    registerOnTouched(fn: any) {
295
        this.onTouchedCallback = fn;
23✔
296
    }
297

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

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

371
    private isEnabledVirtualScroll() {
372
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
373
    }
374

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

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

463
    getChangedIndics(previousValue: Descendant[]) {
464
        const remeasureIndics = [];
×
465
        this.inViewportChildren.forEach((child, index) => {
×
466
            if (previousValue.indexOf(child) === -1) {
×
467
                remeasureIndics.push(this.inViewportIndics[index]);
×
468
            }
469
        });
470
        return remeasureIndics;
×
471
    }
472

473
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
474
        if (!this.virtualScrollInitialized) {
×
475
            return;
×
476
        }
477
        this.virtualTopHeightElement.style.height = `${roundTo(topHeight, 1)}px`;
×
478
        if (bottomHeight !== undefined) {
×
479
            this.virtualBottomHeightElement.style.height = `${roundTo(bottomHeight, 1)}px`;
×
480
        }
481
    }
482

483
    getActualVirtualTopHeight() {
484
        if (!this.virtualScrollInitialized) {
×
485
            return 0;
×
486
        }
487
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
488
    }
489

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

516
    calculateIndicsStartAndEndBySelection() {
NEW
517
        if (!this.editor.selection || Range.isCollapsed(this.editor.selection)) {
×
NEW
518
            return;
×
519
        }
NEW
520
        const isBackward = Range.isBackward(this.editor.selection);
×
NEW
521
        const anchorIndex = this.editor.selection.anchor.path[0];
×
NEW
522
        const focusIndex = this.editor.selection.focus.path[0];
×
NEW
523
        let minStartIndex = anchorIndex;
×
NEW
524
        let minEndIndex = focusIndex;
×
NEW
525
        if (isBackward) {
×
NEW
526
            minStartIndex = focusIndex;
×
NEW
527
            minEndIndex = anchorIndex;
×
528
        }
NEW
529
        if (minStartIndex < this.inViewportIndics[0]) {
×
NEW
530
            minStartIndex = this.inViewportIndics[0];
×
531
        }
NEW
532
        if (minEndIndex > this.inViewportIndics[this.inViewportIndics.length - 1]) {
×
NEW
533
            minEndIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
534
        }
NEW
535
        return { minStartIndex, minEndIndex };
×
536
    }
537

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

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

689
    private applyVirtualView(virtualView: VirtualViewResult) {
690
        this.inViewportChildren = virtualView.inViewportChildren;
×
691
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
692
        this.inViewportIndics = virtualView.inViewportIndics;
×
693
    }
694

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

833
    //#region event proxy
834
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
835
        this.manualListeners.push(
483✔
836
            this.renderer2.listen(target, eventName, (event: Event) => {
837
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
838
                if (beforeInputEvent) {
5!
839
                    this.onFallbackBeforeInput(beforeInputEvent);
×
840
                }
841
                listener(event);
5✔
842
            })
843
        );
844
    }
845

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

885
    private isSelectionInvisible(selection: Selection) {
886
        const anchorIndex = selection.anchor.path[0];
6✔
887
        const focusIndex = selection.focus.path[0];
6✔
888
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
889
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
890
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
891
    }
892

893
    toNativeSelection(autoScroll = true) {
15✔
894
        try {
15✔
895
            let { selection } = this.editor;
15✔
896

897
            if (this.isEnabledVirtualScroll() && Range.isCollapsed(selection)) {
15!
898
                selection = this.calculateVirtualScrollSelection(selection);
×
899
            }
900

901
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
902
            const { activeElement } = root;
15✔
903
            const domSelection = (root as Document).getSelection();
15✔
904

905
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
906
                return;
×
907
            }
908

909
            const hasDomSelection = domSelection.type !== 'None';
15✔
910

911
            // If the DOM selection is properly unset, we're done.
912
            if (!selection && !hasDomSelection) {
15✔
913
                return;
9✔
914
            }
915

916
            // If the DOM selection is already correct, we're done.
917
            // verify that the dom selection is in the editor
918
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
6✔
919
            let hasDomSelectionInEditor = false;
6✔
920
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
6✔
921
                hasDomSelectionInEditor = true;
1✔
922
            }
923

924
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
6✔
925
                return;
5✔
926
            }
927

928
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
929
                return;
×
930
            }
931

932
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
933
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
934
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
935
                    exactMatch: false,
936
                    suppressThrow: true
937
                });
938
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
939
                    return;
×
940
                }
941
            }
942

943
            // prevent updating native selection when active element is void element
944
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
945
                return;
×
946
            }
947

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

957
            // Otherwise the DOM selection is out of sync, so update it.
958
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
959
            this.isUpdatingSelection = true;
1✔
960

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

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

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

1019
    onChange() {
1020
        this.forceRender();
13✔
1021
        this.onChangeCallback(this.editor.children);
13✔
1022
    }
1023

1024
    ngAfterViewChecked() {}
1025

1026
    ngDoCheck() {}
1027

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

1076
    render() {
1077
        const changed = this.updateContext();
2✔
1078
        if (changed) {
2✔
1079
            if (this.isEnabledVirtualScroll()) {
2!
1080
                this.updateListRenderAndRemeasureHeights();
×
1081
            } else {
1082
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
1083
            }
1084
        }
1085
    }
1086

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

1158
    updateContext() {
1159
        const decorations = this.generateDecorations();
17✔
1160
        if (
17✔
1161
            this.context.selection !== this.editor.selection ||
46✔
1162
            this.context.decorate !== this.decorate ||
1163
            this.context.readonly !== this.readonly ||
1164
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
1165
        ) {
1166
            this.context = {
10✔
1167
                parent: this.editor,
1168
                selection: this.editor.selection,
1169
                decorations: decorations,
1170
                decorate: this.decorate,
1171
                readonly: this.readonly
1172
            };
1173
            return true;
10✔
1174
        }
1175
        return false;
7✔
1176
    }
1177

1178
    initializeContext() {
1179
        this.context = {
49✔
1180
            parent: this.editor,
1181
            selection: this.editor.selection,
1182
            decorations: this.generateDecorations(),
1183
            decorate: this.decorate,
1184
            readonly: this.readonly
1185
        };
1186
    }
1187

1188
    initializeViewContext() {
1189
        this.viewContext = {
23✔
1190
            editor: this.editor,
1191
            renderElement: this.renderElement,
1192
            renderLeaf: this.renderLeaf,
1193
            renderText: this.renderText,
1194
            trackBy: this.trackBy,
1195
            isStrictDecorate: this.isStrictDecorate
1196
        };
1197
    }
1198

1199
    composePlaceholderDecorate(editor: Editor) {
1200
        if (this.placeholderDecorate) {
64!
1201
            return this.placeholderDecorate(editor) || [];
×
1202
        }
1203

1204
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
1205
            const start = Editor.start(editor, []);
3✔
1206
            return [
3✔
1207
                {
1208
                    placeholder: this.placeholder,
1209
                    anchor: start,
1210
                    focus: start
1211
                }
1212
            ];
1213
        } else {
1214
            return [];
61✔
1215
        }
1216
    }
1217

1218
    generateDecorations() {
1219
        const decorations = this.decorate([this.editor, []]);
66✔
1220
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1221
        decorations.push(...placeholderDecorations);
66✔
1222
        return decorations;
66✔
1223
    }
1224

1225
    private toSlateSelection() {
1226
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1227
            try {
1✔
1228
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1229
                const { activeElement } = root;
1✔
1230
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1231
                const domSelection = (root as Document).getSelection();
1✔
1232

1233
                if (activeElement === el) {
1!
1234
                    this.latestElement = activeElement;
1✔
1235
                    IS_FOCUSED.set(this.editor, true);
1✔
1236
                } else {
1237
                    IS_FOCUSED.delete(this.editor);
×
1238
                }
1239

1240
                if (!domSelection) {
1!
1241
                    return Transforms.deselect(this.editor);
×
1242
                }
1243

1244
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1245
                const hasDomSelectionInEditor =
1246
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1247
                if (!hasDomSelectionInEditor) {
1!
1248
                    Transforms.deselect(this.editor);
×
1249
                    return;
×
1250
                }
1251

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

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

1352
                // COMPAT: If the selection is expanded, even if the command seems like
1353
                // a delete forward/backward command it should delete the selection.
1354
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1355
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1356
                    Editor.deleteFragment(editor, { direction });
×
1357
                    return;
×
1358
                }
1359

1360
                switch (type) {
×
1361
                    case 'deleteByComposition':
1362
                    case 'deleteByCut':
1363
                    case 'deleteByDrag': {
1364
                        Editor.deleteFragment(editor);
×
1365
                        break;
×
1366
                    }
1367

1368
                    case 'deleteContent':
1369
                    case 'deleteContentForward': {
1370
                        Editor.deleteForward(editor);
×
1371
                        break;
×
1372
                    }
1373

1374
                    case 'deleteContentBackward': {
1375
                        Editor.deleteBackward(editor);
×
1376
                        break;
×
1377
                    }
1378

1379
                    case 'deleteEntireSoftLine': {
1380
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1381
                        Editor.deleteForward(editor, { unit: 'line' });
×
1382
                        break;
×
1383
                    }
1384

1385
                    case 'deleteHardLineBackward': {
1386
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1387
                        break;
×
1388
                    }
1389

1390
                    case 'deleteSoftLineBackward': {
1391
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1392
                        break;
×
1393
                    }
1394

1395
                    case 'deleteHardLineForward': {
1396
                        Editor.deleteForward(editor, { unit: 'block' });
×
1397
                        break;
×
1398
                    }
1399

1400
                    case 'deleteSoftLineForward': {
1401
                        Editor.deleteForward(editor, { unit: 'line' });
×
1402
                        break;
×
1403
                    }
1404

1405
                    case 'deleteWordBackward': {
1406
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1407
                        break;
×
1408
                    }
1409

1410
                    case 'deleteWordForward': {
1411
                        Editor.deleteForward(editor, { unit: 'word' });
×
1412
                        break;
×
1413
                    }
1414

1415
                    case 'insertLineBreak':
1416
                    case 'insertParagraph': {
1417
                        Editor.insertBreak(editor);
×
1418
                        break;
×
1419
                    }
1420

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

1456
    private onDOMBlur(event: FocusEvent) {
1457
        if (
×
1458
            this.readonly ||
×
1459
            this.isUpdatingSelection ||
1460
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1461
            this.isDOMEventHandled(event, this.blur)
1462
        ) {
1463
            return;
×
1464
        }
1465

1466
        const window = AngularEditor.getWindow(this.editor);
×
1467

1468
        // COMPAT: If the current `activeElement` is still the previous
1469
        // one, this is due to the window being blurred when the tab
1470
        // itself becomes unfocused, so we want to abort early to allow to
1471
        // editor to stay focused when the tab becomes focused again.
1472
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1473
        if (this.latestElement === root.activeElement) {
×
1474
            return;
×
1475
        }
1476

1477
        const { relatedTarget } = event;
×
1478
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1479

1480
        // COMPAT: The event should be ignored if the focus is returning
1481
        // to the editor from an embedded editable element (eg. an <input>
1482
        // element inside a void node).
1483
        if (relatedTarget === el) {
×
1484
            return;
×
1485
        }
1486

1487
        // COMPAT: The event should be ignored if the focus is moving from
1488
        // the editor to inside a void node's spacer element.
1489
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1490
            return;
×
1491
        }
1492

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

1499
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1500
                return;
×
1501
            }
1502
        }
1503

1504
        IS_FOCUSED.delete(this.editor);
×
1505
    }
1506

1507
    private onDOMClick(event: MouseEvent) {
1508
        if (
×
1509
            !this.readonly &&
×
1510
            AngularEditor.hasTarget(this.editor, event.target) &&
1511
            !this.isDOMEventHandled(event, this.click) &&
1512
            isDOMNode(event.target)
1513
        ) {
1514
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1515
            const path = AngularEditor.findPath(this.editor, node);
×
1516
            const start = Editor.start(this.editor, path);
×
1517
            const end = Editor.end(this.editor, path);
×
1518

1519
            const startVoid = Editor.void(this.editor, { at: start });
×
1520
            const endVoid = Editor.void(this.editor, { at: end });
×
1521

1522
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1523
                let blockPath = path;
×
1524
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1525
                    const block = Editor.above(this.editor, {
×
1526
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1527
                        at: path
1528
                    });
1529

1530
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1531
                }
1532

1533
                const range = Editor.range(this.editor, blockPath);
×
1534
                Transforms.select(this.editor, range);
×
1535
                return;
×
1536
            }
1537

1538
            if (
×
1539
                startVoid &&
×
1540
                endVoid &&
1541
                Path.equals(startVoid[1], endVoid[1]) &&
1542
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1543
            ) {
1544
                const range = Editor.range(this.editor, start);
×
1545
                Transforms.select(this.editor, range);
×
1546
            }
1547
        }
1548
    }
1549

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

1569
    private onDOMCompositionUpdate(event: CompositionEvent) {
1570
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1571
    }
1572

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

1591
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1592
            // so we need avoid repeat insertText by isComposing === true,
1593
            this.isComposing = false;
×
1594
        }
1595
        this.render();
×
1596
    }
1597

1598
    private onDOMCopy(event: ClipboardEvent) {
1599
        const window = AngularEditor.getWindow(this.editor);
×
1600
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1601
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1602
            event.preventDefault();
×
1603
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1604
        }
1605
    }
1606

1607
    private onDOMCut(event: ClipboardEvent) {
1608
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1609
            event.preventDefault();
×
1610
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1611
            const { selection } = this.editor;
×
1612

1613
            if (selection) {
×
1614
                AngularEditor.deleteCutData(this.editor);
×
1615
            }
1616
        }
1617
    }
1618

1619
    private onDOMDragOver(event: DragEvent) {
1620
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1621
            // Only when the target is void, call `preventDefault` to signal
1622
            // that drops are allowed. Editable content is droppable by
1623
            // default, and calling `preventDefault` hides the cursor.
1624
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1625

1626
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1627
                event.preventDefault();
×
1628
            }
1629
        }
1630
    }
1631

1632
    private onDOMDragStart(event: DragEvent) {
1633
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1634
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1635
            const path = AngularEditor.findPath(this.editor, node);
×
1636
            const voidMatch =
1637
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1638

1639
            // If starting a drag on a void node, make sure it is selected
1640
            // so that it shows up in the selection's fragment.
1641
            if (voidMatch) {
×
1642
                const range = Editor.range(this.editor, path);
×
1643
                Transforms.select(this.editor, range);
×
1644
            }
1645

1646
            this.isDraggingInternally = true;
×
1647

1648
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1649
        }
1650
    }
1651

1652
    private onDOMDrop(event: DragEvent) {
1653
        const editor = this.editor;
×
1654
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1655
            event.preventDefault();
×
1656
            // Keep a reference to the dragged range before updating selection
1657
            const draggedRange = editor.selection;
×
1658

1659
            // Find the range where the drop happened
1660
            const range = AngularEditor.findEventRange(editor, event);
×
1661
            const data = event.dataTransfer;
×
1662

1663
            Transforms.select(editor, range);
×
1664

1665
            if (this.isDraggingInternally) {
×
1666
                if (draggedRange) {
×
1667
                    Transforms.delete(editor, {
×
1668
                        at: draggedRange
1669
                    });
1670
                }
1671

1672
                this.isDraggingInternally = false;
×
1673
            }
1674

1675
            AngularEditor.insertData(editor, data);
×
1676

1677
            // When dragging from another source into the editor, it's possible
1678
            // that the current editor does not have focus.
1679
            if (!AngularEditor.isFocused(editor)) {
×
1680
                AngularEditor.focus(editor);
×
1681
            }
1682
        }
1683
    }
1684

1685
    private onDOMDragEnd(event: DragEvent) {
1686
        if (
×
1687
            !this.readonly &&
×
1688
            this.isDraggingInternally &&
1689
            AngularEditor.hasTarget(this.editor, event.target) &&
1690
            !this.isDOMEventHandled(event, this.dragEnd)
1691
        ) {
1692
            this.isDraggingInternally = false;
×
1693
        }
1694
    }
1695

1696
    private onDOMFocus(event: Event) {
1697
        if (
2✔
1698
            !this.readonly &&
8✔
1699
            !this.isUpdatingSelection &&
1700
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1701
            !this.isDOMEventHandled(event, this.focus)
1702
        ) {
1703
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1704
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1705
            this.latestElement = root.activeElement;
2✔
1706

1707
            // COMPAT: If the editor has nested editable elements, the focus
1708
            // can go to them. In Firefox, this must be prevented because it
1709
            // results in issues with keyboard navigation. (2017/03/30)
1710
            if (IS_FIREFOX && event.target !== el) {
2!
1711
                el.focus();
×
1712
                return;
×
1713
            }
1714

1715
            IS_FOCUSED.set(this.editor, true);
2✔
1716
        }
1717
    }
1718

1719
    private onDOMKeydown(event: KeyboardEvent) {
1720
        const editor = this.editor;
×
1721
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1722
        const { activeElement } = root;
×
1723
        if (
×
1724
            !this.readonly &&
×
1725
            AngularEditor.hasEditableTarget(editor, event.target) &&
1726
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1727
            !this.isComposing &&
1728
            !this.isDOMEventHandled(event, this.keydown)
1729
        ) {
1730
            const nativeEvent = event;
×
1731
            const { selection } = editor;
×
1732

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

1736
            try {
×
1737
                // COMPAT: Since we prevent the default behavior on
1738
                // `beforeinput` events, the browser doesn't think there's ever
1739
                // any history stack to undo or redo, so we have to manage these
1740
                // hotkeys ourselves. (2019/11/06)
1741
                if (Hotkeys.isRedo(nativeEvent)) {
×
1742
                    event.preventDefault();
×
1743

1744
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1745
                        editor.redo();
×
1746
                    }
1747

1748
                    return;
×
1749
                }
1750

1751
                if (Hotkeys.isUndo(nativeEvent)) {
×
1752
                    event.preventDefault();
×
1753

1754
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1755
                        editor.undo();
×
1756
                    }
1757

1758
                    return;
×
1759
                }
1760

1761
                // COMPAT: Certain browsers don't handle the selection updates
1762
                // properly. In Chrome, the selection isn't properly extended.
1763
                // And in Firefox, the selection isn't properly collapsed.
1764
                // (2017/10/17)
1765
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1766
                    event.preventDefault();
×
1767
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1768
                    return;
×
1769
                }
1770

1771
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1772
                    event.preventDefault();
×
1773
                    Transforms.move(editor, { unit: 'line' });
×
1774
                    return;
×
1775
                }
1776

1777
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1778
                    event.preventDefault();
×
1779
                    Transforms.move(editor, {
×
1780
                        unit: 'line',
1781
                        edge: 'focus',
1782
                        reverse: true
1783
                    });
1784
                    return;
×
1785
                }
1786

1787
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1788
                    event.preventDefault();
×
1789
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1790
                    return;
×
1791
                }
1792

1793
                // COMPAT: If a void node is selected, or a zero-width text node
1794
                // adjacent to an inline is selected, we need to handle these
1795
                // hotkeys manually because browsers won't be able to skip over
1796
                // the void node with the zero-width space not being an empty
1797
                // string.
1798
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1799
                    event.preventDefault();
×
1800

1801
                    if (selection && Range.isCollapsed(selection)) {
×
1802
                        Transforms.move(editor, { reverse: !isRTL });
×
1803
                    } else {
1804
                        Transforms.collapse(editor, { edge: 'start' });
×
1805
                    }
1806

1807
                    return;
×
1808
                }
1809

1810
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1811
                    event.preventDefault();
×
1812
                    if (selection && Range.isCollapsed(selection)) {
×
1813
                        Transforms.move(editor, { reverse: isRTL });
×
1814
                    } else {
1815
                        Transforms.collapse(editor, { edge: 'end' });
×
1816
                    }
1817

1818
                    return;
×
1819
                }
1820

1821
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1822
                    event.preventDefault();
×
1823

1824
                    if (selection && Range.isExpanded(selection)) {
×
1825
                        Transforms.collapse(editor, { edge: 'focus' });
×
1826
                    }
1827

1828
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1829
                    return;
×
1830
                }
1831

1832
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1833
                    event.preventDefault();
×
1834

1835
                    if (selection && Range.isExpanded(selection)) {
×
1836
                        Transforms.collapse(editor, { edge: 'focus' });
×
1837
                    }
1838

1839
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1840
                    return;
×
1841
                }
1842

1843
                if (isKeyHotkey('mod+a', event)) {
×
1844
                    this.editor.selectAll();
×
1845
                    event.preventDefault();
×
1846
                    return;
×
1847
                }
1848

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

1860
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1861
                        event.preventDefault();
×
1862
                        Editor.insertBreak(editor);
×
1863
                        return;
×
1864
                    }
1865

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

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

1877
                        return;
×
1878
                    }
1879

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

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

1891
                        return;
×
1892
                    }
1893

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

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

1905
                        return;
×
1906
                    }
1907

1908
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1909
                        event.preventDefault();
×
1910

1911
                        if (selection && Range.isExpanded(selection)) {
×
1912
                            Editor.deleteFragment(editor, {
×
1913
                                direction: 'forward'
1914
                            });
1915
                        } else {
1916
                            Editor.deleteForward(editor, { unit: 'line' });
×
1917
                        }
1918

1919
                        return;
×
1920
                    }
1921

1922
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1923
                        event.preventDefault();
×
1924

1925
                        if (selection && Range.isExpanded(selection)) {
×
1926
                            Editor.deleteFragment(editor, {
×
1927
                                direction: 'backward'
1928
                            });
1929
                        } else {
1930
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1931
                        }
1932

1933
                        return;
×
1934
                    }
1935

1936
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1937
                        event.preventDefault();
×
1938

1939
                        if (selection && Range.isExpanded(selection)) {
×
1940
                            Editor.deleteFragment(editor, {
×
1941
                                direction: 'forward'
1942
                            });
1943
                        } else {
1944
                            Editor.deleteForward(editor, { unit: 'word' });
×
1945
                        }
1946

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

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

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

2028
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
2029
        if (!handler) {
3✔
2030
            return false;
3✔
2031
        }
2032
        handler(event);
×
2033
        return event.defaultPrevented;
×
2034
    }
2035
    //#endregion
2036

2037
    ngOnDestroy() {
2038
        this.editorResizeObserver?.disconnect();
22✔
2039
        this.editorScrollContainerResizeObserver?.disconnect();
22✔
2040
        NODE_TO_ELEMENT.delete(this.editor);
22✔
2041
        this.manualListeners.forEach(manualListener => {
22✔
2042
            manualListener();
462✔
2043
        });
2044
        this.destroy$.complete();
22✔
2045
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
2046
    }
2047
}
2048

2049
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
2050
    // This was affecting the selection of multiple blocks and dragging behavior,
2051
    // so enabled only if the selection has been collapsed.
2052
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
2053
        const leafEl = domRange.startContainer.parentElement!;
×
2054

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

2060
        if (isZeroDimensionRect) {
×
2061
            const leafRect = leafEl.getBoundingClientRect();
×
2062
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2063

2064
            if (leafHasDimensions) {
×
2065
                return;
×
2066
            }
2067
        }
2068

2069
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
2070
        scrollIntoView(leafEl, {
×
2071
            scrollMode: 'if-needed'
2072
        });
2073
        delete leafEl.getBoundingClientRect;
×
2074
    }
2075
};
2076

2077
/**
2078
 * Check if the target is inside void and in the editor.
2079
 */
2080

2081
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
2082
    let slateNode: Node | null = null;
1✔
2083
    try {
1✔
2084
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
2085
    } catch (error) {}
2086
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
2087
};
2088

2089
export const isSelectionInsideVoid = (editor: AngularEditor) => {
1✔
2090
    const selection = editor.selection;
1✔
2091
    if (selection && Range.isCollapsed(selection)) {
1!
2092
        const currentNode = Node.parent(editor, selection.anchor.path);
×
2093
        return Element.isElement(currentNode) && Editor.isVoid(editor, currentNode);
×
2094
    }
2095
    return false;
1✔
2096
};
2097

2098
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
2099
    return (
2✔
2100
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
2101
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
2102
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
2103
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
2104
    );
2105
};
2106

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