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

worktile / slate-angular / c490314e-eac4-47d8-8f9a-5703a76e2b67

04 Dec 2025 06:29AM UTC coverage: 45.146% (-0.05%) from 45.198%
c490314e-eac4-47d8-8f9a-5703a76e2b67

push

circleci

web-flow
fix(virtual): solve runout issue (#306)

* fix(virtual): solve runout issue

* fix: solve error when virtual is disabled

384 of 1057 branches covered (36.33%)

Branch coverage included in aggregate %.

12 of 26 new or added lines in 1 file covered. (46.15%)

1053 of 2126 relevant lines covered (49.53%)

30.5 hits per line

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

27.98
/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
export const JUST_NOW_UPDATED_VIRTUAL_VIEW = new WeakMap<AngularEditor, boolean>();
1✔
70

71
// not correctly clipboardData on beforeinput
72
const forceOnDOMPaste = IS_SAFARI;
1✔
73

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

99
    private destroy$ = new Subject();
23✔
100

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

106
    protected manualListeners: (() => void)[] = [];
23✔
107

108
    private initialized: boolean;
109

110
    private onTouchedCallback: () => void = () => {};
23✔
111

112
    private onChangeCallback: (_: any) => void = () => {};
23✔
113

114
    @Input() editor: AngularEditor;
115

116
    @Input() renderElement: (element: Element) => ViewType | null;
117

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

120
    @Input() renderText: (text: SlateText) => ViewType | null;
121

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

124
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
125

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

128
    @Input() isStrictDecorate: boolean = true;
23✔
129

130
    @Input() trackBy: (node: Element) => any = () => null;
206✔
131

132
    @Input() readonly = false;
23✔
133

134
    @Input() placeholder: string;
135

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

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

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

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

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

185
    viewContainerRef = inject(ViewContainerRef);
23✔
186

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

191
    getOutletElement = () => {
23✔
192
        if (this.virtualScrollInitialized) {
23!
NEW
193
            return this.virtualCenterOutlet;
×
194
        } else {
195
            return null;
23✔
196
        }
197
    };
198

199
    listRender: ListRender;
200

201
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
202
        enabled: false,
203
        scrollTop: 0,
204
        viewportHeight: 0
205
    };
206
    private renderedChildren: Element[] = [];
23✔
207
    private virtualVisibleIndexes = new Set<number>();
23✔
208
    private measuredHeights = new Map<string, number>();
23✔
209
    private measurePending = false;
23✔
210
    private refreshVirtualViewAnimId: number;
211
    private measureVisibleHeightsAnimId: number;
212

213
    constructor(
214
        public elementRef: ElementRef,
23✔
215
        public renderer2: Renderer2,
23✔
216
        public cdr: ChangeDetectorRef,
23✔
217
        private ngZone: NgZone,
23✔
218
        private injector: Injector
23✔
219
    ) {}
220

221
    ngOnInit() {
222
        this.editor.injector = this.injector;
23✔
223
        this.editor.children = [];
23✔
224
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
225
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
226
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
227
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
228
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
229
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
230
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
231
            this.ngZone.run(() => {
13✔
232
                this.onChange();
13✔
233
            });
234
        });
235
        this.ngZone.runOutsideAngular(() => {
23✔
236
            this.initialize();
23✔
237
        });
238
        this.initializeViewContext();
23✔
239
        this.initializeContext();
23✔
240

241
        // add browser class
242
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
243
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
244
        this.initializeVirtualScrolling();
23✔
245
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
246
    }
247

248
    ngOnChanges(simpleChanges: SimpleChanges) {
249
        if (!this.initialized) {
30✔
250
            return;
23✔
251
        }
252
        const decorateChange = simpleChanges['decorate'];
7✔
253
        if (decorateChange) {
7✔
254
            this.forceRender();
2✔
255
        }
256
        const placeholderChange = simpleChanges['placeholder'];
7✔
257
        if (placeholderChange) {
7✔
258
            this.render();
1✔
259
        }
260
        const readonlyChange = simpleChanges['readonly'];
7✔
261
        if (readonlyChange) {
7!
262
            IS_READ_ONLY.set(this.editor, this.readonly);
×
263
            this.render();
×
264
            this.toSlateSelection();
×
265
        }
266
    }
267

268
    registerOnChange(fn: any) {
269
        this.onChangeCallback = fn;
23✔
270
    }
271
    registerOnTouched(fn: any) {
272
        this.onTouchedCallback = fn;
23✔
273
    }
274

275
    writeValue(value: Element[]) {
276
        if (value && value.length) {
49✔
277
            this.editor.children = value;
26✔
278
            this.initializeContext();
26✔
279
            const virtualView = this.refreshVirtualView();
26✔
280
            this.applyVirtualView(virtualView);
26✔
281
            const childrenForRender = virtualView.renderedChildren;
26✔
282
            if (!this.listRender.initialized) {
26✔
283
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
284
            } else {
285
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
286
            }
287
            this.scheduleMeasureVisibleHeights();
26✔
288
            this.cdr.markForCheck();
26✔
289
        }
290
    }
291

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

324
    toNativeSelection() {
325
        try {
15✔
326
            const { selection } = this.editor;
15✔
327
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
328
            const { activeElement } = root;
15✔
329
            const domSelection = (root as Document).getSelection();
15✔
330

331
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
332
                return;
14✔
333
            }
334

335
            const hasDomSelection = domSelection.type !== 'None';
1✔
336

337
            // If the DOM selection is properly unset, we're done.
338
            if (!selection && !hasDomSelection) {
1!
339
                return;
×
340
            }
341

342
            // If the DOM selection is already correct, we're done.
343
            // verify that the dom selection is in the editor
344
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
345
            let hasDomSelectionInEditor = false;
1✔
346
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
347
                hasDomSelectionInEditor = true;
1✔
348
            }
