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

worktile / slate-angular / 13710b17-f539-4868-8bef-48b8d14035f8

04 Dec 2025 05:58AM UTC coverage: 45.198% (-0.6%) from 45.797%
13710b17-f539-4868-8bef-48b8d14035f8

push

circleci

web-flow
feat(virtual): diff scrolling optimization, adding logs (#307)

* feat(virtual): diff scrolling optimization, adding logs

* fix: optimize

* chore: add note

---------

Co-authored-by: pubuzhixing8 <pubuzhixing@gmail.com>

380 of 1050 branches covered (36.19%)

Branch coverage included in aggregate %.

15 of 68 new or added lines in 2 files covered. (22.06%)

1 existing line in 1 file now uncovered.

1046 of 2105 relevant lines covered (49.69%)

30.74 hits per line

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

27.69
/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 } 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 { Subject } from 'rxjs';
42
import {
43
    IS_FIREFOX,
44
    IS_SAFARI,
45
    IS_CHROME,
46
    HAS_BEFORE_INPUT_SUPPORT,
47
    IS_ANDROID,
48
    VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT,
49
    VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT,
50
    SLATE_DEBUG_KEY
51
} from '../../utils/environment';
52
import Hotkeys from '../../utils/hotkeys';
53
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
54
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
55
import { SlateErrorCode } from '../../types/error';
56
import { NG_VALUE_ACCESSOR } from '@angular/forms';
57
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
58
import { ViewType } from '../../types/view';
59
import { HistoryEditor } from 'slate-history';
60
import { ELEMENT_TO_COMPONENT, isDecoratorRangeListEqual } from '../../utils';
61
import { SlatePlaceholder } from '../../types/feature';
62
import { restoreDom } from '../../utils/restore-dom';
63
import { ListRender } from '../../view/render/list-render';
64
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
65
import { BaseElementComponent } from '../../view/base';
66
import { BaseElementFlavour } from '../../view/flavour/element';
67
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
68

69
// not correctly clipboardData on beforeinput
70
const forceOnDOMPaste = IS_SAFARI;
1✔
71

72
@Component({
73
    selector: 'slate-editable',
74
    host: {
75
        class: 'slate-editable-container',
76
        '[attr.contenteditable]': 'readonly ? undefined : true',
77
        '[attr.role]': `readonly ? undefined : 'textbox'`,
78
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
79
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
80
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
81
    },
82
    template: '',
83
    changeDetection: ChangeDetectionStrategy.OnPush,
84
    providers: [
85
        {
86
            provide: NG_VALUE_ACCESSOR,
87
            useExisting: forwardRef(() => SlateEditable),
23✔
88
            multi: true
89
        }
90
    ],
91
    imports: []
92
})
93
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
94
    viewContext: SlateViewContext;
95
    context: SlateChildrenContext;
96

97
    private destroy$ = new Subject();
23✔
98

99
    isComposing = false;
23✔
100
    isDraggingInternally = false;
23✔
101
    isUpdatingSelection = false;
23✔
102
    latestElement = null as DOMElement | null;
23✔
103

104
    protected manualListeners: (() => void)[] = [];
23✔
105

106
    private initialized: boolean;
107

108
    private onTouchedCallback: () => void = () => {};
23✔
109

110
    private onChangeCallback: (_: any) => void = () => {};
23✔
111

112
    @Input() editor: AngularEditor;
113

114
    @Input() renderElement: (element: Element) => ViewType | null;
115

116
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
117

118
    @Input() renderText: (text: SlateText) => ViewType | null;
119

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

122
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
123

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

126
    @Input() isStrictDecorate: boolean = true;
23✔
127

128
    @Input() trackBy: (node: Element) => any = () => null;
206✔
129

130
    @Input() readonly = false;
23✔
131

132
    @Input() placeholder: string;
133

134
    @Input()
135
    set virtualScroll(config: SlateVirtualScrollConfig) {
136
        this.virtualConfig = config;
×
137
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
138
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
NEW
139
            const virtualView = this.refreshVirtualView();
×
NEW
140
            const diff = this.diffVirtualView(virtualView);
×
NEW
141
            if (diff) {
×
NEW
142
                this.applyVirtualView(virtualView);
×
NEW
143
                if (this.listRender.initialized) {
×
NEW
144
                    this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
145
                }
NEW
146
                this.scheduleMeasureVisibleHeights();
×
147
            }
148
        });
149
    }
150

151
    @HostBinding('style.--virtual-top-padding.px') virtualTopPadding = 0;
23✔
152
    @HostBinding('style.--virtual-bottom-padding.px') virtualBottomPadding = 0;
23✔
153

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

172
    //#region DOM attr
173
    @Input() spellCheck = false;
23✔
174
    @Input() autoCorrect = false;
23✔
175
    @Input() autoCapitalize = false;
23✔
176

177
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
178
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
179
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
180

181
    get hasBeforeInputSupport() {
182
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
183
    }
184
    //#endregion
185

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

188
    getOutletParent = () => {
23✔
189
        return this.elementRef.nativeElement;
43✔
190
    };
191

192
    listRender: ListRender;
193

194
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
195
        enabled: false,
196
        scrollTop: 0,
197
        viewportHeight: 0
198
    };
199
    private renderedChildren: Element[] = [];
23✔
200
    private virtualVisibleIndexes = new Set<number>();
23✔
201
    private measuredHeights = new Map<string, number>();
23✔
202
    private measurePending = false;
23✔
203
    private refreshVirtualViewAnimId: number;
204
    private measureVisibleHeightsAnimId: number;
205

206
    constructor(
207
        public elementRef: ElementRef,
23✔
208
        public renderer2: Renderer2,
23✔
209
        public cdr: ChangeDetectorRef,
23✔
210
        private ngZone: NgZone,
23✔
211
        private injector: Injector
23✔
212
    ) {}
213

214
    ngOnInit() {
215
        this.editor.injector = this.injector;
23✔
216
        this.editor.children = [];
23✔
217
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
218
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
219
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
220
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
221
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
222
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
223
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
224
            this.ngZone.run(() => {
13✔
225
                this.onChange();
13✔
226
            });
227
        });
228
        this.ngZone.runOutsideAngular(() => {
23✔
229
            this.initialize();
23✔
230
        });
231
        this.initializeViewContext();
23✔
232
        this.initializeContext();
23✔
233

234
        // add browser class
