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

worktile / slate-angular / 3e573882-9bed-4284-899f-bf81a8896755

pending completion
3e573882-9bed-4284-899f-bf81a8896755

Pull #226

circleci

pubuzhixing8
feat(core): handle select all
Pull Request #226: Android input handing

268 of 894 branches covered (29.98%)

Branch coverage included in aggregate %.

58 of 58 new or added lines in 3 files covered. (100.0%)

686 of 1538 relevant lines covered (44.6%)

29.41 hits per line

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

22.21
/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
    IS_RESTORING
29
} from '../../utils/weak-maps';
30
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
31
import getDirection from 'direction';
32
import { AngularEditor } from '../../plugins/angular-editor';
33
import {
34
    DOMElement,
35
    DOMNode,
36
    isDOMNode,
37
    DOMStaticRange,
38
    DOMRange,
39
    isDOMElement,
40
    isPlainTextOnlyPaste,
41
    DOMSelection,
42
    getDefaultView
43
} from '../../utils/dom';
44
import { Subject } from 'rxjs';
45
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
46
import Hotkeys from '../../utils/hotkeys';
47
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
48
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
49
import { SlateErrorCode } from '../../types/error';
50
import { SlateStringTemplateComponent } from '../string/template.component';
51
import { NG_VALUE_ACCESSOR } from '@angular/forms';
52
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
53
import { ViewType } from '../../types/view';
54
import { HistoryEditor } from 'slate-history';
55
import { isDecoratorRangeListEqual, check, normalize } from '../../utils';
56
import { SlatePlaceholder } from '../../types/feature';
57
import { restoreDom } from '../../utils/restore-dom';
58

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

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

86
    private destroy$ = new Subject();
14✔
87

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

93
    protected manualListeners: (() => void)[] = [];
14✔
94

95
    private initialized: boolean;
96

97
    private onTouchedCallback: () => void = () => {};
14✔
98

99
    private onChangeCallback: (_: any) => void = () => {};
14✔
100

101
    @Input() editor: AngularEditor;
102

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

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

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

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

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

113
    @Input() isStrictDecorate: boolean = true;
14✔
114

115
    @Input() trackBy: (node: Element) => any = () => null;
196✔
116

117
    @Input() readonly = false;
14✔
118

119
    @Input() placeholder: string;
120

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

281
            // If the DOM selection is properly unset, we're done.
282
            if (!selection && !hasDomSelection) {
×
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)!;
×
289
            let hasDomSelectionInEditor = false;
×
290
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
×
291
                hasDomSelectionInEditor = true;
×
292
            }
293

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

305
            // prevent updating native selection when active element is void element
306
            if (isTargetInsideVoid(this.editor, activeElement)) {
×
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)) {
×
315
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection);
×
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);
×
321
            this.isUpdatingSelection = true;
×
322

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

325
            if (newDomRange) {
×
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)) {
×
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(
×
339
                        newDomRange.startContainer,
340
                        newDomRange.startOffset,
341
                        newDomRange.endContainer,
342
                        newDomRange.endOffset
343
                    );
344
                }
345
            } else {
346
                domSelection.removeAllRanges();
×
347
            }
348

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

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

366
    onChange() {
367
        console.log(JSON.stringify(this.editor.operations));
8✔
368
        console.log(JSON.stringify(this.editor.children));
8✔
369
        this.forceFlush();
8✔
370
        this.onChangeCallback(this.editor.children);
8✔
371
    }
372

373
    ngAfterViewChecked() {}
374

375
    ngDoCheck() {}
376

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

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

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

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

