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

worktile / slate-angular / 62ba9eda-73c7-4559-9959-adfb60d29862

03 Dec 2025 03:19AM UTC coverage: 46.809% (-0.4%) from 47.176%
62ba9eda-73c7-4559-9959-adfb60d29862

push

circleci

pubuzhixing8
fix: unit testing

369 of 997 branches covered (37.01%)

Branch coverage included in aggregate %.

1010 of 1949 relevant lines covered (51.82%)

32.48 hits per line

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

29.79
/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 { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
43
import Hotkeys from '../../utils/hotkeys';
44
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
45
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
46
import { SlateErrorCode } from '../../types/error';
47
import { NG_VALUE_ACCESSOR } from '@angular/forms';
48
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
49
import { ViewType } from '../../types/view';
50
import { HistoryEditor } from 'slate-history';
51
import { isDecoratorRangeListEqual } from '../../utils';
52
import { SlatePlaceholder } from '../../types/feature';
53
import { restoreDom } from '../../utils/restore-dom';
54
import { ListRender } from '../../view/render/list-render';
55
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
56

57
// not correctly clipboardData on beforeinput
58
const forceOnDOMPaste = IS_SAFARI;
1✔
59

60
@Component({
61
    selector: 'slate-editable',
62
    host: {
63
        class: 'slate-editable-container',
64
        '[attr.contenteditable]': 'readonly ? undefined : true',
65
        '[attr.role]': `readonly ? undefined : 'textbox'`,
66
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
67
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
68
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
69
    },
70
    template: '',
71
    changeDetection: ChangeDetectionStrategy.OnPush,
72
    providers: [
73
        {
74
            provide: NG_VALUE_ACCESSOR,
75
            useExisting: forwardRef(() => SlateEditable),
23✔
76
            multi: true
77
        }
78
    ],
79
    imports: []
80
})
81
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
82
    viewContext: SlateViewContext;
83
    context: SlateChildrenContext;
84

85
    private destroy$ = new Subject();
23✔
86

87
    isComposing = false;
23✔
88
    isDraggingInternally = false;
23✔
89
    isUpdatingSelection = false;
23✔
90
    latestElement = null as DOMElement | null;
23✔
91

92
    protected manualListeners: (() => void)[] = [];
23✔
93

94
    private initialized: boolean;
95

96
    private onTouchedCallback: () => void = () => {};
23✔
97

98
    private onChangeCallback: (_: any) => void = () => {};
23✔
99

100
    @Input() editor: AngularEditor;
101

102
    @Input() renderElement: (element: Element) => ViewType | null;
103

104
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
105

106
    @Input() renderText: (text: SlateText) => ViewType | null;
107

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

110
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
111

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

114
    @Input() isStrictDecorate: boolean = true;
23✔
115

116
    @Input() trackBy: (node: Element) => any = () => null;
206✔
117

118
    @Input() readonly = false;
23✔
119

120
    @Input() placeholder: string;
121

122
    //#region input event handler
123
    @Input() beforeInput: (event: Event) => void;
124
    @Input() blur: (event: Event) => void;
125
    @Input() click: (event: MouseEvent) => void;
126
    @Input() compositionEnd: (event: CompositionEvent) => void;
127
    @Input() compositionUpdate: (event: CompositionEvent) => void;
128
    @Input() compositionStart: (event: CompositionEvent) => void;
129
    @Input() copy: (event: ClipboardEvent) => void;
130
    @Input() cut: (event: ClipboardEvent) => void;
131
    @Input() dragOver: (event: DragEvent) => void;
132
    @Input() dragStart: (event: DragEvent) => void;
133
    @Input() dragEnd: (event: DragEvent) => void;
134
    @Input() drop: (event: DragEvent) => void;
135
    @Input() focus: (event: Event) => void;
136
    @Input() keydown: (event: KeyboardEvent) => void;
137
    @Input() paste: (event: ClipboardEvent) => void;
138
    //#endregion
139

140
    //#region DOM attr
141
    @Input() spellCheck = false;
23✔
142
    @Input() autoCorrect = false;
23✔
143
    @Input() autoCapitalize = false;
23✔
144

145
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
146
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
147
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
148

149
    get hasBeforeInputSupport() {
150
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
151
    }
152
    //#endregion
153

154
    viewContainerRef = inject(ViewContainerRef);
23✔
155

156
    getOutletParent = () => {
23✔
157
        return this.elementRef.nativeElement;
43✔
158
    };
159

160
    listRender: ListRender;
161

162
    constructor(
163
        public elementRef: ElementRef,
23✔
164
        public renderer2: Renderer2,
23✔
165
        public cdr: ChangeDetectorRef,
23✔
166
        private ngZone: NgZone,
23✔
167
        private injector: Injector
23✔
168
    ) {}
169

170
    ngOnInit() {
171
        this.editor.injector = this.injector;
23✔
172
        this.editor.children = [];
23✔
173
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
174
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
175
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
176
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
177
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
178
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
179
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
180
            this.ngZone.run(() => {
13✔
181
                this.onChange();
13✔
182
            });
183
        });
