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

worktile / slate-angular / d2318e27-26ee-4ac0-9d9e-7213f35b5863

pending completion
d2318e27-26ee-4ac0-9d9e-7213f35b5863

push

circleci

pubuzhixing8
chore: resove gboard

268 of 894 branches covered (29.98%)

Branch coverage included in aggregate %.

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

684 of 1528 relevant lines covered (44.76%)

29.6 hits per line

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

22.22
/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),
14✔
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();
14✔
86

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

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

94
    private initialized: boolean;
95

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

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

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

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

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

116
    @Input() readonly = false;
14✔
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;
14✔
139
    @Input() autoCorrect = false;
14✔
140
    @Input() autoCapitalize = false;
14✔
141

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

146
    get hasBeforeInputSupport() {
147
        return HAS_BEFORE_INPUT_SUPPORT;
288✔
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,
14✔
158
        public renderer2: Renderer2,
14✔
159
        public cdr: ChangeDetectorRef,
14✔
160
        private ngZone: NgZone,
14✔
161
        private injector: Injector
14✔
162
    ) {}
163

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

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

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

192
    ngOnChanges(simpleChanges: SimpleChanges) {
193
        if (!this.initialized) {
17✔
194
            return;
14✔
195
        }
196
        const decorateChange = simpleChanges['decorate'];
3✔
197
        if (decorateChange) {
3✔
198
            this.forceFlush();
2✔
199
        }
200
        const placeholderChange = simpleChanges['placeholder'];
3✔
201
        if (placeholderChange) {
3✔
202
            this.detectContext();
1✔
203
        }
204
        const readonlyChange = simpleChanges['readonly'];
3✔
205
        if (readonlyChange) {
3!
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;
14✔
214
    }
215
    registerOnTouched(fn: any) {
216
        this.onTouchedCallback = fn;
14✔
217
    }
218

219
    writeValue(value: Element[]) {
220
        if (value && value.length) {
31✔
221
            if (check(value)) {
17!
222
                this.editor.children = value;
17✔
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();
17✔
232
            this.cdr.markForCheck();
17✔
233
        }
234
    }
235

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

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

274
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
10!
275
                return;
10✔
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
        }
363
    }
364

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

372
    ngAfterViewChecked() {}
373

374
    ngDoCheck() {}
375

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

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

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

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

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

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

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

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

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

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

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

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

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

541
    private onDOMBeforeInput(
542
        event: Event & {
543
            inputType: string;
544
            isComposing: boolean;
545
            data: string | null;
546
            dataTransfer: DataTransfer | null;
547
            getTargetRanges(): DOMStaticRange[];
548
        }
549
    ) {
550
        const editor = this.editor;
×
551
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
552
        const { activeElement } = root;
×
553
        const { selection } = editor;
×
554
        const { inputType: type } = event;
×
555
        const data = event.dataTransfer || event.data || undefined;
×
556
        console.log(`type: ${type}`, data && data.toString());
×
557
        if (IS_ANDROID) {
×
558
            if (type === 'insertCompositionText') {
×
559
                if (data && data.toString().includes('\n')) {
×
560
                    restoreDom(editor, () => {
×
561
                        Editor.insertBreak(editor);
×
562
                    });
563
                } else {
564
                    let [nativeTargetRange] = (event as any).getTargetRanges();
×
565
                    if (nativeTargetRange) {
×
566
                        const targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange);
×
567
                        if (data) {
×
568
                            restoreDom(editor, () => {
×
569
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
570
                            });
571
                        } else {
572
                            restoreDom(editor, () => {
×
573
                                Transforms.delete(editor, { at: targetRange });
×
574
                            });
575
                        }
576
                    }
577
                }
578
                return;
×
579
            }
580
        }