456
    composePlaceholderDecorate(editor: Editor) {
457
        if (this.placeholderDecorate) {
41!
458
            return this.placeholderDecorate(editor) || [];
×
459
        }
460

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

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

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

495
    private toSlateSelection() {
496
        console.log('toSlateSelection');
1✔
497
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
1!
498
            try {
×
499
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
500
                const { activeElement } = root;
×
501
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
502
                const domSelection = (root as Document).getSelection();
×
503

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

511
                if (!domSelection) {
×
512
                    return Transforms.deselect(this.editor);
×
513
                }
514

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

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

543
    private onDOMBeforeInput(
544
        event: Event & {
545
            inputType: string;
546
            isComposing: boolean;
547
            data: string | null;
548
            dataTransfer: DataTransfer | null;
549
            getTargetRanges(): DOMStaticRange[];
550
        }
551
    ) {
552
        const editor = this.editor;
×
553
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
554
        const { activeElement } = root;
×
555
        const { selection } = editor;
×
556
        const { inputType: type } = event;
×
557
        const data = event.dataTransfer || event.data || undefined;
×
558
        console.log(`type: ${type}`, data && data.toString());
×
559
        if (IS_ANDROID) {
×
560
            if (type === 'insertCompositionText') {
×
561
                if (data && data.toString().includes('\n')) {
×
562
                    restoreDom(editor, () => {
×
563
                        Editor.insertBreak(editor);
×
564
                    });
565
                } else {
566
                    let [nativeTargetRange] = event.getTargetRanges();
×
567
                    if (nativeTargetRange) {
×
568
                        const targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange);
×
569
                        if (data) {
×
570
                            restoreDom(editor, () => {
×
571
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
572
                            });
573
                        } else {
574
                            restoreDom(editor, () => {
×
575
                                Transforms.delete(editor, { at: targetRange });
×
576
                            });
577
                        }
578
                    }
579
                }
580
                return;
×
581
            }
582
            if (type === 'deleteContentBackward') {
×
583
                let [nativeTargetRange] = event.getTargetRanges();
×
584
                const targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange);
×
585
                // Gboard can not prevent default action, so must use restoreDom, Sougou Keyboard can prevent default action.
586
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
587
                if (!Range.isCollapsed(targetRange)) {
×
588
                    restoreDom(editor, () => {
×
589
                        Transforms.delete(editor, { at: targetRange });
×
590
                    });
591
                    return;
×
592
                }
593
            }
594
        }
595
        if (
×
596
            !this.readonly &&
×
597
            hasEditableTarget(editor, event.target) &&
598
            !isTargetInsideVoid(editor, activeElement) &&
599
            !this.isDOMEventHandled(event, this.beforeInput)
600
        ) {
601
            try {
×
602
                event.preventDefault();
×
603

604
                // COMPAT: If the selection is expanded, even if the command seems like
605
                // a delete forward/backward command it should delete the selection.
606
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
607
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
608
                    Editor.deleteFragment(editor, { direction });
×
609
                    return;
×
610
                }
611

612
                switch (type) {
×
613
                    case 'deleteByComposition':
614
                    case 'deleteByCut':
615
                    case 'deleteByDrag': {
616
                        Editor.deleteFragment(editor);
×
617
                        break;
×
618
                    }
619

620
                    case 'deleteContent':
621
                    case 'deleteContentForward': {
622
                        Editor.deleteForward(editor);
×
623
                        break;
×
624
                    }
625

626
                    case 'deleteContentBackward': {
627
                        Editor.deleteBackward(editor);
×
628
                        break;
×
629
                    }
630

631
                    case 'deleteEntireSoftLine': {
632
                        Editor.deleteBackward(editor, { unit: 'line' });
×
633
                        Editor.deleteForward(editor, { unit: 'line' });
×
634
                        break;
×
635
                    }
636

637
                    case 'deleteHardLineBackward': {
638
                        Editor.deleteBackward(editor, { unit: 'block' });
×
639
                        break;
×
640
                    }
641

642
                    case 'deleteSoftLineBackward': {
643
                        Editor.deleteBackward(editor, { unit: 'line' });
×
644
                        break;
×
645
                    }
646

647
                    case 'deleteHardLineForward': {
648
                        Editor.deleteForward(editor, { unit: 'block' });
×
649
                        break;
×
650
                    }
651

652
                    case 'deleteSoftLineForward': {
653
                        Editor.deleteForward(editor, { unit: 'line' });
×
654
                        break;
×
655
                    }
656

657
                    case 'deleteWordBackward': {
658
                        Editor.deleteBackward(editor, { unit: 'word' });
×
659
                        break;
×
660
                    }
661

662
                    case 'deleteWordForward': {
663
                        Editor.deleteForward(editor, { unit: 'word' });
×
664
                        break;
×
665
                    }
666

667
                    case 'insertLineBreak':
668
                    case 'insertParagraph': {
669
                        Editor.insertBreak(editor);
×
670
                        break;
×
671
                    }
672

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

708
    private onDOMBlur(event: FocusEvent) {
709
        if (
×
710
            this.readonly ||
×
711
            this.isUpdatingSelection ||
712
            !hasEditableTarget(this.editor, event.target) ||
713
            this.isDOMEventHandled(event, this.blur)
714
        ) {
715
            return;
×
716
        }
717

718
        const window = AngularEditor.getWindow(this.editor);
×
719

720
        // COMPAT: If the current `activeElement` is still the previous
721
        // one, this is due to the window being blurred when the tab
722
        // itself becomes unfocused, so we want to abort early to allow to
723
        // editor to stay focused when the tab becomes focused again.
724
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
725
        if (this.latestElement === root.activeElement) {
×
726
            return;
×
727
        }
728

729
        const { relatedTarget } = event;
×
730
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
731

732
        // COMPAT: The event should be ignored if the focus is returning
733
        // to the editor from an embedded editable element (eg. an <input>
734
        // element inside a void node).
735
        if (relatedTarget === el) {
×
736
            return;
×
737
        }
738

739
        // COMPAT: The event should be ignored if the focus is moving from
740
        // the editor to inside a void node's spacer element.
741
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
742
            return;
×
743
        }
744

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

751
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
752
                return;
×
753
            }
754
        }
755

756
        IS_FOCUSED.delete(this.editor);
×
757
    }
758

759
    private onDOMClick(event: MouseEvent) {
760
        if (
×
761
            !this.readonly &&
×
762
            hasTarget(this.editor, event.target) &&
763
            !this.isDOMEventHandled(event, this.click) &&
764
            isDOMNode(event.target)
765
        ) {
766
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
767
            const path = AngularEditor.findPath(this.editor, node);
×
768
            const start = Editor.start(this.editor, path);
×
769
            const end = Editor.end(this.editor, path);
×
770

771
            const startVoid = Editor.void(this.editor, { at: start });
×
772
            const endVoid = Editor.void(this.editor, { at: end });
×
773

774
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
775
                const range = Editor.range(this.editor, start);
×
776
                Transforms.select(this.editor, range);
×
777
            }
778
        }
779
    }
