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

worktile / slate-angular / da56a556-b6e8-4ed9-87e7-93234ec6fcce

pending completion
da56a556-b6e8-4ed9-87e7-93234ec6fcce

Pull #228

circleci

pubuzhixing8
chore: remove useless code
Pull Request #228: feat(core): add default string component

269 of 893 branches covered (30.12%)

Branch coverage included in aggregate %.

8 of 8 new or added lines in 2 files covered. (100.0%)

690 of 1533 relevant lines covered (45.01%)

30.5 hits per line

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

22.01
/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
        this.forceFlush();
8✔
367
        this.onChangeCallback(this.editor.children);
8✔
368
    }
369

370
    ngAfterViewChecked() {}
371

372
    ngDoCheck() {}
373

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

608
                switch (type) {
×
609
                    case 'deleteByComposition':
610
                    case 'deleteByCut':
611
                    case 'deleteByDrag': {
612
                        Editor.deleteFragment(editor);
×
613
                        break;
×
614
                    }
615

616
                    case 'deleteContent':
617
                    case 'deleteContentForward': {
618
                        Editor.deleteForward(editor);
×
619
                        break;
×
620
                    }
621

622
                    case 'deleteContentBackward': {
623
                        Editor.deleteBackward(editor);
×
624
                        break;
×
625
                    }
626

627
                    case 'deleteEntireSoftLine': {
628
                        Editor.deleteBackward(editor, { unit: 'line' });
×
629
                        Editor.deleteForward(editor, { unit: 'line' });
×
630
                        break;
×
631
                    }
632

633
                    case 'deleteHardLineBackward': {
634
                        Editor.deleteBackward(editor, { unit: 'block' });
×
635
                        break;
×
636
                    }
637

638
                    case 'deleteSoftLineBackward': {
639
                        Editor.deleteBackward(editor, { unit: 'line' });
×
640
                        break;
×
641
                    }
642

643
                    case 'deleteHardLineForward': {
644
                        Editor.deleteForward(editor, { unit: 'block' });
×
645
                        break;
×
646
                    }
647

648
                    case 'deleteSoftLineForward': {
649
                        Editor.deleteForward(editor, { unit: 'line' });
×
650
                        break;
×
651
                    }
652

653
                    case 'deleteWordBackward': {
654
                        Editor.deleteBackward(editor, { unit: 'word' });
×
655
                        break;
×
656
                    }
657

658
                    case 'deleteWordForward': {
659
                        Editor.deleteForward(editor, { unit: 'word' });
×
660
                        break;
×
661
                    }
662

663
                    case 'insertLineBreak':
664
                    case 'insertParagraph': {
665
                        Editor.insertBreak(editor);
×
666
                        break;
×
667
                    }
668

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

704
    private onDOMBlur(event: FocusEvent) {
705
        if (
×
706
            this.readonly ||
×
707
            this.isUpdatingSelection ||
708
            !hasEditableTarget(this.editor, event.target) ||
709
            this.isDOMEventHandled(event, this.blur)
710
        ) {
711
            return;
×
712
        }
713

714
        const window = AngularEditor.getWindow(this.editor);
×
715

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

725
        const { relatedTarget } = event;
×
726
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
727

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

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

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

747
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
748
                return;
×
749
            }
750
        }
751

752
        IS_FOCUSED.delete(this.editor);
×
753
    }
754

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

767
            const startVoid = Editor.void(this.editor, { at: start });
×
768
            const endVoid = Editor.void(this.editor, { at: end });
×
769

770
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
771
                const range = Editor.range(this.editor, start);
×
772
                Transforms.select(this.editor, range);
×
773
            }
774
        }
775
    }
776

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

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

799
    private onDOMCompositionStart(event: CompositionEvent) {
800
        const { selection } = this.editor;
1✔
801

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

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

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

831
            if (selection) {
×
832
                AngularEditor.deleteCutData(this.editor);
×
833
            }
834
        }
835
    }
836

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

844
            if (Editor.isVoid(this.editor, node)) {
×
845
                event.preventDefault();
×
846
            }
847
        }
848
    }
849

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

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

863
            this.isDraggingInternally = true;
×
864

865
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
866
        }
867
    }
868

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

876
            // Find the range where the drop happened
877
            const range = AngularEditor.findEventRange(editor, event);
×
878
            const data = event.dataTransfer;
×
879

880
            Transforms.select(editor, range);
×
881

882
            if (this.isDraggingInternally) {
×
883
                if (draggedRange) {
×
884
                    Transforms.delete(editor, {
×
885
                        at: draggedRange
886
                    });
887
                }
888

889
                this.isDraggingInternally = false;
×
890
            }
891

892
            AngularEditor.insertData(editor, data);
×
893

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

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

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

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

932
            IS_FOCUSED.set(this.editor, true);
1✔
933
        }
934
    }
935

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

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

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

961
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
962
                        editor.redo();
×
963
                    }
964

965
                    return;
×
966
                }
967

968
                if (Hotkeys.isUndo(nativeEvent)) {
×
969
                    event.preventDefault();
×
970

971
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
972
                        editor.undo();
×
973
                    }
974

975
                    return;
×
976
                }
977

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

988
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
989
                    event.preventDefault();
×
990
                    Transforms.move(editor, { unit: 'line' });
×
991
                    return;
×
992
                }
993

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

1004
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1005
                    event.preventDefault();
×
1006
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1007
                    return;
×
1008
                }
1009

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

1018
                    if (selection && Range.isCollapsed(selection)) {
×
1019
                        Transforms.move(editor, { reverse: !isRTL });
×
1020
                    } else {
1021
                        Transforms.collapse(editor, { edge: 'start' });
×
1022
                    }
1023

1024
                    return;
×
1025
                }
1026

1027
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1028
                    event.preventDefault();
×
1029

1030
                    if (selection && Range.isCollapsed(selection)) {
×
1031
                        Transforms.move(editor, { reverse: isRTL });
×
1032
                    } else {
1033
                        Transforms.collapse(editor, { edge: 'end' });
×
1034
                    }
1035

1036
                    return;
×
1037
                }
1038

1039
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1040
                    event.preventDefault();
×
1041

1042
                    if (selection && Range.isExpanded(selection)) {
×
1043
                        Transforms.collapse(editor, { edge: 'focus' });
×
1044
                    }
1045

1046
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1047
                    return;
×
1048
                }
1049

1050
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1051
                    event.preventDefault();
×
1052

1053
                    if (selection && Range.isExpanded(selection)) {
×
1054
                        Transforms.collapse(editor, { edge: 'focus' });
×
1055
                    }
1056

1057
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1058
                    return;
×
1059
                }
1060

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

1072
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1073
                        event.preventDefault();
×
1074
                        Editor.insertBreak(editor);
×
1075
                        return;
×
1076
                    }
1077

1078
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1079
                        event.preventDefault();
×
1080

1081
                        if (selection && Range.isExpanded(selection)) {
×
1082
                            Editor.deleteFragment(editor, {
×
1083
                                direction: 'backward'
1084
                            });
1085
                        } else {
1086
                            Editor.deleteBackward(editor);
×
1087
                        }
1088

1089
                        return;
×
1090
                    }
1091

1092
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1093
                        event.preventDefault();
×
1094

1095
                        if (selection && Range.isExpanded(selection)) {
×
1096
                            Editor.deleteFragment(editor, {
×
1097
                                direction: 'forward'
1098
                            });
1099
                        } else {
1100
                            Editor.deleteForward(editor);
×
1101
                        }
1102

1103
                        return;
×
1104
                    }
1105

1106
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1107
                        event.preventDefault();
×
1108

1109
                        if (selection && Range.isExpanded(selection)) {
×
1110
                            Editor.deleteFragment(editor, {
×
1111
                                direction: 'backward'
1112
                            });
1113
                        } else {
1114
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1115
                        }
1116

1117
                        return;
×
1118
                    }
1119

1120
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1121
                        event.preventDefault();
×
1122

1123
                        if (selection && Range.isExpanded(selection)) {
×
1124
                            Editor.deleteFragment(editor, {
×
1125
                                direction: 'forward'
1126
                            });
1127
                        } else {
1128
                            Editor.deleteForward(editor, { unit: 'line' });
×
1129
                        }
1130

1131
                        return;
×
1132
                    }
1133

1134
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1135
                        event.preventDefault();
×
1136

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

1145
                        return;
×
1146
                    }
1147

1148
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1149
                        event.preventDefault();
×
1150

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

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

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

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

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

1249
    ngOnDestroy() {
1250
        NODE_TO_ELEMENT.delete(this.editor);
13✔
1251
        this.manualListeners.forEach(manualListener => {
13✔
1252
            manualListener();
260✔
1253
        });
1254
        this.destroy$.complete();
13✔
1255
        EDITOR_TO_ON_CHANGE.delete(this.editor);
13✔
1256
    }
1257
}
1258

1259
/**
1260
 * Check if the target is editable and in the editor.
1261
 */
1262

1263
const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1264
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
2✔
1265
};
1266

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

1283
/**
1284
 * Check if the target is in the editor.
1285
 */
1286

1287
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1288
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
×
1289
};
1290

1291
/**
1292
 * Check if the target is inside void and in the editor.
1293
 */
1294

1295
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1296
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
×
1297
    return Editor.isVoid(editor, slateNode);
×
1298
};
1299

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

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

© 2025 Coveralls, Inc