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

worktile / slate-angular / eb8b2ec0-91a5-4c2c-a946-ec6b1c90109c

pending completion
eb8b2ec0-91a5-4c2c-a946-ec6b1c90109c

push

circleci

pubuzhixing8
fix(core): get targetRange from dom selection when event can not get nativeTargetRange

129 of 901 branches covered (14.32%)

Branch coverage included in aggregate %.

10 of 10 new or added lines in 1 file covered. (100.0%)

428 of 1544 relevant lines covered (27.72%)

0.86 hits per line

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

12.4
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    ViewChild,
6
    HostBinding,
7
    Renderer2,
8
    ElementRef,
9
    ChangeDetectionStrategy,
10
    OnDestroy,
11
    ChangeDetectorRef,
12
    NgZone,
13
    Injector,
14
    forwardRef,
15
    OnChanges,
16
    SimpleChanges,
17
    AfterViewChecked,
18
    DoCheck
19
} from '@angular/core';
20
import {
21
    NODE_TO_ELEMENT,
22
    IS_FOCUSED,
23
    EDITOR_TO_ELEMENT,
24
    ELEMENT_TO_NODE,
25
    IS_READONLY,
26
    EDITOR_TO_ON_CHANGE,
27
    EDITOR_TO_WINDOW
28
} from '../../utils/weak-maps';
29
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
30
import getDirection from 'direction';
31
import { AngularEditor } from '../../plugins/angular-editor';
32
import {
33
    DOMElement,
34
    DOMNode,
35
    isDOMNode,
36
    DOMStaticRange,
37
    DOMRange,
38
    isDOMElement,
39
    isPlainTextOnlyPaste,
40
    DOMSelection,
41
    getDefaultView
42
} from '../../utils/dom';
43
import { Subject } from 'rxjs';
44
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
45
import Hotkeys from '../../utils/hotkeys';
46
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
47
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
48
import { SlateErrorCode } from '../../types/error';
49
import { SlateStringTemplateComponent } from '../string/template.component';
50
import { NG_VALUE_ACCESSOR } from '@angular/forms';
51
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
52
import { ViewType } from '../../types/view';
53
import { HistoryEditor } from 'slate-history';
54
import { isDecoratorRangeListEqual, check, normalize } from '../../utils';
55
import { SlatePlaceholder } from '../../types/feature';
56
import { restoreDom } from '../../utils/restore-dom';
57

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

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

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

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

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

94
    private initialized: boolean;
95

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

98
    private onChangeCallback: (_: any) => void = () => {};
2✔
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[] = () => [];
2✔
109

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

112
    @Input() isStrictDecorate: boolean = true;
2✔
113

114
    @Input() trackBy: (node: Element) => any = () => null;
2✔
115

116
    @Input() readonly = false;
2✔
117

118
    @Input() placeholder: string;
119

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

137
    //#region DOM attr
138
    @Input() spellCheck = false;
2✔
139
    @Input() autoCorrect = false;
2✔
140
    @Input() autoCapitalize = false;
2✔
141

142
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
2✔
143
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
2✔
144
    @HostBinding('attr.data-gramm') dataGramm = false;
2✔
145

146
    get hasBeforeInputSupport() {
147
        return HAS_BEFORE_INPUT_SUPPORT;
24✔
148
    }
149
    //#endregion
150

151
    @ViewChild('templateComponent', { static: true })
152
    templateComponent: SlateStringTemplateComponent;
153
    @ViewChild('templateComponent', { static: true, read: ElementRef })
154
    templateElementRef: ElementRef<any>;
155

156
    constructor(
157
        public elementRef: ElementRef,
2✔
158
        public renderer2: Renderer2,
2✔
159
        public cdr: ChangeDetectorRef,
2✔
160
        private ngZone: NgZone,
2✔
161
        private injector: Injector
2✔
162
    ) {}
163