780

781
    private onDOMCompositionEnd(event: CompositionEvent) {
782
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
783
            Transforms.delete(this.editor);
×
784
        }
785
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
786
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
787
            // aren't correct and never fire the "insertFromComposition"
788
            // type that we need. So instead, insert whenever a composition
789
            // ends since it will already have been committed to the DOM.
790
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
791
                preventInsertFromComposition(event, this.editor);
×
792
                Editor.insertText(this.editor, event.data);
×
793
            }
794

795
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
796
            // so we need avoid repeat isnertText by isComposing === true,
797
            this.isComposing = false;
×
798
        }
799
        this.detectContext();
×
800
        this.cdr.detectChanges();
×
801
    }
802

803
    private onDOMCompositionStart(event: CompositionEvent) {
804
        const { selection } = this.editor;
1✔
805

806
        if (selection) {
1!
807
            // solve the problem of cross node Chinese input
808
            if (Range.isExpanded(selection)) {
×
809
                Editor.deleteFragment(this.editor);
×
810
                this.forceFlush();
×
811
            }
812
        }
813
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
814
            this.isComposing = true;
1✔
815
        }
816
        this.detectContext();
1✔
817
        this.cdr.detectChanges();
1✔
818
    }
819

820
    private onDOMCopy(event: ClipboardEvent) {
821
        const window = AngularEditor.getWindow(this.editor);
×
822
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
823
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
824
            event.preventDefault();
×
825
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
826
        }
827
    }
828

829
    private onDOMCut(event: ClipboardEvent) {
830
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
831
            event.preventDefault();
×
832
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
833
            const { selection } = this.editor;
×
834

835
            if (selection) {
×
836
                AngularEditor.deleteCutData(this.editor);
×
837
            }
838
        }
839
    }
840

841
    private onDOMDragOver(event: DragEvent) {
842
        if (hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
843
            // Only when the target is void, call `preventDefault` to signal
844
            // that drops are allowed. Editable content is droppable by
845
            // default, and calling `preventDefault` hides the cursor.
846
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
847

848
            if (Editor.isVoid(this.editor, node)) {
×
849
                event.preventDefault();
×
850
            }
851
        }
852
    }