235
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
236
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
237
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, () => null);
23✔
238
    }
239

240
    ngOnChanges(simpleChanges: SimpleChanges) {
241
        if (!this.initialized) {
30✔
242
            return;
23✔
243
        }
244
        const decorateChange = simpleChanges['decorate'];
7✔
245
        if (decorateChange) {
7✔
246
            this.forceRender();
2✔
247
        }
248
        const placeholderChange = simpleChanges['placeholder'];
7✔
249
        if (placeholderChange) {
7✔
250
            this.render();
1✔
251
        }
252
        const readonlyChange = simpleChanges['readonly'];
7✔
253
        if (readonlyChange) {
7!
254
            IS_READ_ONLY.set(this.editor, this.readonly);
×
255
            this.render();
×
256
            this.toSlateSelection();
×
257
        }
258
    }
259

260
    registerOnChange(fn: any) {
261
        this.onChangeCallback = fn;
23✔
262
    }
263
    registerOnTouched(fn: any) {
264
        this.onTouchedCallback = fn;
23✔
265
    }
266

267
    writeValue(value: Element[]) {
268
        if (value && value.length) {
49✔
269
            this.editor.children = value;
26✔
270
            this.initializeContext();
26✔
271
            const virtualView = this.refreshVirtualView();
26✔
272
            this.applyVirtualView(virtualView);
26✔
273
            const childrenForRender = virtualView.renderedChildren;
26✔
274
            if (!this.listRender.initialized) {
26✔
275
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
276
            } else {
277
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
278
            }
279
            this.scheduleMeasureVisibleHeights();
26✔
280
            this.cdr.markForCheck();
26✔
281
        }
282
    }
283

284
    initialize() {
285
        this.initialized = true;
23✔
286
        const window = AngularEditor.getWindow(this.editor);
23✔
287
        this.addEventListener(
23✔
288
            'selectionchange',
289
            event => {
290
                this.toSlateSelection();
2✔
291
            },
292
            window.document
293
        );
294
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
295
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
296
        }
297
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
298
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
299
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
300
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
301
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
302
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
303
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
304
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
305
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
306
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
307
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
308
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
309
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
310
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
311
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
312
            this.addEventListener(event.name, () => {});
115✔
313
        });
314
    }
315

316
    toNativeSelection() {
317
        try {
15✔
318
            const { selection } = this.editor;
15✔
319
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
320
            const { activeElement } = root;
15✔
321
            const domSelection = (root as Document).getSelection();
15✔
322

323
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
324
                return;
14✔
325
            }
326

327
            const hasDomSelection = domSelection.type !== 'None';
1✔
328

329
            // If the DOM selection is properly unset, we're done.
330
            if (!selection && !hasDomSelection) {
1!
331
                return;
×
332
            }
333

334
            // If the DOM selection is already correct, we're done.
335
            // verify that the dom selection is in the editor
336
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
337
            let hasDomSelectionInEditor = false;
1✔
338
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
339
                hasDomSelectionInEditor = true;
1✔
340
            }
341

342
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
343
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
344
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
345
                    exactMatch: false,
346
                    suppressThrow: true
347
                });
348
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
349
                    return;
×
350
                }
351
            }
352

353
            // prevent updating native selection when active element is void element
354
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
355
                return;
×
356
            }
357

358
            // when <Editable/> is being controlled through external value
359
            // then its children might just change - DOM responds to it on its own
360
            // but Slate's value is not being updated through any operation
361
            // and thus it doesn't transform selection on its own
362
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
363
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
364
                return;
×
365
            }
366

367
            // Otherwise the DOM selection is out of sync, so update it.
368
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
369
            this.isUpdatingSelection = true;
1✔
370

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

373
            if (newDomRange) {
1!
374
                // COMPAT: Since the DOM range has no concept of backwards/forwards
375
                // we need to check and do the right thing here.
376
                if (Range.isBackward(selection)) {
1!
377
                    // eslint-disable-next-line max-len
378
                    domSelection.setBaseAndExtent(
×
379
                        newDomRange.endContainer,
380
                        newDomRange.endOffset,
381
                        newDomRange.startContainer,
382
                        newDomRange.startOffset
383
                    );
384
                } else {
385
                    // eslint-disable-next-line max-len
386
                    domSelection.setBaseAndExtent(
1✔
387
                        newDomRange.startContainer,
388
                        newDomRange.startOffset,
389
                        newDomRange.endContainer,
390
                        newDomRange.endOffset
391
                    );
392
                }
393
            } else {
394
                domSelection.removeAllRanges();
×
395
            }
396

397
            setTimeout(() => {
1✔
398
                // handle scrolling in setTimeout because of
399
                // dom should not have updated immediately after listRender's updating
400
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
401
                // COMPAT: In Firefox, it's not enough to create a range, you also need
402
                // to focus the contenteditable element too. (2016/11/16)
403
                if (newDomRange && IS_FIREFOX) {
1!
404
                    el.focus();
×
405
                }
406

407
                this.isUpdatingSelection = false;
1✔
408
            });
409
        } catch (error) {
410
            this.editor.onError({
×
411
                code: SlateErrorCode.ToNativeSelectionError,
412
                nativeError: error
413
            });
414
            this.isUpdatingSelection = false;
×
415
        }
416
    }
417

418
    onChange() {
419
        this.forceRender();
13✔
420
        this.onChangeCallback(this.editor.children);
13✔
421
    }
422

423
    ngAfterViewChecked() {}
424

425
    ngDoCheck() {}
426

427
    forceRender() {
428
        this.updateContext();
15✔
429
        const virtualView = this.refreshVirtualView();
15✔
430
        this.applyVirtualView(virtualView);
15✔
431
        this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
15✔
432
        this.scheduleMeasureVisibleHeights();
15✔
433
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
434
        // when the DOMElement where the selection is located is removed
435
        // the compositionupdate and compositionend events will no longer be fired
436
        // so isComposing needs to be corrected
437
        // need exec after this.cdr.detectChanges() to render HTML
438
        // need exec before this.toNativeSelection() to correct native selection
439
        if (this.isComposing) {
15!
440
            // Composition input text be not rendered when user composition input with selection is expanded
441
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
442
            // this time condition is true and isComposing is assigned false
443
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
444
            setTimeout(() => {
×
445
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
446
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
447
                let textContent = '';
×
448
                // skip decorate text
449
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
450
                    let text = stringDOMNode.textContent;
×
451
                    const zeroChar = '\uFEFF';
×
452
                    // remove zero with char
453
                    if (text.startsWith(zeroChar)) {
×
454
                        text = text.slice(1);
×
455
                    }
456
                    if (text.endsWith(zeroChar)) {
×
457
                        text = text.slice(0, text.length - 1);
×
458
                    }
459
                    textContent += text;
×
460
                });
461
                if (Node.string(textNode).endsWith(textContent)) {
×
462
                    this.isComposing = false;
×
463
                }
464
            }, 0);