581
        if (
×
582
            !this.readonly &&
×
583
            hasEditableTarget(editor, event.target) &&
584
            !isTargetInsideVoid(editor, activeElement) &&
585
            !this.isDOMEventHandled(event, this.beforeInput)
586
        ) {
587
            try {
×
588
                event.preventDefault();
×
589

590
                // COMPAT: If the selection is expanded, even if the command seems like
591
                // a delete forward/backward command it should delete the selection.
592
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
593
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
594
                    Editor.deleteFragment(editor, { direction });
×
595
                    return;
×
596
                }
597

598
                switch (type) {
×
599
                    case 'deleteByComposition':
600
                    case 'deleteByCut':
601
                    case 'deleteByDrag': {
602
                        Editor.deleteFragment(editor);
×
603
                        break;
×
604
                    }
605

606
                    case 'deleteContent':
607
                    case 'deleteContentForward': {
608
                        Editor.deleteForward(editor);
×
609
                        break;
×
610
                    }
611

612
                    case 'deleteContentBackward': {
613
                        if (IS_ANDROID) {
×
614
                            restoreDom(editor, () => {
×
615
                                Editor.deleteBackward(editor);
×
616
                            });
617
                        } else {
618
                            Editor.deleteBackward(editor);
×
619
                        }
620
                        break;
×
621
                    }
622

623
                    case 'deleteEntireSoftLine': {
624
                        Editor.deleteBackward(editor, { unit: 'line' });
×
625
                        Editor.deleteForward(editor, { unit: 'line' });
×
626
                        break;
×
627
                    }
628

629
                    case 'deleteHardLineBackward': {
630
                        Editor.deleteBackward(editor, { unit: 'block' });
×
631
                        break;
×
632
                    }
633

634
                    case 'deleteSoftLineBackward': {
635
                        Editor.deleteBackward(editor, { unit: 'line' });
×
636
                        break;
×
637
                    }
638

639
                    case 'deleteHardLineForward': {
640
                        Editor.deleteForward(editor, { unit: 'block' });
×
641
                        break;
×
642
                    }
643

644
                    case 'deleteSoftLineForward': {
645
                        Editor.deleteForward(editor, { unit: 'line' });
×
646
                        break;
×
647
                    }
648

649
                    case 'deleteWordBackward': {
650
                        Editor.deleteBackward(editor, { unit: 'word' });
×
651
                        break;
×
652
                    }
653

654
                    case 'deleteWordForward': {
655
                        Editor.deleteForward(editor, { unit: 'word' });
×
656
                        break;
×
657
                    }
658

659
                    case 'insertLineBreak':
660
                    case 'insertParagraph': {
661
                        Editor.insertBreak(editor);
×
662
                        break;
×
663
                    }
664

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

700
    private onDOMBlur(event: FocusEvent) {
701
        if (
×
702
            this.readonly ||
×
703
            this.isUpdatingSelection ||
704
            !hasEditableTarget(this.editor, event.target) ||
705
            this.isDOMEventHandled(event, this.blur)
706
        ) {
707
            return;
×
708
        }
709

710
        const window = AngularEditor.getWindow(this.editor);
×
711

712
        // COMPAT: If the current `activeElement` is still the previous
713
        // one, this is due to the window being blurred when the tab
714
        // itself becomes unfocused, so we want to abort early to allow to
715
        // editor to stay focused when the tab becomes focused again.
716
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
717
        if (this.latestElement === root.activeElement) {
×
718
            return;
×
719
        }
720

721
        const { relatedTarget } = event;
×
722
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
723

724
        // COMPAT: The event should be ignored if the focus is returning
725
        // to the editor from an embedded editable element (eg. an <input>
726
        // element inside a void node).
727
        if (relatedTarget === el) {
×
728
            return;
×
729
        }
730

731
        // COMPAT: The event should be ignored if the focus is moving from
732
        // the editor to inside a void node's spacer element.
733
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
734
            return;
×
735
        }
736

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

743
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
744
                return;
×
745
            }
746
        }
747

748
        IS_FOCUSED.delete(this.editor);
×
749
    }
750