853

854
    private onDOMDragStart(event: DragEvent) {
855
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
856
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
857
            const path = AngularEditor.findPath(this.editor, node);
×
858
            const voidMatch = Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true });
×
859

860
            // If starting a drag on a void node, make sure it is selected
861
            // so that it shows up in the selection's fragment.
862
            if (voidMatch) {
×
863
                const range = Editor.range(this.editor, path);
×
864
                Transforms.select(this.editor, range);
×
865
            }
866

867
            this.isDraggingInternally = true;
×
868

869
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
870
        }
871
    }
872

873
    private onDOMDrop(event: DragEvent) {
874
        const editor = this.editor;
×
875
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
876
            event.preventDefault();
×
877
            // Keep a reference to the dragged range before updating selection
878
            const draggedRange = editor.selection;
×
879

880
            // Find the range where the drop happened
881
            const range = AngularEditor.findEventRange(editor, event);
×
882
            const data = event.dataTransfer;
×
883

884
            Transforms.select(editor, range);
×
885

886
            if (this.isDraggingInternally) {
×
887
                if (draggedRange) {
×
888
                    Transforms.delete(editor, {
×
889
                        at: draggedRange
890
                    });
891
                }
892

893
                this.isDraggingInternally = false;
×
894
            }
895

896
            AngularEditor.insertData(editor, data);
×
897

898
            // When dragging from another source into the editor, it's possible
899
            // that the current editor does not have focus.
900
            if (!AngularEditor.isFocused(editor)) {
×
901
                AngularEditor.focus(editor);
×
902
            }
903
        }
904
    }
905

906
    private onDOMDragEnd(event: DragEvent) {
907
        if (
×
908
            !this.readonly &&
×
909
            this.isDraggingInternally &&
910
            hasTarget(this.editor, event.target) &&
911
            !this.isDOMEventHandled(event, this.dragEnd)
912
        ) {
913
            this.isDraggingInternally = false;
×
914
        }
915
    }
916

917
    private onDOMFocus(event: Event) {
918
        if (
1✔
919
            !this.readonly &&
4✔
920
            !this.isUpdatingSelection &&
921
            hasEditableTarget(this.editor, event.target) &&
922
            !this.isDOMEventHandled(event, this.focus)
923
        ) {
924
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
925
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
926
            this.latestElement = root.activeElement;
1✔
927

928
            // COMPAT: If the editor has nested editable elements, the focus
929
            // can go to them. In Firefox, this must be prevented because it
930
            // results in issues with keyboard navigation. (2017/03/30)
931
            if (IS_FIREFOX && event.target !== el) {
1!
932
                el.focus();
×
933
                return;
×
934
            }
935

936
            IS_FOCUSED.set(this.editor, true);
1✔
937
        }
938
    }
939

940
    private onDOMKeydown(event: KeyboardEvent) {
941
        const editor = this.editor;
×
942
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
943
        const { activeElement } = root;
×
944
        if (
×
945
            !this.readonly &&
×
946
            hasEditableTarget(editor, event.target) &&
947
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
948
            !this.isComposing &&
949
            !this.isDOMEventHandled(event, this.keydown)
950
        ) {
951
            const nativeEvent = event;
×
952
            const { selection } = editor;
×
953

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

957
            try {
×
958
                // COMPAT: Since we prevent the default behavior on
959
                // `beforeinput` events, the browser doesn't think there's ever
960
                // any history stack to undo or redo, so we have to manage these
961
                // hotkeys ourselves. (2019/11/06)
962
                if (Hotkeys.isRedo(nativeEvent)) {
×
963
                    event.preventDefault();
×
964

965
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
966
                        editor.redo();
×
967
                    }
968

969
                    return;
×
970
                }
971

972
                if (Hotkeys.isUndo(nativeEvent)) {
×
973
                    event.preventDefault();
×
974

975
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
976
                        editor.undo();
×
977
                    }
978

979
                    return;
×
980
                }
981

982
                // COMPAT: Certain browsers don't handle the selection updates
983
                // properly. In Chrome, the selection isn't properly extended.
984
                // And in Firefox, the selection isn't properly collapsed.
985
                // (2017/10/17)
986
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
987
                    event.preventDefault();
×
988
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
989
                    return;
×
990
                }