184
        this.ngZone.runOutsideAngular(() => {
23✔
185
            this.initialize();
23✔
186
        });
187
        this.initializeViewContext();
23✔
188
        this.initializeContext();
23✔
189

190
        // add browser class
191
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
192
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
193
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, () => null);
23✔
194
    }
195

196
    ngOnChanges(simpleChanges: SimpleChanges) {
197
        if (!this.initialized) {
30✔
198
            return;
23✔
199
        }
200
        const decorateChange = simpleChanges['decorate'];
7✔
201
        if (decorateChange) {
7✔
202
            this.forceRender();
2✔
203
        }
204
        const placeholderChange = simpleChanges['placeholder'];
7✔
205
        if (placeholderChange) {
7✔
206
            this.render();
1✔
207
        }
208
        const readonlyChange = simpleChanges['readonly'];
7✔
209
        if (readonlyChange) {
7!
210
            IS_READ_ONLY.set(this.editor, this.readonly);
×
211
            this.render();
×
212
            this.toSlateSelection();
×
213
        }
214
    }
215

216
    registerOnChange(fn: any) {
217
        this.onChangeCallback = fn;
23✔
218
    }
219
    registerOnTouched(fn: any) {
220
        this.onTouchedCallback = fn;
23✔
221
    }
222

223
    writeValue(value: Element[]) {
224
        if (value && value.length) {
49✔
225
            this.editor.children = value;
26✔
226
            this.initializeContext();
26✔
227
            if (!this.listRender.initialized) {
26✔
228
                this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
229
            } else {
230
                this.listRender.update(this.editor.children, this.editor, this.context);
3✔
231
            }
232
            this.cdr.markForCheck();
26✔
233
        }
234
    }
235

236
    initialize() {
237
        this.initialized = true;
23✔
238
        const window = AngularEditor.getWindow(this.editor);
23✔
239
        this.addEventListener(
23✔
240
            'selectionchange',
241
            event => {
242
                this.toSlateSelection();
2✔
243
            },
244
            window.document
245
        );
246
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
247
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
248
        }
249
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
250
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
251
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
252
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
253
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
254
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
255
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
256
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
257
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
258
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
259
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
260
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
261
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
262
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
263
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
264
            this.addEventListener(event.name, () => {});
115✔
265
        });
266
    }
267

268
    toNativeSelection() {
269
        try {
15✔
270
            const { selection } = this.editor;
15✔
271
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
272
            const { activeElement } = root;
15✔
273
            const domSelection = (root as Document).getSelection();
15✔
274

275
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
276
                return;
14✔
277
            }
278

279
            const hasDomSelection = domSelection.type !== 'None';
1✔
280

281
            // If the DOM selection is properly unset, we're done.
282
            if (!selection && !hasDomSelection) {
1!
283
                return;
×
284
            }
285

286
            // If the DOM selection is already correct, we're done.
287
            // verify that the dom selection is in the editor
288
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
289
            let hasDomSelectionInEditor = false;
1✔
290
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
291
                hasDomSelectionInEditor = true;
1✔
292
            }
293

294
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
295
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
296
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
297
                    exactMatch: false,
298
                    suppressThrow: true
299
                });
300
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
301
                    return;
×
302
                }
303
            }
304

305
            // prevent updating native selection when active element is void element
306
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
307
                return;
×
308
            }
309

310
            // when <Editable/> is being controlled through external value
311
            // then its children might just change - DOM responds to it on its own
312
            // but Slate's value is not being updated through any operation
313
            // and thus it doesn't transform selection on its own
314
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
315
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
316
                return;
×
317
            }
318

319
            // Otherwise the DOM selection is out of sync, so update it.
320
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
321
            this.isUpdatingSelection = true;
1✔
322

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

325
            if (newDomRange) {
1!
326
                // COMPAT: Since the DOM range has no concept of backwards/forwards
327
                // we need to check and do the right thing here.
328
                if (Range.isBackward(selection)) {
1!
329
                    // eslint-disable-next-line max-len
330
                    domSelection.setBaseAndExtent(
×
331
                        newDomRange.endContainer,
332
                        newDomRange.endOffset,
333
                        newDomRange.startContainer,
334
                        newDomRange.startOffset
335
                    );
336
                } else {
337
                    // eslint-disable-next-line max-len
338
                    domSelection.setBaseAndExtent(
1✔
339
                        newDomRange.startContainer,
340
                        newDomRange.startOffset,
341
                        newDomRange.endContainer,
342
                        newDomRange.endOffset
343
                    );
344
                }
345
            } else {
346
                domSelection.removeAllRanges();
×
347
            }
348

349
            setTimeout(() => {
1✔
350
                // handle scrolling in setTimeout because of
351
                // dom should not have updated immediately after listRender's updating
352
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
353
                // COMPAT: In Firefox, it's not enough to create a range, you also need
354
                // to focus the contenteditable element too. (2016/11/16)
355
                if (newDomRange && IS_FIREFOX) {
1!
356
                    el.focus();
×
357
                }
358

359
                this.isUpdatingSelection = false;
1✔
360
            });