349

350
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
351
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
352
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
353
                    exactMatch: false,
354
                    suppressThrow: true
355
                });
356
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
357
                    return;
×
358
                }
359
            }
360

361
            // prevent updating native selection when active element is void element
362
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
363
                return;
×
364
            }
365

366
            // when <Editable/> is being controlled through external value
367
            // then its children might just change - DOM responds to it on its own
368
            // but Slate's value is not being updated through any operation
369
            // and thus it doesn't transform selection on its own
370
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
371
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
372
                return;
×
373
            }
374

375
            // Otherwise the DOM selection is out of sync, so update it.
376
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
377
            this.isUpdatingSelection = true;
1✔
378

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

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

405
            setTimeout(() => {
1✔
406
                // handle scrolling in setTimeout because of
407
                // dom should not have updated immediately after listRender's updating
408
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
409
                // COMPAT: In Firefox, it's not enough to create a range, you also need
410
                // to focus the contenteditable element too. (2016/11/16)
411
                if (newDomRange && IS_FIREFOX) {
1!
412
                    el.focus();
×
413
                }
414

415
                this.isUpdatingSelection = false;
1✔
416
            });
417
        } catch (error) {
418
            this.editor.onError({
×
419
                code: SlateErrorCode.ToNativeSelectionError,
420
                nativeError: error
421
            });
422
            this.isUpdatingSelection = false;
×
423
        }
424
    }
425

426
    onChange() {
427
        this.forceRender();
13✔
428
        this.onChangeCallback(this.editor.children);
13✔
429
    }
430

431
    ngAfterViewChecked() {}
432

433
    ngDoCheck() {}
434

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

477
    render() {
478
        const changed = this.updateContext();
2✔
479
        if (changed) {
2✔
480
            const virtualView = this.refreshVirtualView();
2✔
481
            this.applyVirtualView(virtualView);
2✔
482
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
483
            this.scheduleMeasureVisibleHeights();
2✔
484
        }
485
    }
486

487
    updateContext() {
488
        const decorations = this.generateDecorations();
17✔
489
        if (
17✔
490
            this.context.selection !== this.editor.selection ||
46✔
491
            this.context.decorate !== this.decorate ||
492
            this.context.readonly !== this.readonly ||
493
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
494
        ) {
495
            this.context = {
10✔
496
                parent: this.editor,
497
                selection: this.editor.selection,
498
                decorations: decorations,
499
                decorate: this.decorate,
500
                readonly: this.readonly
501
            };
502
            return true;
10✔
503
        }
504
        return false;
7✔
505
    }
506

507
    initializeContext() {
508
        this.context = {
49✔
509
            parent: this.editor,
510
            selection: this.editor.selection,
511
            decorations: this.generateDecorations(),
512
            decorate: this.decorate,
513
            readonly: this.readonly
514
        };
515
    }
516

517
    initializeViewContext() {
518
        this.viewContext = {
23✔
519
            editor: this.editor,
520
            renderElement: this.renderElement,
521
            renderLeaf: this.renderLeaf,
522
            renderText: this.renderText,
523
            trackBy: this.trackBy,
524
            isStrictDecorate: this.isStrictDecorate
525
        };
526
    }
527

528
    composePlaceholderDecorate(editor: Editor) {
529
        if (this.placeholderDecorate) {
64!
530
            return this.placeholderDecorate(editor) || [];
×
531
        }
532

533
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
534
            const start = Editor.start(editor, []);
3✔
535
            return [
3✔
536
                {
537
                    placeholder: this.placeholder,
538
                    anchor: start,
539
                    focus: start
540
                }
541
            ];
542
        } else {
543
            return [];
61✔
544
        }
545
    }
546

547
    generateDecorations() {
548
        const decorations = this.decorate([this.editor, []]);
66✔
549
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
550
        decorations.push(...placeholderDecorations);
66✔
551
        return decorations;
66✔
552
    }
553

554
    private shouldUseVirtual() {
555
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
556
    }
557

558
    virtualScrollInitialized = false;
23✔
559

560
    virtualTopHeightElement: HTMLElement;
561

562
    virtualBottomHeightElement: HTMLElement;
563

564
    virtualCenterOutlet: HTMLElement;
565

566
    initializeVirtualScrolling() {
567
        if (this.virtualScrollInitialized) {
23!
NEW
568
            return;
×
569
        }
570
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
NEW
571
            this.virtualScrollInitialized = true;
×
NEW
572
            this.virtualTopHeightElement = document.createElement('div');
×
NEW
573
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
NEW
574
            this.virtualBottomHeightElement = document.createElement('div');
×
NEW
575
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
NEW
576
            this.virtualCenterOutlet = document.createElement('div');
×
NEW
577
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
NEW
578
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
NEW
579
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
NEW
580
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
581
        }
582
    }
583

584
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
585
        if (!this.virtualScrollInitialized) {
43✔
586
            return;
43✔
587
        }
NEW
588
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
NEW
589
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
590
    }
591