164
    ngOnInit() {
165
        this.editor.injector = this.injector;
2✔
166
        this.editor.children = [];
2✔
167
        let window = getDefaultView(this.elementRef.nativeElement);
2✔
168
        EDITOR_TO_WINDOW.set(this.editor, window);
2✔
169
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
2✔
170
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
2✔
171
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
2✔
172
        IS_READONLY.set(this.editor, this.readonly);
2✔
173
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
2✔
174
            this.ngZone.run(() => {
×
175
                this.onChange();
×
176
            });
177
        });
178
        this.ngZone.runOutsideAngular(() => {
2✔
179
            this.initialize();
2✔
180
        });
181
        this.initializeViewContext();
2✔
182
        this.initializeContext();
2✔
183

184
        // remove unused DOM, just keep templateComponent instance
185
        this.templateElementRef.nativeElement.remove();
2✔
186

187
        // add browser class
188
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
2!
189
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
2!
190
    }
191

192
    ngOnChanges(simpleChanges: SimpleChanges) {
193
        if (!this.initialized) {
2✔
194
            return;
2✔
195
        }
196
        const decorateChange = simpleChanges['decorate'];
×
197
        if (decorateChange) {
×
198
            this.forceFlush();
×
199
        }
200
        const placeholderChange = simpleChanges['placeholder'];
×
201
        if (placeholderChange) {
×
202
            this.detectContext();
×
203
        }
204
        const readonlyChange = simpleChanges['readonly'];
×
205
        if (readonlyChange) {
×
206
            IS_READONLY.set(this.editor, this.readonly);
×
207
            this.detectContext();
×
208
            this.toSlateSelection();
×
209
        }
210
    }
211

212
    registerOnChange(fn: any) {
213
        this.onChangeCallback = fn;
2✔
214
    }
215
    registerOnTouched(fn: any) {
216
        this.onTouchedCallback = fn;
2✔
217
    }
218

219
    writeValue(value: Element[]) {
220
        if (value && value.length) {
4✔
221
            if (check(value)) {
2!
222
                this.editor.children = value;
2✔
223
            } else {
224
                this.editor.onError({
×
225
                    code: SlateErrorCode.InvalidValueError,
226
                    name: 'initialize invalid data',
227
                    data: value
228
                });
229
                this.editor.children = normalize(value);
×
230
            }
231
            this.initializeContext();
2✔
232
            this.cdr.markForCheck();
2✔
233
        }
234
    }
235

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

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

274
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
×
275
                return;
×
276
            }
277

278
            const hasDomSelection = domSelection.type !== 'None';
×
279

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

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

293
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
294
            if (
×
295
                hasDomSelection &&
×
296
                hasDomSelectionInEditor &&
297
                selection &&
298
                hasStringTarget(domSelection) &&
299
                Range.equals(AngularEditor.toSlateRange(this.editor, domSelection), selection)
300
            ) {
301
                return;
×
302
            }
303

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

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

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

322
            const newDomRange = selection && AngularEditor.toDOMRange(this.editor, selection);
×
323

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

348
            setTimeout(() => {
×
349
                // COMPAT: In Firefox, it's not enough to create a range, you also need
350
                // to focus the contenteditable element too. (2016/11/16)
351
                if (newDomRange && IS_FIREFOX) {
×
352
                    el.focus();
×
353
                }
354

355
                this.isUpdatingSelection = false;
×
356
            });
357
        } catch (error) {
358
            this.editor.onError({
×
359
                code: SlateErrorCode.ToNativeSelectionError,
360
                nativeError: error
361
            });
362
            this.isUpdatingSelection = false;
×
363
        }
364
    }
365

366
    onChange() {
367
        this.forceFlush();
×
368
        this.onChangeCallback(this.editor.children);
×
369
    }
370

371
    ngAfterViewChecked() {}
372

373
    ngDoCheck() {}
374

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

414
    initializeContext() {
415
        this.context = {
4✔
416
            parent: this.editor,
417
            selection: this.editor.selection,
418
            decorations: this.generateDecorations(),
419
            decorate: this.decorate,
420
            readonly: this.readonly
421
        };
422
    }
423