465
        }
466
        this.toNativeSelection();
15✔
467
    }
468

469
    render() {
470
        const changed = this.updateContext();
2✔
471
        if (changed) {
2✔
472
            const virtualView = this.refreshVirtualView();
2✔
473
            this.applyVirtualView(virtualView);
2✔
474
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
475
            this.scheduleMeasureVisibleHeights();
2✔
476
        }
477
    }
478

479
    updateContext() {
480
        const decorations = this.generateDecorations();
17✔
481
        if (
17✔
482
            this.context.selection !== this.editor.selection ||
46✔
483
            this.context.decorate !== this.decorate ||
484
            this.context.readonly !== this.readonly ||
485
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
486
        ) {
487
            this.context = {
10✔
488
                parent: this.editor,
489
                selection: this.editor.selection,
490
                decorations: decorations,
491
                decorate: this.decorate,
492
                readonly: this.readonly
493
            };
494
            return true;
10✔
495
        }
496
        return false;
7✔
497
    }
498

499
    initializeContext() {
500
        this.context = {
49✔
501
            parent: this.editor,
502
            selection: this.editor.selection,
503
            decorations: this.generateDecorations(),
504
            decorate: this.decorate,
505
            readonly: this.readonly
506
        };
507
    }
508

509
    initializeViewContext() {
510
        this.viewContext = {
23✔
511
            editor: this.editor,
512
            renderElement: this.renderElement,
513
            renderLeaf: this.renderLeaf,
514
            renderText: this.renderText,
515
            trackBy: this.trackBy,
516
            isStrictDecorate: this.isStrictDecorate
517
        };
518
    }
519

520
    composePlaceholderDecorate(editor: Editor) {
521
        if (this.placeholderDecorate) {
64!
522
            return this.placeholderDecorate(editor) || [];
×
523
        }
524

525
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
526
            const start = Editor.start(editor, []);
3✔
527
            return [
3✔
528
                {
529
                    placeholder: this.placeholder,
530
                    anchor: start,
531
                    focus: start
532
                }
533
            ];
534
        } else {
535
            return [];
61✔
536
        }
537
    }
538

539
    generateDecorations() {
540
        const decorations = this.decorate([this.editor, []]);
66✔
541
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
542
        decorations.push(...placeholderDecorations);
66✔
543
        return decorations;
66✔
544
    }
545

546
    private shouldUseVirtual() {
547
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
548
    }
549

550
    private refreshVirtualView(): VirtualViewResult {
551
        const children = (this.editor.children || []) as Element[];
43!
552
        if (!children.length || !this.shouldUseVirtual()) {
43✔
553
            return {
43✔
554
                renderedChildren: children,
555
                visibleIndexes: new Set<number>(),
556
                top: 0,
557
                bottom: 0,
558
                heights: []
559
            };
560
        }
561
        const scrollTop = this.virtualConfig.scrollTop ?? 0;
×
562
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
563
        if (!viewportHeight) {
×
564
            // 已经启用虚拟滚动,但可视区域高度还未获取到,先置空不渲染
NEW
565
            return {
×
566
                renderedChildren: [],
567
                visibleIndexes: new Set<number>(),
568
                top: 0,
569
                bottom: 0,
570
                heights: []
571
            };
572
        }
573
        const bufferCount = this.virtualConfig.bufferCount ?? VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT;
×
574
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
575
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
576

UNCOV
577
        let visibleStart = 0;
×
578
        // 按真实或估算高度往后累加,找到滚动起点所在块
579
        while (visibleStart < heights.length && accumulatedHeights[visibleStart + 1] <= scrollTop) {
×
580
            visibleStart++;
×
581
        }
582

583
        // 向上预留 bufferCount 块
584
        const startIndex = Math.max(0, visibleStart - bufferCount);
×
585
        const top = accumulatedHeights[startIndex];
×
586
        const bufferBelowHeight = this.getBufferBelowHeight(viewportHeight, visibleStart, bufferCount);
×
587
        const targetHeight = accumulatedHeights[visibleStart] - top + viewportHeight + bufferBelowHeight;
×
588

589
        const visible: Element[] = [];
×
590
        const visibleIndexes: number[] = [];
×
591
        let accumulated = 0;
×
592
        let cursor = startIndex;
×
593
        // 循环累计高度超出目标高度(可视高度 + 上下 buffer)
594
        while (cursor < children.length && accumulated < targetHeight) {
×
595
            visible.push(children[cursor]);
×
596
            visibleIndexes.push(cursor);
×
597
            accumulated += this.getBlockHeight(cursor);
×
598
            cursor++;
×
599
        }
NEW
600
        const bottom = heights.slice(cursor).reduce((acc, height) => acc + height, 0);
×
NEW
601
        const renderedChildren = visible.length ? visible : children;
×
NEW
602
        const visibleIndexesSet = new Set(visibleIndexes);
×
NEW
603
        return {
×
604
            renderedChildren,
605
            visibleIndexes: visibleIndexesSet,
606
            top,
607
            bottom,
608
            heights
609
        };
610
    }
611

612
    private applyVirtualView(virtualView: VirtualViewResult) {
613
        this.renderedChildren = virtualView.renderedChildren;
43✔
614
        this.virtualTopPadding = virtualView.top;
43✔
615
        this.virtualBottomPadding = virtualView.bottom;
43✔
616
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
617
    }
618

