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

worktile / slate-angular / 1a98262e-231a-42e0-80c4-66744cde769e

04 Feb 2026 10:22AM UTC coverage: 35.346% (-0.3%) from 35.625%
1a98262e-231a-42e0-80c4-66744cde769e

push

circleci

pubuzhixing8
feat(virtual-scroll): when selected elements and scroll, should not remove selected elements

408 of 1372 branches covered (29.74%)

Branch coverage included in aggregate %.

0 of 29 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

1126 of 2968 relevant lines covered (37.94%)

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

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

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

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

120
    private initialized: boolean;
121

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

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

126
    @Input() editor: AngularEditor;
127

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

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

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

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

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

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

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

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

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

146
    @Input() placeholder: string;
147

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

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

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

206
    listRender: ListRender;
207

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

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

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

223
    virtualScrollInitialized = false;
23✔
224

225
    virtualTopHeightElement: HTMLElement;
226

227
    virtualBottomHeightElement: HTMLElement;
228

229
    virtualCenterOutlet: HTMLElement;
230

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

664
        const inViewportEndIndex =
665
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
666
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
667
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
668
        return {
×
669
            inViewportChildren,
670
            inViewportIndics,
671
            top,
672
            bottom,
673
            heights,
674
            accumulatedHeights
675
        };
676
    }
677

678
    private applyVirtualView(virtualView: VirtualViewResult) {
679
        this.inViewportChildren = virtualView.inViewportChildren;
×
680
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
681
        this.inViewportIndics = virtualView.inViewportIndics;
×
682
    }
683

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

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

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

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

882
    toNativeSelection(autoScroll = true) {
15✔
883
        try {
15✔
884
            let { selection } = this.editor;
15✔
885

886
            if (this.isEnabledVirtualScroll()) {
15!
887
                selection = this.calculateVirtualScrollSelection(selection);
×
888
            }
889

890
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
891
            const { activeElement } = root;
15✔
892
            const domSelection = (root as Document).getSelection();
15✔
893

894
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
895
                return;
×
896
            }
897

898
            const hasDomSelection = domSelection.type !== 'None';
15✔
899

900
            // If the DOM selection is properly unset, we're done.
901
            if (!selection && !hasDomSelection) {
15✔
902
                return;
4✔
903
            }
904

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

913
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
11✔
914
                return;
10✔
915
            }
916

917
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
918
                return;
×
919
            }
920

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

932
            // prevent updating native selection when active element is void element
933
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
934
                return;
×
935
            }
936

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

946
            // Otherwise the DOM selection is out of sync, so update it.
947
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
948
            this.isUpdatingSelection = true;
1✔
949

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

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

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

1008
    onChange() {
1009
        this.forceRender();
13✔
1010
        this.onChangeCallback(this.editor.children);
13✔
1011
    }
1012

1013
    ngAfterViewChecked() {}
1014

1015
    ngDoCheck() {}
1016

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

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

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

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

1167
    initializeContext() {
1168
        this.context = {
49✔
1169
            parent: this.editor,
1170
            selection: this.editor.selection,
1171
            decorations: this.generateDecorations(),
1172
            decorate: this.decorate,
1173
            readonly: this.readonly
1174
        };
1175
    }
1176

1177
    initializeViewContext() {
1178
        this.viewContext = {
23✔
1179
            editor: this.editor,
1180
            renderElement: this.renderElement,
1181
            renderLeaf: this.renderLeaf,
1182
            renderText: this.renderText,
1183
            trackBy: this.trackBy,
1184
            isStrictDecorate: this.isStrictDecorate
1185
        };
1186
    }
1187

