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

worktile / slate-angular / 88c94cb0-ac7f-429a-b453-e1d616f0b48c

04 Dec 2025 04:09AM UTC coverage: 45.812% (+0.02%) from 45.797%
88c94cb0-ac7f-429a-b453-e1d616f0b48c

Pull #306

circleci

pubuzhixing8
fix: solve error when virtual is disabled
Pull Request #306: fix(virtual): solve runout issue

384 of 1045 branches covered (36.75%)

Branch coverage included in aggregate %.

12 of 29 new or added lines in 1 file covered. (41.38%)

188 existing lines in 1 file now uncovered.

1049 of 2083 relevant lines covered (50.36%)

31.12 hits per line

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

29.1
/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
} from '../../utils/environment';
51
import Hotkeys from '../../utils/hotkeys';
52
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
53
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
54
import { SlateErrorCode } from '../../types/error';
55
import { NG_VALUE_ACCESSOR } from '@angular/forms';
56
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
57
import { ViewType } from '../../types/view';
58
import { HistoryEditor } from 'slate-history';
59
import { ELEMENT_TO_COMPONENT, isDecoratorRangeListEqual } from '../../utils';
60
import { SlatePlaceholder } from '../../types/feature';
61
import { restoreDom } from '../../utils/restore-dom';
62
import { ListRender } from '../../view/render/list-render';
63
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
64
import { BaseElementComponent } from '../../view/base';
65
import { BaseElementFlavour } from '../../view/flavour/element';
66

67
export const JUST_NOW_UPDATED_VIRTUAL_VIEW = new WeakMap<AngularEditor, boolean>();
1✔
68

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

72
export interface SlateVirtualScrollConfig {
73
    enabled?: boolean;
74
    scrollTop: number;
75
    viewportHeight: number;
76
    bufferCount?: number;
77
}
78

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

104
    private destroy$ = new Subject();
23✔
105

106
    isComposing = false;
23✔
107
    isDraggingInternally = false;
23✔
108
    isUpdatingSelection = false;
23✔
109
    latestElement = null as DOMElement | null;
23✔
110

111
    protected manualListeners: (() => void)[] = [];
23✔
112

113
    private initialized: boolean;
114

115
    private onTouchedCallback: () => void = () => {};
23✔
116

117
    private onChangeCallback: (_: any) => void = () => {};
23✔
118

119
    @Input() editor: AngularEditor;
120

121
    @Input() renderElement: (element: Element) => ViewType | null;
122

123
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
124

125
    @Input() renderText: (text: SlateText) => ViewType | null;
126

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

129
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
130

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

133
    @Input() isStrictDecorate: boolean = true;
23✔
134

135
    @Input() trackBy: (node: Element) => any = () => null;
206✔
136

137
    @Input() readonly = false;
23✔
138

139
    @Input() placeholder: string;
140

141
    @Input()
142
    set virtualScroll(config: SlateVirtualScrollConfig) {
143
        this.virtualConfig = config;
×
144
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
145
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
146
            // TODO: 返回 renderedChildren 是否发生变化,变换后的索引范围,变化后的 top 和 bottom
147
            // 计算出隐藏的节点的高度大小,看和 top 的变化值是否一样
148
            // 如果发生变化,记录新的 top 和 bottom
149
            this.refreshVirtualView();
×
150

151
            if (this.listRender.initialized) {
×
152
                this.listRender.update(this.renderedChildren, this.editor, this.context);
×
153
            }
154
            this.scheduleMeasureVisibleHeights();
×
155
        });
156
    }
157

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

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

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

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

190
    viewContainerRef = inject(ViewContainerRef);
23✔
191

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

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

204
    listRender: ListRender;
205

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

218
    constructor(
219
        public elementRef: ElementRef,
23✔
220
        public renderer2: Renderer2,
23✔
221
        public cdr: ChangeDetectorRef,
23✔
222
        private ngZone: NgZone,
23✔
223
        private injector: Injector
23✔
224
    ) {}
225

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

246
        // add browser class
247
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
248
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
249
        this.initializeVirtualScrolling();
23✔
250
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
251
    }
252

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

273
    registerOnChange(fn: any) {
274
        this.onChangeCallback = fn;
23✔
275
    }
276
    registerOnTouched(fn: any) {
277
        this.onTouchedCallback = fn;
23✔
278
    }
279

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

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

328
    toNativeSelection() {
329
        try {
15✔
330
            const { selection } = this.editor;
15✔
331
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
332
            const { activeElement } = root;
15✔
333
            const domSelection = (root as Document).getSelection();
15✔
334

335
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
336
                return;
14✔
337
            }
338

339
            const hasDomSelection = domSelection.type !== 'None';
1✔
340

341
            // If the DOM selection is properly unset, we're done.
342
            if (!selection && !hasDomSelection) {
1!
343
                return;
×
344
            }
345

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

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

365
            // prevent updating native selection when active element is void element
366
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
367
                return;
×
368
            }