991

992
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
993
                    event.preventDefault();
×
994
                    Transforms.move(editor, { unit: 'line' });
×
995
                    return;
×
996
                }
997

998
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
999
                    event.preventDefault();
×
1000
                    Transforms.move(editor, {
×
1001
                        unit: 'line',
1002
                        edge: 'focus',
1003
                        reverse: true
1004
                    });
1005
                    return;
×
1006
                }
1007

1008
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1009
                    event.preventDefault();
×
1010
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1011
                    return;
×
1012
                }
1013

1014
                // COMPAT: If a void node is selected, or a zero-width text node
1015
                // adjacent to an inline is selected, we need to handle these
1016
                // hotkeys manually because browsers won't be able to skip over
1017
                // the void node with the zero-width space not being an empty
1018
                // string.
1019
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1020
                    event.preventDefault();
×
1021

1022
                    if (selection && Range.isCollapsed(selection)) {
×
1023
                        Transforms.move(editor, { reverse: !isRTL });
×
1024
                    } else {
1025
                        Transforms.collapse(editor, { edge: 'start' });
×
1026
                    }
1027

1028
                    return;
×
1029
                }
1030

1031
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1032
                    event.preventDefault();
×
1033

1034
                    if (selection && Range.isCollapsed(selection)) {
×
1035
                        Transforms.move(editor, { reverse: isRTL });
×
1036
                    } else {
1037
                        Transforms.collapse(editor, { edge: 'end' });
×
1038
                    }
1039

1040
                    return;
×
1041
                }
1042

1043
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1044
                    event.preventDefault();
×
1045

1046
                    if (selection && Range.isExpanded(selection)) {
×
1047
                        Transforms.collapse(editor, { edge: 'focus' });
×
1048
                    }
1049

1050
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1051
                    return;
×
1052
                }
1053

1054
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1055
                    event.preventDefault();
×
1056

1057
                    if (selection && Range.isExpanded(selection)) {
×
1058
                        Transforms.collapse(editor, { edge: 'focus' });
×
1059
                    }
1060

1061
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1062
                    return;
×
1063
                }
1064

1065
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1066
                // fall back to guessing at the input intention for hotkeys.
1067
                // COMPAT: In iOS, some of these hotkeys are handled in the
1068
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1069
                    // We don't have a core behavior for these, but they change the
1070
                    // DOM if we don't prevent them, so we have to.
1071
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1072
                        event.preventDefault();
×
1073
                        return;
×
1074
                    }
1075

1076
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1077
                        event.preventDefault();
×
1078
                        Editor.insertBreak(editor);
×
1079
                        return;
×
1080
                    }
1081

1082
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1083
                        event.preventDefault();
×
1084

1085
                        if (selection && Range.isExpanded(selection)) {
×
1086
                            Editor.deleteFragment(editor, {
×
1087
                                direction: 'backward'
1088
                            });
1089
                        } else {
1090
                            Editor.deleteBackward(editor);
×
1091
                        }
1092

1093
                        return;
×
1094
                    }
1095

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

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

1107
                        return;
×
1108
                    }
1109

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

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

1121
                        return;
×
1122
                    }
1123

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

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

1135
                        return;
×
1136
                    }
1137

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

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

1149
                        return;
×
1150
                    }
1151

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

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

1163
                        return;
×
1164
                    }
1165
                } else {
1166
                    if (IS_CHROME || IS_SAFARI) {
×
1167
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1168
                        // an event when deleting backwards in a selected void inline node
1169
                        if (
×
1170
                            selection &&
×
1171
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1172
                            Range.isCollapsed(selection)
1173
                        ) {
1174
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1175
                            if (
×
1176
                                Element.isElement(currentNode) &&
×
1177
                                Editor.isVoid(editor, currentNode) &&
1178
                                Editor.isInline(editor, currentNode)
1179
                            ) {
1180
                                event.preventDefault();
×
1181
                                Editor.deleteBackward(editor, {
×
1182
                                    unit: 'block'
1183
                                });
1184
                                return;
×
1185
                            }
1186
                        }
1187
                    }
1188
                }