751
    private onDOMClick(event: MouseEvent) {
752
        if (
×
753
            !this.readonly &&
×
754
            hasTarget(this.editor, event.target) &&
755
            !this.isDOMEventHandled(event, this.click) &&
756
            isDOMNode(event.target)
757
        ) {
758
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
759
            const path = AngularEditor.findPath(this.editor, node);
×
760
            const start = Editor.start(this.editor, path);
×
761
            const end = Editor.end(this.editor, path);
×
762

763
            const startVoid = Editor.void(this.editor, { at: start });
×
764
            const endVoid = Editor.void(this.editor, { at: end });
×
765

766
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
767
                const range = Editor.range(this.editor, start);
×
768
                Transforms.select(this.editor, range);
×
769
            }
770
        }
771
    }
772

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

787
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
788
            // so we need avoid repeat isnertText by isComposing === true,
789
            this.isComposing = false;
×
790
        }
791
        this.detectContext();
×
792
        this.cdr.detectChanges();
×
793
    }
794

795
    private onDOMCompositionStart(event: CompositionEvent) {
796
        const { selection } = this.editor;
1✔
797

798
        if (selection) {
1!
799
            // solve the problem of cross node Chinese input
800
            if (Range.isExpanded(selection)) {
×
801
                Editor.deleteFragment(this.editor);
×
802
                this.forceFlush();
×
803
            }
804
        }
805
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
806
            this.isComposing = true;
1✔
807
        }
808
        this.detectContext();
1✔
809
        this.cdr.detectChanges();
1✔
810
    }
811

812
    private onDOMCopy(event: ClipboardEvent) {
813
        const window = AngularEditor.getWindow(this.editor);
×
814
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
815
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
816
            event.preventDefault();
×
817
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
818
        }
819
    }
820

821
    private onDOMCut(event: ClipboardEvent) {
822
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
823
            event.preventDefault();
×
824
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
825
            const { selection } = this.editor;
×
826

827
            if (selection) {
×
828
                AngularEditor.deleteCutData(this.editor);
×
829
            }
830
        }
831
    }
832

833
    private onDOMDragOver(event: DragEvent) {
834
        if (hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
835
            // Only when the target is void, call `preventDefault` to signal
836
            // that drops are allowed. Editable content is droppable by
837
            // default, and calling `preventDefault` hides the cursor.
838
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
839

840
            if (Editor.isVoid(this.editor, node)) {
×
841
                event.preventDefault();
×
842
            }
843
        }
844
    }
845

846
    private onDOMDragStart(event: DragEvent) {
847
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
848
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
849
            const path = AngularEditor.findPath(this.editor, node);
×
850
            const voidMatch = Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true });
×
851

852
            // If starting a drag on a void node, make sure it is selected
853
            // so that it shows up in the selection's fragment.
854
            if (voidMatch) {
×
855
                const range = Editor.range(this.editor, path);
×
856
                Transforms.select(this.editor, range);
×
857
            }
858

859
            this.isDraggingInternally = true;
×
860

861
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
862
        }
863
    }
864

865
    private onDOMDrop(event: DragEvent) {
866
        const editor = this.editor;
×
867
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
868
            event.preventDefault();
×
869
            // Keep a reference to the dragged range before updating selection
870
            const draggedRange = editor.selection;
×
871

872
            // Find the range where the drop happened
873
            const range = AngularEditor.findEventRange(editor, event);
×
874
            const data = event.dataTransfer;
×
875

876
            Transforms.select(editor, range);
×
877

878
            if (this.isDraggingInternally) {
×
879
                if (draggedRange) {
×
880
                    Transforms.delete(editor, {
×
881
                        at: draggedRange
882
                    });
883
                }
884

885
                this.isDraggingInternally = false;
×
886
            }
887

888
            AngularEditor.insertData(editor, data);
×
889

890
            // When dragging from another source into the editor, it's possible
891
            // that the current editor does not have focus.
892
            if (!AngularEditor.isFocused(editor)) {
×
893
                AngularEditor.focus(editor);
×
894
            }
895
        }
896
    }
897

898
    private onDOMDragEnd(event: DragEvent) {
899
        if (
×
900
            !this.readonly &&
×
901
            this.isDraggingInternally &&
902
            hasTarget(this.editor, event.target) &&
903
            !this.isDOMEventHandled(event, this.dragEnd)
904
        ) {
905
            this.isDraggingInternally = false;
×
906
        }
907
    }