369

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

379
            // Otherwise the DOM selection is out of sync, so update it.
380
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
381
            this.isUpdatingSelection = true;
1✔
382

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

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

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

419
                this.isUpdatingSelection = false;
1✔
420
            });
421
        } catch (error) {
422
            this.editor.onError({
×
423
                code: SlateErrorCode.ToNativeSelectionError,
424
                nativeError: error
425
            });
426
            this.isUpdatingSelection = false;
×
427
        }
428
    }
429

430
    onChange() {
431
        this.forceRender();
13✔
432
        this.onChangeCallback(this.editor.children);
13✔
433
    }
434

435
    ngAfterViewChecked() {}
436

437
    ngDoCheck() {}
438

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

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

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

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

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

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

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

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

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

560
    virtualScrollInitialized = false;
23✔
561

562
    virtualTopHeightElement: HTMLElement;
563

564
    virtualBottomHeightElement: HTMLElement;
565

566
    virtualCenterOutlet: HTMLElement;
567

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

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

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

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

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

628
        const visible: Element[] = [];
×
UNCOV
629
        const visibleIndexes: number[] = [];
×
630
        let accumulated = 0;
×
631
        let cursor = startIndex;
×
632
        // 循环累计高度超出目标高度(可视高度 + 上下 buffer)
633
        while (cursor < children.length && accumulated < targetHeight) {
×
UNCOV
634
            visible.push(children[cursor]);
×
635
            visibleIndexes.push(cursor);
×
636
            accumulated += this.getBlockHeight(cursor);
×
637
            cursor++;
×
638
        }
639
        const bottom = Math.max(total - top - accumulated, 0); // 下占位高度
×
UNCOV
640
        this.renderedChildren = visible.length ? visible : children;
×
641
        // padding 占位
NEW
642
        this.changeVirtualHeight(Math.round(top), Math.round(bottom));
×
UNCOV
643
        this.virtualVisibleIndexes = new Set(visibleIndexes);
×
NEW
644
        JUST_NOW_UPDATED_VIRTUAL_VIEW.set(this.editor, true);
×
645
    }
646

647
    private getBlockHeight(index: number) {
UNCOV
648
        const node = this.editor.children[index];
×
UNCOV
649
        if (!node) {
×
650
            return VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
651
        }
652
        const key = AngularEditor.findKey(this.editor, node);
×
UNCOV
653
        return this.measuredHeights.get(key.id) ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
654
    }
655

656
    private buildAccumulatedHeight(heights: number[]) {
UNCOV
657
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
658
        for (let i = 0; i < heights.length; i++) {
×
659
            // 存储前 i 个的累计高度
UNCOV
660
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
661
        }
UNCOV
662
        return accumulatedHeights;
×
663
    }
664

665
    private getBufferBelowHeight(viewportHeight: number, visibleStart: number, bufferCount: number) {
UNCOV
666
        let blockHeight = 0;
×
667
        let start = visibleStart;
×
668
        // 循环累计高度超出视图高度代表找到向下缓冲区的起始位置
UNCOV
669
        while (blockHeight < viewportHeight) {
×
670
            blockHeight += this.getBlockHeight(start);
×
671
            start++;
×
672
        }
UNCOV
673
        let bufferHeight = 0;
×
674
        for (let i = start; i < start + bufferCount; i++) {
×
675
            bufferHeight += this.getBlockHeight(i);
×
676
        }
UNCOV
677
        return bufferHeight;
×
678
    }
679

680
    private scheduleMeasureVisibleHeights() {
681
        if (!this.shouldUseVirtual()) {
43✔
682
            return;
43✔
683
        }
UNCOV
684
        if (this.measurePending) {
×
685
            return;
×
686
        }
UNCOV
687
        this.measurePending = true;
×
688
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
689
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
690
            this.measureVisibleHeights();
×
691
            this.measurePending = false;
×
692
        });
693
    }
694

695
    private measureVisibleHeights() {
UNCOV
696
        const children = (this.editor.children || []) as Element[];
×
697
        this.virtualVisibleIndexes.forEach(index => {
×
698
            const node = children[index];
×
699
            if (!node) {
×
700
                return;
×
701
            }
UNCOV
702
            const key = AngularEditor.findKey(this.editor, node);
×
703
            // 跳过已测过的块
UNCOV
704
            if (this.measuredHeights.has(key.id)) {
×
705
                return;
×
706
            }
UNCOV
707
            const view = ELEMENT_TO_COMPONENT.get(node);
×
708
            if (!view) {
×
709
                return;
×
710
            }
UNCOV
711
            (view as BaseElementComponent | BaseElementFlavour).getRealHeight()?.then(height => {
×
712
                this.measuredHeights.set(key.id, height);
×
713
            });
714
        });
715
    }
716

717
    //#region event proxy