361
        } catch (error) {
362
            this.editor.onError({
×
363
                code: SlateErrorCode.ToNativeSelectionError,
364
                nativeError: error
365
            });
366
            this.isUpdatingSelection = false;
×
367
        }
368
    }
369

370
    onChange() {
371
        this.forceRender();
13✔
372
        this.onChangeCallback(this.editor.children);
13✔
373
    }
374

375
    ngAfterViewChecked() {}
376

377
    ngDoCheck() {}
378

379
    forceRender() {
380
        this.updateContext();
15✔
381
        this.listRender.update(this.editor.children, this.editor, this.context);
15✔
382
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
383
        // when the DOMElement where the selection is located is removed
384
        // the compositionupdate and compositionend events will no longer be fired
385
        // so isComposing needs to be corrected
386
        // need exec after this.cdr.detectChanges() to render HTML
387
        // need exec before this.toNativeSelection() to correct native selection
388
        if (this.isComposing) {
15!
389
            // Composition input text be not rendered when user composition input with selection is expanded
390
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
391
            // this time condition is true and isComposing is assigned false
392
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
393
            setTimeout(() => {
×
394
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
395
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
396
                let textContent = '';
×
397
                // skip decorate text
398
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
399
                    let text = stringDOMNode.textContent;
×
400
                    const zeroChar = '\uFEFF';
×
401
                    // remove zero with char
402
                    if (text.startsWith(zeroChar)) {
×
403
                        text = text.slice(1);
×
404
                    }
405
                    if (text.endsWith(zeroChar)) {
×
406
                        text = text.slice(0, text.length - 1);
×
407
                    }
408
                    textContent += text;
×
409
                });
410
                if (Node.string(textNode).endsWith(textContent)) {
×
411
                    this.isComposing = false;
×
412
                }
413
            }, 0);
414
        }
415
        this.toNativeSelection();
15✔
416
    }
417

418
    render() {
419
        const changed = this.updateContext();
2✔
420
        if (changed) {
2✔
421
            this.listRender.update(this.editor.children, this.editor, this.context);
2✔
422
        }
423
    }
424

425
    updateContext() {
426
        const decorations = this.generateDecorations();
17✔
427
        if (
17✔
428
            this.context.selection !== this.editor.selection ||
46✔
429
            this.context.decorate !== this.decorate ||
430
            this.context.readonly !== this.readonly ||
431
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
432
        ) {
433
            this.context = {
10✔
434
                parent: this.editor,
435
                selection: this.editor.selection,
436
                decorations: decorations,
437
                decorate: this.decorate,
438
                readonly: this.readonly
439
            };
440
            return true;
10✔
441
        }
442
        return false;
7✔
443
    }
444

445
    initializeContext() {
446
        this.context = {
49✔
447
            parent: this.editor,
448
            selection: this.editor.selection,
449
            decorations: this.generateDecorations(),
450
            decorate: this.decorate,
451
            readonly: this.readonly
452
        };
453
    }
454

455
    initializeViewContext() {
456
        this.viewContext = {
23✔
457
            editor: this.editor,
458
            renderElement: this.renderElement,
459
            renderLeaf: this.renderLeaf,
460
            renderText: this.renderText,
461
            trackBy: this.trackBy,
462
            isStrictDecorate: this.isStrictDecorate
463
        };
464
    }
465

466
    composePlaceholderDecorate(editor: Editor) {
467
        if (this.placeholderDecorate) {
64!
468
            return this.placeholderDecorate(editor) || [];
×
469
        }
470

471
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
472
            const start = Editor.start(editor, []);
3✔
473
            return [
3✔
474
                {
475
                    placeholder: this.placeholder,
476
                    anchor: start,
477
                    focus: start
478
                }
479
            ];
480
        } else {
481
            return [];
61✔
482
        }
483
    }
484

485
    generateDecorations() {
486
        const decorations = this.decorate([this.editor, []]);
66✔
487
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
488
        decorations.push(...placeholderDecorations);
66✔
489
        return decorations;
66✔
490
    }
491

492
    //#region event proxy
493
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
494
        this.manualListeners.push(
483✔
495
            this.renderer2.listen(target, eventName, (event: Event) => {
496
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
497
                if (beforeInputEvent) {
5!
498
                    this.onFallbackBeforeInput(beforeInputEvent);
×
499
                }
500
                listener(event);
5✔
501
            })
502
        );
503
    }
504

505
    private toSlateSelection() {
506
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
507
            try {
1✔
508
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
509
                const { activeElement } = root;
1✔
510
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
511
                const domSelection = (root as Document).getSelection();
1✔
512

513
                if (activeElement === el) {
1!
514
                    this.latestElement = activeElement;
1✔
515
                    IS_FOCUSED.set(this.editor, true);
1✔
516
                } else {
517
                    IS_FOCUSED.delete(this.editor);
×
518
                }
519

520
                if (!domSelection) {
1!
521
                    return Transforms.deselect(this.editor);
×
522
                }
523

524
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
525
                const hasDomSelectionInEditor =
526
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
527
                if (!hasDomSelectionInEditor) {
1!
528
                    Transforms.deselect(this.editor);
×
529
                    return;
×
530
                }
531

532
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
533
                // for example, double-click the last cell of the table to select a non-editable DOM
534
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
535
                if (range) {
1✔
536
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
537
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
538
                            // force adjust DOMSelection
539
                            this.toNativeSelection();
×
540
                        }
541
                    } else {
542
                        Transforms.select(this.editor, range);
1✔
543
                    }
544
                }