1189
            } catch (error) {
1190
                this.editor.onError({
×
1191
                    code: SlateErrorCode.OnDOMKeydownError,
1192
                    nativeError: error
1193
                });
1194
            }
1195
        }
1196
    }
1197

1198
    private onDOMPaste(event: ClipboardEvent) {
1199
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1200
        // fall back to React's `onPaste` here instead.
1201
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1202
        // when "paste without formatting" option is used.
1203
        // This unfortunately needs to be handled with paste events instead.
1204
        if (
×
1205
            !this.isDOMEventHandled(event, this.paste) &&
×
1206
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1207
            !this.readonly &&
1208
            hasEditableTarget(this.editor, event.target)
1209
        ) {
1210
            event.preventDefault();
×
1211
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1212
        }
1213
    }
1214

1215
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1216
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1217
        // fall back to React's leaky polyfill instead just for it. It
1218
        // only works for the `insertText` input type.
1219
        if (
×
1220
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1221
            !this.readonly &&
1222
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1223
            hasEditableTarget(this.editor, event.nativeEvent.target)
1224
        ) {
1225
            event.nativeEvent.preventDefault();
×
1226
            try {
×
1227
                const text = event.data;
×
1228
                if (!Range.isCollapsed(this.editor.selection)) {
×
1229
                    Editor.deleteFragment(this.editor);
×
1230
                }
1231
                // just handle Non-IME input
1232
                if (!this.isComposing) {
×
1233
                    Editor.insertText(this.editor, text);
×
1234
                }
1235
            } catch (error) {
1236
                this.editor.onError({
×
1237
                    code: SlateErrorCode.ToNativeSelectionError,
1238
                    nativeError: error
1239
                });
1240
            }
1241
        }
1242
    }
1243

1244
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1245
        if (!handler) {
2✔
1246
            return false;
2✔
1247
        }
1248
        handler(event);
×
1249
        return event.defaultPrevented;
×
1250
    }
1251
    //#endregion
1252

1253
    ngOnDestroy() {
1254
        NODE_TO_ELEMENT.delete(this.editor);
14✔
1255
        this.manualListeners.forEach(manualListener => {
14✔
1256
            manualListener();
280✔
1257
        });
1258
        this.destroy$.complete();
14✔
1259
        EDITOR_TO_ON_CHANGE.delete(this.editor);
14✔
1260
    }
1261
}
1262

1263
/**
1264
 * Check if the target is editable and in the editor.
1265
 */
1266

1267
const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1268
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
2✔
1269
};
1270

1271
/**
1272
 * Check if two DOM range objects are equal.
1273
 */
1274
const isRangeEqual = (a: DOMRange, b: DOMRange) => {
1✔
1275
    return (
×
1276
        (a.startContainer === b.startContainer &&
×
1277
            a.startOffset === b.startOffset &&
1278
            a.endContainer === b.endContainer &&
1279
            a.endOffset === b.endOffset) ||
1280
        (a.startContainer === b.endContainer &&
1281
            a.startOffset === b.endOffset &&
1282
            a.endContainer === b.startContainer &&
1283
            a.endOffset === b.startOffset)
1284
    );
1285
};
1286

1287
/**
1288
 * Check if the target is in the editor.
1289
 */
1290

1291
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1292
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
×
1293
};
1294

1295
/**
1296
 * Check if the target is inside void and in the editor.
1297
 */
1298

1299
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1300
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
×
1301
    return Editor.isVoid(editor, slateNode);
×
1302
};
1303

1304
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1305
    return (
×
1306
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
×
1307
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1308
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1309
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1310
    );
1311
};
1312

1313
/**
1314
 * remove default insert from composition
1315
 * @param text
1316
 */
1317
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1318
    const types = ['compositionend', 'insertFromComposition'];
×
1319
    if (!types.includes(event.type)) {
×
1320
        return;
×
1321
    }
1322
    const insertText = (event as CompositionEvent).data;
×
1323
    const window = AngularEditor.getWindow(editor);
×
1324
    const domSelection = window.getSelection();
×
1325
    // ensure text node insert composition input text
1326
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1327
        const textNode = domSelection.anchorNode;
×
1328
        textNode.splitText(textNode.length - insertText.length).remove();
×
1329
    }
1330
};
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