718
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
719
        this.manualListeners.push(
483✔
720
            this.renderer2.listen(target, eventName, (event: Event) => {
721
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
722
                if (beforeInputEvent) {
5!
UNCOV
723
                    this.onFallbackBeforeInput(beforeInputEvent);
×
724
                }
725
                listener(event);
5✔
726
            })
727
        );
728
    }
729

730
    private toSlateSelection() {
731
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
732
            try {
1✔
733
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
734
                const { activeElement } = root;
1✔
735
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
736
                const domSelection = (root as Document).getSelection();
1✔
737

738
                if (activeElement === el) {
1!
739
                    this.latestElement = activeElement;
1✔
740
                    IS_FOCUSED.set(this.editor, true);
1✔
741
                } else {
UNCOV
742
                    IS_FOCUSED.delete(this.editor);
×
743
                }
744

745
                if (!domSelection) {
1!
UNCOV
746
                    return Transforms.deselect(this.editor);
×
747
                }
748

749
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
750
                const hasDomSelectionInEditor =
751
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
752
                if (!hasDomSelectionInEditor) {
1!
UNCOV
753
                    Transforms.deselect(this.editor);
×
754
                    return;
×
755
                }
756

757
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
758
                // for example, double-click the last cell of the table to select a non-editable DOM
759
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
760
                if (range) {
1✔
761
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
UNCOV
762
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
763
                            // force adjust DOMSelection
UNCOV
764
                            this.toNativeSelection();
×
765
                        }
766
                    } else {
767
                        Transforms.select(this.editor, range);
1✔
768
                    }
769
                }
770
            } catch (error) {
UNCOV
771
                this.editor.onError({
×
772
                    code: SlateErrorCode.ToSlateSelectionError,
773
                    nativeError: error
774
                });
775
            }
776
        }
777
    }
778

