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

worktile / slate-angular / 9e1efe2f-97e3-4548-a394-3e9e9742698d

13 Sep 2023 07:10AM UTC coverage: 46.148%. Remained the same
9e1efe2f-97e3-4548-a394-3e9e9742698d

push

circleci

web-flow
feat: bump is-hotkey and direction to 0.2.0 and 2.0.1, add dependencies of package.json (#238)

353 of 928 branches covered (0.0%)

Branch coverage included in aggregate %.

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

815 of 1603 relevant lines covered (50.84%)

49.73 hits per line

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

29.82
/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 { direction } from 'direction';
31
import scrollIntoView from 'scroll-into-view-if-needed';
32
import { AngularEditor } from '../../plugins/angular-editor';
33
import {
34
    DOMElement,
35
    DOMNode,
36
    isDOMNode,
37
    DOMStaticRange,
38
    DOMRange,
39
    isDOMElement,
40
    isPlainTextOnlyPaste,
41
    DOMSelection,
42
    getDefaultView
43
} from '../../utils/dom';
44
import { Subject } from 'rxjs';
45
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
46
import Hotkeys from '../../utils/hotkeys';
47
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
48
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
49
import { SlateErrorCode } from '../../types/error';
50
import { SlateStringTemplate } from '../string/template.component';
51
import { NG_VALUE_ACCESSOR } from '@angular/forms';
52
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
53
import { ViewType } from '../../types/view';
54
import { HistoryEditor } from 'slate-history';
55
import { isDecoratorRangeListEqual, check, normalize } from '../../utils';
56
import { SlatePlaceholder } from '../../types/feature';
57
import { restoreDom } from '../../utils/restore-dom';
58
import { SlateChildren } from '../children/children.component';
59

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

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

89
    private destroy$ = new Subject();
20✔
90

91
    isComposing = false;
20✔
92
    isDraggingInternally = false;
20✔
93
    isUpdatingSelection = false;
20✔
94
    latestElement = null as DOMElement | null;
20✔
95

96
    protected manualListeners: (() => void)[] = [];
20✔
97

98
    private initialized: boolean;
99

100
    private onTouchedCallback: () => void = () => {};
20✔
101

102
    private onChangeCallback: (_: any) => void = () => {};
20✔
103

104
    @Input() editor: AngularEditor;
105

106
    @Input() renderElement: (element: Element) => ViewType | null;
107

108
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
109

110
    @Input() renderText: (text: SlateText) => ViewType | null;
111

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

114
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
115

116
    @Input() scrollSelectionIntoView: (editor: AngularEditor, domRange: DOMRange) => void = defaultScrollSelectionIntoView;
20✔
117

118
    @Input() isStrictDecorate: boolean = true;
20✔
119

120
    @Input() trackBy: (node: Element) => any = () => null;
196✔
121

122
    @Input() readonly = false;
20✔
123

124
    @Input() placeholder: string;
125

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

144
    //#region DOM attr
145
    @Input() spellCheck = false;
20✔
146
    @Input() autoCorrect = false;
20✔
147
    @Input() autoCapitalize = false;
20✔
148

149
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
20✔
150
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
20✔
151
    @HostBinding('attr.data-gramm') dataGramm = false;
20✔
152

153
    get hasBeforeInputSupport() {
154
        return HAS_BEFORE_INPUT_SUPPORT;
396✔
155
    }
156
    //#endregion
157

158
    @ViewChild('templateComponent', { static: true })
159
    templateComponent: SlateStringTemplate;
160

161
    @ViewChild('templateComponent', { static: true, read: ElementRef })
162
    templateElementRef: ElementRef<any>;
163

164
    constructor(
165
        public elementRef: ElementRef,
20✔
166
        public renderer2: Renderer2,
20✔
167
        public cdr: ChangeDetectorRef,
20✔
168
        private ngZone: NgZone,
20✔
169
        private injector: Injector
20✔
170
    ) {}
171

172
    ngOnInit() {
173
        this.editor.injector = this.injector;
20✔
174
        this.editor.children = [];
20✔
175
        let window = getDefaultView(this.elementRef.nativeElement);
20✔
176
        EDITOR_TO_WINDOW.set(this.editor, window);
20✔
177
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
20✔
178
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
20✔
179
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
20✔
180
        IS_READONLY.set(this.editor, this.readonly);
20✔
181
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
20✔
182
            this.ngZone.run(() => {
11✔
183
                this.onChange();
11✔
184
            });
185
        });