908

909
    private onDOMFocus(event: Event) {
910
        if (
1✔
911
            !this.readonly &&
4✔
912
            !this.isUpdatingSelection &&
913
            hasEditableTarget(this.editor, event.target) &&
914
            !this.isDOMEventHandled(event, this.focus)
915
        ) {
916
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
917
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
918
            this.latestElement = root.activeElement;
1✔
919

920
            // COMPAT: If the editor has nested editable elements, the focus
921
            // can go to them. In Firefox, this must be prevented because it
922
            // results in issues with keyboard navigation. (2017/03/30)
923
            if (IS_FIREFOX && event.target !== el) {
1!
924
                el.focus();
×
925
                return;
×
926
            }
927

928
            IS_FOCUSED.set(this.editor, true);
1✔
929
        }
930
    }
931

932
    private onDOMKeydown(event: KeyboardEvent) {
933
        const editor = this.editor;
×
934
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
935
        const { activeElement } = root;
×
936
        if (
×
937
            !this.readonly &&
×
938
            hasEditableTarget(editor, event.target) &&
939
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
940
            !this.isComposing &&
941
            !this.isDOMEventHandled(event, this.keydown)
942
        ) {
943
            const nativeEvent = event;
×
944
            const { selection } = editor;
×
945

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

949
            try {
×
950
                // COMPAT: Since we prevent the default behavior on
951
                // `beforeinput` events, the browser doesn't think there's ever
952
                // any history stack to undo or redo, so we have to manage these
953
                // hotkeys ourselves. (2019/11/06)
954
                if (Hotkeys.isRedo(nativeEvent)) {
×
955
                    event.preventDefault();
×
956

957
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
958
                        editor.redo();
×
959
                    }
960

961
                    return;
×
962
                }
963

964
                if (Hotkeys.isUndo(nativeEvent)) {
×
965
                    event.preventDefault();
×
966

967
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
968
                        editor.undo();
×
969
                    }
970

971
                    return;
×
972
                }
973

974
                // COMPAT: Certain browsers don't handle the selection updates
975
                // properly. In Chrome, the selection isn't properly extended.
976
                // And in Firefox, the selection isn't properly collapsed.
977
                // (2017/10/17)
978
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
979
                    event.preventDefault();
×
980
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
981
                    return;
×
982
                }
983

984
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
985
                    event.preventDefault();
×
986
                    Transforms.move(editor, { unit: 'line' });
×
987
                    return;
×
988
                }
989

990
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
991
                    event.preventDefault();
×
992
                    Transforms.move(editor, {
×
993
                        unit: 'line',
994
                        edge: 'focus',
995
                        reverse: true
996
                    });
997
                    return;
×
998
                }
999

1000
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1001
                    event.preventDefault();
×
1002
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1003
                    return;
×
1004
                }
1005

1006
                // COMPAT: If a void node is selected, or a zero-width text node
1007
                // adjacent to an inline is selected, we need to handle these
1008
                // hotkeys manually because browsers won't be able to skip over
1009
                // the void node with the zero-width space not being an empty
1010
                // string.
1011
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1012
                    event.preventDefault();
×
1013

1014
                    if (selection && Range.isCollapsed(selection)) {
×
1015
                        Transforms.move(editor, { reverse: !isRTL });
×
1016
                    } else {
1017
                        Transforms.collapse(editor, { edge: 'start' });
×
1018
                    }
1019

1020
                    return;
×
1021
                }
1022

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

1026
                    if (selection && Range.isCollapsed(selection)) {
×
1027
                        Transforms.move(editor, { reverse: isRTL });
×
1028
                    } else {
1029
                        Transforms.collapse(editor, { edge: 'end' });
×
1030
                    }
1031

1032
                    return;
×
1033
                }
1034

1035
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1036
                    event.preventDefault();
×
1037

1038
                    if (selection && Range.isExpanded(selection)) {
×
1039
                        Transforms.collapse(editor, { edge: 'focus' });
×
1040
                    }
