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

worktile / slate-angular / 18325f08-2c45-4464-a90a-1769140dbc06

pending completion
18325f08-2c45-4464-a90a-1769140dbc06

Pull #226

circleci

pubuzhixing8
chore(core): update version type
Pull Request #226: Android input handing

268 of 894 branches covered (29.98%)

Branch coverage included in aggregate %.

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

684 of 1532 relevant lines covered (44.65%)

29.52 hits per line

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

22.12
/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
            if (type === 'deleteContentBackward') {
×
581
                const range = window.getSelection();
×
582
                // Gboard can not prevent default action, so must use restoreDom, Sougou Keyboard can prevent default action.
583
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
584
                if (range.isCollapsed === false) {
×
585
                    range.removeAllRanges();
×
586
                    restoreDom(editor, () => {
×
587
                        Editor.deleteBackward(editor);
×
588
                    });
589
                    return;
×
590
                }
591
            }
592
        }
593
        if (
×
594
            !this.readonly &&
×
595
            hasEditableTarget(editor, event.target) &&
596
            !isTargetInsideVoid(editor, activeElement) &&
597
            !this.isDOMEventHandled(event, this.beforeInput)
598
        ) {
599
            try {
×
600
                event.preventDefault();
×
601

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

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

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

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

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

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

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

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

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

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

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

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

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

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

716
        const window = AngularEditor.getWindow(this.editor);
×
717

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

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

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

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

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

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

754
        IS_FOCUSED.delete(this.editor);
×
755
    }
756

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

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

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

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

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

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

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

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

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

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

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

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

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

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

865
            this.isDraggingInternally = true;
×
866

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

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

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

882
            Transforms.select(editor, range);
×
883

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

891
                this.isDraggingInternally = false;
×
892
            }
893

894
            AngularEditor.insertData(editor, data);
×
895

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

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

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

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

934
            IS_FOCUSED.set(this.editor, true);
1✔
935
        }
936
    }
937

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

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

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

963
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
964
                        editor.redo();
×
965
                    }
966

967
                    return;
×
968
                }
969

970
                if (Hotkeys.isUndo(nativeEvent)) {
×
971
                    event.preventDefault();
×
972

973
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
974
                        editor.undo();
×
975
                    }
976

977
                    return;
×
978
                }
979

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

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

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

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

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

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

1026
                    return;
×
1027
                }
1028

1029
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1030
                    event.preventDefault();
×
1031

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

1038
                    return;
×
1039
                }
1040

1041
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1042
                    event.preventDefault();
×
1043

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

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

1052
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1053
                    event.preventDefault();
×
1054

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

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

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

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

1080
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1081
                        event.preventDefault();
×
1082

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

1091
                        return;
×
1092
                    }
1093

1094
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1095
                        event.preventDefault();
×
1096

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

1105
                        return;
×
1106
                    }
1107

1108
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1109
                        event.preventDefault();
×
1110

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

1119
                        return;
×
1120
                    }
1121

1122
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1123
                        event.preventDefault();
×
1124

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

1133
                        return;
×
1134
                    }
1135

1136
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1137
                        event.preventDefault();
×
1138

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

1147
                        return;
×
1148
                    }
1149

1150
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1151
                        event.preventDefault();
×
1152

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

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

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

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

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

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

1261
/**
1262
 * Check if the target is editable and in the editor.
1263
 */
1264

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

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

1285
/**
1286
 * Check if the target is in the editor.
1287
 */
1288

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

1293
/**
1294
 * Check if the target is inside void and in the editor.
1295
 */
1296

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

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

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