592
    private refreshVirtualView() {
593
        const children = (this.editor.children || []) as Element[];
43!
594
        if (!children.length || !this.shouldUseVirtual()) {
43✔
595
            return {
43✔
596
                renderedChildren: children,
597
                visibleIndexes: new Set<number>(),
598
                top: 0,
599
                bottom: 0,
600
                heights: []
601
            };
602
        }
603
        const scrollTop = this.virtualConfig.scrollTop ?? 0;
×
604
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
605
        if (!viewportHeight) {
×
606
            // 已经启用虚拟滚动,但可视区域高度还未获取到,先置空不渲染
607
            return {
×
608
                renderedChildren: [],
609
                visibleIndexes: new Set<number>(),
610
                top: 0,
611
                bottom: 0,
612
                heights: []
613
            };
614
        }
615
        const bufferCount = this.virtualConfig.bufferCount ?? VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT;
×
616
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
617
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
618

619
        let visibleStart = 0;
×
620
        // 按真实或估算高度往后累加,找到滚动起点所在块
621
        while (visibleStart < heights.length && accumulatedHeights[visibleStart + 1] <= scrollTop) {
×
622
            visibleStart++;
×
623
        }
624

625
        // 向上预留 bufferCount 块
626
        const startIndex = Math.max(0, visibleStart - bufferCount);
×
627
        const top = accumulatedHeights[startIndex];
×
628
        const bufferBelowHeight = this.getBufferBelowHeight(viewportHeight, visibleStart, bufferCount);
×
629
        const targetHeight = accumulatedHeights[visibleStart] - top + viewportHeight + bufferBelowHeight;
×
630

631
        const visible: Element[] = [];
×
632
        const visibleIndexes: number[] = [];
×
633
        let accumulated = 0;
×
634
        let cursor = startIndex;
×
635
        // 循环累计高度超出目标高度(可视高度 + 上下 buffer)
636
        while (cursor < children.length && accumulated < targetHeight) {
×
637
            visible.push(children[cursor]);
×
638
            visibleIndexes.push(cursor);
×
639
            accumulated += this.getBlockHeight(cursor);
×
640
            cursor++;
×
641
        }
642
        const bottom = heights.slice(cursor).reduce((acc, height) => acc + height, 0);
×
643
        const renderedChildren = visible.length ? visible : children;
×
644
        const visibleIndexesSet = new Set(visibleIndexes);
×
645
        return {
×
646
            renderedChildren,
647
            visibleIndexes: visibleIndexesSet,
648
            top,
649
            bottom,
650
            heights
651
        };
652
    }
653

654
    private applyVirtualView(virtualView: VirtualViewResult) {
655
        this.renderedChildren = virtualView.renderedChildren;
43✔
656
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
657
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
658
    }
659

660
    private diffVirtualView(virtualView: VirtualViewResult) {
661
        if (!this.renderedChildren.length) {
×
662
            return true;
×
663
        }
664
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
665
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
666
        if (newVisibleIndexes[0] !== oldVisibleIndexes[0]) {
×
667
            if (localStorage.getItem(SLATE_DEBUG_KEY) === 'true') {
×
668
                const diffTopRenderedIndexes = [];
×
669
                const diffBottomRenderedIndexes = [];
×
670
                if (newVisibleIndexes[0] > oldVisibleIndexes[0]) {
×
671
                    // 向下
672
                    for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
673
                        const element = oldVisibleIndexes[index];
×
674
                        if (!newVisibleIndexes.includes(element)) {
×
675
                            diffTopRenderedIndexes.push(element);
×
676
                        } else {
677
                            break;
×
678
                        }
679
                    }
680
                    for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
681
                        const element = newVisibleIndexes[index];
×
682
                        if (!oldVisibleIndexes.includes(element)) {
×
683
                            diffBottomRenderedIndexes.push(element);
×
684
                        } else {
685
                            break;
×
686
                        }
687
                    }
688
                } else {
689
                    // 向上
690
                    for (let index = 0; index < newVisibleIndexes.length; index++) {
×
691
                        const element = newVisibleIndexes[index];
×
692
                        if (!oldVisibleIndexes.includes(element)) {
×
693
                            diffTopRenderedIndexes.push(element);
×
694
                        } else {
695
                            break;
×
696
                        }
697
                    }
698
                    for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
699
                        const element = oldVisibleIndexes[index];
×
700
                        if (!newVisibleIndexes.includes(element)) {
×
701
                            diffBottomRenderedIndexes.push(element);
×
702
                        } else {
703
                            break;
×
704
                        }
705
                    }
706
                }
707
                console.log('oldVisibleIndexes:', oldVisibleIndexes);
×
708
                console.log('newVisibleIndexes:', newVisibleIndexes);
×
709
                console.log('diffTopRenderedChildren:', diffTopRenderedIndexes);
×
710
                console.log('diffBottomRenderedChildren:', diffBottomRenderedIndexes);
×
711
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
712
                const needBottom = virtualView.heights
×
713
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
714
                    .reduce((acc, height) => acc + height, 0);
×
715
                console.log('needTop:', needTop, 'calcTop:', virtualView.top);
×
716
                console.log('needBottom:', needBottom, 'calcBottom:', virtualView.bottom);
×
717
                console.warn('=========== Dividing line ===========');
×
718
            }
719
            return true;
×
720
        }
721
        return false;
×
722
    }
723

724
    private getBlockHeight(index: number) {
725
        const node = this.editor.children[index];
×
726
        if (!node) {
×
727
            return VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
728
        }
729
        const key = AngularEditor.findKey(this.editor, node);
×
730
        return this.measuredHeights.get(key.id) ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
731
    }
732

733
    private buildAccumulatedHeight(heights: number[]) {
734
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
735
        for (let i = 0; i < heights.length; i++) {
×
736
            // 存储前 i 个的累计高度
737
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
738
        }
739
        return accumulatedHeights;
×
740
    }
741