545
            } catch (error) {
546
                this.editor.onError({
×
547
                    code: SlateErrorCode.ToSlateSelectionError,
548
                    nativeError: error
549
                });
550
            }
551
        }
552
    }
553

554
    private onDOMBeforeInput(
555
        event: Event & {
556
            inputType: string;
557
            isComposing: boolean;
558
            data: string | null;
559
            dataTransfer: DataTransfer | null;
560
            getTargetRanges(): DOMStaticRange[];
561
        }
562
    ) {
563
        const editor = this.editor;
×
564
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
565
        const { activeElement } = root;
×
566
        const { selection } = editor;
×
567
        const { inputType: type } = event;
×
568
        const data = event.dataTransfer || event.data || undefined;
×
569
        if (IS_ANDROID) {
×
570
            let targetRange: Range | null = null;
×
571
            let [nativeTargetRange] = event.getTargetRanges();
×
572
            if (nativeTargetRange) {
×
573
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
574
            }
575
            // COMPAT: SelectionChange event is fired after the action is performed, so we
576
            // have to manually get the selection here to ensure it's up-to-date.
577
            const window = AngularEditor.getWindow(editor);
×
578
            const domSelection = window.getSelection();
×
579
            if (!targetRange && domSelection) {
×
580
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
581
            }
582
            targetRange = targetRange ?? editor.selection;
×
583
            if (type === 'insertCompositionText') {
×
584
                if (data && data.toString().includes('\n')) {
×
585
                    restoreDom(editor, () => {
×
586
                        Editor.insertBreak(editor);
×
587
                    });
588
                } else {
589
                    if (targetRange) {
×
590
                        if (data) {
×
591
                            restoreDom(editor, () => {
×
592
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
593
                            });
594
                        } else {
595
                            restoreDom(editor, () => {
×
596
                                Transforms.delete(editor, { at: targetRange });
×
597
                            });
598
                        }
599
                    }
600
                }
601
                return;
×
602
            }
603
            if (type === 'deleteContentBackward') {
×
604
                // gboard can not prevent default action, so must use restoreDom,
605
                // sougou Keyboard can prevent default action(only in Chinese input mode).
606
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
607
                if (!Range.isCollapsed(targetRange)) {
×
608
                    restoreDom(editor, () => {
×
609
                        Transforms.delete(editor, { at: targetRange });
×
610
                    });
611
                    return;
×
612
                }
613
            }
614
            if (type === 'insertText') {
×
615
                restoreDom(editor, () => {
×
616
                    if (typeof data === 'string') {
×
617
                        Editor.insertText(editor, data);
×
618
                    }
619
                });
620
                return;
×
621
            }
622
        }
623
        if (
×
624
            !this.readonly &&
×
625
            AngularEditor.hasEditableTarget(editor, event.target) &&
626
            !isTargetInsideVoid(editor, activeElement) &&
627
            !this.isDOMEventHandled(event, this.beforeInput)
628
        ) {
629
            try {
×
630
                event.preventDefault();
×
631

632
                // COMPAT: If the selection is expanded, even if the command seems like
633
                // a delete forward/backward command it should delete the selection.
634
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
635
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
636
                    Editor.deleteFragment(editor, { direction });
×
637
                    return;
×
638
                }
639

640
                switch (type) {
×
641
                    case 'deleteByComposition':
642
                    case 'deleteByCut':
643
                    case 'deleteByDrag': {
644
                        Editor.deleteFragment(editor);
×
645
                        break;
×
646
                    }
647

648
                    case 'deleteContent':
649
                    case 'deleteContentForward': {
650
                        Editor.deleteForward(editor);
×
651
                        break;
×
652
                    }
653

654
                    case 'deleteContentBackward': {
655
                        Editor.deleteBackward(editor);
×
656
                        break;
×
657
                    }
658

659
                    case 'deleteEntireSoftLine': {
660
                        Editor.deleteBackward(editor, { unit: 'line' });
×
661
                        Editor.deleteForward(editor, { unit: 'line' });
×
662
                        break;
×
663
                    }
664

665
                    case 'deleteHardLineBackward': {
666
                        Editor.deleteBackward(editor, { unit: 'block' });
×
667
                        break;
×
668
                    }
669

670
                    case 'deleteSoftLineBackward': {
671
                        Editor.deleteBackward(editor, { unit: 'line' });
×
672
                        break;
×
673
                    }
674

675
                    case 'deleteHardLineForward': {
676
                        Editor.deleteForward(editor, { unit: 'block' });
×
677
                        break;
×
678
                    }
679

680
                    case 'deleteSoftLineForward': {
681
                        Editor.deleteForward(editor, { unit: 'line' });
×
682
                        break;
×
683
                    }
684

685
                    case 'deleteWordBackward': {
686
                        Editor.deleteBackward(editor, { unit: 'word' });
×
687
                        break;
×
688
                    }
689

690
                    case 'deleteWordForward': {
691
                        Editor.deleteForward(editor, { unit: 'word' });
×
692
                        break;
×
693
                    }
694

695
                    case 'insertLineBreak':
696
                    case 'insertParagraph': {
697
                        Editor.insertBreak(editor);
×
698
                        break;
×
699
                    }
700

701
                    case 'insertFromComposition': {
702
                        // COMPAT: in safari, `compositionend` event is dispatched after
703
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
704
                        // https://www.w3.org/TR/input-events-2/
705
                        // so the following code is the right logic
706
                        // because DOM selection in sync will be exec before `compositionend` event
707
                        // isComposing is true will prevent DOM selection being update correctly.
708
                        this.isComposing = false;
×
709
                        preventInsertFromComposition(event, this.editor);
×
710
                    }
711
                    case 'insertFromDrop':
712
                    case 'insertFromPaste':
713
                    case 'insertFromYank':
714
                    case 'insertReplacementText':
715
                    case 'insertText': {
716
                        // use a weak comparison instead of 'instanceof' to allow
717
                        // programmatic access of paste events coming from external windows
718
                        // like cypress where cy.window does not work realibly
719
                        if (data?.constructor.name === 'DataTransfer') {
×
720
                            AngularEditor.insertData(editor, data as DataTransfer);
×
721
                        } else if (typeof data === 'string') {
×
722
                            Editor.insertText(editor, data);
×
723
                        }
724
                        break;
×
725
                    }
726
                }
727
            } catch (error) {
728
                this.editor.onError({
×
729
                    code: SlateErrorCode.OnDOMBeforeInputError,
730
                    nativeError: error
731
                });
732
            }
733
        }