424
    initializeViewContext() {
425
        this.viewContext = {
2✔
426
            editor: this.editor,
427
            renderElement: this.renderElement,
428
            renderLeaf: this.renderLeaf,
429
            renderText: this.renderText,
430
            trackBy: this.trackBy,
431
            isStrictDecorate: this.isStrictDecorate,
432
            templateComponent: this.templateComponent
433
        };
434
    }
435

436
    detectContext() {
437
        const decorations = this.generateDecorations();
×
438
        if (
×
439
            this.context.selection !== this.editor.selection ||
×
440
            this.context.decorate !== this.decorate ||
441
            this.context.readonly !== this.readonly ||
442
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
443
        ) {
444
            this.context = {
×
445
                parent: this.editor,
446
                selection: this.editor.selection,
447
                decorations: decorations,
448
                decorate: this.decorate,
449
                readonly: this.readonly
450
            };
451
        }
452
    }
453

454
    composePlaceholderDecorate(editor: Editor) {
455
        if (this.placeholderDecorate) {
4!
456
            return this.placeholderDecorate(editor) || [];
×
457
        }
458

459
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
4!
460
            const start = Editor.start(editor, []);
×
461
            return [
×
462
                {
463
                    placeholder: this.placeholder,
464
                    anchor: start,
465
                    focus: start
466
                }
467
            ];
468
        } else {
469
            return [];
4✔
470
        }
471
    }
472

473
    generateDecorations() {
474
        const decorations = this.decorate([this.editor, []]);
4✔
475
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
4!
476
        decorations.push(...placeholderDecorations);
4✔
477
        return decorations;
4✔
478
    }
479

480
    //#region event proxy
481
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
38✔
482
        this.manualListeners.push(
40✔
483
            this.renderer2.listen(target, eventName, (event: Event) => {
484
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
×
485
                if (beforeInputEvent) {
×
486
                    this.onFallbackBeforeInput(beforeInputEvent);
×
487
                }
488
                listener(event);
×
489
            })
490
        );
491
    }
492

493
    private toSlateSelection() {
494
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
×
495
            try {
×
496
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
497
                const { activeElement } = root;
×
498
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
499
                const domSelection = (root as Document).getSelection();
×
500

501
                if (activeElement === el) {
×
502
                    this.latestElement = activeElement;
×
503
                    IS_FOCUSED.set(this.editor, true);
×
504
                } else {
505
                    IS_FOCUSED.delete(this.editor);
×
506
                }
507

508
                if (!domSelection) {
×
509
                    return Transforms.deselect(this.editor);
×
510
                }
511

512
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
×
513
                const hasDomSelectionInEditor =
514
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
×
515
                if (!hasDomSelectionInEditor) {
×
516
                    Transforms.deselect(this.editor);
×
517
                    return;
×
518
                }
519

520
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
521
                // for example, double-click the last cell of the table to select a non-editable DOM
522
                const range = AngularEditor.toSlateRange(this.editor, domSelection);
×
523
                if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
×
524
                    if (!isTargetInsideVoid(this.editor, activeElement)) {
×
525
                        // force adjust DOMSelection
526
                        this.toNativeSelection();
×
527
                    }
528
                } else {
529
                    Transforms.select(this.editor, range);
×
530
                }
531
            } catch (error) {
532
                this.editor.onError({
×
533
                    code: SlateErrorCode.ToSlateSelectionError,
534
                    nativeError: error
535
                });
536
            }
537
        }
538
    }
539

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

618
                // COMPAT: If the selection is expanded, even if the command seems like
619
                // a delete forward/backward command it should delete the selection.
620
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
621
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
622
                    Editor.deleteFragment(editor, { direction });
×
623
                    return;
×
624
                }
625