186
        this.ngZone.runOutsideAngular(() => {
20✔
187
            this.initialize();
20✔
188
        });
189
        this.initializeViewContext();
20✔
190
        this.initializeContext();
20✔
191

192
        // remove unused DOM, just keep templateComponent instance
193
        this.templateElementRef.nativeElement.remove();
20✔
194

195
        // add browser class
196
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
20!
197
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
20!
198
    }
199

200
    ngOnChanges(simpleChanges: SimpleChanges) {
201
        if (!this.initialized) {
23✔
202
            return;
20✔
203
        }
204
        const decorateChange = simpleChanges['decorate'];
3✔
205
        if (decorateChange) {
3✔
206
            this.forceFlush();
2✔
207
        }
208
        const placeholderChange = simpleChanges['placeholder'];
3✔
209
        if (placeholderChange) {
3✔
210
            this.detectContext();
1✔
211
        }
212
        const readonlyChange = simpleChanges['readonly'];
3✔
213
        if (readonlyChange) {
3!
214
            IS_READONLY.set(this.editor, this.readonly);
×
215
            this.detectContext();
×
216
            this.toSlateSelection();
×
217
        }
218
    }
219

220
    registerOnChange(fn: any) {
221
        this.onChangeCallback = fn;
20✔
222
    }
223
    registerOnTouched(fn: any) {
224
        this.onTouchedCallback = fn;
20✔
225
    }
226

227
    writeValue(value: Element[]) {
228
        if (value && value.length) {
43✔
229
            if (check(value)) {
23!
230
                this.editor.children = value;
23✔
231
            } else {
232
                this.editor.onError({
×
233
                    code: SlateErrorCode.InvalidValueError,
234
                    name: 'initialize invalid data',
235
                    data: value
236
                });
237
                this.editor.children = normalize(value);
×
238
            }
239
            this.initializeContext();
23✔
240
            this.cdr.markForCheck();
23✔
241
        }
242
    }
243

244
    initialize() {
245
        this.initialized = true;
20✔
246
        const window = AngularEditor.getWindow(this.editor);
20✔
247
        this.addEventListener(
20✔
248
            'selectionchange',
249
            event => {
250
                this.toSlateSelection();
3✔
251
            },
252
            window.document
253
        );
254
        if (HAS_BEFORE_INPUT_SUPPORT) {
20✔
255
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
20✔
256
        }
257
        this.addEventListener('blur', this.onDOMBlur.bind(this));
20✔
258
        this.addEventListener('click', this.onDOMClick.bind(this));
20✔
259
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
20✔
260
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
20✔
261
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
20✔
262
        this.addEventListener('copy', this.onDOMCopy.bind(this));
20✔
263
        this.addEventListener('cut', this.onDOMCut.bind(this));
20✔
264
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
20✔
265
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
20✔
266
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
20✔
267
        this.addEventListener('drop', this.onDOMDrop.bind(this));
20✔
268
        this.addEventListener('focus', this.onDOMFocus.bind(this));
20✔
269
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
20✔
270
        this.addEventListener('paste', this.onDOMPaste.bind(this));
20✔
271
        BEFORE_INPUT_EVENTS.forEach(event => {
20✔
272
            this.addEventListener(event.name, () => {});
100✔
273
        });
274
    }
275

276
    toNativeSelection() {
277
        try {
13✔
278
            const { selection } = this.editor;
13✔
279
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
13✔
280
            const { activeElement } = root;
13✔
281
            const domSelection = (root as Document).getSelection();
13✔
282

283
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
13!
284
                return;
12✔
285
            }
286

287
            const hasDomSelection = domSelection.type !== 'None';
1✔
288

289
            // If the DOM selection is properly unset, we're done.
290
            if (!selection && !hasDomSelection) {
1!
291
                return;
×
292
            }
293

294
            // If the DOM selection is already correct, we're done.
295
            // verify that the dom selection is in the editor
296
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
297
            let hasDomSelectionInEditor = false;
1✔
298
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
299
                hasDomSelectionInEditor = true;
1✔
300
            }