779
    private onDOMBeforeInput(
780
        event: Event & {
781
            inputType: string;
782
            isComposing: boolean;
783
            data: string | null;
784
            dataTransfer: DataTransfer | null;
785
            getTargetRanges(): DOMStaticRange[];
786
        }
787
    ) {
UNCOV
788
        const editor = this.editor;
×
789
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
790
        const { activeElement } = root;
×
791
        const { selection } = editor;
×
792
        const { inputType: type } = event;
×
793
        const data = event.dataTransfer || event.data || undefined;
×
794
        if (IS_ANDROID) {
×
795
            let targetRange: Range | null = null;
×
796
            let [nativeTargetRange] = event.getTargetRanges();
×
797
            if (nativeTargetRange) {
×
798
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
799
            }
800
            // COMPAT: SelectionChange event is fired after the action is performed, so we
801
            // have to manually get the selection here to ensure it's up-to-date.
UNCOV
802
            const window = AngularEditor.getWindow(editor);
×
803
            const domSelection = window.getSelection();
×
804
            if (!targetRange && domSelection) {
×
805
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
806
            }
UNCOV
807
            targetRange = targetRange ?? editor.selection;
×
808
            if (type === 'insertCompositionText') {
×
809
                if (data && data.toString().includes('\n')) {
×
810
                    restoreDom(editor, () => {
×
811
                        Editor.insertBreak(editor);
×
812
                    });
813
                } else {
UNCOV
814
                    if (targetRange) {
×
815
                        if (data) {
×
816
                            restoreDom(editor, () => {
×
817
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
818
                            });
819
                        } else {
UNCOV
820
                            restoreDom(editor, () => {
×
821
                                Transforms.delete(editor, { at: targetRange });
×
822
                            });
823
                        }
824
                    }
825
                }
UNCOV
826
                return;
×
827
            }
UNCOV
828
            if (type === 'deleteContentBackward') {
×
829
                // gboard can not prevent default action, so must use restoreDom,
830
                // sougou Keyboard can prevent default action(only in Chinese input mode).
831
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
UNCOV
832
                if (!Range.isCollapsed(targetRange)) {
×
833
                    restoreDom(editor, () => {
×
834
                        Transforms.delete(editor, { at: targetRange });
×
835
                    });
UNCOV
836
                    return;
×
837
                }
838
            }
UNCOV
839
            if (type === 'insertText') {
×
840
                restoreDom(editor, () => {
×
841
                    if (typeof data === 'string') {
×
842
                        Editor.insertText(editor, data);
×
843
                    }
844
                });
UNCOV
845
                return;
×
846
            }
847
        }
UNCOV
848
        if (
×
849
            !this.readonly &&
×
850
            AngularEditor.hasEditableTarget(editor, event.target) &&
851
            !isTargetInsideVoid(editor, activeElement) &&
852
            !this.isDOMEventHandled(event, this.beforeInput)
853
        ) {
UNCOV
854
            try {
×
855
                event.preventDefault();
×
856

857
                // COMPAT: If the selection is expanded, even if the command seems like
858
                // a delete forward/backward command it should delete the selection.
UNCOV
859
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
860
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
861
                    Editor.deleteFragment(editor, { direction });
×
862
                    return;
×
863
                }
864

UNCOV
865
                switch (type) {
×
866
                    case 'deleteByComposition':
867
                    case 'deleteByCut':
868
                    case 'deleteByDrag': {
UNCOV
869
                        Editor.deleteFragment(editor);
×
870
                        break;
×
871
                    }
872

873
                    case 'deleteContent':
874
                    case 'deleteContentForward': {
UNCOV
875
                        Editor.deleteForward(editor);
×
876
                        break;
×
877
                    }
878

879
                    case 'deleteContentBackward': {
UNCOV
880
                        Editor.deleteBackward(editor);
×
881
                        break;
×
882
                    }
883

884
                    case 'deleteEntireSoftLine': {
UNCOV
885
                        Editor.deleteBackward(editor, { unit: 'line' });
×
886
                        Editor.deleteForward(editor, { unit: 'line' });
×
887
                        break;
×
888
                    }
889

890
                    case 'deleteHardLineBackward': {
UNCOV
891
                        Editor.deleteBackward(editor, { unit: 'block' });
×
892
                        break;
×
893
                    }
894

895
                    case 'deleteSoftLineBackward': {
UNCOV
896
                        Editor.deleteBackward(editor, { unit: 'line' });
×
897
                        break;
×
898
                    }
899

900
                    case 'deleteHardLineForward': {
UNCOV
901
                        Editor.deleteForward(editor, { unit: 'block' });
×
902
                        break;
×
903
                    }
904

905
                    case 'deleteSoftLineForward': {
UNCOV
906
                        Editor.deleteForward(editor, { unit: 'line' });
×
907
                        break;
×
908
                    }
909

910
                    case 'deleteWordBackward': {
UNCOV
911
                        Editor.deleteBackward(editor, { unit: 'word' });
×
912
                        break;
×
913
                    }
914

915
                    case 'deleteWordForward': {
UNCOV
916
                        Editor.deleteForward(editor, { unit: 'word' });
×
917
                        break;
×
918
                    }
919

920
                    case 'insertLineBreak':
921
                    case 'insertParagraph': {
UNCOV
922
                        Editor.insertBreak(editor);
×
923
                        break;
×
924
                    }
925

926
                    case 'insertFromComposition': {
927
                        // COMPAT: in safari, `compositionend` event is dispatched after
928
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
929
                        // https://www.w3.org/TR/input-events-2/
930
                        // so the following code is the right logic
931
                        // because DOM selection in sync will be exec before `compositionend` event
932
                        // isComposing is true will prevent DOM selection being update correctly.
UNCOV
933
                        this.isComposing = false;
×
934
                        preventInsertFromComposition(event, this.editor);
×
935
                    }
936
                    case 'insertFromDrop':
937
                    case 'insertFromPaste':
938
                    case 'insertFromYank':
939
                    case 'insertReplacementText':
940
                    case 'insertText': {
941
                        // use a weak comparison instead of 'instanceof' to allow
942
                        // programmatic access of paste events coming from external windows
943
                        // like cypress where cy.window does not work realibly
UNCOV
944
                        if (data?.constructor.name === 'DataTransfer') {
×
945
                            AngularEditor.insertData(editor, data as DataTransfer);
×
946
                        } else if (typeof data === 'string') {
×
947
                            Editor.insertText(editor, data);
×
948
                        }
UNCOV
949
                        break;
×
950
                    }
951
                }
952
            } catch (error) {
UNCOV
953
                this.editor.onError({
×
954
                    code: SlateErrorCode.OnDOMBeforeInputError,
955
                    nativeError: error
956
                });
957
            }
958
        }
959
    }
960

961
    private onDOMBlur(event: FocusEvent) {
UNCOV
962
        if (
×
963
            this.readonly ||
×
964
            this.isUpdatingSelection ||
965
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
966
            this.isDOMEventHandled(event, this.blur)
967
        ) {
UNCOV
968
            return;
×
969
        }
970

UNCOV
971
        const window = AngularEditor.getWindow(this.editor);
×
972

973
        // COMPAT: If the current `activeElement` is still the previous
974
        // one, this is due to the window being blurred when the tab
975
        // itself becomes unfocused, so we want to abort early to allow to
976
        // editor to stay focused when the tab becomes focused again.
UNCOV
977
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
978
        if (this.latestElement === root.activeElement) {
×
979
            return;
×
980
        }
981

UNCOV
982
        const { relatedTarget } = event;
×
983
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
984

985
        // COMPAT: The event should be ignored if the focus is returning
986
        // to the editor from an embedded editable element (eg. an <input>
987
        // element inside a void node).
UNCOV
988
        if (relatedTarget === el) {
×
989
            return;
×
990
        }
991

992
        // COMPAT: The event should be ignored if the focus is moving from
993
        // the editor to inside a void node's spacer element.
UNCOV
994
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
995
            return;
×
996
        }