619
    private diffVirtualView(virtualView: VirtualViewResult) {
NEW
620
        if (!this.renderedChildren.length) {
×
NEW
621
            return true;
×
622
        }
NEW
623
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
NEW
624
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
NEW
625
        if (newVisibleIndexes[0] !== oldVisibleIndexes[0]) {
×
NEW
626
            if (localStorage.getItem(SLATE_DEBUG_KEY) === 'true') {
×
NEW
627
                const diffTopRenderedIndexes = [];
×
NEW
628
                const diffBottomRenderedIndexes = [];
×
NEW
629
                if (newVisibleIndexes[0] > oldVisibleIndexes[0]) {
×
630
                    // 向下
NEW
631
                    for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
NEW
632
                        const element = oldVisibleIndexes[index];
×
NEW
633
                        if (!newVisibleIndexes.includes(element)) {
×
NEW
634
                            diffTopRenderedIndexes.push(element);
×
635
                        } else {
NEW
636
                            break;
×
637
                        }
638
                    }
NEW
639
                    for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
NEW
640
                        const element = newVisibleIndexes[index];
×
NEW
641
                        if (!oldVisibleIndexes.includes(element)) {
×
NEW
642
                            diffBottomRenderedIndexes.push(element);
×
643
                        } else {
NEW
644
                            break;
×
645
                        }
646
                    }
647
                } else {
648
                    // 向上
NEW
649
                    for (let index = 0; index < newVisibleIndexes.length; index++) {
×
NEW
650
                        const element = newVisibleIndexes[index];
×
NEW
651
                        if (!oldVisibleIndexes.includes(element)) {
×
NEW
652
                            diffTopRenderedIndexes.push(element);
×
653
                        } else {
NEW
654
                            break;
×
655
                        }
656
                    }
NEW
657
                    for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
NEW
658
                        const element = oldVisibleIndexes[index];
×
NEW
659
                        if (!newVisibleIndexes.includes(element)) {
×
NEW
660
                            diffBottomRenderedIndexes.push(element);
×
661
                        } else {
NEW
662
                            break;
×
663
                        }
664
                    }
665
                }
NEW
666
                console.log('oldVisibleIndexes:', oldVisibleIndexes);
×
NEW
667
                console.log('newVisibleIndexes:', newVisibleIndexes);
×
NEW
668
                console.log('diffTopRenderedChildren:', diffTopRenderedIndexes);
×
NEW
669
                console.log('diffBottomRenderedChildren:', diffBottomRenderedIndexes);
×
NEW
670
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
NEW
671
                const needBottom = virtualView.heights
×
672
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
NEW
673
                    .reduce((acc, height) => acc + height, 0);
×
NEW
674
                console.log('needTop:', needTop, 'calcTop:', virtualView.top);
×
NEW
675
                console.log('needBottom:', needBottom, 'calcBottom:', virtualView.bottom);
×
NEW
676
                console.warn('=========== Dividing line ===========');
×
677
            }
NEW
678
            return true;
×
679
        }
NEW
680
        return false;
×
681
    }
682

683
    private getBlockHeight(index: number) {
684
        const node = this.editor.children[index];
×
685
        if (!node) {
×
686
            return VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
687
        }
688
        const key = AngularEditor.findKey(this.editor, node);
×
689
        return this.measuredHeights.get(key.id) ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
690
    }
691

692
    private buildAccumulatedHeight(heights: number[]) {
693
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
694
        for (let i = 0; i < heights.length; i++) {
×
695
            // 存储前 i 个的累计高度
696
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
697
        }
698
        return accumulatedHeights;
×
699
    }
700

701
    private getBufferBelowHeight(viewportHeight: number, visibleStart: number, bufferCount: number) {
702
        let blockHeight = 0;
×
703
        let start = visibleStart;
×
704
        // 循环累计高度超出视图高度代表找到向下缓冲区的起始位置
705
        while (blockHeight < viewportHeight) {
×
706
            blockHeight += this.getBlockHeight(start);
×
707
            start++;
×
708
        }
709
        let bufferHeight = 0;
×
710
        for (let i = start; i < start + bufferCount; i++) {
×
711
            bufferHeight += this.getBlockHeight(i);
×
712
        }
713
        return bufferHeight;
×
714
    }
715

716
    private scheduleMeasureVisibleHeights() {
717
        if (!this.shouldUseVirtual()) {
43✔
718
            return;
43✔
719
        }
720
        if (this.measurePending) {
×
721
            return;
×
722
        }
723
        this.measurePending = true;
×
724
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
725
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
726
            this.measureVisibleHeights();
×
727
            this.measurePending = false;
×
728
        });
729
    }
730

731
    private measureVisibleHeights() {
732
        const children = (this.editor.children || []) as Element[];
×
733
        this.virtualVisibleIndexes.forEach(index => {
×
734
            const node = children[index];
×
735
            if (!node) {
×
736
                return;
×
737
            }
738
            const key = AngularEditor.findKey(this.editor, node);
×
739
            // 跳过已测过的块
740
            if (this.measuredHeights.has(key.id)) {
×
741
                return;
×
742
            }
743
            const view = ELEMENT_TO_COMPONENT.get(node);
×
744
            if (!view) {
×
745
                return;
×
746
            }
747
            (view as BaseElementComponent | BaseElementFlavour).getRealHeight()?.then(height => {
×
748
                this.measuredHeights.set(key.id, height);
×
749
            });
750
        });
751
    }
752

753
    //#region event proxy
754
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
755
        this.manualListeners.push(
483✔
756
            this.renderer2.listen(target, eventName, (event: Event) => {
757
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
758
                if (beforeInputEvent) {
5!
759
                    this.onFallbackBeforeInput(beforeInputEvent);
×
760
                }
761
                listener(event);
5✔
762
            })
763
        );
764
    }
765

766
    private toSlateSelection() {
767
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
768
            try {
1✔
769
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
770
                const { activeElement } = root;
1✔
771
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
772
                const domSelection = (root as Document).getSelection();
1✔
773

774
                if (activeElement === el) {
1!
775
                    this.latestElement = activeElement;
1✔
776
                    IS_FOCUSED.set(this.editor, true);
1✔
777
                } else {
778
                    IS_FOCUSED.delete(this.editor);
×
779
                }
780

781
                if (!domSelection) {
1!
782
                    return Transforms.deselect(this.editor);
×
783
                }
784

785
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
786
                const hasDomSelectionInEditor =
787
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
788
                if (!hasDomSelectionInEditor) {
1!
789
                    Transforms.deselect(this.editor);
×
790
                    return;
×
791
                }
792

793
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
794
                // for example, double-click the last cell of the table to select a non-editable DOM
795
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
796
                if (range) {
1✔
797
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
798
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
799
                            // force adjust DOMSelection
800
                            this.toNativeSelection();
×
801
                        }
802
                    } else {
803
                        Transforms.select(this.editor, range);
1✔
804
                    }
805
                }