301

302
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
303
            if (
1!
304
                hasDomSelection &&
5✔
305
                hasDomSelectionInEditor &&
306
                selection &&
307
                hasStringTarget(domSelection) &&
308
                Range.equals(AngularEditor.toSlateRange(this.editor, domSelection), selection)
309
            ) {
310
                return;
×
311
            }
312

313
            // prevent updating native selection when active element is void element
314
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
315
                return;
×
316
            }
317

318
            // when <Editable/> is being controlled through external value
319
            // then its children might just change - DOM responds to it on its own
320
            // but Slate's value is not being updated through any operation
321
            // and thus it doesn't transform selection on its own
322
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
323
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection);
×
324
                return;
×
325
            }
326

327
            // Otherwise the DOM selection is out of sync, so update it.
328
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
329
            this.isUpdatingSelection = true;
1✔
330

331
            const newDomRange = selection && AngularEditor.toDOMRange(this.editor, selection);
1✔
332

333
            if (newDomRange) {
1!
334
                // COMPAT: Since the DOM range has no concept of backwards/forwards
335
                // we need to check and do the right thing here.
336
                if (Range.isBackward(selection)) {
1!
337
                    // eslint-disable-next-line max-len
338
                    domSelection.setBaseAndExtent(
×
339
                        newDomRange.endContainer,
340
                        newDomRange.endOffset,
341
                        newDomRange.startContainer,
342
                        newDomRange.startOffset
343
                    );
344
                } else {
345
                    // eslint-disable-next-line max-len
346
                    domSelection.setBaseAndExtent(
1✔
347
                        newDomRange.startContainer,
348
                        newDomRange.startOffset,
349
                        newDomRange.endContainer,
350
                        newDomRange.endOffset
351
                    );
352
                }
353
            } else {
354
                domSelection.removeAllRanges();
×
355
            }
356

357
            newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
358

359
            setTimeout(() => {
1✔
360
                // COMPAT: In Firefox, it's not enough to create a range, you also need
361
                // to focus the contenteditable element too. (2016/11/16)
362
                if (newDomRange && IS_FIREFOX) {
1!
363
                    el.focus();
×
364
                }
365

366
                this.isUpdatingSelection = false;
1✔
367
            });
368
        } catch (error) {
369
            this.editor.onError({
×
370
                code: SlateErrorCode.ToNativeSelectionError,
371
                nativeError: error
372
            });
373
            this.isUpdatingSelection = false;
×
374
        }
375
    }
376

377
    onChange() {
378
        this.forceFlush();
11✔
379
        this.onChangeCallback(this.editor.children);
11✔
380
    }
381

382
    ngAfterViewChecked() {}
383

384
    ngDoCheck() {}
385

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

425
    initializeContext() {
426
        this.context = {
43✔
427
            parent: this.editor,
428
            selection: this.editor.selection,
429
            decorations: this.generateDecorations(),
430
            decorate: this.decorate,
431
            readonly: this.readonly
432
        };
433
    }
434

435
    initializeViewContext() {
436
        this.viewContext = {
20✔
437
            editor: this.editor,
438
            renderElement: this.renderElement,
439
            renderLeaf: this.renderLeaf,
440
            renderText: this.renderText,
441
            trackBy: this.trackBy,
442
            isStrictDecorate: this.isStrictDecorate,
443
            templateComponent: this.templateComponent
444
        };
445
    }
446

447
    detectContext() {
448
        const decorations = this.generateDecorations();
15✔
449
        if (
15✔
450
            this.context.selection !== this.editor.selection ||
38✔
451
            this.context.decorate !== this.decorate ||
452
            this.context.readonly !== this.readonly ||
453
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
454
        ) {
455
            this.context = {
10✔
456
                parent: this.editor,
457
                selection: this.editor.selection,
458
                decorations: decorations,
459
                decorate: this.decorate,
460
                readonly: this.readonly
461
            };
462
        }
463
    }
464