997

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

UNCOV
1004
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1005
                return;
×
1006
            }
1007
        }
1008

UNCOV
1009
        IS_FOCUSED.delete(this.editor);
×
1010
    }
1011

1012
    private onDOMClick(event: MouseEvent) {
UNCOV
1013
        if (
×
1014
            !this.readonly &&
×
1015
            AngularEditor.hasTarget(this.editor, event.target) &&
1016
            !this.isDOMEventHandled(event, this.click) &&
1017
            isDOMNode(event.target)
1018
        ) {
UNCOV
1019
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1020
            const path = AngularEditor.findPath(this.editor, node);
×
1021
            const start = Editor.start(this.editor, path);
×
1022
            const end = Editor.end(this.editor, path);
×
1023

UNCOV
1024
            const startVoid = Editor.void(this.editor, { at: start });
×
1025
            const endVoid = Editor.void(this.editor, { at: end });
×
1026

UNCOV
1027
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1028
                let blockPath = path;
×
1029
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1030
                    const block = Editor.above(this.editor, {
×
1031
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1032
                        at: path
1033
                    });
1034

UNCOV
1035
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1036
                }
1037

UNCOV
1038
                const range = Editor.range(this.editor, blockPath);
×
1039
                Transforms.select(this.editor, range);
×
1040
                return;
×
1041
            }
1042

UNCOV
1043
            if (
×
1044
                startVoid &&
×
1045
                endVoid &&
1046
                Path.equals(startVoid[1], endVoid[1]) &&
1047
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1048
            ) {
UNCOV
1049
                const range = Editor.range(this.editor, start);
×
1050
                Transforms.select(this.editor, range);
×
1051
            }
1052
        }
1053
    }
1054

1055
    private onDOMCompositionStart(event: CompositionEvent) {
1056
        const { selection } = this.editor;
1✔
1057
        if (selection) {
1!
1058
            // solve the problem of cross node Chinese input
UNCOV
1059
            if (Range.isExpanded(selection)) {
×
1060
                Editor.deleteFragment(this.editor);
×
1061
                this.forceRender();
×
1062
            }
1063
        }
1064
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1065
            this.isComposing = true;
1✔
1066
        }
1067
        this.render();
1✔
1068
    }
1069

1070
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1071
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1072
    }
1073

1074
    private onDOMCompositionEnd(event: CompositionEvent) {
UNCOV
1075
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1076
            Transforms.delete(this.editor);
×
1077
        }
UNCOV
1078
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1079
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1080
            // aren't correct and never fire the "insertFromComposition"
1081
            // type that we need. So instead, insert whenever a composition
1082
            // ends since it will already have been committed to the DOM.
UNCOV
1083
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1084
                preventInsertFromComposition(event, this.editor);
×
1085
                Editor.insertText(this.editor, event.data);
×
1086
            }
1087

1088
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1089
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1090
            this.isComposing = false;
×
1091
        }
UNCOV
1092
        this.render();
×
1093
    }
1094

1095
    private onDOMCopy(event: ClipboardEvent) {
UNCOV
1096
        const window = AngularEditor.getWindow(this.editor);
×
1097
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1098
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1099
            event.preventDefault();
×
1100
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1101
        }
1102
    }
1103

1104
    private onDOMCut(event: ClipboardEvent) {
UNCOV
1105
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1106
            event.preventDefault();
×
1107
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1108
            const { selection } = this.editor;
×
1109

UNCOV
1110
            if (selection) {
×
1111
                AngularEditor.deleteCutData(this.editor);
×
1112
            }
1113
        }
1114
    }
1115

1116
    private onDOMDragOver(event: DragEvent) {
UNCOV
1117
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1118
            // Only when the target is void, call `preventDefault` to signal
1119
            // that drops are allowed. Editable content is droppable by
1120
            // default, and calling `preventDefault` hides the cursor.
UNCOV
1121
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1122

UNCOV
1123
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1124
                event.preventDefault();
×
1125
            }
1126
        }
1127
    }
1128

1129
    private onDOMDragStart(event: DragEvent) {
UNCOV
1130
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1131
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1132
            const path = AngularEditor.findPath(this.editor, node);
×
1133
            const voidMatch =
UNCOV
1134
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1135

1136
            // If starting a drag on a void node, make sure it is selected
1137
            // so that it shows up in the selection's fragment.
UNCOV
1138
            if (voidMatch) {
×
1139
                const range = Editor.range(this.editor, path);
×
1140
                Transforms.select(this.editor, range);
×
1141
            }
1142

UNCOV
1143
            this.isDraggingInternally = true;
×
1144

UNCOV
1145
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1146
        }
1147
    }
1148