806
            } catch (error) {
807
                this.editor.onError({
×
808
                    code: SlateErrorCode.ToSlateSelectionError,
809
                    nativeError: error
810
                });
811
            }
812
        }
813
    }
814

815
    private onDOMBeforeInput(
816
        event: Event & {
817
            inputType: string;
818
            isComposing: boolean;
819
            data: string | null;
820
            dataTransfer: DataTransfer | null;
821
            getTargetRanges(): DOMStaticRange[];
822
        }
823
    ) {
824
        const editor = this.editor;
×
825
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
826
        const { activeElement } = root;
×
827
        const { selection } = editor;
×
828
        const { inputType: type } = event;
×
829
        const data = event.dataTransfer || event.data || undefined;
×
830
        if (IS_ANDROID) {
×
831
            let targetRange: Range | null = null;
×
832
            let [nativeTargetRange] = event.getTargetRanges();
×
833
            if (nativeTargetRange) {
×
834
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
835
            }
836
            // COMPAT: SelectionChange event is fired after the action is performed, so we
837
            // have to manually get the selection here to ensure it's up-to-date.
838
            const window = AngularEditor.getWindow(editor);
×
839
            const domSelection = window.getSelection();
×
840
            if (!targetRange && domSelection) {
×
841
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
842
            }
843
            targetRange = targetRange ?? editor.selection;
×
844
            if (type === 'insertCompositionText') {
×
845
                if (data && data.toString().includes('\n')) {
×
846
                    restoreDom(editor, () => {
×
847
                        Editor.insertBreak(editor);
×
848
                    });
849
                } else {
850
                    if (targetRange) {
×
851
                        if (data) {
×
852
                            restoreDom(editor, () => {
×
853
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
854
                            });
855
                        } else {
856
                            restoreDom(editor, () => {
×
857
                                Transforms.delete(editor, { at: targetRange });
×
858
                            });
859
                        }
860
                    }
861
                }
862
                return;
×
863
            }
864
            if (type === 'deleteContentBackward') {
×
865
                // gboard can not prevent default action, so must use restoreDom,
866
                // sougou Keyboard can prevent default action(only in Chinese input mode).
867
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
868
                if (!Range.isCollapsed(targetRange)) {
×
869
                    restoreDom(editor, () => {
×
870
                        Transforms.delete(editor, { at: targetRange });
×
871
                    });
872
                    return;
×
873
                }
874
            }
875
            if (type === 'insertText') {
×
876
                restoreDom(editor, () => {
×
877
                    if (typeof data === 'string') {
×
878
                        Editor.insertText(editor, data);
×
879
                    }
880
                });
881
                return;
×
882
            }
883
        }
884
        if (
×
885
            !this.readonly &&
×
886
            AngularEditor.hasEditableTarget(editor, event.target) &&
887
            !isTargetInsideVoid(editor, activeElement) &&
888
            !this.isDOMEventHandled(event, this.beforeInput)
889
        ) {
890
            try {
×
891
                event.preventDefault();
×
892

893
                // COMPAT: If the selection is expanded, even if the command seems like
894
                // a delete forward/backward command it should delete the selection.
895
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
896
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
897
                    Editor.deleteFragment(editor, { direction });
×
898
                    return;
×
899
                }
900

901
                switch (type) {
×
902
                    case 'deleteByComposition':
903
                    case 'deleteByCut':
904
                    case 'deleteByDrag': {
905
                        Editor.deleteFragment(editor);
×
906
                        break;
×
907
                    }
908

909
                    case 'deleteContent':
910
                    case 'deleteContentForward': {
911
                        Editor.deleteForward(editor);
×
912
                        break;
×
913
                    }
914

915
                    case 'deleteContentBackward': {
916
                        Editor.deleteBackward(editor);
×
917
                        break;
×
918
                    }
919

920
                    case 'deleteEntireSoftLine': {
921
                        Editor.deleteBackward(editor, { unit: 'line' });
×
922
                        Editor.deleteForward(editor, { unit: 'line' });
×
923
                        break;
×
924
                    }
925

926
                    case 'deleteHardLineBackward': {
927
                        Editor.deleteBackward(editor, { unit: 'block' });
×
928
                        break;
×
929
                    }
930

931
                    case 'deleteSoftLineBackward': {
932
                        Editor.deleteBackward(editor, { unit: 'line' });
×
933
                        break;
×
934
                    }
935

936
                    case 'deleteHardLineForward': {
937
                        Editor.deleteForward(editor, { unit: 'block' });
×
938
                        break;
×
939
                    }
940

941
                    case 'deleteSoftLineForward': {
942
                        Editor.deleteForward(editor, { unit: 'line' });
×
943
                        break;
×
944
                    }
945

946
                    case 'deleteWordBackward': {
947
                        Editor.deleteBackward(editor, { unit: 'word' });
×
948
                        break;
×
949
                    }
950

951
                    case 'deleteWordForward': {
952
                        Editor.deleteForward(editor, { unit: 'word' });
×
953
                        break;
×
954
                    }
955

956
                    case 'insertLineBreak':
957
                    case 'insertParagraph': {
958
                        Editor.insertBreak(editor);
×
959
                        break;
×
960
                    }
961

962
                    case 'insertFromComposition': {
963
                        // COMPAT: in safari, `compositionend` event is dispatched after
964
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
965
                        // https://www.w3.org/TR/input-events-2/
966
                        // so the following code is the right logic
967
                        // because DOM selection in sync will be exec before `compositionend` event
968
                        // isComposing is true will prevent DOM selection being update correctly.
969
                        this.isComposing = false;
×
970
                        preventInsertFromComposition(event, this.editor);
×
971
                    }
972
                    case 'insertFromDrop':
973
                    case 'insertFromPaste':
974
                    case 'insertFromYank':
975
                    case 'insertReplacementText':
976
                    case 'insertText': {
977
                        // use a weak comparison instead of 'instanceof' to allow
978
                        // programmatic access of paste events coming from external windows
979
                        // like cypress where cy.window does not work realibly
980
                        if (data?.constructor.name === 'DataTransfer') {
×
981
                            AngularEditor.insertData(editor, data as DataTransfer);
×
982
                        } else if (typeof data === 'string') {
×
983
                            Editor.insertText(editor, data);
×
984
                        }
985
                        break;
×
986
                    }
987
                }
988
            } catch (error) {
989
                this.editor.onError({
×
990
                    code: SlateErrorCode.OnDOMBeforeInputError,
991
                    nativeError: error
992
                });
993
            }
994
        }