465
    composePlaceholderDecorate(editor: Editor) {
466
        if (this.placeholderDecorate) {
56!
467
            return this.placeholderDecorate(editor) || [];
×
468
        }
469

470
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
56✔
471
            const start = Editor.start(editor, []);
3✔
472
            return [
3✔
473
                {
474
                    placeholder: this.placeholder,
475
                    anchor: start,
476
                    focus: start
477
                }
478
            ];
479
        } else {
480
            return [];
53✔
481
        }
482
    }
483

484
    generateDecorations() {
485
        const decorations = this.decorate([this.editor, []]);
58✔
486
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
58✔
487
        decorations.push(...placeholderDecorations);
58✔
488
        return decorations;
58✔
489
    }
490

491
    //#region event proxy
492
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
400✔
493
        this.manualListeners.push(
420✔
494
            this.renderer2.listen(target, eventName, (event: Event) => {
495
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
6✔
496
                if (beforeInputEvent) {
6!
497
                    this.onFallbackBeforeInput(beforeInputEvent);
×
498
                }
499
                listener(event);
6✔
500
            })
501
        );
502
    }
503

504
    private toSlateSelection() {
505
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
3✔
506
            try {
2✔
507
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
508
                const { activeElement } = root;
2✔
509
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
510
                const domSelection = (root as Document).getSelection();
2✔
511

512
                if (activeElement === el) {
2!
513
                    this.latestElement = activeElement;
2✔
514
                    IS_FOCUSED.set(this.editor, true);
2✔
515
                } else {
516
                    IS_FOCUSED.delete(this.editor);
×
517
                }
518

519
                if (!domSelection) {
2!
520
                    return Transforms.deselect(this.editor);
×
521
                }
522

523
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
2✔
524
                const hasDomSelectionInEditor =
525
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
2✔
526
                if (!hasDomSelectionInEditor) {
2!
527
                    Transforms.deselect(this.editor);
×
528
                    return;
×
529
                }
530

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

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

629
                // COMPAT: If the selection is expanded, even if the command seems like
630
                // a delete forward/backward command it should delete the selection.
631
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
632
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
633
                    Editor.deleteFragment(editor, { direction });
×
634
                    return;
×
635
                }
636

637
                switch (type) {
×
638
                    case 'deleteByComposition':
639
                    case 'deleteByCut':
640
                    case 'deleteByDrag': {
641
                        Editor.deleteFragment(editor);
×
642
                        break;
×
643
                    }
644

645
                    case 'deleteContent':
646
                    case 'deleteContentForward': {
647
                        Editor.deleteForward(editor);
×
648
                        break;
×
649
                    }
650

651
                    case 'deleteContentBackward': {
652
                        Editor.deleteBackward(editor);
×
653
                        break;
×
654
                    }
655

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

662
                    case 'deleteHardLineBackward': {
663
                        Editor.deleteBackward(editor, { unit: 'block' });
×
664
                        break;
×
665
                    }
666

667
                    case 'deleteSoftLineBackward': {
668
                        Editor.deleteBackward(editor, { unit: 'line' });
×
669
                        break;
×
670
                    }
671

672
                    case 'deleteHardLineForward': {
673
                        Editor.deleteForward(editor, { unit: 'block' });
×
674
                        break;
×
675
                    }
676

677
                    case 'deleteSoftLineForward': {
678
                        Editor.deleteForward(editor, { unit: 'line' });
×
679
                        break;
×
680
                    }
681

682
                    case 'deleteWordBackward': {
683
                        Editor.deleteBackward(editor, { unit: 'word' });
×
684
                        break;
×
685
                    }
686

687
                    case 'deleteWordForward': {
688
                        Editor.deleteForward(editor, { unit: 'word' });
×
689
                        break;
×
690
                    }
691

692
                    case 'insertLineBreak':
693
                    case 'insertParagraph': {
694
                        Editor.insertBreak(editor);
×
695
                        break;
×
696
                    }
697

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

733
    private onDOMBlur(event: FocusEvent) {
734
        if (
×
735
            this.readonly ||
×
736
            this.isUpdatingSelection ||
737
            !hasEditableTarget(this.editor, event.target) ||
738
            this.isDOMEventHandled(event, this.blur)
739
        ) {
740
            return;
×
741
        }
742

743
        const window = AngularEditor.getWindow(this.editor);
×
744

745
        // COMPAT: If the current `activeElement` is still the previous
746
        // one, this is due to the window being blurred when the tab
747
        // itself becomes unfocused, so we want to abort early to allow to
748
        // editor to stay focused when the tab becomes focused again.
749
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
750
        if (this.latestElement === root.activeElement) {
×
751
            return;
×
752
        }
753

754
        const { relatedTarget } = event;
×
755
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
756

757
        // COMPAT: The event should be ignored if the focus is returning
758
        // to the editor from an embedded editable element (eg. an <input>
759
        // element inside a void node).
760
        if (relatedTarget === el) {
×
761
            return;
×
762
        }
763

764
        // COMPAT: The event should be ignored if the focus is moving from
765
        // the editor to inside a void node's spacer element.
766
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
767
            return;
×
768
        }
769

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

776
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
777
                return;
×
778
            }
779
        }