734
    }
735

736
    private onDOMBlur(event: FocusEvent) {
737
        if (
×
738
            this.readonly ||
×
739
            this.isUpdatingSelection ||
740
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
741
            this.isDOMEventHandled(event, this.blur)
742
        ) {
743
            return;
×
744
        }
745

746
        const window = AngularEditor.getWindow(this.editor);
×
747

748
        // COMPAT: If the current `activeElement` is still the previous
749
        // one, this is due to the window being blurred when the tab
750
        // itself becomes unfocused, so we want to abort early to allow to
751
        // editor to stay focused when the tab becomes focused again.
752
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
753
        if (this.latestElement === root.activeElement) {
×
754
            return;
×
755
        }
756

757
        const { relatedTarget } = event;
×
758
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
759

760
        // COMPAT: The event should be ignored if the focus is returning
761
        // to the editor from an embedded editable element (eg. an <input>
762
        // element inside a void node).
763
        if (relatedTarget === el) {
×
764
            return;
×
765
        }
766

767
        // COMPAT: The event should be ignored if the focus is moving from
768
        // the editor to inside a void node's spacer element.
769
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
770
            return;
×
771
        }
772

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

779
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
780
                return;
×
781
            }
782
        }
783

784
        IS_FOCUSED.delete(this.editor);
×
785
    }
786

787
    private onDOMClick(event: MouseEvent) {
788
        if (
×
789
            !this.readonly &&
×
790
            AngularEditor.hasTarget(this.editor, event.target) &&
791
            !this.isDOMEventHandled(event, this.click) &&
792
            isDOMNode(event.target)
793
        ) {
794
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
795
            const path = AngularEditor.findPath(this.editor, node);
×
796
            const start = Editor.start(this.editor, path);
×
797
            const end = Editor.end(this.editor, path);
×
798

799
            const startVoid = Editor.void(this.editor, { at: start });
×
800
            const endVoid = Editor.void(this.editor, { at: end });
×
801

802
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
803
                let blockPath = path;
×
804
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
805
                    const block = Editor.above(this.editor, {
×
806
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
807
                        at: path
808
                    });
809

810
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
811
                }
812

813
                const range = Editor.range(this.editor, blockPath);
×
814
                Transforms.select(this.editor, range);
×
815
                return;
×
816
            }
817

818
            if (
×
819
                startVoid &&
×
820
                endVoid &&
821
                Path.equals(startVoid[1], endVoid[1]) &&
822
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
823
            ) {
824
                const range = Editor.range(this.editor, start);
×
825
                Transforms.select(this.editor, range);
×
826
            }
827
        }
828
    }
829

830
    private onDOMCompositionStart(event: CompositionEvent) {
831
        const { selection } = this.editor;
1✔
832
        if (selection) {
1!
833
            // solve the problem of cross node Chinese input
834
            if (Range.isExpanded(selection)) {
×
835
                Editor.deleteFragment(this.editor);
×
836
                this.forceRender();
×
837
            }
838
        }
839
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
840
            this.isComposing = true;
1✔
841
        }
842
        this.render();
1✔
843
    }
844

845
    private onDOMCompositionUpdate(event: CompositionEvent) {
846
        this.isDOMEventHandled(event, this.compositionUpdate);
×
847
    }
848