1041

1042
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1043
                    return;
×
1044
                }
1045

1046
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1047
                    event.preventDefault();
×
1048

1049
                    if (selection && Range.isExpanded(selection)) {
×
1050
                        Transforms.collapse(editor, { edge: 'focus' });
×
1051
                    }
1052

1053
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1054
                    return;
×
1055
                }
1056

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

1068
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1069
                        event.preventDefault();
×
1070
                        Editor.insertBreak(editor);
×
1071
                        return;
×
1072
                    }
1073

1074
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1075
                        event.preventDefault();
×
1076

1077
                        if (selection && Range.isExpanded(selection)) {
×
1078
                            Editor.deleteFragment(editor, {
×
1079
                                direction: 'backward'
1080
                            });
1081
                        } else {
1082
                            Editor.deleteBackward(editor);
×
1083
                        }
1084

1085
                        return;
×
1086
                    }
1087

1088
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1089
                        event.preventDefault();
×
1090

1091
                        if (selection && Range.isExpanded(selection)) {
×
1092
                            Editor.deleteFragment(editor, {
×
1093
                                direction: 'forward'
1094
                            });
1095
                        } else {
1096
                            Editor.deleteForward(editor);
×
1097
                        }
1098

1099
                        return;
×
1100
                    }
1101

1102
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1103
                        event.preventDefault();
×
1104

1105
                        if (selection && Range.isExpanded(selection)) {
×
1106
                            Editor.deleteFragment(editor, {
×
1107
                                direction: 'backward'
1108
                            });
1109
                        } else {
1110
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1111
                        }
1112

1113
                        return;
×
1114
                    }
1115

1116
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1117
                        event.preventDefault();
×
1118

1119
                        if (selection && Range.isExpanded(selection)) {
×
1120
                            Editor.deleteFragment(editor, {
×
1121
                                direction: 'forward'
1122
                            });
1123
                        } else {
1124
                            Editor.deleteForward(editor, { unit: 'line' });
×
1125
                        }
1126

1127
                        return;
×
1128
                    }
1129

1130
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1131
                        event.preventDefault();
×
1132

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

1141
                        return;
×
1142
                    }
1143

1144
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1145
                        event.preventDefault();
×
1146

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

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

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

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

1236
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1237
        if (!handler) {
2✔
1238
            return false;
2✔
1239
        }
1240
        handler(event);
×
1241
        return event.defaultPrevented;
×
1242
    }
1243
    //#endregion
1244

1245
    ngOnDestroy() {
1246
        NODE_TO_ELEMENT.delete(this.editor);
14✔
1247
        this.manualListeners.forEach(manualListener => {
14✔
1248
            manualListener();
280✔
1249
        });
1250
        this.destroy$.complete();
14✔
1251
        EDITOR_TO_ON_CHANGE.delete(this.editor);
14✔
1252
    }
1253
}
1254

1255
/**
1256
 * Check if the target is editable and in the editor.
1257
 */
1258

1259
const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1260
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
2✔
1261
};
1262

1263
/**
1264
 * Check if two DOM range objects are equal.
1265
 */
1266
const isRangeEqual = (a: DOMRange, b: DOMRange) => {
1✔
1267
    return (
×
1268
        (a.startContainer === b.startContainer &&
×
1269
            a.startOffset === b.startOffset &&
1270
            a.endContainer === b.endContainer &&
1271
            a.endOffset === b.endOffset) ||
1272
        (a.startContainer === b.endContainer &&
1273
            a.startOffset === b.endOffset &&
1274
            a.endContainer === b.startContainer &&
1275
            a.endOffset === b.startOffset)
1276
    );
1277
};
1278

1279
/**
1280
 * Check if the target is in the editor.
1281
 */
1282

1283
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1284
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
×
1285
};
1286

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

1291
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1292
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
×
1293
    return Editor.isVoid(editor, slateNode);
×
1294
};
1295

1296
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1297
    return (
×
1298
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
×
1299
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1300
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1301
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1302
    );
1303
};
1304

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