780

781
        IS_FOCUSED.delete(this.editor);
×
782
    }
783

784
    private onDOMClick(event: MouseEvent) {
785
        if (
×
786
            !this.readonly &&
×
787
            hasTarget(this.editor, event.target) &&
788
            !this.isDOMEventHandled(event, this.click) &&
789
            isDOMNode(event.target)
790
        ) {
791
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
792
            const path = AngularEditor.findPath(this.editor, node);
×
793
            const start = Editor.start(this.editor, path);
×
794
            const end = Editor.end(this.editor, path);
×
795

796
            const startVoid = Editor.void(this.editor, { at: start });
×
797
            const endVoid = Editor.void(this.editor, { at: end });
×
798

799
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
800
                const range = Editor.range(this.editor, start);
×
801
                Transforms.select(this.editor, range);
×
802
            }
803
        }
804
    }
805

806
    private onDOMCompositionStart(event: CompositionEvent) {
807
        const { selection } = this.editor;
1✔
808

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

823
    private onDOMCompositionUpdate(event: CompositionEvent) {
824
        this.isDOMEventHandled(event, this.compositionUpdate);
×
825
    }
826

827
    private onDOMCompositionEnd(event: CompositionEvent) {
828
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
829
            Transforms.delete(this.editor);
×
830
        }
831
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
832
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
833
            // aren't correct and never fire the "insertFromComposition"
834
            // type that we need. So instead, insert whenever a composition
835
            // ends since it will already have been committed to the DOM.
836
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
837
                preventInsertFromComposition(event, this.editor);
×
838
                Editor.insertText(this.editor, event.data);
×
839
            }
840

841
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
842
            // so we need avoid repeat isnertText by isComposing === true,
843
            this.isComposing = false;
×
844
        }
845
        this.detectContext();
×
846
        this.cdr.detectChanges();
×
847
    }
848

849
    private onDOMCopy(event: ClipboardEvent) {
850
        const window = AngularEditor.getWindow(this.editor);
×
851
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
852
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
853
            event.preventDefault();
×
854
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
855
        }
856
    }
857

858
    private onDOMCut(event: ClipboardEvent) {
859
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
860
            event.preventDefault();
×
861
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
862
            const { selection } = this.editor;
×
863

864
            if (selection) {
×
865
                AngularEditor.deleteCutData(this.editor);
×
866
            }
867
        }
868
    }
869

870
    private onDOMDragOver(event: DragEvent) {
871
        if (hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
872
            // Only when the target is void, call `preventDefault` to signal
873
            // that drops are allowed. Editable content is droppable by
874
            // default, and calling `preventDefault` hides the cursor.
875
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
876

877
            if (Editor.isVoid(this.editor, node)) {
×
878
                event.preventDefault();
×
879
            }
880
        }
881
    }
882

883
    private onDOMDragStart(event: DragEvent) {
884
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
885
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
886
            const path = AngularEditor.findPath(this.editor, node);
×
887
            const voidMatch = Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true });
×
888

889
            // If starting a drag on a void node, make sure it is selected
890
            // so that it shows up in the selection's fragment.
891
            if (voidMatch) {
×
892
                const range = Editor.range(this.editor, path);
×
893
                Transforms.select(this.editor, range);
×
894
            }
895

896
            this.isDraggingInternally = true;
×
897

898
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
899
        }
900
    }
901