742
    private getBufferBelowHeight(viewportHeight: number, visibleStart: number, bufferCount: number) {
743
        let blockHeight = 0;
×
744
        let start = visibleStart;
×
745
        // 循环累计高度超出视图高度代表找到向下缓冲区的起始位置
746
        while (blockHeight < viewportHeight) {
×
747
            blockHeight += this.getBlockHeight(start);
×
748
            start++;
×
749
        }
750
        let bufferHeight = 0;
×
751
        for (let i = start; i < start + bufferCount; i++) {
×
752
            bufferHeight += this.getBlockHeight(i);
×
753
        }
754
        return bufferHeight;
×
755
    }
756

757
    private scheduleMeasureVisibleHeights() {
758
        if (!this.shouldUseVirtual()) {
43✔
759
            return;
43✔
760
        }
761
        if (this.measurePending) {
×
762
            return;
×
763
        }
764
        this.measurePending = true;
×
765
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
766
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
767
            this.measureVisibleHeights();
×
768
            this.measurePending = false;
×
769
        });
770
    }
771

772
    private measureVisibleHeights() {
773
        const children = (this.editor.children || []) as Element[];
×
774
        this.virtualVisibleIndexes.forEach(index => {
×
775
            const node = children[index];
×
776
            if (!node) {
×
777
                return;
×
778
            }
779
            const key = AngularEditor.findKey(this.editor, node);
×
780
            // 跳过已测过的块
781
            if (this.measuredHeights.has(key.id)) {
×
782
                return;
×
783
            }
784
            const view = ELEMENT_TO_COMPONENT.get(node);
×
785
            if (!view) {
×
786
                return;
×
787
            }
788
            (view as BaseElementComponent | BaseElementFlavour).getRealHeight()?.then(height => {
×
789
                this.measuredHeights.set(key.id, height);
×
790
            });
791
        });
792
    }
793

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

807
    private toSlateSelection() {
808
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
809
            try {
1✔
810
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
811
                const { activeElement } = root;
1✔
812
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
813
                const domSelection = (root as Document).getSelection();
1✔
814

815
                if (activeElement === el) {
1!
816
                    this.latestElement = activeElement;
1✔
817
                    IS_FOCUSED.set(this.editor, true);
1✔
818
                } else {
819
                    IS_FOCUSED.delete(this.editor);
×
820
                }
821

822
                if (!domSelection) {
1!
823
                    return Transforms.deselect(this.editor);
×
824
                }
825

826
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
827
                const hasDomSelectionInEditor =
828
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
829
                if (!hasDomSelectionInEditor) {
1!
830
                    Transforms.deselect(this.editor);
×
831
                    return;
×
832
                }
833

834
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
835
                // for example, double-click the last cell of the table to select a non-editable DOM
836
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
837
                if (range) {
1✔
838
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
839
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
840
                            // force adjust DOMSelection
841
                            this.toNativeSelection();
×
842
                        }
843
                    } else {
844
                        Transforms.select(this.editor, range);
1✔
845
                    }
846
                }
847
            } catch (error) {
848
                this.editor.onError({
×
849
                    code: SlateErrorCode.ToSlateSelectionError,
850
                    nativeError: error
851
                });
852
            }
853
        }
854
    }
855