1188
    composePlaceholderDecorate(editor: Editor) {
1189
        if (this.placeholderDecorate) {
64!
1190
            return this.placeholderDecorate(editor) || [];
×
1191
        }
1192

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

1207
    generateDecorations() {
1208
        const decorations = this.decorate([this.editor, []]);
66✔
1209
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1210
        decorations.push(...placeholderDecorations);
66✔
1211
        return decorations;
66✔
1212
    }
1213

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

1222
                if (activeElement === el) {
1!
1223
                    this.latestElement = activeElement;
1✔
1224
                    IS_FOCUSED.set(this.editor, true);
1✔
1225
                } else {
1226
                    IS_FOCUSED.delete(this.editor);
×
1227
                }
1228

1229
                if (!domSelection) {
1!
1230
                    return Transforms.deselect(this.editor);
×
1231
                }
1232

1233
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1234
                const hasDomSelectionInEditor =
1235
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1236
                if (!hasDomSelectionInEditor) {
1!
1237
                    Transforms.deselect(this.editor);
×
1238
                    return;
×
1239
                }
1240

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

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

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

1349
                switch (type) {
×
1350
                    case 'deleteByComposition':
1351
                    case 'deleteByCut':
1352
                    case 'deleteByDrag': {
1353
                        Editor.deleteFragment(editor);
×
1354
                        break;
×
1355
                    }
1356

1357
                    case 'deleteContent':
1358
                    case 'deleteContentForward': {
1359
                        Editor.deleteForward(editor);
×
1360
                        break;
×
1361
                    }
1362

1363
                    case 'deleteContentBackward': {
1364
                        Editor.deleteBackward(editor);
×
1365
                        break;
×
1366
                    }
1367

1368
                    case 'deleteEntireSoftLine': {
1369
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1370
                        Editor.deleteForward(editor, { unit: 'line' });
×
1371
                        break;
×
1372
                    }
1373

1374
                    case 'deleteHardLineBackward': {
1375
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1376
                        break;
×
1377
                    }
1378

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

1384
                    case 'deleteHardLineForward': {
1385
                        Editor.deleteForward(editor, { unit: 'block' });
×
1386
                        break;
×
1387
                    }
1388

1389
                    case 'deleteSoftLineForward': {
1390
                        Editor.deleteForward(editor, { unit: 'line' });
×
1391
                        break;
×
1392
                    }
1393

1394
                    case 'deleteWordBackward': {
1395
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1396
                        break;
×
1397
                    }
1398

1399
                    case 'deleteWordForward': {
1400
                        Editor.deleteForward(editor, { unit: 'word' });
×
1401
                        break;
×
1402
                    }
1403

1404
                    case 'insertLineBreak':
1405
                    case 'insertParagraph': {
1406
                        Editor.insertBreak(editor);
×
1407
                        break;
×
1408
                    }
1409

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

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

1455
        const window = AngularEditor.getWindow(this.editor);
×
1456

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

1466
        const { relatedTarget } = event;
×
1467
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1468

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

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

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

1488
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1489
                return;
×
1490
            }
1491
        }
1492

1493
        IS_FOCUSED.delete(this.editor);
×
1494
    }
1495

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

1508
            const startVoid = Editor.void(this.editor, { at: start });
×
1509
            const endVoid = Editor.void(this.editor, { at: end });
×
1510

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

1519
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1520
                }
1521

1522
                const range = Editor.range(this.editor, blockPath);
×
1523
                Transforms.select(this.editor, range);
×
1524
                return;
×
1525
            }
1526

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

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

1558
    private onDOMCompositionUpdate(event: CompositionEvent) {
1559
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1560
    }
1561

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

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

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

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

1602
            if (selection) {
×
1603
                AngularEditor.deleteCutData(this.editor);
×
1604
            }
1605
        }
1606
    }
1607

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

1615
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1616
                event.preventDefault();
×
1617
            }
1618
        }
1619
    }
1620

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

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

1635
            this.isDraggingInternally = true;
×
1636

1637
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1638
        }
1639
    }
1640

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

1648
            // Find the range where the drop happened
1649
            const range = AngularEditor.findEventRange(editor, event);
×
1650
            const data = event.dataTransfer;
×
1651

1652
            Transforms.select(editor, range);
×
1653