902
    private onDOMDrop(event: DragEvent) {
903
        const editor = this.editor;
×
904
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
905
            event.preventDefault();
×
906
            // Keep a reference to the dragged range before updating selection
907
            const draggedRange = editor.selection;
×
908

909
            // Find the range where the drop happened
910
            const range = AngularEditor.findEventRange(editor, event);
×
911
            const data = event.dataTransfer;
×
912

913
            Transforms.select(editor, range);
×
914

915
            if (this.isDraggingInternally) {
×
916
                if (draggedRange) {
×
917
                    Transforms.delete(editor, {
×
918
                        at: draggedRange
919
                    });
920
                }
921

922
                this.isDraggingInternally = false;
×
923
            }
924

925
            AngularEditor.insertData(editor, data);
×
926

927
            // When dragging from another source into the editor, it's possible
928
            // that the current editor does not have focus.
929
            if (!AngularEditor.isFocused(editor)) {
×
930
                AngularEditor.focus(editor);
×
931
            }
932
        }
933
    }
934

935
    private onDOMDragEnd(event: DragEvent) {
936
        if (
×
937
            !this.readonly &&
×
938
            this.isDraggingInternally &&
939
            hasTarget(this.editor, event.target) &&
940
            !this.isDOMEventHandled(event, this.dragEnd)
941
        ) {
942
            this.isDraggingInternally = false;
×
943
        }
944
    }
945

946
    private onDOMFocus(event: Event) {
947
        if (
2✔
948
            !this.readonly &&
8✔
949
            !this.isUpdatingSelection &&
950
            hasEditableTarget(this.editor, event.target) &&
951
            !this.isDOMEventHandled(event, this.focus)
952
        ) {
953
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
954
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
955
            this.latestElement = root.activeElement;
2✔
956

957
            // COMPAT: If the editor has nested editable elements, the focus
958
            // can go to them. In Firefox, this must be prevented because it
959
            // results in issues with keyboard navigation. (2017/03/30)
960
            if (IS_FIREFOX && event.target !== el) {
2!
961
                el.focus();
×
962
                return;
×
963
            }
964

965
            IS_FOCUSED.set(this.editor, true);
2✔
966
        }
967
    }
968

969
    private onDOMKeydown(event: KeyboardEvent) {
970
        const editor = this.editor;
×
971
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
972
        const { activeElement } = root;
×
973
        if (
×
974
            !this.readonly &&
×
975
            hasEditableTarget(editor, event.target) &&
976
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
977
            !this.isComposing &&
978
            !this.isDOMEventHandled(event, this.keydown)
979
        ) {
980
            const nativeEvent = event;
×
981
            const { selection } = editor;
×
982

983
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
984
            const isRTL = direction(Node.string(element)) === 'rtl';
×
985

986
            try {
×
987
                // COMPAT: Since we prevent the default behavior on
988
                // `beforeinput` events, the browser doesn't think there's ever
989
                // any history stack to undo or redo, so we have to manage these
990
                // hotkeys ourselves. (2019/11/06)
991
                if (Hotkeys.isRedo(nativeEvent)) {
×
992
                    event.preventDefault();
×
993

994
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
995
                        editor.redo();
×
996
                    }
997

998
                    return;
×
999
                }
1000

1001
                if (Hotkeys.isUndo(nativeEvent)) {
×
1002
                    event.preventDefault();
×
1003

1004
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1005
                        editor.undo();
×
1006
                    }
1007

1008
                    return;
×
1009
                }
1010

1011
                // COMPAT: Certain browsers don't handle the selection updates
1012
                // properly. In Chrome, the selection isn't properly extended.
1013
                // And in Firefox, the selection isn't properly collapsed.
1014
                // (2017/10/17)
1015
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1016
                    event.preventDefault();
×
1017
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1018
                    return;
×
1019
                }
1020

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

1027
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1028
                    event.preventDefault();
×
1029
                    Transforms.move(editor, {
×
1030
                        unit: 'line',
1031
                        edge: 'focus',
1032
                        reverse: true
1033
                    });
1034
                    return;
×
1035
                }
1036

1037
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1038
                    event.preventDefault();
×
1039
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1040
                    return;
×
1041
                }
1042

1043
                // COMPAT: If a void node is selected, or a zero-width text node
1044
                // adjacent to an inline is selected, we need to handle these