995
    }
996

997
    private onDOMBlur(event: FocusEvent) {
998
        if (
×
999
            this.readonly ||
×
1000
            this.isUpdatingSelection ||
1001
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1002
            this.isDOMEventHandled(event, this.blur)
1003
        ) {
1004
            return;
×
1005
        }
1006

1007
        const window = AngularEditor.getWindow(this.editor);
×
1008

1009
        // COMPAT: If the current `activeElement` is still the previous
1010
        // one, this is due to the window being blurred when the tab
1011
        // itself becomes unfocused, so we want to abort early to allow to
1012
        // editor to stay focused when the tab becomes focused again.
1013
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1014
        if (this.latestElement === root.activeElement) {
×
1015
            return;
×
1016
        }
1017

1018
        const { relatedTarget } = event;
×
1019
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1020

1021
        // COMPAT: The event should be ignored if the focus is returning
1022
        // to the editor from an embedded editable element (eg. an <input>
1023
        // element inside a void node).
1024
        if (relatedTarget === el) {
×
1025
            return;
×
1026
        }
1027

1028
        // COMPAT: The event should be ignored if the focus is moving from
1029
        // the editor to inside a void node's spacer element.
1030
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1031
            return;
×
1032
        }
1033

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

1040
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1041
                return;
×
1042
            }
1043
        }
1044

1045
        IS_FOCUSED.delete(this.editor);
×
1046
    }
1047

1048
    private onDOMClick(event: MouseEvent) {
1049
        if (
×
1050
            !this.readonly &&
×
1051
            AngularEditor.hasTarget(this.editor, event.target) &&
1052
            !this.isDOMEventHandled(event, this.click) &&
1053
            isDOMNode(event.target)
1054
        ) {
1055
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1056
            const path = AngularEditor.findPath(this.editor, node);
×
1057
            const start = Editor.start(this.editor, path);
×
1058
            const end = Editor.end(this.editor, path);
×
1059

1060
            const startVoid = Editor.void(this.editor, { at: start });
×
1061
            const endVoid = Editor.void(this.editor, { at: end });
×
1062

1063
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1064
                let blockPath = path;
×
1065
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1066
                    const block = Editor.above(this.editor, {
×
1067
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1068
                        at: path
1069
                    });
1070

1071
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1072
                }
1073

1074
                const range = Editor.range(this.editor, blockPath);
×
1075
                Transforms.select(this.editor, range);
×
1076
                return;
×
1077
            }
1078

1079
            if (
×
1080
                startVoid &&
×
1081
                endVoid &&
1082
                Path.equals(startVoid[1], endVoid[1]) &&
1083
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1084
            ) {
1085
                const range = Editor.range(this.editor, start);
×
1086
                Transforms.select(this.editor, range);
×
1087
            }
1088
        }
1089
    }
1090

1091
    private onDOMCompositionStart(event: CompositionEvent) {
1092
        const { selection } = this.editor;
1✔
1093
        if (selection) {
1!
1094
            // solve the problem of cross node Chinese input
1095
            if (Range.isExpanded(selection)) {
×
1096
                Editor.deleteFragment(this.editor);
×
1097
                this.forceRender();
×
1098
            }
1099
        }
1100
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1101
            this.isComposing = true;
1✔
1102
        }
1103
        this.render();
1✔
1104
    }
1105

1106
    private onDOMCompositionUpdate(event: CompositionEvent) {
1107
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1108
    }
1109

1110
    private onDOMCompositionEnd(event: CompositionEvent) {
1111
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1112
            Transforms.delete(this.editor);
×
1113
        }
1114
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1115
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1116
            // aren't correct and never fire the "insertFromComposition"
1117
            // type that we need. So instead, insert whenever a composition
1118
            // ends since it will already have been committed to the DOM.
1119
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1120
                preventInsertFromComposition(event, this.editor);
×
1121
                Editor.insertText(this.editor, event.data);
×
1122
            }
1123

1124
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1125
            // so we need avoid repeat isnertText by isComposing === true,
1126
            this.isComposing = false;
×
1127
        }
1128
        this.render();
×
1129
    }
1130

1131
    private onDOMCopy(event: ClipboardEvent) {
1132
        const window = AngularEditor.getWindow(this.editor);
×
1133
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1134
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1135
            event.preventDefault();
×
1136
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1137
        }
1138
    }
1139

1140
    private onDOMCut(event: ClipboardEvent) {
1141
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1142
            event.preventDefault();
×
1143
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1144
            const { selection } = this.editor;
×
1145

1146
            if (selection) {
×
1147
                AngularEditor.deleteCutData(this.editor);
×
1148
            }
1149
        }
1150
    }
1151

1152
    private onDOMDragOver(event: DragEvent) {
1153
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1154
            // Only when the target is void, call `preventDefault` to signal
1155
            // that drops are allowed. Editable content is droppable by
1156
            // default, and calling `preventDefault` hides the cursor.
1157
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1158

1159
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1160
                event.preventDefault();
×
1161
            }
1162
        }
1163
    }
1164

1165
    private onDOMDragStart(event: DragEvent) {
1166
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1167
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1168
            const path = AngularEditor.findPath(this.editor, node);
×
1169
            const voidMatch =
1170
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1171

1172
            // If starting a drag on a void node, make sure it is selected
1173
            // so that it shows up in the selection's fragment.
1174
            if (voidMatch) {
×
1175
                const range = Editor.range(this.editor, path);
×
1176
                Transforms.select(this.editor, range);
×
1177
            }
1178

1179
            this.isDraggingInternally = true;
×
1180

1181
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1182
        }
1183
    }
1184

1185
    private onDOMDrop(event: DragEvent) {
1186
        const editor = this.editor;
×
1187
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1188
            event.preventDefault();
×
1189
            // Keep a reference to the dragged range before updating selection
1190
            const draggedRange = editor.selection;
×
1191

1192
            // Find the range where the drop happened
1193
            const range = AngularEditor.findEventRange(editor, event);
×
1194
            const data = event.dataTransfer;
×
1195

1196
            Transforms.select(editor, range);
×
1197

1198
            if (this.isDraggingInternally) {
×
1199
                if (draggedRange) {
×
1200
                    Transforms.delete(editor, {
×
1201
                        at: draggedRange
1202
                    });
1203
                }
1204

1205
                this.isDraggingInternally = false;
×
1206
            }
1207

1208
            AngularEditor.insertData(editor, data);
×
1209

1210
            // When dragging from another source into the editor, it's possible
1211
            // that the current editor does not have focus.
1212
            if (!AngularEditor.isFocused(editor)) {
×
1213
                AngularEditor.focus(editor);
×
1214
            }
1215
        }