849
    private onDOMCompositionEnd(event: CompositionEvent) {
850
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
851
            Transforms.delete(this.editor);
×
852
        }
853
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
854
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
855
            // aren't correct and never fire the "insertFromComposition"
856
            // type that we need. So instead, insert whenever a composition
857
            // ends since it will already have been committed to the DOM.
858
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
859
                preventInsertFromComposition(event, this.editor);
×
860
                Editor.insertText(this.editor, event.data);
×
861
            }
862

863
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
864
            // so we need avoid repeat isnertText by isComposing === true,
865
            this.isComposing = false;
×
866
        }
867
        this.render();
×
868
    }
869

870
    private onDOMCopy(event: ClipboardEvent) {
871
        const window = AngularEditor.getWindow(this.editor);
×
872
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
873
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
874
            event.preventDefault();
×
875
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
876
        }
877
    }
878

879
    private onDOMCut(event: ClipboardEvent) {
880
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
881
            event.preventDefault();
×
882
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
883
            const { selection } = this.editor;
×
884

885
            if (selection) {
×
886
                AngularEditor.deleteCutData(this.editor);
×
887
            }
888
        }
889
    }
890

891
    private onDOMDragOver(event: DragEvent) {
892
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
893
            // Only when the target is void, call `preventDefault` to signal
894
            // that drops are allowed. Editable content is droppable by
895
            // default, and calling `preventDefault` hides the cursor.
896
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
897

898
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
899
                event.preventDefault();
×
900
            }
901
        }
902
    }
903

904
    private onDOMDragStart(event: DragEvent) {
905
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
906
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
907
            const path = AngularEditor.findPath(this.editor, node);
×
908
            const voidMatch =
909
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
910

911
            // If starting a drag on a void node, make sure it is selected
912
            // so that it shows up in the selection's fragment.
913
            if (voidMatch) {
×
914
                const range = Editor.range(this.editor, path);
×
915
                Transforms.select(this.editor, range);
×
916
            }
917

918
            this.isDraggingInternally = true;
×
919

920
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
921
        }
922
    }
923

924
    private onDOMDrop(event: DragEvent) {
925
        const editor = this.editor;
×
926
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
927
            event.preventDefault();
×
928
            // Keep a reference to the dragged range before updating selection
929
            const draggedRange = editor.selection;
×
930

931
            // Find the range where the drop happened
932
            const range = AngularEditor.findEventRange(editor, event);
×
933
            const data = event.dataTransfer;
×
934

935
            Transforms.select(editor, range);
×
936

937
            if (this.isDraggingInternally) {
×
938
                if (draggedRange) {
×
939
                    Transforms.delete(editor, {
×
940
                        at: draggedRange
941
                    });
942
                }
943

944
                this.isDraggingInternally = false;
×
945
            }
946

947
            AngularEditor.insertData(editor, data);
×
948

949
            // When dragging from another source into the editor, it's possible
950
            // that the current editor does not have focus.
951
            if (!AngularEditor.isFocused(editor)) {
×
952
                AngularEditor.focus(editor);
×
953
            }
954
        }
955
    }
956

957
    private onDOMDragEnd(event: DragEvent) {
958
        if (
×
959
            !this.readonly &&
×
960
            this.isDraggingInternally &&
961
            AngularEditor.hasTarget(this.editor, event.target) &&
962
            !this.isDOMEventHandled(event, this.dragEnd)
963
        ) {
964
            this.isDraggingInternally = false;
×
965
        }
966
    }
967

968
    private onDOMFocus(event: Event) {
969
        if (
2✔
970
            !this.readonly &&
8✔
971
            !this.isUpdatingSelection &&
972
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
973
            !this.isDOMEventHandled(event, this.focus)
974
        ) {
975
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
976
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
977
            this.latestElement = root.activeElement;
2✔
978

979
            // COMPAT: If the editor has nested editable elements, the focus
980
            // can go to them. In Firefox, this must be prevented because it
981
            // results in issues with keyboard navigation. (2017/03/30)
982
            if (IS_FIREFOX && event.target !== el) {
2!
983
                el.focus();
×
984
                return;
×
985
            }
986

987
            IS_FOCUSED.set(this.editor, true);
2✔
988
        }
989
    }
990

991
    private onDOMKeydown(event: KeyboardEvent) {
992
        const editor = this.editor;
×
993
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
994
        const { activeElement } = root;
×
995
        if (
×
996
            !this.readonly &&
×
997
            AngularEditor.hasEditableTarget(editor, event.target) &&
998
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
999
            !this.isComposing &&
1000
            !this.isDOMEventHandled(event, this.keydown)
1001
        ) {
1002
            const nativeEvent = event;
×
1003
            const { selection } = editor;
×
1004

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

1008
            try {
×
1009
                // COMPAT: Since we prevent the default behavior on
1010
                // `beforeinput` events, the browser doesn't think there's ever
1011
                // any history stack to undo or redo, so we have to manage these
1012
                // hotkeys ourselves. (2019/11/06)
1013
                if (Hotkeys.isRedo(nativeEvent)) {
×
1014
                    event.preventDefault();
×
1015

1016
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1017
                        editor.redo();
×
1018
                    }
1019

1020
                    return;
×
1021
                }
1022

1023
                if (Hotkeys.isUndo(nativeEvent)) {
×
1024
                    event.preventDefault();
×
1025

1026
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1027
                        editor.undo();
×
1028
                    }
1029

1030
                    return;
×
1031
                }
1032

1033
                // COMPAT: Certain browsers don't handle the selection updates
1034
                // properly. In Chrome, the selection isn't properly extended.
1035
                // And in Firefox, the selection isn't properly collapsed.
1036
                // (2017/10/17)
1037
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1038
                    event.preventDefault();
×
1039
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1040
                    return;
×
1041
                }