856
    private onDOMBeforeInput(
857
        event: Event & {
858
            inputType: string;
859
            isComposing: boolean;
860
            data: string | null;
861
            dataTransfer: DataTransfer | null;
862
            getTargetRanges(): DOMStaticRange[];
863
        }
864
    ) {
865
        const editor = this.editor;
×
866
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
867
        const { activeElement } = root;
×
868
        const { selection } = editor;
×
869
        const { inputType: type } = event;
×
870
        const data = event.dataTransfer || event.data || undefined;
×
871
        if (IS_ANDROID) {
×
872
            let targetRange: Range | null = null;
×
873
            let [nativeTargetRange] = event.getTargetRanges();
×
874
            if (nativeTargetRange) {
×
875
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
876
            }
877
            // COMPAT: SelectionChange event is fired after the action is performed, so we
878
            // have to manually get the selection here to ensure it's up-to-date.
879
            const window = AngularEditor.getWindow(editor);
×
880
            const domSelection = window.getSelection();
×
881
            if (!targetRange && domSelection) {
×
882
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
883
            }
884
            targetRange = targetRange ?? editor.selection;
×
885
            if (type === 'insertCompositionText') {
×
886
                if (data && data.toString().includes('\n')) {
×
887
                    restoreDom(editor, () => {
×
888
                        Editor.insertBreak(editor);
×
889
                    });
890
                } else {
891
                    if (targetRange) {
×
892
                        if (data) {
×
893
                            restoreDom(editor, () => {
×
894
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
895
                            });
896
                        } else {
897
                            restoreDom(editor, () => {
×
898
                                Transforms.delete(editor, { at: targetRange });
×
899
                            });
900
                        }
901
                    }
902
                }
903
                return;
×
904
            }
905
            if (type === 'deleteContentBackward') {
×
906
                // gboard can not prevent default action, so must use restoreDom,
907
                // sougou Keyboard can prevent default action(only in Chinese input mode).
908
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
909
                if (!Range.isCollapsed(targetRange)) {
×
910
                    restoreDom(editor, () => {
×
911
                        Transforms.delete(editor, { at: targetRange });
×
912
                    });
913
                    return;
×
914
                }
915
            }
916
            if (type === 'insertText') {
×
917
                restoreDom(editor, () => {
×
918
                    if (typeof data === 'string') {
×
919
                        Editor.insertText(editor, data);
×
920
                    }
921
                });
922
                return;
×
923
            }
924
        }
925
        if (
×
926
            !this.readonly &&
×
927
            AngularEditor.hasEditableTarget(editor, event.target) &&
928
            !isTargetInsideVoid(editor, activeElement) &&
929
            !this.isDOMEventHandled(event, this.beforeInput)
930
        ) {
931
            try {
×
932
                event.preventDefault();
×
933

934
                // COMPAT: If the selection is expanded, even if the command seems like
935
                // a delete forward/backward command it should delete the selection.
936
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
937
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
938
                    Editor.deleteFragment(editor, { direction });
×
939
                    return;
×
940
                }
941

942
                switch (type) {
×
943
                    case 'deleteByComposition':
944
                    case 'deleteByCut':
945
                    case 'deleteByDrag': {
946
                        Editor.deleteFragment(editor);
×
947
                        break;
×
948
                    }
949

950
                    case 'deleteContent':
951
                    case 'deleteContentForward': {
952
                        Editor.deleteForward(editor);
×
953
                        break;
×
954
                    }
955

956
                    case 'deleteContentBackward': {
957
                        Editor.deleteBackward(editor);
×
958
                        break;
×
959
                    }
960

961
                    case 'deleteEntireSoftLine': {
962
                        Editor.deleteBackward(editor, { unit: 'line' });
×
963
                        Editor.deleteForward(editor, { unit: 'line' });
×
964
                        break;
×
965
                    }
966

967
                    case 'deleteHardLineBackward': {
968
                        Editor.deleteBackward(editor, { unit: 'block' });
×
969
                        break;
×
970
                    }
971

972
                    case 'deleteSoftLineBackward': {
973
                        Editor.deleteBackward(editor, { unit: 'line' });
×
974
                        break;
×
975
                    }
976

977
                    case 'deleteHardLineForward': {
978
                        Editor.deleteForward(editor, { unit: 'block' });
×
979
                        break;
×
980
                    }
981

982
                    case 'deleteSoftLineForward': {
983
                        Editor.deleteForward(editor, { unit: 'line' });
×
984
                        break;
×
985
                    }
986

987
                    case 'deleteWordBackward': {
988
                        Editor.deleteBackward(editor, { unit: 'word' });
×
989
                        break;
×
990
                    }
991

992
                    case 'deleteWordForward': {
993
                        Editor.deleteForward(editor, { unit: 'word' });
×
994
                        break;
×
995
                    }
996

997
                    case 'insertLineBreak':
998
                    case 'insertParagraph': {
999
                        Editor.insertBreak(editor);
×
1000
                        break;
×
1001
                    }
1002

1003
                    case 'insertFromComposition': {
1004
                        // COMPAT: in safari, `compositionend` event is dispatched after
1005
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1006
                        // https://www.w3.org/TR/input-events-2/
1007
                        // so the following code is the right logic
1008
                        // because DOM selection in sync will be exec before `compositionend` event
1009
                        // isComposing is true will prevent DOM selection being update correctly.
1010
                        this.isComposing = false;
×
1011
                        preventInsertFromComposition(event, this.editor);
×
1012
                    }
1013
                    case 'insertFromDrop':
1014
                    case 'insertFromPaste':
1015
                    case 'insertFromYank':
1016
                    case 'insertReplacementText':
1017
                    case 'insertText': {
1018
                        // use a weak comparison instead of 'instanceof' to allow
1019
                        // programmatic access of paste events coming from external windows
1020
                        // like cypress where cy.window does not work realibly
1021
                        if (data?.constructor.name === 'DataTransfer') {
×
1022
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1023
                        } else if (typeof data === 'string') {
×
1024
                            Editor.insertText(editor, data);
×
1025
                        }
1026
                        break;
×
1027
                    }
1028
                }
1029
            } catch (error) {
1030
                this.editor.onError({
×
1031
                    code: SlateErrorCode.OnDOMBeforeInputError,
1032
                    nativeError: error
1033
                });
1034
            }
1035
        }
1036
    }
1037

1038
    private onDOMBlur(event: FocusEvent) {
1039
        if (
×
1040
            this.readonly ||
×
1041
            this.isUpdatingSelection ||
1042
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1043
            this.isDOMEventHandled(event, this.blur)
1044
        ) {
1045
            return;
×
1046
        }
1047

1048
        const window = AngularEditor.getWindow(this.editor);
×
1049

1050
        // COMPAT: If the current `activeElement` is still the previous
1051
        // one, this is due to the window being blurred when the tab
1052
        // itself becomes unfocused, so we want to abort early to allow to
1053
        // editor to stay focused when the tab becomes focused again.
1054
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1055
        if (this.latestElement === root.activeElement) {
×
1056
            return;
×
1057
        }
1058

1059
        const { relatedTarget } = event;
×
1060
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1061

1062
        // COMPAT: The event should be ignored if the focus is returning
1063
        // to the editor from an embedded editable element (eg. an <input>
1064
        // element inside a void node).
1065
        if (relatedTarget === el) {
×
1066
            return;
×
1067
        }
1068

1069
        // COMPAT: The event should be ignored if the focus is moving from
1070
        // the editor to inside a void node's spacer element.
1071
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1072
            return;
×
1073
        }
1074

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

1081
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1082
                return;
×
1083
            }
1084
        }
1085

1086
        IS_FOCUSED.delete(this.editor);
×
1087
    }
1088

1089
    private onDOMClick(event: MouseEvent) {
1090
        if (
×
1091
            !this.readonly &&
×
1092
            AngularEditor.hasTarget(this.editor, event.target) &&
1093
            !this.isDOMEventHandled(event, this.click) &&
1094
            isDOMNode(event.target)
1095
        ) {
1096
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1097
            const path = AngularEditor.findPath(this.editor, node);
×
1098
            const start = Editor.start(this.editor, path);
×
1099
            const end = Editor.end(this.editor, path);
×
1100

1101
            const startVoid = Editor.void(this.editor, { at: start });
×
1102
            const endVoid = Editor.void(this.editor, { at: end });
×
1103

1104
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1105
                let blockPath = path;
×
1106
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1107
                    const block = Editor.above(this.editor, {
×
1108
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1109
                        at: path
1110
                    });
1111

1112
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1113
                }
1114

1115
                const range = Editor.range(this.editor, blockPath);
×
1116
                Transforms.select(this.editor, range);
×
1117
                return;
×
1118
            }