626
                switch (type) {
×
627
                    case 'deleteByComposition':
628
                    case 'deleteByCut':
629
                    case 'deleteByDrag': {
630
                        Editor.deleteFragment(editor);
×
631
                        break;
×
632
                    }
633

634
                    case 'deleteContent':
635
                    case 'deleteContentForward': {
636
                        Editor.deleteForward(editor);
×
637
                        break;
×
638
                    }
639

640
                    case 'deleteContentBackward': {
641
                        Editor.deleteBackward(editor);
×
642
                        break;
×
643
                    }
644

645
                    case 'deleteEntireSoftLine': {
646
                        Editor.deleteBackward(editor, { unit: 'line' });
×
647
                        Editor.deleteForward(editor, { unit: 'line' });
×
648
                        break;
×
649
                    }
650

651
                    case 'deleteHardLineBackward': {
652
                        Editor.deleteBackward(editor, { unit: 'block' });
×
653
                        break;
×
654
                    }
655

656
                    case 'deleteSoftLineBackward': {
657
                        Editor.deleteBackward(editor, { unit: 'line' });
×
658
                        break;
×
659
                    }
660

661
                    case 'deleteHardLineForward': {
662
                        Editor.deleteForward(editor, { unit: 'block' });
×
663
                        break;
×
664
                    }
665

666
                    case 'deleteSoftLineForward': {
667
                        Editor.deleteForward(editor, { unit: 'line' });
×
668
                        break;
×
669
                    }
670

671
                    case 'deleteWordBackward': {
672
                        Editor.deleteBackward(editor, { unit: 'word' });
×
673
                        break;
×
674
                    }
675

676
                    case 'deleteWordForward': {
677
                        Editor.deleteForward(editor, { unit: 'word' });
×
678
                        break;
×
679
                    }
680

681
                    case 'insertLineBreak':
682
                    case 'insertParagraph': {
683
                        Editor.insertBreak(editor);
×
684
                        break;
×
685
                    }
686

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

722
    private onDOMBlur(event: FocusEvent) {
723
        if (
×
724
            this.readonly ||
×
725
            this.isUpdatingSelection ||
726
            !hasEditableTarget(this.editor, event.target) ||
727
            this.isDOMEventHandled(event, this.blur)
728
        ) {
729
            return;
×
730
        }
731

732
        const window = AngularEditor.getWindow(this.editor);
×
733

734
        // COMPAT: If the current `activeElement` is still the previous
735
        // one, this is due to the window being blurred when the tab
736
        // itself becomes unfocused, so we want to abort early to allow to
737
        // editor to stay focused when the tab becomes focused again.
738
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
739
        if (this.latestElement === root.activeElement) {
×
740
            return;
×
741
        }
742

743
        const { relatedTarget } = event;
×
744
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
745

746
        // COMPAT: The event should be ignored if the focus is returning
747
        // to the editor from an embedded editable element (eg. an <input>
748
        // element inside a void node).
749
        if (relatedTarget === el) {
×
750
            return;
×
751
        }
752

753
        // COMPAT: The event should be ignored if the focus is moving from
754
        // the editor to inside a void node's spacer element.
755
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
756
            return;
×
757
        }
758

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

765
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
766
                return;
×
767
            }
768
        }
769

770
        IS_FOCUSED.delete(this.editor);
×
771
    }
772

773
    private onDOMClick(event: MouseEvent) {
774
        if (
×
775
            !this.readonly &&
×
776
            hasTarget(this.editor, event.target) &&
777
            !this.isDOMEventHandled(event, this.click) &&
778
            isDOMNode(event.target)
779
        ) {
780
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
781
            const path = AngularEditor.findPath(this.editor, node);
×
782
            const start = Editor.start(this.editor, path);
×
783
            const end = Editor.end(this.editor, path);
×
784

785
            const startVoid = Editor.void(this.editor, { at: start });
×
786
            const endVoid = Editor.void(this.editor, { at: end });
×
787

788
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
789
                const range = Editor.range(this.editor, start);
×
790
                Transforms.select(this.editor, range);
×
791
            }
792
        }
793
    }
794

795
    private onDOMCompositionEnd(event: CompositionEvent) {
796
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
797
            Transforms.delete(this.editor);
×
798
        }
799
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
800
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
801
            // aren't correct and never fire the "insertFromComposition"
802
            // type that we need. So instead, insert whenever a composition
803
            // ends since it will already have been committed to the DOM.