1149
    private onDOMDrop(event: DragEvent) {
UNCOV
1150
        const editor = this.editor;
×
1151
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1152
            event.preventDefault();
×
1153
            // Keep a reference to the dragged range before updating selection
UNCOV
1154
            const draggedRange = editor.selection;
×
1155

1156
            // Find the range where the drop happened
UNCOV
1157
            const range = AngularEditor.findEventRange(editor, event);
×
1158
            const data = event.dataTransfer;
×
1159

UNCOV
1160
            Transforms.select(editor, range);
×
1161

UNCOV
1162
            if (this.isDraggingInternally) {
×
1163
                if (draggedRange) {
×
1164
                    Transforms.delete(editor, {
×
1165
                        at: draggedRange
1166
                    });
1167
                }
1168

UNCOV
1169
                this.isDraggingInternally = false;
×
1170
            }
1171

UNCOV
1172
            AngularEditor.insertData(editor, data);
×
1173

1174
            // When dragging from another source into the editor, it's possible
1175
            // that the current editor does not have focus.
UNCOV
1176
            if (!AngularEditor.isFocused(editor)) {
×
1177
                AngularEditor.focus(editor);
×
1178
            }
1179
        }
1180
    }
1181

1182
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1183
        if (
×
1184
            !this.readonly &&
×
1185
            this.isDraggingInternally &&
1186
            AngularEditor.hasTarget(this.editor, event.target) &&
1187
            !this.isDOMEventHandled(event, this.dragEnd)
1188
        ) {
UNCOV
1189
            this.isDraggingInternally = false;
×
1190
        }
1191
    }
1192

1193
    private onDOMFocus(event: Event) {
1194
        if (
2✔
1195
            !this.readonly &&
8✔
1196
            !this.isUpdatingSelection &&
1197
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1198
            !this.isDOMEventHandled(event, this.focus)
1199
        ) {
1200
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1201
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1202
            this.latestElement = root.activeElement;
2✔
1203

1204
            // COMPAT: If the editor has nested editable elements, the focus
1205
            // can go to them. In Firefox, this must be prevented because it
1206
            // results in issues with keyboard navigation. (2017/03/30)
1207
            if (IS_FIREFOX && event.target !== el) {
2!
UNCOV
1208
                el.focus();
×
1209
                return;
×
1210
            }
1211

1212
            IS_FOCUSED.set(this.editor, true);
2✔
1213
        }
1214
    }
1215

1216
    private onDOMKeydown(event: KeyboardEvent) {
UNCOV
1217
        const editor = this.editor;
×
1218
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1219
        const { activeElement } = root;
×
1220
        if (
×
1221
            !this.readonly &&
×
1222
            AngularEditor.hasEditableTarget(editor, event.target) &&
1223
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1224
            !this.isComposing &&
1225
            !this.isDOMEventHandled(event, this.keydown)
1226
        ) {
UNCOV
1227
            const nativeEvent = event;
×
1228
            const { selection } = editor;
×
1229

UNCOV
1230
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
1231
            const isRTL = direction(Node.string(element)) === 'rtl';
×
1232

UNCOV
1233
            try {
×
1234
                // COMPAT: Since we prevent the default behavior on
1235
                // `beforeinput` events, the browser doesn't think there's ever
1236
                // any history stack to undo or redo, so we have to manage these
1237
                // hotkeys ourselves. (2019/11/06)
UNCOV
1238
                if (Hotkeys.isRedo(nativeEvent)) {
×
1239
                    event.preventDefault();
×
1240

UNCOV
1241
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1242
                        editor.redo();
×
1243
                    }
1244

UNCOV
1245
                    return;
×
1246
                }
1247

UNCOV
1248
                if (Hotkeys.isUndo(nativeEvent)) {
×
1249
                    event.preventDefault();
×
1250

UNCOV
1251
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1252
                        editor.undo();
×
1253
                    }
1254

UNCOV
1255
                    return;
×
1256
                }
1257

1258
                // COMPAT: Certain browsers don't handle the selection updates
1259
                // properly. In Chrome, the selection isn't properly extended.
1260
                // And in Firefox, the selection isn't properly collapsed.
1261
                // (2017/10/17)
UNCOV
1262
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1263
                    event.preventDefault();
×
1264
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1265
                    return;
×
1266
                }
1267

UNCOV
1268
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1269
                    event.preventDefault();
×
1270
                    Transforms.move(editor, { unit: 'line' });
×
1271
                    return;
×
1272
                }
1273

UNCOV
1274
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1275
                    event.preventDefault();
×
1276
                    Transforms.move(editor, {
×
1277
                        unit: 'line',
1278
                        edge: 'focus',
1279
                        reverse: true
1280
                    });
UNCOV
1281
                    return;
×
1282
                }
1283

UNCOV
1284
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1285
                    event.preventDefault();
×
1286
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1287
                    return;
×
1288
                }
1289

1290
                // COMPAT: If a void node is selected, or a zero-width text node
1291
                // adjacent to an inline is selected, we need to handle these
1292
                // hotkeys manually because browsers won't be able to skip over
1293
                // the void node with the zero-width space not being an empty
1294
                // string.