1119

1120
            if (
×
1121
                startVoid &&
×
1122
                endVoid &&
1123
                Path.equals(startVoid[1], endVoid[1]) &&
1124
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1125
            ) {
1126
                const range = Editor.range(this.editor, start);
×
1127
                Transforms.select(this.editor, range);
×
1128
            }
1129
        }
1130
    }
1131

1132
    private onDOMCompositionStart(event: CompositionEvent) {
1133
        const { selection } = this.editor;
1✔
1134
        if (selection) {
1!
1135
            // solve the problem of cross node Chinese input
1136
            if (Range.isExpanded(selection)) {
×
1137
                Editor.deleteFragment(this.editor);
×
1138
                this.forceRender();
×
1139
            }
1140
        }
1141
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1142
            this.isComposing = true;
1✔
1143
        }
1144
        this.render();
1✔
1145
    }
1146

1147
    private onDOMCompositionUpdate(event: CompositionEvent) {
1148
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1149
    }
1150

1151
    private onDOMCompositionEnd(event: CompositionEvent) {
1152
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1153
            Transforms.delete(this.editor);
×
1154
        }
1155
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1156
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1157
            // aren't correct and never fire the "insertFromComposition"
1158
            // type that we need. So instead, insert whenever a composition
1159
            // ends since it will already have been committed to the DOM.
1160
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1161
                preventInsertFromComposition(event, this.editor);
×
1162
                Editor.insertText(this.editor, event.data);
×
1163
            }
1164

1165
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1166
            // so we need avoid repeat isnertText by isComposing === true,
1167
            this.isComposing = false;
×
1168
        }
1169
        this.render();
×
1170
    }
1171

1172
    private onDOMCopy(event: ClipboardEvent) {
1173
        const window = AngularEditor.getWindow(this.editor);
×
1174
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1175
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1176
            event.preventDefault();
×
1177
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1178
        }
1179
    }
1180

1181
    private onDOMCut(event: ClipboardEvent) {
1182
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1183
            event.preventDefault();
×
1184
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1185
            const { selection } = this.editor;
×
1186

1187
            if (selection) {
×
1188
                AngularEditor.deleteCutData(this.editor);
×
1189
            }
1190
        }
1191
    }
1192

1193
    private onDOMDragOver(event: DragEvent) {
1194
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1195
            // Only when the target is void, call `preventDefault` to signal
1196
            // that drops are allowed. Editable content is droppable by
1197
            // default, and calling `preventDefault` hides the cursor.
1198
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1199

1200
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1201
                event.preventDefault();
×
1202
            }
1203
        }
1204
    }
1205

1206
    private onDOMDragStart(event: DragEvent) {
1207
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1208
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1209
            const path = AngularEditor.findPath(this.editor, node);
×
1210
            const voidMatch =
1211
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1212

1213
            // If starting a drag on a void node, make sure it is selected
1214
            // so that it shows up in the selection's fragment.
1215
            if (voidMatch) {
×
1216
                const range = Editor.range(this.editor, path);
×
1217
                Transforms.select(this.editor, range);
×
1218
            }
1219

1220
            this.isDraggingInternally = true;
×
1221

1222
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1223
        }
1224
    }
1225

1226
    private onDOMDrop(event: DragEvent) {
1227
        const editor = this.editor;
×
1228
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1229
            event.preventDefault();
×
1230
            // Keep a reference to the dragged range before updating selection
1231
            const draggedRange = editor.selection;
×
1232

1233
            // Find the range where the drop happened
1234
            const range = AngularEditor.findEventRange(editor, event);
×
1235
            const data = event.dataTransfer;
×
1236

1237
            Transforms.select(editor, range);
×
1238

1239
            if (this.isDraggingInternally) {
×
1240
                if (draggedRange) {
×
1241
                    Transforms.delete(editor, {
×
1242
                        at: draggedRange
1243
                    });
1244
                }
1245

1246
                this.isDraggingInternally = false;
×
1247
            }
1248

1249
            AngularEditor.insertData(editor, data);
×
1250

1251
            // When dragging from another source into the editor, it's possible
1252
            // that the current editor does not have focus.
1253
            if (!AngularEditor.isFocused(editor)) {
×
1254
                AngularEditor.focus(editor);
×
1255
            }
1256
        }
1257
    }
1258

1259
    private onDOMDragEnd(event: DragEvent) {
1260
        if (
×
1261
            !this.readonly &&
×
1262
            this.isDraggingInternally &&
1263
            AngularEditor.hasTarget(this.editor, event.target) &&
1264
            !this.isDOMEventHandled(event, this.dragEnd)
1265
        ) {
1266
            this.isDraggingInternally = false;
×
1267
        }
1268
    }
1269

1270
    private onDOMFocus(event: Event) {
1271
        if (
2✔
1272
            !this.readonly &&
8✔
1273
            !this.isUpdatingSelection &&
1274
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1275
            !this.isDOMEventHandled(event, this.focus)
1276
        ) {
1277
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1278
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1279
            this.latestElement = root.activeElement;
2✔
1280

1281
            // COMPAT: If the editor has nested editable elements, the focus
1282
            // can go to them. In Firefox, this must be prevented because it
1283
            // results in issues with keyboard navigation. (2017/03/30)
1284
            if (IS_FIREFOX && event.target !== el) {
2!
1285
                el.focus();
×
1286
                return;
×
1287
            }
1288

1289
            IS_FOCUSED.set(this.editor, true);
2✔
1290
        }
1291
    }