1042

1043
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1044
                    event.preventDefault();
×
1045
                    Transforms.move(editor, { unit: 'line' });
×
1046
                    return;
×
1047
                }
1048

1049
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1050
                    event.preventDefault();
×
1051
                    Transforms.move(editor, {
×
1052
                        unit: 'line',
1053
                        edge: 'focus',
1054
                        reverse: true
1055
                    });
1056
                    return;
×
1057
                }
1058

1059
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1060
                    event.preventDefault();
×
1061
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1062
                    return;
×
1063
                }
1064

1065
                // COMPAT: If a void node is selected, or a zero-width text node
1066
                // adjacent to an inline is selected, we need to handle these
1067
                // hotkeys manually because browsers won't be able to skip over
1068
                // the void node with the zero-width space not being an empty
1069
                // string.
1070
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1071
                    event.preventDefault();
×
1072

1073
                    if (selection && Range.isCollapsed(selection)) {
×
1074
                        Transforms.move(editor, { reverse: !isRTL });
×
1075
                    } else {
1076
                        Transforms.collapse(editor, { edge: 'start' });
×
1077
                    }
1078

1079
                    return;
×
1080
                }
1081

1082
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1083
                    event.preventDefault();
×
1084
                    if (selection && Range.isCollapsed(selection)) {
×
1085
                        Transforms.move(editor, { reverse: isRTL });
×
1086
                    } else {
1087
                        Transforms.collapse(editor, { edge: 'end' });
×
1088
                    }
1089

1090
                    return;
×
1091
                }
1092

1093
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1094
                    event.preventDefault();
×
1095

1096
                    if (selection && Range.isExpanded(selection)) {
×
1097
                        Transforms.collapse(editor, { edge: 'focus' });
×
1098
                    }
1099

1100
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1101
                    return;
×
1102
                }
1103

1104
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1105
                    event.preventDefault();
×
1106

1107
                    if (selection && Range.isExpanded(selection)) {
×
1108
                        Transforms.collapse(editor, { edge: 'focus' });
×
1109
                    }
1110

1111
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1112
                    return;
×
1113
                }
1114

1115
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1116
                // fall back to guessing at the input intention for hotkeys.
1117
                // COMPAT: In iOS, some of these hotkeys are handled in the
1118
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1119
                    // We don't have a core behavior for these, but they change the
1120
                    // DOM if we don't prevent them, so we have to.
1121
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1122
                        event.preventDefault();
×
1123
                        return;
×
1124
                    }
1125

1126
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1127
                        event.preventDefault();
×
1128
                        Editor.insertBreak(editor);
×
1129
                        return;
×
1130
                    }
1131

1132
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1133
                        event.preventDefault();
×
1134

1135
                        if (selection && Range.isExpanded(selection)) {
×
1136
                            Editor.deleteFragment(editor, {
×
1137
                                direction: 'backward'
1138
                            });
1139
                        } else {
1140
                            Editor.deleteBackward(editor);
×
1141
                        }
1142

1143
                        return;
×
1144
                    }
1145

1146
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1147
                        event.preventDefault();
×
1148

1149
                        if (selection && Range.isExpanded(selection)) {
×
1150
                            Editor.deleteFragment(editor, {
×
1151
                                direction: 'forward'
1152
                            });
1153
                        } else {
1154
                            Editor.deleteForward(editor);
×
1155
                        }
1156

1157
                        return;
×
1158
                    }
1159

1160
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1161
                        event.preventDefault();
×
1162

1163
                        if (selection && Range.isExpanded(selection)) {
×
1164
                            Editor.deleteFragment(editor, {
×
1165
                                direction: 'backward'
1166
                            });
1167
                        } else {
1168
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1169
                        }
1170

1171
                        return;
×
1172
                    }
1173

1174
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1175
                        event.preventDefault();
×
1176

1177
                        if (selection && Range.isExpanded(selection)) {
×
1178
                            Editor.deleteFragment(editor, {
×
1179
                                direction: 'forward'
1180
                            });
1181
                        } else {
1182
                            Editor.deleteForward(editor, { unit: 'line' });
×
1183
                        }
1184

1185
                        return;
×
1186
                    }
1187

1188
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1189
                        event.preventDefault();
×
1190

1191
                        if (selection && Range.isExpanded(selection)) {
×
1192
                            Editor.deleteFragment(editor, {
×
1193
                                direction: 'backward'
1194
                            });
1195
                        } else {
1196
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1197
                        }