1045
                // hotkeys manually because browsers won't be able to skip over
1046
                // the void node with the zero-width space not being an empty
1047
                // string.
1048
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1049
                    event.preventDefault();
×
1050

1051
                    if (selection && Range.isCollapsed(selection)) {
×
1052
                        Transforms.move(editor, { reverse: !isRTL });
×
1053
                    } else {
1054
                        Transforms.collapse(editor, { edge: 'start' });
×
1055
                    }
1056

1057
                    return;
×
1058
                }
1059

1060
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1061
                    event.preventDefault();
×
1062

1063
                    if (selection && Range.isCollapsed(selection)) {
×
1064
                        Transforms.move(editor, { reverse: isRTL });
×
1065
                    } else {
1066
                        Transforms.collapse(editor, { edge: 'end' });
×
1067
                    }
1068

1069
                    return;
×
1070
                }
1071

1072
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1073
                    event.preventDefault();
×
1074

1075
                    if (selection && Range.isExpanded(selection)) {
×
1076
                        Transforms.collapse(editor, { edge: 'focus' });
×
1077
                    }
1078

1079
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1080
                    return;
×
1081
                }
1082

1083
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1084
                    event.preventDefault();
×
1085

1086
                    if (selection && Range.isExpanded(selection)) {
×
1087
                        Transforms.collapse(editor, { edge: 'focus' });
×
1088
                    }
1089

1090
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1091
                    return;
×
1092
                }
1093

1094
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1095
                // fall back to guessing at the input intention for hotkeys.
1096
                // COMPAT: In iOS, some of these hotkeys are handled in the
1097
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1098
                    // We don't have a core behavior for these, but they change the
1099
                    // DOM if we don't prevent them, so we have to.
1100
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1101
                        event.preventDefault();
×
1102
                        return;
×
1103
                    }
1104

1105
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1106
                        event.preventDefault();
×
1107
                        Editor.insertBreak(editor);
×
1108
                        return;
×
1109
                    }
1110

1111
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1112
                        event.preventDefault();
×
1113

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

1122
                        return;
×
1123
                    }
1124

1125
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1126
                        event.preventDefault();
×
1127

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

1136
                        return;
×
1137
                    }
1138

1139
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1140
                        event.preventDefault();
×
1141

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

1150
                        return;
×
1151
                    }
1152

1153
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1154
                        event.preventDefault();
×
1155

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

1164
                        return;
×
1165
                    }
1166

1167
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1168
                        event.preventDefault();
×
1169

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

1178
                        return;
×
1179
                    }
1180

1181
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1182
                        event.preventDefault();
×
1183

1184
                        if (selection && Range.isExpanded(selection)) {
×
1185
                            Editor.deleteFragment(editor, {
×
1186
                                direction: 'forward'
1187
                            });
1188
                        } else {
1189
                            Editor.deleteForward(editor, { unit: 'word' });
×
1190
                        }
1191

1192
                        return;
×
1193
                    }
1194
                } else {
1195
                    if (IS_CHROME || IS_SAFARI) {
×
1196
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1197
                        // an event when deleting backwards in a selected void inline node
1198
                        if (
×
1199
                            selection &&
×
1200
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1201
                            Range.isCollapsed(selection)
1202
                        ) {
1203
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1204
                            if (
×
1205
                                Element.isElement(currentNode) &&
×
1206
                                Editor.isVoid(editor, currentNode) &&
1207
                                Editor.isInline(editor, currentNode)
1208
                            ) {
1209
                                event.preventDefault();
×
1210
                                Editor.deleteBackward(editor, {
×
1211
                                    unit: 'block'
1212
                                });
1213
                                return;
×
1214
                            }
1215
                        }
1216
                    }
1217
                }
1218
            } catch (error) {
1219
                this.editor.onError({
×
1220
                    code: SlateErrorCode.OnDOMKeydownError,
1221
                    nativeError: error
1222
                });
1223
            }
1224
        }
1225
    }
1226

