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

worktile / slate-angular / 6532a0fc-cda7-4ca1-9754-ec5483fed80c

11 Dec 2025 11:40AM UTC coverage: 38.161% (-0.03%) from 38.191%
6532a0fc-cda7-4ca1-9754-ec5483fed80c

Pull #321

circleci

Xwatson
fix: add error
Pull Request #321: fix(virtual-scroll): get measured height strengthen the judgment of numeric types

386 of 1203 branches covered (32.09%)

Branch coverage included in aggregate %.

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

239 existing lines in 1 file now uncovered.

1071 of 2615 relevant lines covered (40.96%)

24.92 hits per line

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

25.48
/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
import { isKeyHotkey } from 'is-hotkey';
69
import { VirtualScrollDebugOverlay } from './debug';
70

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

73
export const ELEMENT_KEY_TO_HEIGHTS = new WeakMap<AngularEditor, Map<string, number>>();
1✔
74

75
// not correctly clipboardData on beforeinput
76
const forceOnDOMPaste = IS_SAFARI;
1✔
77

78
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
79

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

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

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

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

114
    private initialized: boolean;
115

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

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

120
    @Input() editor: AngularEditor;
121

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

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

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

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

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

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

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

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

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

140
    @Input() placeholder: string;
141

142
    @Input()
143
    set virtualScroll(config: SlateVirtualScrollConfig) {
144
        this.virtualConfig = config;
×
145
        this.doVirtualScroll();
×
146
    }
147

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

166
    //#region DOM attr
167
    @Input() spellCheck = false;
23✔
168
    @Input() autoCorrect = false;
23✔
169
    @Input() autoCapitalize = false;
23✔
170

171
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
172
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
173
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
174

175
    get hasBeforeInputSupport() {
176
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
177
    }
178
    //#endregion
179

180
    viewContainerRef = inject(ViewContainerRef);
23✔
181

182
    getOutletParent = () => {
23✔
183
        return this.elementRef.nativeElement;
43✔
184
    };
185

186
    getOutletElement = () => {
23✔
187
        if (this.virtualScrollInitialized) {
23!
188
            return this.virtualCenterOutlet;
×
189
        } else {
190
            return null;
23✔
191
        }
192
    };
193

194
    listRender: ListRender;
195

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

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

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

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

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

264
    registerOnChange(fn: any) {
265
        this.onChangeCallback = fn;
23✔
266
    }
267
    registerOnTouched(fn: any) {
268
        this.onTouchedCallback = fn;
23✔
269
    }
270

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

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