1292

1293
    private onDOMKeydown(event: KeyboardEvent) {
1294
        const editor = this.editor;
×
1295
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1296
        const { activeElement } = root;
×
1297
        if (
×
1298
            !this.readonly &&
×
1299
            AngularEditor.hasEditableTarget(editor, event.target) &&
1300
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1301
            !this.isComposing &&
1302
            !this.isDOMEventHandled(event, this.keydown)
1303
        ) {
1304
            const nativeEvent = event;
×
1305
            const { selection } = editor;
×
1306

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

1310
            try {
×
1311
                // COMPAT: Since we prevent the default behavior on
1312
                // `beforeinput` events, the browser doesn't think there's ever
1313
                // any history stack to undo or redo, so we have to manage these
1314
                // hotkeys ourselves. (2019/11/06)
1315
                if (Hotkeys.isRedo(nativeEvent)) {
×
1316
                    event.preventDefault();
×
1317

1318
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1319
                        editor.redo();
×
1320
                    }
1321

1322
                    return;
×
1323
                }
1324

1325
                if (Hotkeys.isUndo(nativeEvent)) {
×
1326
                    event.preventDefault();
×
1327

1328
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1329
                        editor.undo();
×
1330
                    }
1331

1332
                    return;
×
1333
                }
1334

1335
                // COMPAT: Certain browsers don't handle the selection updates
1336
                // properly. In Chrome, the selection isn't properly extended.
1337
                // And in Firefox, the selection isn't properly collapsed.
1338
                // (2017/10/17)
1339
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1340
                    event.preventDefault();
×
1341
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1342
                    return;
×
1343
                }
1344

1345
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1346
                    event.preventDefault();
×
1347
                    Transforms.move(editor, { unit: 'line' });
×
1348
                    return;
×
1349
                }
1350

1351
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1352
                    event.preventDefault();
×
1353
                    Transforms.move(editor, {
×
1354
                        unit: 'line',
1355
                        edge: 'focus',
1356
                        reverse: true
1357
                    });
1358
                    return;
×
1359
                }
1360

1361
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1362
                    event.preventDefault();
×
1363
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1364
                    return;
×
1365
                }
1366

1367
                // COMPAT: If a void node is selected, or a zero-width text node
1368
                // adjacent to an inline is selected, we need to handle these
1369
                // hotkeys manually because browsers won't be able to skip over
1370
                // the void node with the zero-width space not being an empty
1371
                // string.
1372
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1373
                    event.preventDefault();
×
1374

1375
                    if (selection && Range.isCollapsed(selection)) {
×
1376
                        Transforms.move(editor, { reverse: !isRTL });
×
1377
                    } else {
1378
                        Transforms.collapse(editor, { edge: 'start' });
×
1379
                    }
1380

1381
                    return;
×
1382
                }
1383

1384
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1385
                    event.preventDefault();
×
1386
                    if (selection && Range.isCollapsed(selection)) {
×
1387
                        Transforms.move(editor, { reverse: isRTL });
×
1388
                    } else {
1389
                        Transforms.collapse(editor, { edge: 'end' });
×
1390
                    }
1391

1392
                    return;
×
1393
                }
1394

1395
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1396
                    event.preventDefault();
×
1397

1398
                    if (selection && Range.isExpanded(selection)) {
×
1399
                        Transforms.collapse(editor, { edge: 'focus' });
×
1400
                    }
1401

1402
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1403
                    return;
×
1404
                }
1405

1406
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1407
                    event.preventDefault();
×
1408

1409
                    if (selection && Range.isExpanded(selection)) {
×
1410
                        Transforms.collapse(editor, { edge: 'focus' });
×
1411
                    }
1412

1413
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1414
                    return;
×
1415
                }
1416

1417
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1418
                // fall back to guessing at the input intention for hotkeys.
1419
                // COMPAT: In iOS, some of these hotkeys are handled in the
1420
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1421
                    // We don't have a core behavior for these, but they change the
1422
                    // DOM if we don't prevent them, so we have to.
1423
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1424
                        event.preventDefault();
×
1425
                        return;
×
1426
                    }
1427

1428
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1429
                        event.preventDefault();
×
1430
                        Editor.insertBreak(editor);
×
1431
                        return;
×
1432
                    }
1433

1434
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1435
                        event.preventDefault();
×
1436

1437
                        if (selection && Range.isExpanded(selection)) {
×
1438
                            Editor.deleteFragment(editor, {
×
1439
                                direction: 'backward'
1440
                            });
1441
                        } else {
1442
                            Editor.deleteBackward(editor);
×
1443
                        }
1444

1445
                        return;
×
1446
                    }
1447

1448
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1449
                        event.preventDefault();
×
1450

1451
                        if (selection && Range.isExpanded(selection)) {
×
1452
                            Editor.deleteFragment(editor, {
×
1453
                                direction: 'forward'
1454
                            });
1455
                        } else {
1456
                            Editor.deleteForward(editor);
×
1457
                        }
1458

1459
                        return;
×
1460
                    }
1461

1462
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1463
                        event.preventDefault();
×
1464

1465
                        if (selection && Range.isExpanded(selection)) {
×
1466
                            Editor.deleteFragment(editor, {
×
1467
                                direction: 'backward'
1468
                            });
1469
                        } else {
1470
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1471
                        }
1472

1473
                        return;
×
1474
                    }
1475

1476
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1477
                        event.preventDefault();
×
1478