1654
            if (this.isDraggingInternally) {
×
1655
                if (draggedRange) {
×
1656
                    Transforms.delete(editor, {
×
1657
                        at: draggedRange
1658
                    });
1659
                }
1660

1661
                this.isDraggingInternally = false;
×
1662
            }
1663

1664
            AngularEditor.insertData(editor, data);
×
1665

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

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

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

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

1704
            IS_FOCUSED.set(this.editor, true);
2✔
1705
        }
1706
    }
1707

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

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

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

1733
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1734
                        editor.redo();
×
1735
                    }
1736

1737
                    return;
×
1738
                }
1739

1740
                if (Hotkeys.isUndo(nativeEvent)) {
×
1741
                    event.preventDefault();
×
1742

1743
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1744
                        editor.undo();
×
1745
                    }
1746

1747
                    return;
×
1748
                }
1749

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

1760
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1761
                    event.preventDefault();
×
1762
                    Transforms.move(editor, { unit: 'line' });
×
1763
                    return;
×
1764
                }
1765

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

1776
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1777
                    event.preventDefault();
×
1778
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1779
                    return;
×
1780
                }
1781

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

1790
                    if (selection && Range.isCollapsed(selection)) {
×
1791
                        Transforms.move(editor, { reverse: !isRTL });
×
1792
                    } else {
1793
                        Transforms.collapse(editor, { edge: 'start' });
×
1794
                    }
1795

1796
                    return;
×
1797
                }
1798

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

1807
                    return;
×
1808
                }
1809

1810
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1811
                    event.preventDefault();
×
1812

1813
                    if (selection && Range.isExpanded(selection)) {
×
1814
                        Transforms.collapse(editor, { edge: 'focus' });
×
1815
                    }
1816

1817
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1818
                    return;
×
1819
                }
1820

1821
                if (Hotkeys.isMoveWordForward(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 (isKeyHotkey('mod+a', event)) {
×
1833
                    this.editor.selectAll();
×
1834
                    event.preventDefault();
×
1835
                    return;
×
1836
                }
1837

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

1849
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1850
                        event.preventDefault();
×
1851
                        Editor.insertBreak(editor);
×
1852
                        return;
×
1853
                    }
1854

1855
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1856
                        event.preventDefault();
×
1857

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

1866
                        return;
×
1867
                    }
1868

1869
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1870
                        event.preventDefault();
×
1871

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

1880
                        return;
×
1881
                    }
1882

1883
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1884
                        event.preventDefault();
×
1885

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

1894
                        return;
×
1895
                    }
1896

1897
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1898
                        event.preventDefault();
×
1899

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

1908
                        return;
×
1909
                    }
1910

1911
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1912
                        event.preventDefault();
×
1913

1914
                        if (selection && Range.isExpanded(selection)) {
×
1915
                            Editor.deleteFragment(editor, {
×
1916
                                direction: 'backward'
1917
                            });
1918
                        } else {
1919
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1920
                        }
1921

1922
                        return;
×
1923
                    }
1924

1925
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1926
                        event.preventDefault();
×
1927

1928
                        if (selection && Range.isExpanded(selection)) {
×
1929
                            Editor.deleteFragment(editor, {
×
1930
                                direction: 'forward'
1931
                            });
1932
                        } else {
1933
                            Editor.deleteForward(editor, { unit: 'word' });
×
1934
                        }
1935

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

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

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

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

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

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

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

2049
        if (isZeroDimensionRect) {
×
2050
            const leafRect = leafEl.getBoundingClientRect();
×
2051
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2052

2053
            if (leafHasDimensions) {
×
2054
                return;
×
2055
            }
2056
        }
2057

2058
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
2059
        scrollIntoView(leafEl, {
×
2060
            scrollMode: 'if-needed'
2061
        });
2062
        delete leafEl.getBoundingClientRect;
×
2063
    }
2064
};
2065

2066
/**
2067
 * Check if the target is inside void and in the editor.
2068
 */
2069

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

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

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

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