UNCOV
1295
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1296
                    event.preventDefault();
×
1297

UNCOV
1298
                    if (selection && Range.isCollapsed(selection)) {
×
1299
                        Transforms.move(editor, { reverse: !isRTL });
×
1300
                    } else {
UNCOV
1301
                        Transforms.collapse(editor, { edge: 'start' });
×
1302
                    }
1303

UNCOV
1304
                    return;
×
1305
                }
1306

UNCOV
1307
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1308
                    event.preventDefault();
×
1309
                    if (selection && Range.isCollapsed(selection)) {
×
1310
                        Transforms.move(editor, { reverse: isRTL });
×
1311
                    } else {
UNCOV
1312
                        Transforms.collapse(editor, { edge: 'end' });
×
1313
                    }
1314

UNCOV
1315
                    return;
×
1316
                }
1317

UNCOV
1318
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1319
                    event.preventDefault();
×
1320

UNCOV
1321
                    if (selection && Range.isExpanded(selection)) {
×
1322
                        Transforms.collapse(editor, { edge: 'focus' });
×
1323
                    }
1324

UNCOV
1325
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1326
                    return;
×
1327
                }
1328

UNCOV
1329
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1330
                    event.preventDefault();
×
1331

UNCOV
1332
                    if (selection && Range.isExpanded(selection)) {
×
1333
                        Transforms.collapse(editor, { edge: 'focus' });
×
1334
                    }
1335

UNCOV
1336
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1337
                    return;
×
1338
                }
1339

1340
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1341
                // fall back to guessing at the input intention for hotkeys.
1342
                // COMPAT: In iOS, some of these hotkeys are handled in the
UNCOV
1343
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1344
                    // We don't have a core behavior for these, but they change the
1345
                    // DOM if we don't prevent them, so we have to.
UNCOV
1346
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1347
                        event.preventDefault();
×
1348
                        return;
×
1349
                    }
1350

UNCOV
1351
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1352
                        event.preventDefault();
×
1353
                        Editor.insertBreak(editor);
×
1354
                        return;
×
1355
                    }
1356

UNCOV
1357
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1358
                        event.preventDefault();
×
1359

UNCOV
1360
                        if (selection && Range.isExpanded(selection)) {
×
1361
                            Editor.deleteFragment(editor, {
×
1362
                                direction: 'backward'
1363
                            });
1364
                        } else {
UNCOV
1365
                            Editor.deleteBackward(editor);
×
1366
                        }
1367

UNCOV
1368
                        return;
×
1369
                    }
1370

UNCOV
1371
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1372
                        event.preventDefault();
×
1373

UNCOV
1374
                        if (selection && Range.isExpanded(selection)) {
×
1375
                            Editor.deleteFragment(editor, {
×
1376
                                direction: 'forward'
1377
                            });
1378
                        } else {
UNCOV
1379
                            Editor.deleteForward(editor);
×
1380
                        }
1381

UNCOV
1382
                        return;
×
1383
                    }
1384

UNCOV
1385
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1386
                        event.preventDefault();
×
1387

UNCOV
1388
                        if (selection && Range.isExpanded(selection)) {
×
1389
                            Editor.deleteFragment(editor, {
×
1390
                                direction: 'backward'
1391
                            });
1392
                        } else {
UNCOV
1393
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1394
                        }
1395

UNCOV
1396
                        return;
×
1397
                    }
1398

UNCOV
1399
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1400
                        event.preventDefault();
×
1401

UNCOV
1402
                        if (selection && Range.isExpanded(selection)) {
×
1403
                            Editor.deleteFragment(editor, {
×
1404
                                direction: 'forward'
1405
                            });
1406
                        } else {
UNCOV
1407
                            Editor.deleteForward(editor, { unit: 'line' });
×
1408
                        }
1409

UNCOV
1410
                        return;
×
1411
                    }
1412

UNCOV
1413
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1414
                        event.preventDefault();
×
1415

UNCOV
1416
                        if (selection && Range.isExpanded(selection)) {
×
1417
                            Editor.deleteFragment(editor, {
×
1418
                                direction: 'backward'
1419
                            });
1420
                        } else {
UNCOV
1421
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1422
                        }
1423

UNCOV
1424
                        return;
×
1425
                    }
1426

UNCOV
1427
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1428
                        event.preventDefault();
×
1429

UNCOV
1430
                        if (selection && Range.isExpanded(selection)) {
×
1431
                            Editor.deleteFragment(editor, {
×
1432
                                direction: 'forward'
1433
                            });
1434
                        } else {
UNCOV
1435
                            Editor.deleteForward(editor, { unit: 'word' });
×
1436
                        }
1437

UNCOV
1438
                        return;
×
1439
                    }