1479
                        if (selection && Range.isExpanded(selection)) {
×
1480
                            Editor.deleteFragment(editor, {
×
1481
                                direction: 'forward'
1482
                            });
1483
                        } else {
1484
                            Editor.deleteForward(editor, { unit: 'line' });
×
1485
                        }
1486

1487
                        return;
×
1488
                    }
1489

1490
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1491
                        event.preventDefault();
×
1492

1493
                        if (selection && Range.isExpanded(selection)) {
×
1494
                            Editor.deleteFragment(editor, {
×
1495
                                direction: 'backward'
1496
                            });
1497
                        } else {
1498
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1499
                        }
1500

1501
                        return;
×
1502
                    }
1503

1504
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1505
                        event.preventDefault();
×
1506

1507
                        if (selection && Range.isExpanded(selection)) {
×
1508
                            Editor.deleteFragment(editor, {
×
1509
                                direction: 'forward'
1510
                            });
1511
                        } else {
1512
                            Editor.deleteForward(editor, { unit: 'word' });
×
1513
                        }
1514

1515
                        return;
×
1516
                    }
1517
                } else {
1518
                    if (IS_CHROME || IS_SAFARI) {
×
1519
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1520
                        // an event when deleting backwards in a selected void inline node
1521
                        if (
×
1522
                            selection &&
×
1523
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1524
                            Range.isCollapsed(selection)
1525
                        ) {
1526
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1527
                            if (
×
1528
                                Element.isElement(currentNode) &&
×
1529
                                Editor.isVoid(editor, currentNode) &&
1530
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1531
                            ) {
1532
                                event.preventDefault();
×
1533
                                Editor.deleteBackward(editor, {
×
1534
                                    unit: 'block'
1535
                                });
1536
                                return;
×
1537
                            }
1538
                        }
1539
                    }
1540
                }
1541
            } catch (error) {
1542
                this.editor.onError({
×
1543
                    code: SlateErrorCode.OnDOMKeydownError,
1544
                    nativeError: error
1545
                });
1546
            }
1547
        }
1548
    }
1549

1550
    private onDOMPaste(event: ClipboardEvent) {
1551
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1552
        // fall back to React's `onPaste` here instead.
1553
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1554
        // when "paste without formatting" option is used.
1555
        // This unfortunately needs to be handled with paste events instead.
1556
        if (
×
1557
            !this.isDOMEventHandled(event, this.paste) &&
×
1558
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1559
            !this.readonly &&
1560
            AngularEditor.hasEditableTarget(this.editor, event.target)
1561
        ) {
1562
            event.preventDefault();
×
1563
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1564
        }
1565
    }
1566

1567
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1568
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1569
        // fall back to React's leaky polyfill instead just for it. It
1570
        // only works for the `insertText` input type.
1571
        if (
×
1572
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1573
            !this.readonly &&
1574
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1575
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1576
        ) {
1577
            event.nativeEvent.preventDefault();
×
1578
            try {
×
1579
                const text = event.data;
×
1580
                if (!Range.isCollapsed(this.editor.selection)) {
×
1581
                    Editor.deleteFragment(this.editor);
×
1582
                }
1583
                // just handle Non-IME input
1584
                if (!this.isComposing) {
×
1585
                    Editor.insertText(this.editor, text);
×
1586
                }
1587
            } catch (error) {
1588
                this.editor.onError({
×
1589
                    code: SlateErrorCode.ToNativeSelectionError,
1590
                    nativeError: error
1591
                });
1592
            }
1593
        }
1594
    }
1595

1596
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1597
        if (!handler) {
3✔
1598
            return false;
3✔
1599
        }
1600
        handler(event);
×
1601
        return event.defaultPrevented;
×
1602
    }
1603
    //#endregion
1604

1605
    ngOnDestroy() {
1606
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1607
        this.manualListeners.forEach(manualListener => {
22✔
1608
            manualListener();
462✔
1609
        });
1610
        this.destroy$.complete();
22✔
1611
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1612
    }
1613
}
1614

1615
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1616
    // This was affecting the selection of multiple blocks and dragging behavior,
1617
    // so enabled only if the selection has been collapsed.
1618
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1619
        const leafEl = domRange.startContainer.parentElement!;
×
1620

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

1626
        if (isZeroDimensionRect) {
×
1627
            const leafRect = leafEl.getBoundingClientRect();
×
1628
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1629

1630
            if (leafHasDimensions) {
×
1631
                return;
×
1632
            }
1633
        }
1634

1635
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1636
        scrollIntoView(leafEl, {
×
1637
            scrollMode: 'if-needed'
1638
        });
1639
        delete leafEl.getBoundingClientRect;
×
1640
    }
1641
};
1642

1643
/**
1644
 * Check if the target is inside void and in the editor.
1645
 */
1646

1647
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1648
    let slateNode: Node | null = null;
1✔
1649
    try {
1✔
1650
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1651
    } catch (error) {}
1652
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1653
};
1654

1655
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1656
    return (
2✔
1657
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1658
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1659
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1660
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1661
    );
1662
};
1663

1664
/**
1665
 * remove default insert from composition
1666
 * @param text
1667
 */
1668
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1669
    const types = ['compositionend', 'insertFromComposition'];
×
1670
    if (!types.includes(event.type)) {
×
1671
        return;
×
1672
    }
1673
    const insertText = (event as CompositionEvent).data;
×
1674
    const window = AngularEditor.getWindow(editor);
×
1675
    const domSelection = window.getSelection();
×
1676
    // ensure text node insert composition input text
1677
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1678
        const textNode = domSelection.anchorNode;
×
1679
        textNode.splitText(textNode.length - insertText.length).remove();
×
1680
    }
1681
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc