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

worktile / slate-angular / 481f38a4-0122-4a38-ac16-5467b1fdb7c2

15 Dec 2025 03:04AM UTC coverage: 38.108% (-8.7%) from 46.809%
481f38a4-0122-4a38-ac16-5467b1fdb7c2

push

circleci

pubuzhixing8
build: release 20.2.0-next.12

386 of 1205 branches covered (32.03%)

Branch coverage included in aggregate %.

1072 of 2621 relevant lines covered (40.9%)

24.88 hits per line

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

25.37
/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] as Element;
×
851
        const isVisible = this.editor.isVisible(node);
×
852
        if (!isVisible) {
×
853
            return 0;
×
854
        }
855
        if (!node) {
×
856
            return defaultHeight;
×
857
        }
858
        const key = AngularEditor.findKey(this.editor, node);
×
859
        const height = this.measuredHeights.get(key.id);
×
860
        if (typeof height === 'number') {
×
861
            return height;
×
862
        }
863
        if (this.measuredHeights.has(key.id)) {
×
864
            console.error('getBlockHeight: invalid height value', key.id, height);
×
865
        }
866
        return defaultHeight;
×
867
    }
868

869
    private buildAccumulatedHeight(heights: number[]) {
870
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
871
        for (let i = 0; i < heights.length; i++) {
×
872
            // 存储前 i 个的累计高度
873
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
874
        }
875
        return accumulatedHeights;
×
876
    }
877

878
    private scheduleMeasureVisibleHeights() {
879
        if (!this.shouldUseVirtual()) {
28✔
880
            return;
28✔
881
        }
882
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
883
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
884
            this.measureVisibleHeights();
×
885
        });
886
    }
887

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

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

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

966
    private toSlateSelection() {
967
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
968
            try {
1✔
969
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
970
                const { activeElement } = root;
1✔
971
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
972
                const domSelection = (root as Document).getSelection();
1✔
973

974
                if (activeElement === el) {
1!
975
                    this.latestElement = activeElement;
1✔
976
                    IS_FOCUSED.set(this.editor, true);
1✔
977
                } else {
978
                    IS_FOCUSED.delete(this.editor);
×
979
                }
980

981
                if (!domSelection) {
1!
982
                    return Transforms.deselect(this.editor);
×
983
                }
984

985
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
986
                const hasDomSelectionInEditor =
987
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
988
                if (!hasDomSelectionInEditor) {
1!
989
                    Transforms.deselect(this.editor);
×
990
                    return;
×
991
                }
992

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

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

1093
                // COMPAT: If the selection is expanded, even if the command seems like
1094
                // a delete forward/backward command it should delete the selection.
1095
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1096
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1097
                    Editor.deleteFragment(editor, { direction });
×
1098
                    return;
×
1099
                }
1100

1101
                switch (type) {
×
1102
                    case 'deleteByComposition':
1103
                    case 'deleteByCut':
1104
                    case 'deleteByDrag': {
1105
                        Editor.deleteFragment(editor);
×
1106
                        break;
×
1107
                    }
1108

1109
                    case 'deleteContent':
1110
                    case 'deleteContentForward': {
1111
                        Editor.deleteForward(editor);
×
1112
                        break;
×
1113
                    }
1114

1115
                    case 'deleteContentBackward': {
1116
                        Editor.deleteBackward(editor);
×
1117
                        break;
×
1118
                    }
1119

1120
                    case 'deleteEntireSoftLine': {
1121
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1122
                        Editor.deleteForward(editor, { unit: 'line' });
×
1123
                        break;
×
1124
                    }
1125

1126
                    case 'deleteHardLineBackward': {
1127
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1128
                        break;
×
1129
                    }
1130

1131
                    case 'deleteSoftLineBackward': {
1132
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1133
                        break;
×
1134
                    }
1135

1136
                    case 'deleteHardLineForward': {
1137
                        Editor.deleteForward(editor, { unit: 'block' });
×
1138
                        break;
×
1139
                    }
1140

1141
                    case 'deleteSoftLineForward': {
1142
                        Editor.deleteForward(editor, { unit: 'line' });
×
1143
                        break;
×
1144
                    }
1145

1146
                    case 'deleteWordBackward': {
1147
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1148
                        break;
×
1149
                    }
1150

1151
                    case 'deleteWordForward': {
1152
                        Editor.deleteForward(editor, { unit: 'word' });
×
1153
                        break;
×
1154
                    }
1155

1156
                    case 'insertLineBreak':
1157
                    case 'insertParagraph': {
1158
                        Editor.insertBreak(editor);
×
1159
                        break;
×
1160
                    }
1161

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

1197
    private onDOMBlur(event: FocusEvent) {
1198
        if (
×
1199
            this.readonly ||
×
1200
            this.isUpdatingSelection ||
1201
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1202
            this.isDOMEventHandled(event, this.blur)
1203
        ) {
1204
            return;
×
1205
        }
1206

1207
        const window = AngularEditor.getWindow(this.editor);
×
1208

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

1218
        const { relatedTarget } = event;
×
1219
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1220

1221
        // COMPAT: The event should be ignored if the focus is returning
1222
        // to the editor from an embedded editable element (eg. an <input>
1223
        // element inside a void node).
1224
        if (relatedTarget === el) {
×
1225
            return;
×
1226
        }
1227

1228
        // COMPAT: The event should be ignored if the focus is moving from
1229
        // the editor to inside a void node's spacer element.
1230
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1231
            return;
×
1232
        }
1233

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

1240
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1241
                return;
×
1242
            }
1243
        }
1244

1245
        IS_FOCUSED.delete(this.editor);
×
1246
    }
1247

1248
    private onDOMClick(event: MouseEvent) {
1249
        if (
×
1250
            !this.readonly &&
×
1251
            AngularEditor.hasTarget(this.editor, event.target) &&
1252
            !this.isDOMEventHandled(event, this.click) &&
1253
            isDOMNode(event.target)
1254
        ) {
1255
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1256
            const path = AngularEditor.findPath(this.editor, node);
×
1257
            const start = Editor.start(this.editor, path);
×
1258
            const end = Editor.end(this.editor, path);
×
1259

1260
            const startVoid = Editor.void(this.editor, { at: start });
×
1261
            const endVoid = Editor.void(this.editor, { at: end });
×
1262

1263
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1264
                let blockPath = path;
×
1265
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1266
                    const block = Editor.above(this.editor, {
×
1267
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1268
                        at: path
1269
                    });
1270

1271
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1272
                }
1273

1274
                const range = Editor.range(this.editor, blockPath);
×
1275
                Transforms.select(this.editor, range);
×
1276
                return;
×
1277
            }
1278

1279
            if (
×
1280
                startVoid &&
×
1281
                endVoid &&
1282
                Path.equals(startVoid[1], endVoid[1]) &&
1283
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1284
            ) {
1285
                const range = Editor.range(this.editor, start);
×
1286
                Transforms.select(this.editor, range);
×
1287
            }
1288
        }
1289
    }
1290

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

1306
    private onDOMCompositionUpdate(event: CompositionEvent) {
1307
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1308
    }
1309

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

1324
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1325
            // so we need avoid repeat isnertText by isComposing === true,
1326
            this.isComposing = false;
×
1327
        }
1328
        this.render();
×
1329
    }
1330

1331
    private onDOMCopy(event: ClipboardEvent) {
1332
        const window = AngularEditor.getWindow(this.editor);
×
1333
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1334
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1335
            event.preventDefault();
×
1336
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1337
        }
1338
    }
1339

1340
    private onDOMCut(event: ClipboardEvent) {
1341
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1342
            event.preventDefault();
×
1343
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1344
            const { selection } = this.editor;
×
1345

1346
            if (selection) {
×
1347
                AngularEditor.deleteCutData(this.editor);
×
1348
            }
1349
        }
1350
    }
1351

1352
    private onDOMDragOver(event: DragEvent) {
1353
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1354
            // Only when the target is void, call `preventDefault` to signal
1355
            // that drops are allowed. Editable content is droppable by
1356
            // default, and calling `preventDefault` hides the cursor.
1357
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1358

1359
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1360
                event.preventDefault();
×
1361
            }
1362
        }
1363
    }
1364

1365
    private onDOMDragStart(event: DragEvent) {
1366
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1367
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1368
            const path = AngularEditor.findPath(this.editor, node);
×
1369
            const voidMatch =
1370
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1371

1372
            // If starting a drag on a void node, make sure it is selected
1373
            // so that it shows up in the selection's fragment.
1374
            if (voidMatch) {
×
1375
                const range = Editor.range(this.editor, path);
×
1376
                Transforms.select(this.editor, range);
×
1377
            }
1378

1379
            this.isDraggingInternally = true;
×
1380

1381
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1382
        }
1383
    }
1384

1385
    private onDOMDrop(event: DragEvent) {
1386
        const editor = this.editor;
×
1387
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1388
            event.preventDefault();
×
1389
            // Keep a reference to the dragged range before updating selection
1390
            const draggedRange = editor.selection;
×
1391

1392
            // Find the range where the drop happened
1393
            const range = AngularEditor.findEventRange(editor, event);
×
1394
            const data = event.dataTransfer;
×
1395

1396
            Transforms.select(editor, range);
×
1397

1398
            if (this.isDraggingInternally) {
×
1399
                if (draggedRange) {
×
1400
                    Transforms.delete(editor, {
×
1401
                        at: draggedRange
1402
                    });
1403
                }
1404

1405
                this.isDraggingInternally = false;
×
1406
            }
1407

1408
            AngularEditor.insertData(editor, data);
×
1409

1410
            // When dragging from another source into the editor, it's possible
1411
            // that the current editor does not have focus.
1412
            if (!AngularEditor.isFocused(editor)) {
×
1413
                AngularEditor.focus(editor);
×
1414
            }
1415
        }
1416
    }
1417

1418
    private onDOMDragEnd(event: DragEvent) {
1419
        if (
×
1420
            !this.readonly &&
×
1421
            this.isDraggingInternally &&
1422
            AngularEditor.hasTarget(this.editor, event.target) &&
1423
            !this.isDOMEventHandled(event, this.dragEnd)
1424
        ) {
1425
            this.isDraggingInternally = false;
×
1426
        }
1427
    }
1428

1429
    private onDOMFocus(event: Event) {
1430
        if (
2✔
1431
            !this.readonly &&
8✔
1432
            !this.isUpdatingSelection &&
1433
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1434
            !this.isDOMEventHandled(event, this.focus)
1435
        ) {
1436
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1437
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1438
            this.latestElement = root.activeElement;
2✔
1439

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

1448
            IS_FOCUSED.set(this.editor, true);
2✔
1449
        }
1450
    }
1451

1452
    private onDOMKeydown(event: KeyboardEvent) {
1453
        const editor = this.editor;
×
1454
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1455
        const { activeElement } = root;
×
1456
        if (
×
1457
            !this.readonly &&
×
1458
            AngularEditor.hasEditableTarget(editor, event.target) &&
1459
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1460
            !this.isComposing &&
1461
            !this.isDOMEventHandled(event, this.keydown)
1462
        ) {
1463
            const nativeEvent = event;
×
1464
            const { selection } = editor;
×
1465

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

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

1477
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1478
                        editor.redo();
×
1479
                    }
1480

1481
                    return;
×
1482
                }
1483

1484
                if (Hotkeys.isUndo(nativeEvent)) {
×
1485
                    event.preventDefault();
×
1486

1487
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1488
                        editor.undo();
×
1489
                    }
1490

1491
                    return;
×
1492
                }
1493

1494
                // COMPAT: Certain browsers don't handle the selection updates
1495
                // properly. In Chrome, the selection isn't properly extended.
1496
                // And in Firefox, the selection isn't properly collapsed.
1497
                // (2017/10/17)
1498
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1499
                    event.preventDefault();
×
1500
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1501
                    return;
×
1502
                }
1503

1504
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1505
                    event.preventDefault();
×
1506
                    Transforms.move(editor, { unit: 'line' });
×
1507
                    return;
×
1508
                }
1509

1510
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1511
                    event.preventDefault();
×
1512
                    Transforms.move(editor, {
×
1513
                        unit: 'line',
1514
                        edge: 'focus',
1515
                        reverse: true
1516
                    });
1517
                    return;
×
1518
                }
1519

1520
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1521
                    event.preventDefault();
×
1522
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1523
                    return;
×
1524
                }
1525

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

1534
                    if (selection && Range.isCollapsed(selection)) {
×
1535
                        Transforms.move(editor, { reverse: !isRTL });
×
1536
                    } else {
1537
                        Transforms.collapse(editor, { edge: 'start' });
×
1538
                    }
1539

1540
                    return;
×
1541
                }
1542

1543
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1544
                    event.preventDefault();
×
1545
                    if (selection && Range.isCollapsed(selection)) {
×
1546
                        Transforms.move(editor, { reverse: isRTL });
×
1547
                    } else {
1548
                        Transforms.collapse(editor, { edge: 'end' });
×
1549
                    }
1550

1551
                    return;
×
1552
                }
1553

1554
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1555
                    event.preventDefault();
×
1556

1557
                    if (selection && Range.isExpanded(selection)) {
×
1558
                        Transforms.collapse(editor, { edge: 'focus' });
×
1559
                    }
1560

1561
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1562
                    return;
×
1563
                }
1564

1565
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1566
                    event.preventDefault();
×
1567

1568
                    if (selection && Range.isExpanded(selection)) {
×
1569
                        Transforms.collapse(editor, { edge: 'focus' });
×
1570
                    }
1571

1572
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1573
                    return;
×
1574
                }
1575

1576
                if (isKeyHotkey('mod+a', event)) {
×
1577
                    this.editor.selectAll();
×
1578
                    event.preventDefault();
×
1579
                    return;
×
1580
                }
1581

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

1593
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1594
                        event.preventDefault();
×
1595
                        Editor.insertBreak(editor);
×
1596
                        return;
×
1597
                    }
1598

1599
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1600
                        event.preventDefault();
×
1601

1602
                        if (selection && Range.isExpanded(selection)) {
×
1603
                            Editor.deleteFragment(editor, {
×
1604
                                direction: 'backward'
1605
                            });
1606
                        } else {
1607
                            Editor.deleteBackward(editor);
×
1608
                        }
1609

1610
                        return;
×
1611
                    }
1612

1613
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1614
                        event.preventDefault();
×
1615

1616
                        if (selection && Range.isExpanded(selection)) {
×
1617
                            Editor.deleteFragment(editor, {
×
1618
                                direction: 'forward'
1619
                            });
1620
                        } else {
1621
                            Editor.deleteForward(editor);
×
1622
                        }
1623

1624
                        return;
×
1625
                    }
1626

1627
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1628
                        event.preventDefault();
×
1629

1630
                        if (selection && Range.isExpanded(selection)) {
×
1631
                            Editor.deleteFragment(editor, {
×
1632
                                direction: 'backward'
1633
                            });
1634
                        } else {
1635
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1636
                        }
1637

1638
                        return;
×
1639
                    }
1640

1641
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1642
                        event.preventDefault();
×
1643

1644
                        if (selection && Range.isExpanded(selection)) {
×
1645
                            Editor.deleteFragment(editor, {
×
1646
                                direction: 'forward'
1647
                            });
1648
                        } else {
1649
                            Editor.deleteForward(editor, { unit: 'line' });
×
1650
                        }
1651

1652
                        return;
×
1653
                    }
1654

1655
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1656
                        event.preventDefault();
×
1657

1658
                        if (selection && Range.isExpanded(selection)) {
×
1659
                            Editor.deleteFragment(editor, {
×
1660
                                direction: 'backward'
1661
                            });
1662
                        } else {
1663
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1664
                        }
1665

1666
                        return;
×
1667
                    }
1668

1669
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1670
                        event.preventDefault();
×
1671

1672
                        if (selection && Range.isExpanded(selection)) {
×
1673
                            Editor.deleteFragment(editor, {
×
1674
                                direction: 'forward'
1675
                            });
1676
                        } else {
1677
                            Editor.deleteForward(editor, { unit: 'word' });
×
1678
                        }
1679

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

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

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

1761
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1762
        if (!handler) {
3✔
1763
            return false;
3✔
1764
        }
1765
        handler(event);
×
1766
        return event.defaultPrevented;
×
1767
    }
1768
    //#endregion
1769

1770
    ngOnDestroy() {
1771
        this.editorResizeObserver?.disconnect();
23✔
1772
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1773
        this.manualListeners.forEach(manualListener => {
23✔
1774
            manualListener();
483✔
1775
        });
1776
        this.destroy$.complete();
23✔
1777
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1778
    }
1779
}
1780

1781
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1782
    // This was affecting the selection of multiple blocks and dragging behavior,
1783
    // so enabled only if the selection has been collapsed.
1784
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1785
        const leafEl = domRange.startContainer.parentElement!;
×
1786

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

1792
        if (isZeroDimensionRect) {
×
1793
            const leafRect = leafEl.getBoundingClientRect();
×
1794
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1795

1796
            if (leafHasDimensions) {
×
1797
                return;
×
1798
            }
1799
        }
1800

1801
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1802
        scrollIntoView(leafEl, {
×
1803
            scrollMode: 'if-needed'
1804
        });
1805
        delete leafEl.getBoundingClientRect;
×
1806
    }
1807
};
1808

1809
/**
1810
 * Check if the target is inside void and in the editor.
1811
 */
1812

1813
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1814
    let slateNode: Node | null = null;
1✔
1815
    try {
1✔
1816
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1817
    } catch (error) {}
1818
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1819
};
1820

1821
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1822
    return (
2✔
1823
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1824
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1825
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1826
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1827
    );
1828
};
1829

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