804
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
805
                preventInsertFromComposition(event, this.editor);
×
806
                Editor.insertText(this.editor, event.data);
×
807
            }
808

809
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
810
            // so we need avoid repeat isnertText by isComposing === true,
811
            this.isComposing = false;
×
812
        }
813
        this.detectContext();
×
814
        this.cdr.detectChanges();
×
815
    }
816

817
    private onDOMCompositionStart(event: CompositionEvent) {
818
        const { selection } = this.editor;
×
819

820
        if (selection) {
×
821
            // solve the problem of cross node Chinese input
822
            if (Range.isExpanded(selection)) {
×
823
                Editor.deleteFragment(this.editor);
×
824
                this.forceFlush();
×
825
            }
826
        }
827
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
×
828
            this.isComposing = true;
×
829
        }
830
        this.detectContext();
×
831
        this.cdr.detectChanges();
×
832
    }
833

834
    private onDOMCopy(event: ClipboardEvent) {
835
        const window = AngularEditor.getWindow(this.editor);
×
836
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
837
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
838
            event.preventDefault();
×
839
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
840
        }
841
    }
842

843
    private onDOMCut(event: ClipboardEvent) {
844
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
845
            event.preventDefault();
×
846
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
847
            const { selection } = this.editor;
×
848

849
            if (selection) {
×
850
                AngularEditor.deleteCutData(this.editor);
×
851
            }
852
        }
853
    }
854

855
    private onDOMDragOver(event: DragEvent) {
856
        if (hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
857
            // Only when the target is void, call `preventDefault` to signal
858
            // that drops are allowed. Editable content is droppable by
859
            // default, and calling `preventDefault` hides the cursor.
860
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
861

862
            if (Editor.isVoid(this.editor, node)) {
×
863
                event.preventDefault();
×
864
            }
865
        }
866
    }
867

868
    private onDOMDragStart(event: DragEvent) {
869
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
870
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
871
            const path = AngularEditor.findPath(this.editor, node);
×
872
            const voidMatch = Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true });
×
873

874
            // If starting a drag on a void node, make sure it is selected
875
            // so that it shows up in the selection's fragment.
876
            if (voidMatch) {
×
877
                const range = Editor.range(this.editor, path);
×
878
                Transforms.select(this.editor, range);
×
879
            }
880

881
            this.isDraggingInternally = true;
×
882

883
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
884
        }
885
    }
886

887
    private onDOMDrop(event: DragEvent) {
888
        const editor = this.editor;
×
889
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
890
            event.preventDefault();
×
891
            // Keep a reference to the dragged range before updating selection
892
            const draggedRange = editor.selection;
×
893

894
            // Find the range where the drop happened
895
            const range = AngularEditor.findEventRange(editor, event);
×
896
            const data = event.dataTransfer;
×
897

898
            Transforms.select(editor, range);
×
899

900
            if (this.isDraggingInternally) {
×
901
                if (draggedRange) {
×
902
                    Transforms.delete(editor, {
×
903
                        at: draggedRange
904
                    });
905
                }
906

907
                this.isDraggingInternally = false;
×
908
            }
909

910
            AngularEditor.insertData(editor, data);
×
911

912
            // When dragging from another source into the editor, it's possible
913
            // that the current editor does not have focus.
914
            if (!AngularEditor.isFocused(editor)) {
×
915
                AngularEditor.focus(editor);
×
916
            }
917
        }
918
    }
919

920
    private onDOMDragEnd(event: DragEvent) {
921
        if (
×
922
            !this.readonly &&
×
923
            this.isDraggingInternally &&
924
            hasTarget(this.editor, event.target) &&
925
            !this.isDOMEventHandled(event, this.dragEnd)
926
        ) {
927
            this.isDraggingInternally = false;
×
928
        }
929
    }
930