320
    toNativeSelection() {
321
        try {
15✔
322
            let { selection } = this.editor;
15✔
323
            if (this.virtualConfig?.enabled && selection) {
15!
324
                const indics = Array.from(this.virtualVisibleIndexes.values());
×
325
                if (indics.length > 0) {
×
326
                    const currentVisibleRange: Range = {
×
327
                        anchor: Editor.start(this.editor, [indics[0]]),
328
                        focus: Editor.end(this.editor, [indics[indics.length - 1]])
329
                    };
330
                    const [start, end] = Range.edges(selection);
×
331
                    const forwardSelection = { anchor: start, focus: end };
×
332
                    const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
333
                    if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
334
                        selection = intersectedSelection;
×
335
                        if (isDebug) {
×
336
                            this.debugLog(
×
337
                                'log',
338
                                `selection is not in visible range, selection: ${JSON.stringify(
339
                                    selection
340
                                )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
341
                            );
342
                        }
343
                    }
344
                }
345
            }
346
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
347
            const { activeElement } = root;
15✔
348
            const domSelection = (root as Document).getSelection();
15✔
349

350
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
351
                return;
14✔
352
            }
353

354
            const hasDomSelection = domSelection.type !== 'None';
1✔
355

356
            // If the DOM selection is properly unset, we're done.
357
            if (!selection && !hasDomSelection) {
1!
358
                return;
×
359
            }
360

361
            // If the DOM selection is already correct, we're done.
362
            // verify that the dom selection is in the editor
363
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
364
            let hasDomSelectionInEditor = false;
1✔
365
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
366
                hasDomSelectionInEditor = true;
1✔
367
            }
368

369
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
370
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
371
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
372
                    exactMatch: false,
373
                    suppressThrow: true
374
                });
375
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
376
                    return;
×
377
                }
378
            }
379

380
            // prevent updating native selection when active element is void element
381
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
382
                return;
×
383
            }
384

385
            // when <Editable/> is being controlled through external value
386
            // then its children might just change - DOM responds to it on its own
387
            // but Slate's value is not being updated through any operation
388
            // and thus it doesn't transform selection on its own
389
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
390
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
391
                return;
×
392
            }
393

394
            // Otherwise the DOM selection is out of sync, so update it.
395
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
396
            this.isUpdatingSelection = true;
1✔
397

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

400
            if (newDomRange) {
1!
401
                // COMPAT: Since the DOM range has no concept of backwards/forwards
402
                // we need to check and do the right thing here.
403
                if (Range.isBackward(selection)) {
1!
404
                    // eslint-disable-next-line max-len
405
                    domSelection.setBaseAndExtent(
×
406
                        newDomRange.endContainer,
407
                        newDomRange.endOffset,
408
                        newDomRange.startContainer,
409
                        newDomRange.startOffset
410
                    );
411
                } else {
412
                    // eslint-disable-next-line max-len
413
                    domSelection.setBaseAndExtent(
1✔
414
                        newDomRange.startContainer,
415
                        newDomRange.startOffset,
416
                        newDomRange.endContainer,
417
                        newDomRange.endOffset
418
                    );
419
                }
420
            } else {
421
                domSelection.removeAllRanges();
×
422
            }
423

424
            setTimeout(() => {
1✔
425
                // handle scrolling in setTimeout because of
426
                // dom should not have updated immediately after listRender's updating
427
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
428
                // COMPAT: In Firefox, it's not enough to create a range, you also need
429
                // to focus the contenteditable element too. (2016/11/16)
430
                if (newDomRange && IS_FIREFOX) {
1!
431
                    el.focus();
×
432
                }
433

434
                this.isUpdatingSelection = false;
1✔
435
            });
436
        } catch (error) {
437
            this.editor.onError({
×
438
                code: SlateErrorCode.ToNativeSelectionError,
439
                nativeError: error
440
            });
441
            this.isUpdatingSelection = false;
×
442
        }
443
    }
444

445
    onChange() {
446
        this.forceRender();
13✔
447
        this.onChangeCallback(this.editor.children);
13✔
448
    }
449

450
    ngAfterViewChecked() {}
451

452
    ngDoCheck() {}
453

454
    forceRender() {
455
        this.updateContext();
15✔
456
        const virtualView = this.refreshVirtualView();
15✔
457
        this.applyVirtualView(virtualView);
15✔
458
        const visibleIndexes = Array.from(this.virtualVisibleIndexes);
15✔
459
        this.listRender.update(this.renderedChildren, this.editor, this.context);
15✔
460
        this.remeasureHeightByIndics(visibleIndexes);
15✔
461
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
462
        // when the DOMElement where the selection is located is removed
463
        // the compositionupdate and compositionend events will no longer be fired
464
        // so isComposing needs to be corrected
465
        // need exec after this.cdr.detectChanges() to render HTML
466
        // need exec before this.toNativeSelection() to correct native selection
467
        if (this.isComposing) {
15!
468
            // Composition input text be not rendered when user composition input with selection is expanded
469
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
470
            // this time condition is true and isComposing is assigned false
471
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
472
            setTimeout(() => {
×
473
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
474
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
475
                let textContent = '';
×
476
                // skip decorate text
477
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
478
                    let text = stringDOMNode.textContent;
×
479
                    const zeroChar = '\uFEFF';
×
480
                    // remove zero with char
481
                    if (text.startsWith(zeroChar)) {
×
482
                        text = text.slice(1);
×
483
                    }
484
                    if (text.endsWith(zeroChar)) {
×
485
                        text = text.slice(0, text.length - 1);
×
486
                    }
487
                    textContent += text;
×
488
                });
489
                if (Node.string(textNode).endsWith(textContent)) {
×
490
                    this.isComposing = false;
×
491
                }
492
            }, 0);
493
        }
494
        this.toNativeSelection();
15✔
495
    }
496

497
    render() {
498
        const changed = this.updateContext();
2✔
499
        if (changed) {
2✔
500
            const virtualView = this.refreshVirtualView();
2✔
501
            this.applyVirtualView(virtualView);
2✔
502
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
503
            this.scheduleMeasureVisibleHeights();
2✔
504
        }
505
    }
506

507
    updateContext() {
508
        const decorations = this.generateDecorations();
17✔
509
        if (
17✔
510
            this.context.selection !== this.editor.selection ||
46✔
511
            this.context.decorate !== this.decorate ||
512
            this.context.readonly !== this.readonly ||
513
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
514
        ) {
515
            this.context = {
10✔
516
                parent: this.editor,
517
                selection: this.editor.selection,
518
                decorations: decorations,
519
                decorate: this.decorate,
520
                readonly: this.readonly
521
            };
522
            return true;
10✔
523
        }
524
        return false;
7✔
525
    }
526

527
    initializeContext() {
528
        this.context = {
49✔
529
            parent: this.editor,
530
            selection: this.editor.selection,
531
            decorations: this.generateDecorations(),
532
            decorate: this.decorate,
533
            readonly: this.readonly
534
        };
535
    }
536

537
    initializeViewContext() {
538
        this.viewContext = {
23✔
539
            editor: this.editor,
540
            renderElement: this.renderElement,
541
            renderLeaf: this.renderLeaf,
542
            renderText: this.renderText,
543
            trackBy: this.trackBy,
544
            isStrictDecorate: this.isStrictDecorate
545
        };
546
    }
547

548
    composePlaceholderDecorate(editor: Editor) {
549
        if (this.placeholderDecorate) {
64!
550
            return this.placeholderDecorate(editor) || [];
×
551
        }
552

553
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
554
            const start = Editor.start(editor, []);
3✔
555
            return [
3✔
556
                {
557
                    placeholder: this.placeholder,
558
                    anchor: start,
559
                    focus: start
560
                }
561
            ];
562
        } else {
563
            return [];
61✔
564
        }
565
    }
566

567
    generateDecorations() {
568
        const decorations = this.decorate([this.editor, []]);
66✔
569
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
570
        decorations.push(...placeholderDecorations);
66✔
571
        return decorations;
66✔
572
    }
573

574
    private shouldUseVirtual() {
575
        return !!(this.virtualConfig && this.virtualConfig.enabled);
71✔
576
    }
577

578
    // the height from scroll container top to editor top height element
579
    private businessHeight: number = 0;
23✔
580

581
    virtualScrollInitialized = false;
23✔
582

583
    virtualTopHeightElement: HTMLElement;
584

585
    virtualBottomHeightElement: HTMLElement;
586

587
    virtualCenterOutlet: HTMLElement;
588

589
    initializeVirtualScrolling() {
590
        if (this.virtualScrollInitialized) {
23!
591
            return;
×
592
        }
593
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
594
            this.virtualScrollInitialized = true;
×
595
            this.virtualTopHeightElement = document.createElement('div');
×
596
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
597
            this.virtualTopHeightElement.contentEditable = 'false';
×
598
            this.virtualBottomHeightElement = document.createElement('div');
×
599
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
600
            this.virtualBottomHeightElement.contentEditable = 'false';
×
601
            this.virtualCenterOutlet = document.createElement('div');
×
602
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
603
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
604
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
605
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
606
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
607

608
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
609
            this.editorResizeObserver = new ResizeObserver(entries => {
×
610
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
611
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
612
                    this.remeasureHeightByIndics(Array.from(this.virtualVisibleIndexes));
×
613
                }
614
            });
615
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
616
            if (isDebug) {
×
617
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
618
                VirtualScrollDebugOverlay.getInstance(doc);
×
619
            }
620
        }
621
    }
622

623
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
624
        if (!this.virtualScrollInitialized) {
43✔
625
            return;
43✔
626
        }
627
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
628
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
629
    }
630

631
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
632
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
633
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
634
    }
635

636
    private doVirtualScroll() {
637
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
638
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
639
            let virtualView = this.refreshVirtualView();
×
640
            let diff = this.diffVirtualView(virtualView);
×
641
            if (!diff.isDiff) {
×
642
                return;
×
643
            }
644
            if (diff.isMissingTop) {
×
645
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
646
                if (result) {
×
647
                    virtualView = this.refreshVirtualView();
×
648
                    diff = this.diffVirtualView(virtualView, 'second');
×
649
                    if (!diff.isDiff) {
×
650
                        return;
×
651
                    }
652
                }
653
            }
654
            this.applyVirtualView(virtualView);
×
655
            if (this.listRender.initialized) {
×
656
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
657
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
658
                    this.toNativeSelection();
×
659
                }
660
            }
661
            this.scheduleMeasureVisibleHeights();
×
662
        });
663
    }
664

665
    private refreshVirtualView() {
666
        const children = (this.editor.children || []) as Element[];
43!
667
        if (!children.length || !this.shouldUseVirtual()) {
43✔
668
            return {
43✔
669
                renderedChildren: children,
670
                visibleIndexes: new Set<number>(),
671
                top: 0,
672
                bottom: 0,
673
                heights: []
674
            };
675
        }
676
        const scrollTop = this.virtualConfig.scrollTop;
×
677
        if (isDebug) {
×
678
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
679
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
680
        }
681
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
682
        if (!viewportHeight) {
×
683
            return {
×
684
                renderedChildren: [],
685
                visibleIndexes: new Set<number>(),
686
                top: 0,
687
                bottom: 0,
688
                heights: []
689
            };
690
        }
691
        const elementLength = children.length;
×
692
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
693
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
694
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
695
        const totalHeight = accumulatedHeights[elementLength];
×
696
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
697
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
698
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
699
        let accumulatedOffset = 0;
×
700
        let visibleStartIndex = -1;
×
701
        const visible: Element[] = [];
×
702
        const visibleIndexes: number[] = [];
×
703

704
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
705
            const currentHeight = heights[i];
×
706
            const nextOffset = accumulatedOffset + currentHeight;
×
707
            // 可视区域有交集,加入渲染
708
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
709
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
710
                visible.push(children[i]);
×
711
                visibleIndexes.push(i);
×
712
            }
713
            accumulatedOffset = nextOffset;
×
714
        }
715

716
        if (visibleStartIndex === -1 && elementLength) {
×
717
            visibleStartIndex = elementLength - 1;
×
718
            visible.push(children[visibleStartIndex]);
×
719
            visibleIndexes.push(visibleStartIndex);
×
720
        }
721

722
        const visibleEndIndex =
723
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
724
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
725
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
726

727
        return {
×
728
            renderedChildren: visible.length ? visible : children,
×
729
            visibleIndexes: new Set(visibleIndexes),
730
            top,
731
            bottom,
732
            heights
733
        };
734
    }
735

736
    private applyVirtualView(virtualView: VirtualViewResult) {
737
        this.renderedChildren = virtualView.renderedChildren;
43✔
738
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
739
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
740
    }
741

742
    private diffVirtualView(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
743
        if (!this.renderedChildren.length) {
×
744
            return {
×
745
                isDiff: true,
746
                diffTopRenderedIndexes: [],
747
                diffBottomRenderedIndexes: []
748
            };
749
        }
750
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
751
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
752
        const firstNewIndex = newVisibleIndexes[0];
×
753
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
754
        const firstOldIndex = oldVisibleIndexes[0];
×
755
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
756
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
757
            const diffTopRenderedIndexes = [];
×
758
            const diffBottomRenderedIndexes = [];
×
759
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
760
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
761
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
762
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
763
            if (isMissingTop || isAddedBottom) {
×
764
                // 向下
765
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
766
                    const element = oldVisibleIndexes[index];
×
767
                    if (!newVisibleIndexes.includes(element)) {
×
768
                        diffTopRenderedIndexes.push(element);
×
769
                    } else {
770
                        break;
×
771
                    }
772
                }
773
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
774
                    const element = newVisibleIndexes[index];
×
775
                    if (!oldVisibleIndexes.includes(element)) {
×
776
                        diffBottomRenderedIndexes.push(element);
×
777
                    } else {
778
                        break;
×
779
                    }
780
                }
781
            } else if (isAddedTop || isMissingBottom) {
×
782
                // 向上
783
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
784
                    const element = newVisibleIndexes[index];
×
785
                    if (!oldVisibleIndexes.includes(element)) {
×
786
                        diffTopRenderedIndexes.push(element);
×
787
                    } else {
788
                        break;
×
789
                    }
790
                }
791
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
792
                    const element = oldVisibleIndexes[index];
×
793
                    if (!newVisibleIndexes.includes(element)) {
×
794
                        diffBottomRenderedIndexes.push(element);
×
795
                    } else {
796
                        break;
×
797
                    }
798
                }
799
            }
800
            if (isDebug) {
×
801
                this.debugLog('log', `====== diffVirtualView stage: ${stage} ======`);
×
802
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
803
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
804
                this.debugLog(
×
805
                    'log',
806
                    'diffTopRenderedIndexes:',
807
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
808
                    diffTopRenderedIndexes,
809
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
810
                );
811
                this.debugLog(
×
812
                    'log',
813
                    'diffBottomRenderedIndexes:',
814
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
815
                    diffBottomRenderedIndexes,
816
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
817
                );
818
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
819
                const needBottom = virtualView.heights
×
820
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
821
                    .reduce((acc, height) => acc + height, 0);
×
822
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
823
                this.debugLog(
×
824
                    'log',
825
                    'newBottomHeight:',
826
                    needBottom,
827
                    'prevBottomHeight:',
828
                    parseFloat(this.virtualBottomHeightElement.style.height)
829
                );
830
                this.debugLog('warn', '=========== Dividing line ===========');
×
831
            }
832
            return {
×
833
                isDiff: true,
834
                isMissingTop,
835
                isAddedTop,
836
                isMissingBottom,
837
                isAddedBottom,
838
                diffTopRenderedIndexes,
839
                diffBottomRenderedIndexes
840
            };
841
        }
842
        return {
×
843
            isDiff: false,
844
            diffTopRenderedIndexes: [],
845
            diffBottomRenderedIndexes: []
846
        };
847
    }
848

849
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
850
        const node = this.editor.children[index];
×
851
        if (!node) {
×
852
            return defaultHeight;
×
853
        }
854
        const key = AngularEditor.findKey(this.editor, node);
×
NEW
855
        const height = this.measuredHeights.get(key.id);
×
NEW
856
        if (typeof height === 'number') {
×
NEW
857
            return height;
×
858
        }
NEW
859
        console.error('getBlockHeight: height not found', key.id, height);
×
NEW
860
        return defaultHeight;
×
861
    }
862

863
    private buildAccumulatedHeight(heights: number[]) {
UNCOV
864
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
UNCOV
865
        for (let i = 0; i < heights.length; i++) {
×
866
            // 存储前 i 个的累计高度
867
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
868
        }
869
        return accumulatedHeights;
×
870
    }
871

872
    private scheduleMeasureVisibleHeights() {
873
        if (!this.shouldUseVirtual()) {
28✔
874
            return;
28✔
875
        }
UNCOV
876
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
UNCOV
877
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
878
            this.measureVisibleHeights();
×
879
        });
880
    }
881

882
    private measureVisibleHeights() {
UNCOV
883
        const children = (this.editor.children || []) as Element[];
×
UNCOV
884
        this.virtualVisibleIndexes.forEach(index => {
×
885
            const node = children[index];
×
886
            if (!node) {
×
887
                return;
×
888
            }
889
            const key = AngularEditor.findKey(this.editor, node);
×
890
            // 跳过已测过的块,除非强制测量
891
            if (this.measuredHeights.has(key.id)) {
×
UNCOV
892
                return;
×
893
            }
894
            const view = ELEMENT_TO_COMPONENT.get(node);
×
UNCOV
895
            if (!view) {
×
896
                return;
×
897
            }
898
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
UNCOV
899
            if (ret instanceof Promise) {
×
900
                ret.then(height => {
×
901
                    this.measuredHeights.set(key.id, height);
×
902
                });
903
            } else {
UNCOV
904
                this.measuredHeights.set(key.id, ret);
×
905
            }
906
        });
907
    }
908

909
    private remeasureHeightByIndics(indics: number[]): boolean {
910
        const children = (this.editor.children || []) as Element[];
15!
911
        let isHeightChanged = false;
15✔
912
        indics.forEach(index => {
15✔
UNCOV
913
            const node = children[index];
×
UNCOV
914
            if (!node) {
×
915
                return;
×
916
            }
917
            const key = AngularEditor.findKey(this.editor, node);
×
UNCOV
918
            const view = ELEMENT_TO_COMPONENT.get(node);
×
919
            if (!view) {
×
920
                return;
×
921
            }
922
            const prevHeight = this.measuredHeights.get(key.id);
×
UNCOV
923
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
924
            if (ret instanceof Promise) {
×
925
                ret.then(height => {
×
926
                    if (height !== prevHeight) {
×
927
                        this.measuredHeights.set(key.id, height);
×
928
                        isHeightChanged = true;
×
929
                        if (isDebug) {
×
930
                            this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
931
                        }
932
                    }
933
                });
934
            } else {
UNCOV
935
                if (ret !== prevHeight) {
×
UNCOV
936
                    this.measuredHeights.set(key.id, ret);
×
937
                    isHeightChanged = true;
×
938
                    if (isDebug) {
×
939
                        this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
940
                    }
941
                }
942
            }
943
        });
944
        return isHeightChanged;
15✔
945
    }
946

947
    //#region event proxy
948
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
949
        this.manualListeners.push(
483✔
950
            this.renderer2.listen(target, eventName, (event: Event) => {
951
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
952
                if (beforeInputEvent) {
5!
UNCOV
953
                    this.onFallbackBeforeInput(beforeInputEvent);
×
954
                }
955
                listener(event);
5✔
956
            })
957
        );
958
    }
959

960
    private toSlateSelection() {
961
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
962
            try {
1✔
963
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
964
                const { activeElement } = root;
1✔
965
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
966
                const domSelection = (root as Document).getSelection();
1✔
967

968
                if (activeElement === el) {
1!
969
                    this.latestElement = activeElement;
1✔
970
                    IS_FOCUSED.set(this.editor, true);
1✔
971
                } else {
UNCOV
972
                    IS_FOCUSED.delete(this.editor);
×
973
                }
974

975
                if (!domSelection) {
1!
UNCOV
976
                    return Transforms.deselect(this.editor);
×
977
                }
978

979
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
980
                const hasDomSelectionInEditor =
981
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
982
                if (!hasDomSelectionInEditor) {
1!
UNCOV
983
                    Transforms.deselect(this.editor);
×
UNCOV
984
                    return;
×
985
                }
986

987
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
988
                // for example, double-click the last cell of the table to select a non-editable DOM
989
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
990
                if (range) {
1✔
991
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
UNCOV
992
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
993
                            // force adjust DOMSelection
994
                            this.toNativeSelection();
×
995
                        }
996
                    } else {
997
                        Transforms.select(this.editor, range);
1✔
998
                    }
999
                }
1000
            } catch (error) {
UNCOV
1001
                this.editor.onError({
×
1002
                    code: SlateErrorCode.ToSlateSelectionError,
1003
                    nativeError: error
1004
                });
1005
            }
1006
        }
1007
    }
1008

1009
    private onDOMBeforeInput(
1010
        event: Event & {
1011
            inputType: string;
1012
            isComposing: boolean;
1013
            data: string | null;
1014
            dataTransfer: DataTransfer | null;
1015
            getTargetRanges(): DOMStaticRange[];
1016
        }
1017
    ) {
UNCOV
1018
        const editor = this.editor;
×
UNCOV
1019
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1020
        const { activeElement } = root;
×
1021
        const { selection } = editor;
×
1022
        const { inputType: type } = event;
×
1023
        const data = event.dataTransfer || event.data || undefined;
×
1024
        if (IS_ANDROID) {
×
1025
            let targetRange: Range | null = null;
×
1026
            let [nativeTargetRange] = event.getTargetRanges();
×
1027
            if (nativeTargetRange) {
×
1028
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1029
            }
1030
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1031
            // have to manually get the selection here to ensure it's up-to-date.
UNCOV
1032
            const window = AngularEditor.getWindow(editor);
×
UNCOV
1033
            const domSelection = window.getSelection();
×
1034
            if (!targetRange && domSelection) {
×
1035
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1036
            }
1037
            targetRange = targetRange ?? editor.selection;
×
UNCOV
1038
            if (type === 'insertCompositionText') {
×
1039
                if (data && data.toString().includes('\n')) {
×
1040
                    restoreDom(editor, () => {
×
1041
                        Editor.insertBreak(editor);
×
1042
                    });
1043
                } else {
UNCOV
1044
                    if (targetRange) {
×
UNCOV
1045
                        if (data) {
×
1046
                            restoreDom(editor, () => {
×
1047
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1048
                            });
1049
                        } else {
UNCOV
1050
                            restoreDom(editor, () => {
×
UNCOV
1051
                                Transforms.delete(editor, { at: targetRange });
×
1052
                            });
1053
                        }
1054
                    }
1055
                }
UNCOV
1056
                return;
×
1057
            }
1058
            if (type === 'deleteContentBackward') {
×
1059
                // gboard can not prevent default action, so must use restoreDom,
1060
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1061
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
UNCOV
1062
                if (!Range.isCollapsed(targetRange)) {
×
UNCOV
1063
                    restoreDom(editor, () => {
×
1064
                        Transforms.delete(editor, { at: targetRange });
×
1065
                    });
1066
                    return;
×
1067
                }
1068
            }
UNCOV
1069
            if (type === 'insertText') {
×
UNCOV
1070
                restoreDom(editor, () => {
×
1071
                    if (typeof data === 'string') {
×
1072
                        Editor.insertText(editor, data);
×
1073
                    }
1074
                });
UNCOV
1075
                return;
×
1076
            }
1077
        }
UNCOV
1078
        if (
×
1079
            !this.readonly &&
×
1080
            AngularEditor.hasEditableTarget(editor, event.target) &&
1081
            !isTargetInsideVoid(editor, activeElement) &&
1082
            !this.isDOMEventHandled(event, this.beforeInput)
1083
        ) {
UNCOV
1084
            try {
×
UNCOV
1085
                event.preventDefault();
×
1086

1087
                // COMPAT: If the selection is expanded, even if the command seems like
1088
                // a delete forward/backward command it should delete the selection.
UNCOV
1089
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
UNCOV
1090
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1091
                    Editor.deleteFragment(editor, { direction });
×
1092
                    return;
×
1093
                }
1094

UNCOV
1095
                switch (type) {
×
1096
                    case 'deleteByComposition':
1097
                    case 'deleteByCut':
1098
                    case 'deleteByDrag': {
UNCOV
1099
                        Editor.deleteFragment(editor);
×
UNCOV
1100
                        break;
×
1101
                    }
1102

1103
                    case 'deleteContent':
1104
                    case 'deleteContentForward': {
UNCOV
1105
                        Editor.deleteForward(editor);
×
UNCOV
1106
                        break;
×
1107
                    }
1108

1109
                    case 'deleteContentBackward': {
UNCOV
1110
                        Editor.deleteBackward(editor);
×
UNCOV
1111
                        break;
×
1112
                    }
1113

1114
                    case 'deleteEntireSoftLine': {
UNCOV
1115
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1116
                        Editor.deleteForward(editor, { unit: 'line' });
×
1117
                        break;
×
1118
                    }
1119

1120
                    case 'deleteHardLineBackward': {
UNCOV
1121
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
1122
                        break;
×
1123
                    }
1124

1125
                    case 'deleteSoftLineBackward': {
UNCOV
1126
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1127
                        break;
×
1128
                    }
1129

1130
                    case 'deleteHardLineForward': {
UNCOV
1131
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
1132
                        break;
×
1133
                    }
1134

1135
                    case 'deleteSoftLineForward': {
UNCOV
1136
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1137
                        break;
×
1138
                    }
1139

1140
                    case 'deleteWordBackward': {
UNCOV
1141
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1142
                        break;
×
1143
                    }
1144

1145
                    case 'deleteWordForward': {
UNCOV
1146
                        Editor.deleteForward(editor, { unit: 'word' });
×
UNCOV
1147
                        break;
×
1148
                    }
1149

1150
                    case 'insertLineBreak':
1151
                    case 'insertParagraph': {
UNCOV
1152
                        Editor.insertBreak(editor);
×
UNCOV
1153
                        break;
×
1154
                    }
1155

1156
                    case 'insertFromComposition': {
1157
                        // COMPAT: in safari, `compositionend` event is dispatched after
1158
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1159
                        // https://www.w3.org/TR/input-events-2/
1160
                        // so the following code is the right logic
1161
                        // because DOM selection in sync will be exec before `compositionend` event
1162
                        // isComposing is true will prevent DOM selection being update correctly.
UNCOV
1163
                        this.isComposing = false;
×
UNCOV
1164
                        preventInsertFromComposition(event, this.editor);
×
1165
                    }
1166
                    case 'insertFromDrop':
1167
                    case 'insertFromPaste':
1168
                    case 'insertFromYank':
1169
                    case 'insertReplacementText':
1170
                    case 'insertText': {
1171
                        // use a weak comparison instead of 'instanceof' to allow
1172
                        // programmatic access of paste events coming from external windows
1173
                        // like cypress where cy.window does not work realibly
UNCOV
1174
                        if (data?.constructor.name === 'DataTransfer') {
×
UNCOV
1175
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1176
                        } else if (typeof data === 'string') {
×
1177
                            Editor.insertText(editor, data);
×
1178
                        }
1179
                        break;
×
1180
                    }
1181
                }
1182
            } catch (error) {
UNCOV
1183
                this.editor.onError({
×
1184
                    code: SlateErrorCode.OnDOMBeforeInputError,
1185
                    nativeError: error
1186
                });
1187
            }
1188
        }
1189
    }
1190

1191
    private onDOMBlur(event: FocusEvent) {
UNCOV
1192
        if (
×
1193
            this.readonly ||
×
1194
            this.isUpdatingSelection ||
1195
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1196
            this.isDOMEventHandled(event, this.blur)
1197
        ) {
UNCOV
1198
            return;
×
1199
        }
1200

UNCOV
1201
        const window = AngularEditor.getWindow(this.editor);
×
1202

1203
        // COMPAT: If the current `activeElement` is still the previous
1204
        // one, this is due to the window being blurred when the tab
1205
        // itself becomes unfocused, so we want to abort early to allow to
1206
        // editor to stay focused when the tab becomes focused again.
UNCOV
1207
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
UNCOV
1208
        if (this.latestElement === root.activeElement) {
×
1209
            return;
×
1210
        }
1211

UNCOV
1212
        const { relatedTarget } = event;
×
UNCOV
1213
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1214

1215
        // COMPAT: The event should be ignored if the focus is returning
1216
        // to the editor from an embedded editable element (eg. an <input>
1217
        // element inside a void node).
UNCOV
1218
        if (relatedTarget === el) {
×
UNCOV
1219
            return;
×
1220
        }
1221

1222
        // COMPAT: The event should be ignored if the focus is moving from
1223
        // the editor to inside a void node's spacer element.
UNCOV
1224
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
UNCOV
1225
            return;
×
1226
        }
1227

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

1234
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
UNCOV
1235
                return;
×
1236
            }
1237
        }
1238

UNCOV
1239
        IS_FOCUSED.delete(this.editor);
×
1240
    }
1241

1242
    private onDOMClick(event: MouseEvent) {
UNCOV
1243
        if (
×
1244
            !this.readonly &&
×
1245
            AngularEditor.hasTarget(this.editor, event.target) &&
1246
            !this.isDOMEventHandled(event, this.click) &&
1247
            isDOMNode(event.target)
1248
        ) {
UNCOV
1249
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1250
            const path = AngularEditor.findPath(this.editor, node);
×
1251
            const start = Editor.start(this.editor, path);
×
1252
            const end = Editor.end(this.editor, path);
×
1253

1254
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
1255
            const endVoid = Editor.void(this.editor, { at: end });
×
1256

1257
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
UNCOV
1258
                let blockPath = path;
×
1259
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1260
                    const block = Editor.above(this.editor, {
×
1261
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1262
                        at: path
1263
                    });
1264

UNCOV
1265
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1266
                }
1267

UNCOV
1268
                const range = Editor.range(this.editor, blockPath);
×
UNCOV
1269
                Transforms.select(this.editor, range);
×
1270
                return;
×
1271
            }
1272

UNCOV
1273
            if (
×
1274
                startVoid &&
×
1275
                endVoid &&
1276
                Path.equals(startVoid[1], endVoid[1]) &&
1277
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1278
            ) {
UNCOV
1279
                const range = Editor.range(this.editor, start);
×
UNCOV
1280
                Transforms.select(this.editor, range);
×
1281
            }
1282
        }
1283
    }
1284

1285
    private onDOMCompositionStart(event: CompositionEvent) {
1286
        const { selection } = this.editor;
1✔
1287
        if (selection) {
1!
1288
            // solve the problem of cross node Chinese input
UNCOV
1289
            if (Range.isExpanded(selection)) {
×
UNCOV
1290
                Editor.deleteFragment(this.editor);
×
1291
                this.forceRender();
×
1292
            }
1293
        }
1294
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1295
            this.isComposing = true;
1✔
1296
        }
1297
        this.render();
1✔
1298
    }
1299

1300
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1301
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1302
    }
1303

1304
    private onDOMCompositionEnd(event: CompositionEvent) {
UNCOV
1305
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1306
            Transforms.delete(this.editor);
×
1307
        }
1308
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1309
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1310
            // aren't correct and never fire the "insertFromComposition"
1311
            // type that we need. So instead, insert whenever a composition
1312
            // ends since it will already have been committed to the DOM.
UNCOV
1313
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
UNCOV
1314
                preventInsertFromComposition(event, this.editor);
×
1315
                Editor.insertText(this.editor, event.data);
×
1316
            }
1317

1318
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1319
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1320
            this.isComposing = false;
×
1321
        }
1322
        this.render();
×
1323
    }
1324

1325
    private onDOMCopy(event: ClipboardEvent) {
UNCOV
1326
        const window = AngularEditor.getWindow(this.editor);
×
UNCOV
1327
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1328
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1329
            event.preventDefault();
×
1330
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1331
        }
1332
    }
1333

1334
    private onDOMCut(event: ClipboardEvent) {
UNCOV
1335
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
UNCOV
1336
            event.preventDefault();
×
1337
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1338
            const { selection } = this.editor;
×
1339

1340
            if (selection) {
×
UNCOV
1341
                AngularEditor.deleteCutData(this.editor);
×
1342
            }
1343
        }
1344
    }
1345

1346
    private onDOMDragOver(event: DragEvent) {
UNCOV
1347
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1348
            // Only when the target is void, call `preventDefault` to signal
1349
            // that drops are allowed. Editable content is droppable by
1350
            // default, and calling `preventDefault` hides the cursor.
UNCOV
1351
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1352

1353
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1354
                event.preventDefault();
×
1355
            }
1356
        }
1357
    }
1358

1359
    private onDOMDragStart(event: DragEvent) {
UNCOV
1360
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
UNCOV
1361
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1362
            const path = AngularEditor.findPath(this.editor, node);
×
1363
            const voidMatch =
1364
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1365

1366
            // If starting a drag on a void node, make sure it is selected
1367
            // so that it shows up in the selection's fragment.
UNCOV
1368
            if (voidMatch) {
×
UNCOV
1369
                const range = Editor.range(this.editor, path);
×
1370
                Transforms.select(this.editor, range);
×
1371
            }
1372

UNCOV
1373
            this.isDraggingInternally = true;
×
1374

1375
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1376
        }
1377
    }
1378

1379
    private onDOMDrop(event: DragEvent) {
UNCOV
1380
        const editor = this.editor;
×
UNCOV
1381
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1382
            event.preventDefault();
×
1383
            // Keep a reference to the dragged range before updating selection
1384
            const draggedRange = editor.selection;
×
1385

1386
            // Find the range where the drop happened
UNCOV
1387
            const range = AngularEditor.findEventRange(editor, event);
×
UNCOV
1388
            const data = event.dataTransfer;
×
1389

1390
            Transforms.select(editor, range);
×
1391

1392
            if (this.isDraggingInternally) {
×
UNCOV
1393
                if (draggedRange) {
×
1394
                    Transforms.delete(editor, {
×
1395
                        at: draggedRange
1396
                    });
1397
                }
1398

UNCOV
1399
                this.isDraggingInternally = false;
×
1400
            }
1401

UNCOV
1402
            AngularEditor.insertData(editor, data);
×
1403

1404
            // When dragging from another source into the editor, it's possible
1405
            // that the current editor does not have focus.
UNCOV
1406
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1407
                AngularEditor.focus(editor);
×
1408
            }
1409
        }
1410
    }
1411

1412
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1413
        if (
×
1414
            !this.readonly &&
×
1415
            this.isDraggingInternally &&
1416
            AngularEditor.hasTarget(this.editor, event.target) &&
1417
            !this.isDOMEventHandled(event, this.dragEnd)
1418
        ) {
UNCOV
1419
            this.isDraggingInternally = false;
×
1420
        }
1421
    }
1422

1423
    private onDOMFocus(event: Event) {
1424
        if (
2✔
1425
            !this.readonly &&
8✔
1426
            !this.isUpdatingSelection &&
1427
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1428
            !this.isDOMEventHandled(event, this.focus)
1429
        ) {
1430
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1431
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1432
            this.latestElement = root.activeElement;
2✔
1433

1434
            // COMPAT: If the editor has nested editable elements, the focus
1435
            // can go to them. In Firefox, this must be prevented because it
1436
            // results in issues with keyboard navigation. (2017/03/30)
1437
            if (IS_FIREFOX && event.target !== el) {
2!
UNCOV
1438
                el.focus();
×
UNCOV
1439
                return;
×
1440
            }
1441

1442
            IS_FOCUSED.set(this.editor, true);
2✔
1443
        }
1444
    }
1445

1446
    private onDOMKeydown(event: KeyboardEvent) {
UNCOV
1447
        const editor = this.editor;
×
UNCOV
1448
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1449
        const { activeElement } = root;
×
1450
        if (
×
1451
            !this.readonly &&
×
1452
            AngularEditor.hasEditableTarget(editor, event.target) &&
1453
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1454
            !this.isComposing &&
1455
            !this.isDOMEventHandled(event, this.keydown)
1456
        ) {
UNCOV
1457
            const nativeEvent = event;
×
UNCOV
1458
            const { selection } = editor;
×
1459

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

1463
            try {
×
1464
                // COMPAT: Since we prevent the default behavior on
1465
                // `beforeinput` events, the browser doesn't think there's ever
1466
                // any history stack to undo or redo, so we have to manage these
1467
                // hotkeys ourselves. (2019/11/06)
UNCOV
1468
                if (Hotkeys.isRedo(nativeEvent)) {
×
UNCOV
1469
                    event.preventDefault();
×
1470

1471
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1472
                        editor.redo();
×
1473
                    }
1474

UNCOV
1475
                    return;
×
1476
                }
1477

UNCOV
1478
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1479
                    event.preventDefault();
×
1480

1481
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1482
                        editor.undo();
×
1483
                    }
1484

UNCOV
1485
                    return;
×
1486
                }
1487

1488
                // COMPAT: Certain browsers don't handle the selection updates
1489
                // properly. In Chrome, the selection isn't properly extended.
1490
                // And in Firefox, the selection isn't properly collapsed.
1491
                // (2017/10/17)
UNCOV
1492
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
UNCOV
1493
                    event.preventDefault();
×
1494
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1495
                    return;
×
1496
                }
1497

UNCOV
1498
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
UNCOV
1499
                    event.preventDefault();
×
1500
                    Transforms.move(editor, { unit: 'line' });
×
1501
                    return;
×
1502
                }
1503

UNCOV
1504
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
UNCOV
1505
                    event.preventDefault();
×
1506
                    Transforms.move(editor, {
×
1507
                        unit: 'line',
1508
                        edge: 'focus',
1509
                        reverse: true
1510
                    });
UNCOV
1511
                    return;
×
1512
                }
1513

UNCOV
1514
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
UNCOV
1515
                    event.preventDefault();
×
1516
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1517
                    return;
×
1518
                }
1519

1520
                // COMPAT: If a void node is selected, or a zero-width text node
1521
                // adjacent to an inline is selected, we need to handle these
1522
                // hotkeys manually because browsers won't be able to skip over
1523
                // the void node with the zero-width space not being an empty
1524
                // string.
UNCOV
1525
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
UNCOV
1526
                    event.preventDefault();
×
1527

1528
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1529
                        Transforms.move(editor, { reverse: !isRTL });
×
1530
                    } else {
1531
                        Transforms.collapse(editor, { edge: 'start' });
×
1532
                    }
1533

UNCOV
1534
                    return;
×
1535
                }
1536

UNCOV
1537
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
UNCOV
1538
                    event.preventDefault();
×
1539
                    if (selection && Range.isCollapsed(selection)) {
×
1540
                        Transforms.move(editor, { reverse: isRTL });
×
1541
                    } else {
1542
                        Transforms.collapse(editor, { edge: 'end' });
×
1543
                    }
1544

UNCOV
1545
                    return;
×
1546
                }
1547

UNCOV
1548
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1549
                    event.preventDefault();
×
1550

1551
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1552
                        Transforms.collapse(editor, { edge: 'focus' });
×
1553
                    }
1554

UNCOV
1555
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1556
                    return;
×
1557
                }
1558

UNCOV
1559
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1560
                    event.preventDefault();
×
1561

1562
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1563
                        Transforms.collapse(editor, { edge: 'focus' });
×
1564
                    }
1565

UNCOV
1566
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
UNCOV
1567
                    return;
×
1568
                }
1569

UNCOV
1570
                if (isKeyHotkey('mod+a', event)) {
×
UNCOV
1571
                    this.editor.selectAll();
×
1572
                    event.preventDefault();
×
1573
                    return;
×
1574
                }
1575

1576
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1577
                // fall back to guessing at the input intention for hotkeys.
1578
                // COMPAT: In iOS, some of these hotkeys are handled in the
UNCOV
1579
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1580
                    // We don't have a core behavior for these, but they change the
1581
                    // DOM if we don't prevent them, so we have to.
UNCOV
1582
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
UNCOV
1583
                        event.preventDefault();
×
1584
                        return;
×
1585
                    }
1586

UNCOV
1587
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
UNCOV
1588
                        event.preventDefault();
×
1589
                        Editor.insertBreak(editor);
×
1590
                        return;
×
1591
                    }
1592

UNCOV
1593
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1594
                        event.preventDefault();
×
1595

1596
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1597
                            Editor.deleteFragment(editor, {
×
1598
                                direction: 'backward'
1599
                            });
1600
                        } else {
UNCOV
1601
                            Editor.deleteBackward(editor);
×
1602
                        }
1603

UNCOV
1604
                        return;
×
1605
                    }
1606

UNCOV
1607
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1608
                        event.preventDefault();
×
1609

1610
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1611
                            Editor.deleteFragment(editor, {
×
1612
                                direction: 'forward'
1613
                            });
1614
                        } else {
UNCOV
1615
                            Editor.deleteForward(editor);
×
1616
                        }
1617

UNCOV
1618
                        return;
×
1619
                    }
1620

UNCOV
1621
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1622
                        event.preventDefault();
×
1623

1624
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1625
                            Editor.deleteFragment(editor, {
×
1626
                                direction: 'backward'
1627
                            });
1628
                        } else {
UNCOV
1629
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1630
                        }
1631

UNCOV
1632
                        return;
×
1633
                    }
1634

UNCOV
1635
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1636
                        event.preventDefault();
×
1637

1638
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1639
                            Editor.deleteFragment(editor, {
×
1640
                                direction: 'forward'
1641
                            });
1642
                        } else {
UNCOV
1643
                            Editor.deleteForward(editor, { unit: 'line' });
×
1644
                        }
1645

UNCOV
1646
                        return;
×
1647
                    }
1648

UNCOV
1649
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1650
                        event.preventDefault();
×
1651

1652
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1653
                            Editor.deleteFragment(editor, {
×
1654
                                direction: 'backward'
1655
                            });
1656
                        } else {
UNCOV
1657
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1658
                        }
1659

UNCOV
1660
                        return;
×
1661
                    }
1662

UNCOV
1663
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1664
                        event.preventDefault();
×
1665

1666
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1667
                            Editor.deleteFragment(editor, {
×
1668
                                direction: 'forward'
1669
                            });
1670
                        } else {
UNCOV
1671
                            Editor.deleteForward(editor, { unit: 'word' });
×
1672
                        }
1673

UNCOV
1674
                        return;
×
1675
                    }
1676
                } else {
UNCOV
1677
                    if (IS_CHROME || IS_SAFARI) {
×
1678
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1679
                        // an event when deleting backwards in a selected void inline node
UNCOV
1680
                        if (
×
1681
                            selection &&
×
1682
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1683
                            Range.isCollapsed(selection)
1684
                        ) {
UNCOV
1685
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
UNCOV
1686
                            if (
×
1687
                                Element.isElement(currentNode) &&
×
1688
                                Editor.isVoid(editor, currentNode) &&
1689
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1690
                            ) {
UNCOV
1691
                                event.preventDefault();
×
UNCOV
1692
                                Editor.deleteBackward(editor, {
×
1693
                                    unit: 'block'
1694
                                });
UNCOV
1695
                                return;
×
1696
                            }
1697
                        }
1698
                    }
1699
                }
1700
            } catch (error) {
UNCOV
1701
                this.editor.onError({
×
1702
                    code: SlateErrorCode.OnDOMKeydownError,
1703
                    nativeError: error
1704
                });
1705
            }
1706
        }
1707
    }
1708

1709
    private onDOMPaste(event: ClipboardEvent) {
1710
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1711
        // fall back to React's `onPaste` here instead.
1712
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1713
        // when "paste without formatting" option is used.
1714
        // This unfortunately needs to be handled with paste events instead.
UNCOV
1715
        if (
×
1716
            !this.isDOMEventHandled(event, this.paste) &&
×
1717
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1718
            !this.readonly &&
1719
            AngularEditor.hasEditableTarget(this.editor, event.target)
1720
        ) {
UNCOV
1721
            event.preventDefault();
×
UNCOV
1722
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1723
        }
1724
    }
1725

1726
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1727
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1728
        // fall back to React's leaky polyfill instead just for it. It
1729
        // only works for the `insertText` input type.
UNCOV
1730
        if (
×
1731
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1732
            !this.readonly &&
1733
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1734
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1735
        ) {
UNCOV
1736
            event.nativeEvent.preventDefault();
×
UNCOV
1737
            try {
×
1738
                const text = event.data;
×
1739
                if (!Range.isCollapsed(this.editor.selection)) {
×
1740
                    Editor.deleteFragment(this.editor);
×
1741
                }
1742
                // just handle Non-IME input
UNCOV
1743
                if (!this.isComposing) {
×
UNCOV
1744
                    Editor.insertText(this.editor, text);
×
1745
                }
1746
            } catch (error) {
UNCOV
1747
                this.editor.onError({
×
1748
                    code: SlateErrorCode.ToNativeSelectionError,
1749
                    nativeError: error
1750
                });
1751
            }
1752
        }
1753
    }
1754

1755
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1756
        if (!handler) {
3✔
1757
            return false;
3✔
1758
        }
UNCOV
1759
        handler(event);
×
UNCOV
1760
        return event.defaultPrevented;
×
1761
    }
1762
    //#endregion
1763

1764
    ngOnDestroy() {
1765
        this.editorResizeObserver?.disconnect();
22✔
1766
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1767
        this.manualListeners.forEach(manualListener => {
22✔
1768
            manualListener();
462✔
1769
        });
1770
        this.destroy$.complete();
22✔
1771
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1772
    }
1773
}
1774

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

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

1786
        if (isZeroDimensionRect) {
×
UNCOV
1787
            const leafRect = leafEl.getBoundingClientRect();
×
1788
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1789

1790
            if (leafHasDimensions) {
×
UNCOV
1791
                return;
×
1792
            }
1793
        }
1794

UNCOV
1795
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1796
        scrollIntoView(leafEl, {
×
1797
            scrollMode: 'if-needed'
1798
        });
UNCOV
1799
        delete leafEl.getBoundingClientRect;
×
1800
    }
1801
};
1802

1803
/**
1804
 * Check if the target is inside void and in the editor.
1805
 */
1806

1807
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1808
    let slateNode: Node | null = null;
1✔
1809
    try {
1✔
1810
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1811
    } catch (error) {}
1812
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1813
};
1814

1815
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1816
    return (
2✔
1817
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1818
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1819
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1820
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1821
    );
1822
};
1823

1824
/**
1825
 * remove default insert from composition
1826
 * @param text
1827
 */
1828
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
UNCOV
1829
    const types = ['compositionend', 'insertFromComposition'];
×
UNCOV
1830
    if (!types.includes(event.type)) {
×
1831
        return;
×
1832
    }
1833
    const insertText = (event as CompositionEvent).data;
×
UNCOV
1834
    const window = AngularEditor.getWindow(editor);
×
1835
    const domSelection = window.getSelection();
×
1836
    // ensure text node insert composition input text
1837
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
UNCOV
1838
        const textNode = domSelection.anchorNode;
×
1839
        textNode.splitText(textNode.length - insertText.length).remove();
×
1840
    }
1841
};
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