1440
                } else {
UNCOV
1441
                    if (IS_CHROME || IS_SAFARI) {
×
1442
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1443
                        // an event when deleting backwards in a selected void inline node
UNCOV
1444
                        if (
×
1445
                            selection &&
×
1446
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1447
                            Range.isCollapsed(selection)
1448
                        ) {
UNCOV
1449
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1450
                            if (
×
1451
                                Element.isElement(currentNode) &&
×
1452
                                Editor.isVoid(editor, currentNode) &&
1453
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1454
                            ) {
UNCOV
1455
                                event.preventDefault();
×
1456
                                Editor.deleteBackward(editor, {
×
1457
                                    unit: 'block'
1458
                                });
UNCOV
1459
                                return;
×
1460
                            }
1461
                        }
1462
                    }
1463
                }
1464
            } catch (error) {
UNCOV
1465
                this.editor.onError({
×
1466
                    code: SlateErrorCode.OnDOMKeydownError,
1467
                    nativeError: error
1468
                });
1469
            }
1470
        }
1471
    }
1472

1473
    private onDOMPaste(event: ClipboardEvent) {
1474
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1475
        // fall back to React's `onPaste` here instead.
1476
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1477
        // when "paste without formatting" option is used.
1478
        // This unfortunately needs to be handled with paste events instead.
UNCOV
1479
        if (
×
1480
            !this.isDOMEventHandled(event, this.paste) &&
×
1481
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1482
            !this.readonly &&
1483
            AngularEditor.hasEditableTarget(this.editor, event.target)
1484
        ) {
UNCOV
1485
            event.preventDefault();
×
1486
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1487
        }
1488
    }
1489

1490
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1491
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1492
        // fall back to React's leaky polyfill instead just for it. It
1493
        // only works for the `insertText` input type.
UNCOV
1494
        if (
×
1495
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1496
            !this.readonly &&
1497
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1498
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1499
        ) {
UNCOV
1500
            event.nativeEvent.preventDefault();
×
1501
            try {
×
1502
                const text = event.data;
×
1503
                if (!Range.isCollapsed(this.editor.selection)) {
×
1504
                    Editor.deleteFragment(this.editor);
×
1505
                }
1506
                // just handle Non-IME input
UNCOV
1507
                if (!this.isComposing) {
×
1508
                    Editor.insertText(this.editor, text);
×
1509
                }
1510
            } catch (error) {
UNCOV
1511
                this.editor.onError({
×
1512
                    code: SlateErrorCode.ToNativeSelectionError,
1513
                    nativeError: error
1514
                });
1515
            }
1516
        }
1517
    }
1518

1519
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1520
        if (!handler) {
3✔
1521
            return false;
3✔
1522
        }
UNCOV
1523
        handler(event);
×
1524
        return event.defaultPrevented;
×
1525
    }
1526
    //#endregion
1527

1528
    ngOnDestroy() {
1529
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1530
        this.manualListeners.forEach(manualListener => {
23✔
1531
            manualListener();
483✔
1532
        });
1533
        this.destroy$.complete();
23✔
1534
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1535
    }
1536
}
1537

1538
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1539
    // This was affecting the selection of multiple blocks and dragging behavior,
1540
    // so enabled only if the selection has been collapsed.
UNCOV
1541
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1542
        const leafEl = domRange.startContainer.parentElement!;
×
1543

1544
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1545
        // When this happens, do not scroll like most editors do.
UNCOV
1546
        const domRect = domRange.getBoundingClientRect();
×
1547
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1548

UNCOV
1549
        if (isZeroDimensionRect) {
×
1550
            const leafRect = leafEl.getBoundingClientRect();
×
1551
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1552

UNCOV
1553
            if (leafHasDimensions) {
×
1554
                return;
×
1555
            }
1556
        }
1557

UNCOV
1558
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1559
        scrollIntoView(leafEl, {
×
1560
            scrollMode: 'if-needed'
1561
        });
UNCOV
1562
        delete leafEl.getBoundingClientRect;
×
1563
    }
1564
};
1565

1566
/**
1567
 * Check if the target is inside void and in the editor.
1568
 */
1569

1570
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1571
    let slateNode: Node | null = null;
1✔
1572
    try {
1✔
1573
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1574
    } catch (error) {}
1575
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1576
};
1577

1578
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1579
    return (
2✔
1580
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1581
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1582
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1583
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1584
    );
1585
};
1586

1587
/**
1588
 * remove default insert from composition
1589
 * @param text
1590
 */
1591
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
UNCOV
1592
    const types = ['compositionend', 'insertFromComposition'];
×
1593
    if (!types.includes(event.type)) {
×
1594
        return;
×
1595
    }
UNCOV
1596
    const insertText = (event as CompositionEvent).data;
×
1597
    const window = AngularEditor.getWindow(editor);
×
1598
    const domSelection = window.getSelection();
×
1599
    // ensure text node insert composition input text
UNCOV
1600
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1601
        const textNode = domSelection.anchorNode;
×
1602
        textNode.splitText(textNode.length - insertText.length).remove();
×
1603
    }
1604
};
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