931
    private onDOMFocus(event: Event) {
932
        if (
×
933
            !this.readonly &&
×
934
            !this.isUpdatingSelection &&
935
            hasEditableTarget(this.editor, event.target) &&
936
            !this.isDOMEventHandled(event, this.focus)
937
        ) {
938
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
939
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
940
            this.latestElement = root.activeElement;
×
941

942
            // COMPAT: If the editor has nested editable elements, the focus
943
            // can go to them. In Firefox, this must be prevented because it
944
            // results in issues with keyboard navigation. (2017/03/30)
945
            if (IS_FIREFOX && event.target !== el) {
×
946
                el.focus();
×
947
                return;
×
948
            }
949

950
            IS_FOCUSED.set(this.editor, true);
×
951
        }
952
    }
953

954
    private onDOMKeydown(event: KeyboardEvent) {
955
        const editor = this.editor;
×
956
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
957
        const { activeElement } = root;
×
958
        if (
×
959
            !this.readonly &&
×
960
            hasEditableTarget(editor, event.target) &&
961
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
962
            !this.isComposing &&
963
            !this.isDOMEventHandled(event, this.keydown)
964
        ) {
965
            const nativeEvent = event;
×
966
            const { selection } = editor;
×
967

968
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
969
            const isRTL = getDirection(Node.string(element)) === 'rtl';
×
970

971
            try {
×
972
                // COMPAT: Since we prevent the default behavior on
973
                // `beforeinput` events, the browser doesn't think there's ever
974
                // any history stack to undo or redo, so we have to manage these
975
                // hotkeys ourselves. (2019/11/06)
976
                if (Hotkeys.isRedo(nativeEvent)) {
×
977
                    event.preventDefault();
×
978

979
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
980
                        editor.redo();
×
981
                    }
982

983
                    return;
×
984
                }
985

986
                if (Hotkeys.isUndo(nativeEvent)) {
×
987
                    event.preventDefault();
×
988

989
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
990
                        editor.undo();
×
991
                    }
992

993
                    return;
×
994
                }
995

996
                // COMPAT: Certain browsers don't handle the selection updates
997
                // properly. In Chrome, the selection isn't properly extended.
998
                // And in Firefox, the selection isn't properly collapsed.
999
                // (2017/10/17)
1000
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1001
                    event.preventDefault();
×
1002
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1003
                    return;
×
1004
                }
1005

1006
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1007
                    event.preventDefault();
×
1008
                    Transforms.move(editor, { unit: 'line' });
×
1009
                    return;
×
1010
                }
1011

1012
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1013
                    event.preventDefault();
×
1014
                    Transforms.move(editor, {
×
1015
                        unit: 'line',
1016
                        edge: 'focus',
1017
                        reverse: true
1018
                    });
1019
                    return;
×
1020
                }
1021

1022
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1023
                    event.preventDefault();
×
1024
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1025
                    return;
×
1026
                }
1027

1028
                // COMPAT: If a void node is selected, or a zero-width text node
1029
                // adjacent to an inline is selected, we need to handle these
1030
                // hotkeys manually because browsers won't be able to skip over
1031
                // the void node with the zero-width space not being an empty
1032
                // string.
1033
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1034
                    event.preventDefault();
×
1035

1036
                    if (selection && Range.isCollapsed(selection)) {
×
1037
                        Transforms.move(editor, { reverse: !isRTL });
×
1038
                    } else {
1039
                        Transforms.collapse(editor, { edge: 'start' });
×
1040
                    }
1041

1042
                    return;
×
1043
                }
1044

1045
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1046
                    event.preventDefault();
×
1047

1048
                    if (selection && Range.isCollapsed(selection)) {
×
1049
                        Transforms.move(editor, { reverse: isRTL });
×
1050
                    } else {
1051
                        Transforms.collapse(editor, { edge: 'end' });
×
1052
                    }
1053

1054
                    return;
×
1055
                }
1056

1057
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1058
                    event.preventDefault();
×
1059

1060
                    if (selection && Range.isExpanded(selection)) {
×
1061
                        Transforms.collapse(editor, { edge: 'focus' });
×
1062
                    }
1063

1064
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1065
                    return;
×
1066
                }
1067

1068
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1069
                    event.preventDefault();
×
1070