1216
    }
1217

1218
    private onDOMDragEnd(event: DragEvent) {
1219
        if (
×
1220
            !this.readonly &&
×
1221
            this.isDraggingInternally &&
1222
            AngularEditor.hasTarget(this.editor, event.target) &&
1223
            !this.isDOMEventHandled(event, this.dragEnd)
1224
        ) {
1225
            this.isDraggingInternally = false;
×
1226
        }
1227
    }
1228

1229
    private onDOMFocus(event: Event) {
1230
        if (
2✔
1231
            !this.readonly &&
8✔
1232
            !this.isUpdatingSelection &&
1233
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1234
            !this.isDOMEventHandled(event, this.focus)
1235
        ) {
1236
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1237
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1238
            this.latestElement = root.activeElement;
2✔
1239

1240
            // COMPAT: If the editor has nested editable elements, the focus
1241
            // can go to them. In Firefox, this must be prevented because it
1242
            // results in issues with keyboard navigation. (2017/03/30)
1243
            if (IS_FIREFOX && event.target !== el) {
2!
1244
                el.focus();
×
1245
                return;
×
1246
            }
1247

1248
            IS_FOCUSED.set(this.editor, true);
2✔
1249
        }
1250
    }
1251

1252
    private onDOMKeydown(event: KeyboardEvent) {
1253
        const editor = this.editor;
×
1254
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1255
        const { activeElement } = root;
×
1256
        if (
×
1257
            !this.readonly &&
×
1258
            AngularEditor.hasEditableTarget(editor, event.target) &&
1259
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1260
            !this.isComposing &&
1261
            !this.isDOMEventHandled(event, this.keydown)
1262
        ) {
1263
            const nativeEvent = event;
×
1264
            const { selection } = editor;
×
1265

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

1269
            try {
×
1270
                // COMPAT: Since we prevent the default behavior on
1271
                // `beforeinput` events, the browser doesn't think there's ever
1272
                // any history stack to undo or redo, so we have to manage these
1273
                // hotkeys ourselves. (2019/11/06)
1274
                if (Hotkeys.isRedo(nativeEvent)) {
×
1275
                    event.preventDefault();
×
1276

1277
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1278
                        editor.redo();
×
1279
                    }
1280

1281
                    return;
×
1282
                }
1283

1284
                if (Hotkeys.isUndo(nativeEvent)) {
×
1285
                    event.preventDefault();
×
1286

1287
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1288
                        editor.undo();
×
1289
                    }
1290

1291
                    return;
×
1292
                }
1293

1294
                // COMPAT: Certain browsers don't handle the selection updates
1295
                // properly. In Chrome, the selection isn't properly extended.
1296
                // And in Firefox, the selection isn't properly collapsed.
1297
                // (2017/10/17)
1298
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1299
                    event.preventDefault();
×
1300
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1301
                    return;
×
1302
                }
1303

1304
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1305
                    event.preventDefault();
×
1306
                    Transforms.move(editor, { unit: 'line' });
×
1307
                    return;
×
1308
                }
1309

1310
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1311
                    event.preventDefault();
×
1312
                    Transforms.move(editor, {
×
1313
                        unit: 'line',
1314
                        edge: 'focus',
1315
                        reverse: true
1316
                    });
1317
                    return;
×
1318
                }
1319

1320
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1321
                    event.preventDefault();
×
1322
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1323
                    return;
×
1324
                }
1325

1326
                // COMPAT: If a void node is selected, or a zero-width text node
1327
                // adjacent to an inline is selected, we need to handle these
1328
                // hotkeys manually because browsers won't be able to skip over
1329
                // the void node with the zero-width space not being an empty
1330
                // string.
1331
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1332
                    event.preventDefault();
×
1333

1334
                    if (selection && Range.isCollapsed(selection)) {
×
1335
                        Transforms.move(editor, { reverse: !isRTL });
×
1336
                    } else {
1337
                        Transforms.collapse(editor, { edge: 'start' });
×
1338
                    }
1339

1340
                    return;
×
1341
                }
1342

1343
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1344
                    event.preventDefault();
×
1345
                    if (selection && Range.isCollapsed(selection)) {
×
1346
                        Transforms.move(editor, { reverse: isRTL });
×
1347
                    } else {
1348
                        Transforms.collapse(editor, { edge: 'end' });
×
1349
                    }
1350

1351
                    return;
×
1352
                }
1353

1354
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1355
                    event.preventDefault();
×
1356

1357
                    if (selection && Range.isExpanded(selection)) {
×
1358
                        Transforms.collapse(editor, { edge: 'focus' });
×
1359
                    }
1360

1361
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1362
                    return;
×
1363
                }
1364

1365
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1366
                    event.preventDefault();
×
1367

1368
                    if (selection && Range.isExpanded(selection)) {
×
1369
                        Transforms.collapse(editor, { edge: 'focus' });
×
1370
                    }
1371

1372
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1373
                    return;
×
1374
                }
1375

1376
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1377
                // fall back to guessing at the input intention for hotkeys.
1378
                // COMPAT: In iOS, some of these hotkeys are handled in the
1379
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1380
                    // We don't have a core behavior for these, but they change the
1381
                    // DOM if we don't prevent them, so we have to.
1382
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1383
                        event.preventDefault();
×
1384
                        return;
×
1385
                    }
1386

1387
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1388
                        event.preventDefault();
×
1389
                        Editor.insertBreak(editor);
×
1390
                        return;
×
1391
                    }
1392

1393
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1394
                        event.preventDefault();
×
1395

1396
                        if (selection && Range.isExpanded(selection)) {
×
1397
                            Editor.deleteFragment(editor, {
×
1398
                                direction: 'backward'
1399
                            });
1400
                        } else {
1401
                            Editor.deleteBackward(editor);
×
1402
                        }
1403

1404
                        return;
×
1405
                    }
1406

1407
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1408
                        event.preventDefault();
×
1409