1198

1199
                        return;
×
1200
                    }
1201

1202
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1203
                        event.preventDefault();
×
1204

1205
                        if (selection && Range.isExpanded(selection)) {
×
1206
                            Editor.deleteFragment(editor, {
×
1207
                                direction: 'forward'
1208
                            });
1209
                        } else {
1210
                            Editor.deleteForward(editor, { unit: 'word' });
×
1211
                        }
1212

1213
                        return;
×
1214
                    }
1215
                } else {
1216
                    if (IS_CHROME || IS_SAFARI) {
×
1217
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1218
                        // an event when deleting backwards in a selected void inline node
1219
                        if (
×
1220
                            selection &&
×
1221
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1222
                            Range.isCollapsed(selection)
1223
                        ) {
1224
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1225
                            if (
×
1226
                                Element.isElement(currentNode) &&
×
1227
                                Editor.isVoid(editor, currentNode) &&
1228
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1229
                            ) {
1230
                                event.preventDefault();
×
1231
                                Editor.deleteBackward(editor, {
×
1232
                                    unit: 'block'
1233
                                });
1234
                                return;
×
1235
                            }
1236
                        }
1237
                    }
1238
                }
1239
            } catch (error) {
1240
                this.editor.onError({
×
1241
                    code: SlateErrorCode.OnDOMKeydownError,
1242
                    nativeError: error
1243
                });
1244
            }
1245
        }
1246
    }
1247

1248
    private onDOMPaste(event: ClipboardEvent) {
1249
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1250
        // fall back to React's `onPaste` here instead.
1251
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1252
        // when "paste without formatting" option is used.
1253
        // This unfortunately needs to be handled with paste events instead.
1254
        if (
×
1255
            !this.isDOMEventHandled(event, this.paste) &&
×
1256
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1257
            !this.readonly &&
1258
            AngularEditor.hasEditableTarget(this.editor, event.target)
1259
        ) {
1260
            event.preventDefault();
×
1261
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1262
        }
1263
    }
1264

1265
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1266
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1267
        // fall back to React's leaky polyfill instead just for it. It
1268
        // only works for the `insertText` input type.
1269
        if (
×
1270
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1271
            !this.readonly &&
1272
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1273
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1274
        ) {
1275
            event.nativeEvent.preventDefault();
×
1276
            try {
×
1277
                const text = event.data;
×
1278
                if (!Range.isCollapsed(this.editor.selection)) {
×
1279
                    Editor.deleteFragment(this.editor);
×
1280
                }
1281
                // just handle Non-IME input
1282
                if (!this.isComposing) {
×
1283
                    Editor.insertText(this.editor, text);
×
1284
                }
1285
            } catch (error) {
1286
                this.editor.onError({
×
1287
                    code: SlateErrorCode.ToNativeSelectionError,
1288
                    nativeError: error
1289
                });
1290
            }
1291
        }
1292
    }
1293

1294
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1295
        if (!handler) {
3✔
1296
            return false;
3✔
1297
        }
1298
        handler(event);
×
1299
        return event.defaultPrevented;
×
1300
    }
1301
    //#endregion
1302

1303
    ngOnDestroy() {
1304
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1305
        this.manualListeners.forEach(manualListener => {
22✔
1306
            manualListener();
462✔
1307
        });
1308
        this.destroy$.complete();
22✔
1309
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1310
    }
1311
}
1312

1313
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1314
    // This was affecting the selection of multiple blocks and dragging behavior,
1315
    // so enabled only if the selection has been collapsed.
1316
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1317
        const leafEl = domRange.startContainer.parentElement!;
×
1318

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

1324
        if (isZeroDimensionRect) {
×
1325
            const leafRect = leafEl.getBoundingClientRect();
×
1326
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1327

1328
            if (leafHasDimensions) {
×
1329
                return;
×
1330
            }
1331
        }
1332

1333
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1334
        scrollIntoView(leafEl, {
×
1335
            scrollMode: 'if-needed'
1336
        });
1337
        delete leafEl.getBoundingClientRect;
×
1338
    }
1339
};
1340

1341
/**
1342
 * Check if the target is inside void and in the editor.
1343
 */
1344

1345
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1346
    let slateNode: Node | null = null;
1✔
1347
    try {
1✔
1348
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1349
    } catch (error) {}
1350
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1351
};
1352

1353
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1354
    return (
2✔
1355
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1356
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1357
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1358
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1359
    );
1360
};
1361

1362
/**
1363
 * remove default insert from composition
1364
 * @param text
1365
 */
1366
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1367
    const types = ['compositionend', 'insertFromComposition'];
×
1368
    if (!types.includes(event.type)) {
×
1369
        return;
×
1370
    }
1371
    const insertText = (event as CompositionEvent).data;
×
1372
    const window = AngularEditor.getWindow(editor);
×
1373
    const domSelection = window.getSelection();
×
1374
    // ensure text node insert composition input text
1375
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1376
        const textNode = domSelection.anchorNode;
×
1377
        textNode.splitText(textNode.length - insertText.length).remove();
×
1378
    }
1379
};
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