1071
                    if (selection && Range.isExpanded(selection)) {
×
1072
                        Transforms.collapse(editor, { edge: 'focus' });
×
1073
                    }
1074

1075
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1076
                    return;
×
1077
                }
1078

1079
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1080
                // fall back to guessing at the input intention for hotkeys.
1081
                // COMPAT: In iOS, some of these hotkeys are handled in the
1082
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1083
                    // We don't have a core behavior for these, but they change the
1084
                    // DOM if we don't prevent them, so we have to.
1085
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1086
                        event.preventDefault();
×
1087
                        return;
×
1088
                    }
1089

1090
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1091
                        event.preventDefault();
×
1092
                        Editor.insertBreak(editor);
×
1093
                        return;
×
1094
                    }
1095

1096
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1097
                        event.preventDefault();
×
1098

1099
                        if (selection && Range.isExpanded(selection)) {
×
1100
                            Editor.deleteFragment(editor, {
×
1101
                                direction: 'backward'
1102
                            });
1103
                        } else {
1104
                            Editor.deleteBackward(editor);
×
1105
                        }
1106

1107
                        return;
×
1108
                    }
1109

1110
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1111
                        event.preventDefault();
×
1112

1113
                        if (selection && Range.isExpanded(selection)) {
×
1114
                            Editor.deleteFragment(editor, {
×
1115
                                direction: 'forward'
1116
                            });
1117
                        } else {
1118
                            Editor.deleteForward(editor);
×
1119
                        }
1120

1121
                        return;
×
1122
                    }
1123

1124
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1125
                        event.preventDefault();
×
1126

1127
                        if (selection && Range.isExpanded(selection)) {
×
1128
                            Editor.deleteFragment(editor, {
×
1129
                                direction: 'backward'
1130
                            });
1131
                        } else {
1132
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1133
                        }
1134

1135
                        return;
×
1136
                    }
1137

1138
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1139
                        event.preventDefault();
×
1140

1141
                        if (selection && Range.isExpanded(selection)) {
×
1142
                            Editor.deleteFragment(editor, {
×
1143
                                direction: 'forward'
1144
                            });
1145
                        } else {
1146
                            Editor.deleteForward(editor, { unit: 'line' });
×
1147
                        }
1148

1149
                        return;
×
1150
                    }
1151

1152
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1153
                        event.preventDefault();
×
1154

1155
                        if (selection && Range.isExpanded(selection)) {
×
1156
                            Editor.deleteFragment(editor, {
×
1157
                                direction: 'backward'
1158
                            });
1159
                        } else {
1160
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1161
                        }
1162

1163
                        return;
×
1164
                    }
1165

1166
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1167
                        event.preventDefault();
×
1168

1169
                        if (selection && Range.isExpanded(selection)) {
×
1170
                            Editor.deleteFragment(editor, {
×
1171
                                direction: 'forward'
1172
                            });
1173
                        } else {
1174
                            Editor.deleteForward(editor, { unit: 'word' });
×
1175
                        }
1176

1177
                        return;
×
1178
                    }
1179
                } else {
1180
                    if (IS_CHROME || IS_SAFARI) {
×
1181
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1182
                        // an event when deleting backwards in a selected void inline node
1183
                        if (
×
1184
                            selection &&
×
1185
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1186
                            Range.isCollapsed(selection)
1187
                        ) {
1188
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1189
                            if (
×
1190
                                Element.isElement(currentNode) &&
×
1191
                                Editor.isVoid(editor, currentNode) &&
1192
                                Editor.isInline(editor, currentNode)
1193
                            ) {
1194
                                event.preventDefault();
×
1195
                                Editor.deleteBackward(editor, {
×
1196
                                    unit: 'block'
1197
                                });
1198
                                return;
×
1199
                            }
1200
                        }
1201
                    }
1202
                }
1203
            } catch (error) {
1204
                this.editor.onError({
×
1205
                    code: SlateErrorCode.OnDOMKeydownError,
1206
                    nativeError: error
1207
                });
1208
            }
1209
        }