1227
    private onDOMPaste(event: ClipboardEvent) {
1228
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1229
        // fall back to React's `onPaste` here instead.
1230
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1231
        // when "paste without formatting" option is used.
1232
        // This unfortunately needs to be handled with paste events instead.
1233
        if (
×
1234
            !this.isDOMEventHandled(event, this.paste) &&
×
1235
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1236
            !this.readonly &&
1237
            hasEditableTarget(this.editor, event.target)
1238
        ) {
1239
            event.preventDefault();
×
1240
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1241
        }
1242
    }
1243

1244
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1245
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1246
        // fall back to React's leaky polyfill instead just for it. It
1247
        // only works for the `insertText` input type.
1248
        if (
×
1249
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1250
            !this.readonly &&
1251
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1252
            hasEditableTarget(this.editor, event.nativeEvent.target)
1253
        ) {
1254
            event.nativeEvent.preventDefault();
×
1255
            try {
×
1256
                const text = event.data;
×
1257
                if (!Range.isCollapsed(this.editor.selection)) {
×
1258
                    Editor.deleteFragment(this.editor);
×
1259
                }
1260
                // just handle Non-IME input
1261
                if (!this.isComposing) {
×
1262
                    Editor.insertText(this.editor, text);
×
1263
                }
1264
            } catch (error) {
1265
                this.editor.onError({
×
1266
                    code: SlateErrorCode.ToNativeSelectionError,
1267
                    nativeError: error
1268
                });
1269
            }
1270
        }
1271
    }
1272

1273
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1274
        if (!handler) {
3✔
1275
            return false;
3✔
1276
        }
1277
        handler(event);
×
1278
        return event.defaultPrevented;
×
1279
    }
1280
    //#endregion
1281

1282
    ngOnDestroy() {
1283
        NODE_TO_ELEMENT.delete(this.editor);
20✔
1284
        this.manualListeners.forEach(manualListener => {
20✔
1285
            manualListener();
420✔
1286
        });
1287
        this.destroy$.complete();
20✔
1288
        EDITOR_TO_ON_CHANGE.delete(this.editor);
20✔
1289
    }
1290
}
1291

1292
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1293
    // This was affecting the selection of multiple blocks and dragging behavior,
1294
    // so enabled only if the selection has been collapsed.
1295
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1296
        const leafEl = domRange.startContainer.parentElement!;
×
1297
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1298
        scrollIntoView(leafEl, {
×
1299
            scrollMode: 'if-needed'
1300
        });
1301
        delete leafEl.getBoundingClientRect;
×
1302
    }
1303
};
1304

1305
/**
1306
 * Check if the target is editable and in the editor.
1307
 */
1308

1309
export const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1310
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
3✔
1311
};
1312

1313
/**
1314
 * Check if two DOM range objects are equal.
1315
 */
1316
const isRangeEqual = (a: DOMRange, b: DOMRange) => {
1✔
1317
    return (
×
1318
        (a.startContainer === b.startContainer &&
×
1319
            a.startOffset === b.startOffset &&
1320
            a.endContainer === b.endContainer &&
1321
            a.endOffset === b.endOffset) ||
1322
        (a.startContainer === b.endContainer &&
1323
            a.startOffset === b.endOffset &&
1324
            a.endContainer === b.startContainer &&
1325
            a.endOffset === b.startOffset)
1326
    );
1327
};
1328

1329
/**
1330
 * Check if the target is in the editor.
1331
 */
1332

1333
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1334
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
1✔
1335
};
1336

1337
/**
1338
 * Check if the target is inside void and in the editor.
1339
 */
1340

1341
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1342
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1343
    return Editor.isVoid(editor, slateNode);
1✔
1344
};
1345

1346
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1347
    return (
3✔
1348
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
6!
1349
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1350
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1351
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1352
    );
1353
};
1354

1355
/**
1356
 * remove default insert from composition
1357
 * @param text
1358
 */
1359
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1360
    const types = ['compositionend', 'insertFromComposition'];
×
1361
    if (!types.includes(event.type)) {
×
1362
        return;
×
1363
    }
1364
    const insertText = (event as CompositionEvent).data;
×
1365
    const window = AngularEditor.getWindow(editor);
×
1366
    const domSelection = window.getSelection();
×
1367
    // ensure text node insert composition input text
1368
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1369
        const textNode = domSelection.anchorNode;
×
1370
        textNode.splitText(textNode.length - insertText.length).remove();
×
1371
    }
1372
};
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