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

worktile / slate-angular / ac7d4a0e-4361-44b1-8570-ddc1317dc7d3

04 Dec 2025 04:00AM UTC coverage: 45.155% (-0.6%) from 45.797%
ac7d4a0e-4361-44b1-8570-ddc1317dc7d3

push

circleci

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

380 of 1052 branches covered (36.12%)

Branch coverage included in aggregate %.

15 of 71 new or added lines in 2 files covered. (21.13%)

1 existing line in 1 file now uncovered.

1046 of 2106 relevant lines covered (49.67%)

30.73 hits per line

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

27.62
/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) {
NEW
684
        const blockHeight = this.virtualConfig.blockHeight ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
685
        const node = this.editor.children[index];
×
686
        if (!node) {
×
NEW
687
            return blockHeight;
×
688
        }
689
        const key = AngularEditor.findKey(this.editor, node);
×
NEW
690
        return this.measuredHeights.get(key.id) ?? blockHeight;
×
691
    }
692

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1180
            this.isDraggingInternally = true;
×
1181

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

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

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

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

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

1206
                this.isDraggingInternally = false;
×
1207
            }
1208

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

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

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

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

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

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

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

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

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

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

1282
                    return;
×
1283
                }
1284

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

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

1292
                    return;
×
1293
                }
1294

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

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

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

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

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

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

1341
                    return;
×
1342
                }
1343

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

1352
                    return;
×
1353
                }
1354

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

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

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

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

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

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

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

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

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

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

1405
                        return;
×
1406
                    }
1407

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

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

1419
                        return;
×
1420
                    }
1421

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

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

1433
                        return;
×
1434
                    }
1435

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

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

1447
                        return;
×
1448
                    }
1449

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

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

1461
                        return;
×
1462
                    }
1463

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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