1210
    }
1211

1212
    private onDOMPaste(event: ClipboardEvent) {
1213
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1214
        // fall back to React's `onPaste` here instead.
1215
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1216
        // when "paste without formatting" option is used.
1217
        // This unfortunately needs to be handled with paste events instead.
1218
        if (
×
1219
            !this.isDOMEventHandled(event, this.paste) &&
×
1220
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1221
            !this.readonly &&
1222
            hasEditableTarget(this.editor, event.target)
1223
        ) {
1224
            event.preventDefault();
×
1225
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1226
        }
1227
    }
1228

1229
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1230
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1231
        // fall back to React's leaky polyfill instead just for it. It
1232
        // only works for the `insertText` input type.
1233
        if (
×
1234
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1235
            !this.readonly &&
1236
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1237
            hasEditableTarget(this.editor, event.nativeEvent.target)
1238
        ) {
1239
            event.nativeEvent.preventDefault();
×
1240
            try {
×
1241
                const text = event.data;
×
1242
                if (!Range.isCollapsed(this.editor.selection)) {
×
1243
                    Editor.deleteFragment(this.editor);
×
1244
                }
1245
                // just handle Non-IME input
1246
                if (!this.isComposing) {
×
1247
                    Editor.insertText(this.editor, text);
×
1248
                }
1249
            } catch (error) {
1250
                this.editor.onError({
×
1251
                    code: SlateErrorCode.ToNativeSelectionError,
1252
                    nativeError: error
1253
                });
1254
            }
1255
        }
1256
    }
1257

1258
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1259
        if (!handler) {
×
1260
            return false;
×
1261
        }
1262
        handler(event);
×
1263
        return event.defaultPrevented;
×
1264
    }
1265
    //#endregion
1266

1267
    ngOnDestroy() {
1268
        NODE_TO_ELEMENT.delete(this.editor);
1✔
1269
        this.manualListeners.forEach(manualListener => {
1✔
1270
            manualListener();
20✔
1271
        });
1272
        this.destroy$.complete();
1✔
1273
        EDITOR_TO_ON_CHANGE.delete(this.editor);
1✔
1274
    }
1275
}
1276

1277
/**
1278
 * Check if the target is editable and in the editor.
1279
 */
1280

1281
const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1282
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
×
1283
};
1284

1285
/**
1286
 * Check if two DOM range objects are equal.
1287
 */
1288
const isRangeEqual = (a: DOMRange, b: DOMRange) => {
1✔
1289
    return (
×
1290
        (a.startContainer === b.startContainer &&
×
1291
            a.startOffset === b.startOffset &&
1292
            a.endContainer === b.endContainer &&
1293
            a.endOffset === b.endOffset) ||
1294
        (a.startContainer === b.endContainer &&
1295
            a.startOffset === b.endOffset &&
1296
            a.endContainer === b.startContainer &&
1297
            a.endOffset === b.startOffset)
1298
    );
1299
};
1300

1301
/**
1302
 * Check if the target is in the editor.
1303
 */
1304

1305
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1306
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
×
1307
};
1308

1309
/**
1310
 * Check if the target is inside void and in the editor.
1311
 */
1312

1313
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1314
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
×
1315
    return Editor.isVoid(editor, slateNode);
×
1316
};
1317

1318
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1319
    return (
×
1320
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
×
1321
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1322
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1323
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1324
    );
1325
};
1326

1327
/**
1328
 * remove default insert from composition
1329
 * @param text
1330
 */
1331
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1332
    const types = ['compositionend', 'insertFromComposition'];
×
1333
    if (!types.includes(event.type)) {
×
1334
        return;
×
1335
    }
1336
    const insertText = (event as CompositionEvent).data;
×
1337
    const window = AngularEditor.getWindow(editor);
×
1338
    const domSelection = window.getSelection();
×
1339
    // ensure text node insert composition input text
1340
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1341
        const textNode = domSelection.anchorNode;
×
1342
        textNode.splitText(textNode.length - insertText.length).remove();
×
1343
    }
1344
};
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