1410
                        if (selection && Range.isExpanded(selection)) {
×
1411
                            Editor.deleteFragment(editor, {
×
1412
                                direction: 'forward'
1413
                            });
1414
                        } else {
1415
                            Editor.deleteForward(editor);
×
1416
                        }
1417

1418
                        return;
×
1419
                    }
1420

1421
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1422
                        event.preventDefault();
×
1423

1424
                        if (selection && Range.isExpanded(selection)) {
×
1425
                            Editor.deleteFragment(editor, {
×
1426
                                direction: 'backward'
1427
                            });
1428
                        } else {
1429
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1430
                        }
1431

1432
                        return;
×
1433
                    }
1434

1435
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1436
                        event.preventDefault();
×
1437

1438
                        if (selection && Range.isExpanded(selection)) {
×
1439
                            Editor.deleteFragment(editor, {
×
1440
                                direction: 'forward'
1441
                            });
1442
                        } else {
1443
                            Editor.deleteForward(editor, { unit: 'line' });
×
1444
                        }
1445

1446
                        return;
×
1447
                    }
1448

1449
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1450
                        event.preventDefault();
×
1451

1452
                        if (selection && Range.isExpanded(selection)) {
×
1453
                            Editor.deleteFragment(editor, {
×
1454
                                direction: 'backward'
1455
                            });
1456
                        } else {
1457
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1458
                        }
1459

1460
                        return;
×
1461
                    }
1462

1463
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1464
                        event.preventDefault();
×
1465

1466
                        if (selection && Range.isExpanded(selection)) {
×
1467
                            Editor.deleteFragment(editor, {
×
1468
                                direction: 'forward'
1469
                            });
1470
                        } else {
1471
                            Editor.deleteForward(editor, { unit: 'word' });
×
1472
                        }
1473

1474
                        return;
×
1475
                    }
1476
                } else {
1477
                    if (IS_CHROME || IS_SAFARI) {
×
1478
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1479
                        // an event when deleting backwards in a selected void inline node
1480
                        if (
×
1481
                            selection &&
×
1482
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1483
                            Range.isCollapsed(selection)
1484
                        ) {
1485
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1486
                            if (
×
1487
                                Element.isElement(currentNode) &&
×
1488
                                Editor.isVoid(editor, currentNode) &&
1489
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1490
                            ) {
1491
                                event.preventDefault();
×
1492
                                Editor.deleteBackward(editor, {
×
1493
                                    unit: 'block'
1494
                                });
1495
                                return;
×
1496
                            }
1497
                        }
1498
                    }
1499
                }
1500
            } catch (error) {
1501
                this.editor.onError({
×
1502
                    code: SlateErrorCode.OnDOMKeydownError,
1503
                    nativeError: error
1504
                });
1505
            }
1506
        }
1507
    }
1508

1509
    private onDOMPaste(event: ClipboardEvent) {
1510
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1511
        // fall back to React's `onPaste` here instead.
1512
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1513
        // when "paste without formatting" option is used.
1514
        // This unfortunately needs to be handled with paste events instead.
1515
        if (
×
1516
            !this.isDOMEventHandled(event, this.paste) &&
×
1517
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1518
            !this.readonly &&
1519
            AngularEditor.hasEditableTarget(this.editor, event.target)
1520
        ) {
1521
            event.preventDefault();
×
1522
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1523
        }
1524
    }
1525

1526
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1527
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1528
        // fall back to React's leaky polyfill instead just for it. It
1529
        // only works for the `insertText` input type.
1530
        if (
×
1531
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1532
            !this.readonly &&
1533
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1534
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1535
        ) {
1536
            event.nativeEvent.preventDefault();
×
1537
            try {
×
1538
                const text = event.data;
×
1539
                if (!Range.isCollapsed(this.editor.selection)) {
×
1540
                    Editor.deleteFragment(this.editor);
×
1541
                }
1542
                // just handle Non-IME input
1543
                if (!this.isComposing) {
×
1544
                    Editor.insertText(this.editor, text);
×
1545
                }
1546
            } catch (error) {
1547
                this.editor.onError({
×
1548
                    code: SlateErrorCode.ToNativeSelectionError,
1549
                    nativeError: error
1550
                });
1551
            }
1552
        }
1553
    }
1554

1555
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1556
        if (!handler) {
3✔
1557
            return false;
3✔
1558
        }
1559
        handler(event);
×
1560
        return event.defaultPrevented;
×
1561
    }
1562
    //#endregion
1563

1564
    ngOnDestroy() {
1565
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1566
        this.manualListeners.forEach(manualListener => {
23✔
1567
            manualListener();
483✔
1568
        });
1569
        this.destroy$.complete();
23✔
1570
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1571
    }
1572
}
1573

1574
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1575
    // This was affecting the selection of multiple blocks and dragging behavior,
1576
    // so enabled only if the selection has been collapsed.
1577
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1578
        const leafEl = domRange.startContainer.parentElement!;
×
1579

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

1585
        if (isZeroDimensionRect) {
×
1586
            const leafRect = leafEl.getBoundingClientRect();
×
1587
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1588

1589
            if (leafHasDimensions) {
×
1590
                return;
×
1591
            }
1592
        }
1593

1594
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1595
        scrollIntoView(leafEl, {
×
1596
            scrollMode: 'if-needed'
1597
        });
1598
        delete leafEl.getBoundingClientRect;
×
1599
    }
1600
};
1601

1602
/**
1603
 * Check if the target is inside void and in the editor.
1604
 */
1605

1606
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1607
    let slateNode: Node | null = null;
1✔
1608
    try {
1✔
1609
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1610
    } catch (error) {}
1611
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1612
};
1613

1614
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1615
    return (
2✔
1616
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1617
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1618
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1619
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1620
    );
1621
};
1622

1623
/**
1624
 * remove default insert from composition
1625
 * @param text
1626
 */
1627
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1628
    const types = ['compositionend', 'insertFromComposition'];
×
1629
    if (!types.includes(event.type)) {
×
1630
        return;
×
1631
    }
1632
    const insertText = (event as CompositionEvent).data;
×
1633
    const window = AngularEditor.getWindow(editor);
×
1634
    const domSelection = window.getSelection();
×
1635
    // ensure text node insert composition input text
1636
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1637
        const textNode = domSelection.anchorNode;
×
1638
        textNode.splitText(textNode.length - insertText.length).remove();
×
1639
    }
1640
};
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