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

worktile / slate-angular / bbef38c2-b9dd-46f4-8180-1ef56bbede3e

08 Mar 2024 09:19AM UTC coverage: 48.043% (+19.3%) from 28.702%
bbef38c2-b9dd-46f4-8180-1ef56bbede3e

push

circleci

pubuzhixing8
feat(core): support suppressThrow in toSlateRange/toSlatePoint/isLeafInEditor to check domSelection is valid

402 of 1034 branches covered (38.88%)

Branch coverage included in aggregate %.

19 of 32 new or added lines in 3 files covered. (59.38%)

2 existing lines in 1 file now uncovered.

985 of 1853 relevant lines covered (53.16%)

46.22 hits per line

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

30.86
/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
    Inject,
20
    inject,
21
    ViewContainerRef
22
} from '@angular/core';
23
import {
24
    NODE_TO_ELEMENT,
25
    IS_FOCUSED,
26
    EDITOR_TO_ELEMENT,
27
    ELEMENT_TO_NODE,
28
    IS_READONLY,
29
    EDITOR_TO_ON_CHANGE,
30
    EDITOR_TO_WINDOW
31
} from '../../utils/weak-maps';
32
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
33
import { direction } from 'direction';
34
import scrollIntoView from 'scroll-into-view-if-needed';
35
import { AngularEditor } from '../../plugins/angular-editor';
36
import {
37
    DOMElement,
38
    DOMNode,
39
    isDOMNode,
40
    DOMStaticRange,
41
    DOMRange,
42
    isDOMElement,
43
    isPlainTextOnlyPaste,
44
    DOMSelection,
45
    getDefaultView
46
} from '../../utils/dom';
47
import { Subject } from 'rxjs';
48
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
49
import Hotkeys from '../../utils/hotkeys';
50
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
51
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
52
import { SlateErrorCode } from '../../types/error';
53
import { SlateStringTemplate } from '../string/template.component';
54
import { NG_VALUE_ACCESSOR } from '@angular/forms';
55
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
56
import { ComponentType, ViewType } from '../../types/view';
57
import { HistoryEditor } from 'slate-history';
58
import { isDecoratorRangeListEqual, check, normalize } from '../../utils';
59
import { SlatePlaceholder } from '../../types/feature';
60
import { restoreDom } from '../../utils/restore-dom';
61
import { SlateChildren } from '../children/children.component';
62
import { SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN } from '../element/default-element.component.token';
63
import { SLATE_DEFAULT_TEXT_COMPONENT_TOKEN, SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN } from '../text/token';
64
import { SlateVoidText } from '../text/void-text.component';
65
import { SlateDefaultText } from '../text/default-text.component';
66
import { SlateDefaultElement } from '../element/default-element.component';
67
import { SlateDefaultLeaf } from '../leaf/default-leaf.component';
68
import { SLATE_DEFAULT_LEAF_COMPONENT_TOKEN } from '../leaf/token';
69
import { BaseElementComponent, BaseLeafComponent, BaseTextComponent } from '../../view/base';
70
import { ListRender } from '../../view/render/list-render';
71
import { TRIPLE_CLICK } from '../../utils/constants';
72

73
// not correctly clipboardData on beforeinput
74
const forceOnDOMPaste = IS_SAFARI;
1✔
75

76
@Component({
77
    selector: 'slate-editable',
78
    host: {
79
        class: 'slate-editable-container',
80
        '[attr.contenteditable]': 'readonly ? undefined : true',
81
        '[attr.role]': `readonly ? undefined : 'textbox'`,
82
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
83
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
84
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
85
    },
86
    templateUrl: 'editable.component.html',
87
    changeDetection: ChangeDetectionStrategy.OnPush,
88
    providers: [
89
        {
90
            provide: NG_VALUE_ACCESSOR,
91
            useExisting: forwardRef(() => SlateEditable),
23✔
92
            multi: true
93
        },
94
        {
95
            provide: SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN,
96
            useValue: SlateDefaultElement
97
        },
98
        {
99
            provide: SLATE_DEFAULT_TEXT_COMPONENT_TOKEN,
100
            useValue: SlateDefaultText
101
        },
102
        {
103
            provide: SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN,
104
            useValue: SlateVoidText
105
        },
106
        {
107
            provide: SLATE_DEFAULT_LEAF_COMPONENT_TOKEN,
108
            useValue: SlateDefaultLeaf
109
        }
110
    ],
111
    standalone: true,
112
    imports: [SlateChildren, SlateStringTemplate]
113
})
114
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
115
    viewContext: SlateViewContext;
116
    context: SlateChildrenContext;
117

118
    private destroy$ = new Subject();
23✔
119

120
    isComposing = false;
23✔
121
    isDraggingInternally = false;
23✔
122
    isUpdatingSelection = false;
23✔
123
    latestElement = null as DOMElement | null;
23✔
124

125
    protected manualListeners: (() => void)[] = [];
23✔
126

127
    private initialized: boolean;
128

129
    private onTouchedCallback: () => void = () => {};
23✔
130

131
    private onChangeCallback: (_: any) => void = () => {};
23✔
132

133
    @Input() editor: AngularEditor;
134

135
    @Input() renderElement: (element: Element) => ViewType | null;
136

137
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
138

139
    @Input() renderText: (text: SlateText) => ViewType | null;
140

141
    @Input() decorate: (entry: NodeEntry) => Range[] = () => [];
228✔
142

143
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
144

145
    @Input() scrollSelectionIntoView: (editor: AngularEditor, domRange: DOMRange) => void = defaultScrollSelectionIntoView;
23✔
146

147
    @Input() isStrictDecorate: boolean = true;
23✔
148

149
    @Input() trackBy: (node: Element) => any = () => null;
206✔
150

151
    @Input() readonly = false;
23✔
152

153
    @Input() placeholder: string;
154

155
    //#region input event handler
156
    @Input() beforeInput: (event: Event) => void;
157
    @Input() blur: (event: Event) => void;
158
    @Input() click: (event: MouseEvent) => void;
159
    @Input() compositionEnd: (event: CompositionEvent) => void;
160
    @Input() compositionUpdate: (event: CompositionEvent) => void;
161
    @Input() compositionStart: (event: CompositionEvent) => void;
162
    @Input() copy: (event: ClipboardEvent) => void;
163
    @Input() cut: (event: ClipboardEvent) => void;
164
    @Input() dragOver: (event: DragEvent) => void;
165
    @Input() dragStart: (event: DragEvent) => void;
166
    @Input() dragEnd: (event: DragEvent) => void;
167
    @Input() drop: (event: DragEvent) => void;
168
    @Input() focus: (event: Event) => void;
169
    @Input() keydown: (event: KeyboardEvent) => void;
170
    @Input() paste: (event: ClipboardEvent) => void;
171
    //#endregion
172

173
    //#region DOM attr
174
    @Input() spellCheck = false;
23✔
175
    @Input() autoCorrect = false;
23✔
176
    @Input() autoCapitalize = false;
23✔
177

178
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
179
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
180
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
181

182
    get hasBeforeInputSupport() {
183
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
184
    }
185
    //#endregion
186

187
    @ViewChild('templateComponent', { static: true })
188
    templateComponent: SlateStringTemplate;
189

190
    @ViewChild('templateComponent', { static: true, read: ElementRef })
191
    templateElementRef: ElementRef<any>;
192

193
    viewContainerRef = inject(ViewContainerRef);
23✔
194

195
    getOutletParent = () => {
23✔
196
        return this.elementRef.nativeElement;
43✔
197
    };
198

199
    listRender: ListRender;
200

201
    constructor(
202
        public elementRef: ElementRef,
23✔
203
        public renderer2: Renderer2,
23✔
204
        public cdr: ChangeDetectorRef,
23✔
205
        private ngZone: NgZone,
23✔
206
        private injector: Injector,
23✔
207
        @Inject(SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN)
208
        public defaultElement: ComponentType<BaseElementComponent>,
23✔
209
        @Inject(SLATE_DEFAULT_TEXT_COMPONENT_TOKEN)
210
        public defaultText: ComponentType<BaseTextComponent>,
23✔
211
        @Inject(SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN)
212
        public defaultVoidText: ComponentType<BaseTextComponent>,
23✔
213
        @Inject(SLATE_DEFAULT_LEAF_COMPONENT_TOKEN)
214
        public defaultLeaf: ComponentType<BaseLeafComponent>
23✔
215
    ) {}
216

217
    ngOnInit() {
218
        this.editor.injector = this.injector;
23✔
219
        this.editor.children = [];
23✔
220
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
221
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
222
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
223
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
224
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
225
        IS_READONLY.set(this.editor, this.readonly);
23✔
226
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
227
            this.ngZone.run(() => {
13✔
228
                this.onChange();
13✔
229
            });
230
        });
231
        this.ngZone.runOutsideAngular(() => {
23✔
232
            this.initialize();
23✔
233
        });
234
        this.initializeViewContext();
23✔
235
        this.initializeContext();
23✔
236

237
        // remove unused DOM, just keep templateComponent instance
238
        this.templateElementRef.nativeElement.remove();
23✔
239

240
        // add browser class
241
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
242
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
243
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, () => null);
23✔
244
    }
245

246
    ngOnChanges(simpleChanges: SimpleChanges) {
247
        if (!this.initialized) {
30✔
248
            return;
23✔
249
        }
250
        const decorateChange = simpleChanges['decorate'];
7✔
251
        if (decorateChange) {
7✔
252
            this.forceRender();
2✔
253
        }
254
        const placeholderChange = simpleChanges['placeholder'];
7✔
255
        if (placeholderChange) {
7✔
256
            this.render();
1✔
257
        }
258
        const readonlyChange = simpleChanges['readonly'];
7✔
259
        if (readonlyChange) {
7!
260
            IS_READONLY.set(this.editor, this.readonly);
×
261
            this.render();
×
262
            this.toSlateSelection();
×
263
        }
264
    }
265

266
    registerOnChange(fn: any) {
267
        this.onChangeCallback = fn;
23✔
268
    }
269
    registerOnTouched(fn: any) {
270
        this.onTouchedCallback = fn;
23✔
271
    }
272

273
    writeValue(value: Element[]) {
274
        if (value && value.length) {
49✔
275
            if (check(value)) {
26!
276
                this.editor.children = value;
26✔
277
            } else {
278
                this.editor.onError({
×
279
                    code: SlateErrorCode.InvalidValueError,
280
                    name: 'initialize invalid data',
281
                    data: value
282
                });
283
                this.editor.children = normalize(value);
×
284
            }
285
            this.initializeContext();
26✔
286
            if (!this.listRender.initialized) {
26✔
287
                this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
288
            } else {
289
                this.listRender.update(this.editor.children, this.editor, this.context);
3✔
290
            }
291
            this.cdr.markForCheck();
26✔
292
        }
293
    }
294

295
    initialize() {
296
        this.initialized = true;
23✔
297
        const window = AngularEditor.getWindow(this.editor);
23✔
298
        this.addEventListener(
23✔
299
            'selectionchange',
300
            event => {
301
                this.toSlateSelection();
3✔
302
            },
303
            window.document
304
        );
305
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
306
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
307
        }
308
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
309
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
310
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
311
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
312
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
313
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
314
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
315
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
316
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
317
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
318
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
319
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
320
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
321
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
322
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
323
            this.addEventListener(event.name, () => {});
115✔
324
        });
325
    }
326

327
    toNativeSelection() {
328
        try {
15✔
329
            const { selection } = this.editor;
15✔
330
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
331
            const { activeElement } = root;
15✔
332
            const domSelection = (root as Document).getSelection();
15✔
333

334
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
335
                return;
14✔
336
            }
337

338
            const hasDomSelection = domSelection.type !== 'None';
1✔
339

340
            // If the DOM selection is properly unset, we're done.
341
            if (!selection && !hasDomSelection) {
1!
342
                return;
×
343
            }
344

345
            // If the DOM selection is already correct, we're done.
346
            // verify that the dom selection is in the editor
347
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
348
            let hasDomSelectionInEditor = false;
1✔
349
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
350
                hasDomSelectionInEditor = true;
1✔
351
            }
352

353
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
354
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
355
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, { suppressThrow: true });
1✔
356
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
NEW
357
                    return;
×
358
                }
359
            }
360

361
            // prevent updating native selection when active element is void element
362
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
363
                return;
×
364
            }
365

366
            // when <Editable/> is being controlled through external value
367
            // then its children might just change - DOM responds to it on its own
368
            // but Slate's value is not being updated through any operation
369
            // and thus it doesn't transform selection on its own
370
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
NEW
371
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { suppressThrow: false });
×
372
                return;
×
373
            }
374

375
            // Otherwise the DOM selection is out of sync, so update it.
376
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
377
            this.isUpdatingSelection = true;
1✔
378

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

381
            if (newDomRange) {
1!
382
                // COMPAT: Since the DOM range has no concept of backwards/forwards
383
                // we need to check and do the right thing here.
384
                if (Range.isBackward(selection)) {
1!
385
                    // eslint-disable-next-line max-len
386
                    domSelection.setBaseAndExtent(
×
387
                        newDomRange.endContainer,
388
                        newDomRange.endOffset,
389
                        newDomRange.startContainer,
390
                        newDomRange.startOffset
391
                    );
392
                } else {
393
                    // eslint-disable-next-line max-len
394
                    domSelection.setBaseAndExtent(
1✔
395
                        newDomRange.startContainer,
396
                        newDomRange.startOffset,
397
                        newDomRange.endContainer,
398
                        newDomRange.endOffset
399
                    );
400
                }
401
            } else {
402
                domSelection.removeAllRanges();
×
403
            }
404

405
            newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
406

407
            setTimeout(() => {
1✔
408
                // COMPAT: In Firefox, it's not enough to create a range, you also need
409
                // to focus the contenteditable element too. (2016/11/16)
410
                if (newDomRange && IS_FIREFOX) {
1!
411
                    el.focus();
×
412
                }
413

414
                this.isUpdatingSelection = false;
1✔
415
            });
416
        } catch (error) {
417
            this.editor.onError({
×
418
                code: SlateErrorCode.ToNativeSelectionError,
419
                nativeError: error
420
            });
421
            this.isUpdatingSelection = false;
×
422
        }
423
    }
424

425
    onChange() {
426
        this.forceRender();
13✔
427
        this.onChangeCallback(this.editor.children);
13✔
428
    }
429

430
    ngAfterViewChecked() {}
431

432
    ngDoCheck() {}
433

434
    forceRender() {
435
        this.updateContext();
15✔
436
        this.listRender.update(this.editor.children, this.editor, this.context);
15✔
437
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
438
        // when the DOMElement where the selection is located is removed
439
        // the compositionupdate and compositionend events will no longer be fired
440
        // so isComposing needs to be corrected
441
        // need exec after this.cdr.detectChanges() to render HTML
442
        // need exec before this.toNativeSelection() to correct native selection
443
        if (this.isComposing) {
15!
444
            // Composition input text be not rendered when user composition input with selection is expanded
445
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
446
            // this time condition is true and isComposiing is assigned false
447
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
448
            setTimeout(() => {
×
449
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
450
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
451
                let textContent = '';
×
452
                // skip decorate text
453
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
454
                    let text = stringDOMNode.textContent;
×
455
                    const zeroChar = '\uFEFF';
×
456
                    // remove zero with char
457
                    if (text.startsWith(zeroChar)) {
×
458
                        text = text.slice(1);
×
459
                    }
460
                    if (text.endsWith(zeroChar)) {
×
461
                        text = text.slice(0, text.length - 1);
×
462
                    }
463
                    textContent += text;
×
464
                });
465
                if (Node.string(textNode).endsWith(textContent)) {
×
466
                    this.isComposing = false;
×
467
                }
468
            }, 0);
469
        }
470
        this.toNativeSelection();
15✔
471
    }
472

473
    render() {
474
        const changed = this.updateContext();
2✔
475
        if (changed) {
2✔
476
            this.listRender.update(this.editor.children, this.editor, this.context);
2✔
477
        }
478
    }
479

480
    updateContext() {
481
        const decorations = this.generateDecorations();
17✔
482
        if (
17✔
483
            this.context.selection !== this.editor.selection ||
46✔
484
            this.context.decorate !== this.decorate ||
485
            this.context.readonly !== this.readonly ||
486
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
487
        ) {
488
            this.context = {
10✔
489
                parent: this.editor,
490
                selection: this.editor.selection,
491
                decorations: decorations,
492
                decorate: this.decorate,
493
                readonly: this.readonly
494
            };
495
            return true;
10✔
496
        }
497
        return false;
7✔
498
    }
499

500
    initializeContext() {
501
        this.context = {
49✔
502
            parent: this.editor,
503
            selection: this.editor.selection,
504
            decorations: this.generateDecorations(),
505
            decorate: this.decorate,
506
            readonly: this.readonly
507
        };
508
    }
509

510
    initializeViewContext() {
511
        this.viewContext = {
23✔
512
            editor: this.editor,
513
            renderElement: this.renderElement,
514
            renderLeaf: this.renderLeaf,
515
            renderText: this.renderText,
516
            trackBy: this.trackBy,
517
            isStrictDecorate: this.isStrictDecorate,
518
            templateComponent: this.templateComponent,
519
            defaultElement: this.defaultElement,
520
            defaultText: this.defaultText,
521
            defaultVoidText: this.defaultVoidText,
522
            defaultLeaf: this.defaultLeaf
523
        };
524
    }
525

526
    composePlaceholderDecorate(editor: Editor) {
527
        if (this.placeholderDecorate) {
64!
528
            return this.placeholderDecorate(editor) || [];
×
529
        }
530

531
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
532
            const start = Editor.start(editor, []);
3✔
533
            return [
3✔
534
                {
535
                    placeholder: this.placeholder,
536
                    anchor: start,
537
                    focus: start
538
                }
539
            ];
540
        } else {
541
            return [];
61✔
542
        }
543
    }
544

545
    generateDecorations() {
546
        const decorations = this.decorate([this.editor, []]);
66✔
547
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
548
        decorations.push(...placeholderDecorations);
66✔
549
        return decorations;
66✔
550
    }
551

552
    //#region event proxy
553
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
554
        this.manualListeners.push(
483✔
555
            this.renderer2.listen(target, eventName, (event: Event) => {
556
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
6✔
557
                if (beforeInputEvent) {
6!
558
                    this.onFallbackBeforeInput(beforeInputEvent);
×
559
                }
560
                listener(event);
6✔
561
            })
562
        );
563
    }
564

565
    private toSlateSelection() {
566
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
3✔
567
            try {
2✔
568
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
569
                const { activeElement } = root;
2✔
570
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
571
                const domSelection = (root as Document).getSelection();
2✔
572

573
                if (activeElement === el) {
2!
574
                    this.latestElement = activeElement;
2✔
575
                    IS_FOCUSED.set(this.editor, true);
2✔
576
                } else {
577
                    IS_FOCUSED.delete(this.editor);
×
578
                }
579

580
                if (!domSelection) {
2!
581
                    return Transforms.deselect(this.editor);
×
582
                }
583

584
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
2✔
585
                const hasDomSelectionInEditor =
586
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
2✔
587
                if (!hasDomSelectionInEditor) {
2!
588
                    Transforms.deselect(this.editor);
×
589
                    return;
×
590
                }
591

592
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
593
                // for example, double-click the last cell of the table to select a non-editable DOM
594
                const range = AngularEditor.toSlateRange(this.editor, domSelection);
2✔
595
                if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
2!
596
                    if (!isTargetInsideVoid(this.editor, activeElement)) {
×
597
                        // force adjust DOMSelection
598
                        this.toNativeSelection();
×
599
                    }
600
                } else {
601
                    Transforms.select(this.editor, range);
2✔
602
                }
603
            } catch (error) {
604
                this.editor.onError({
×
605
                    code: SlateErrorCode.ToSlateSelectionError,
606
                    nativeError: error
607
                });
608
            }
609
        }
610
    }
611

612
    private onDOMBeforeInput(
613
        event: Event & {
614
            inputType: string;
615
            isComposing: boolean;
616
            data: string | null;
617
            dataTransfer: DataTransfer | null;
618
            getTargetRanges(): DOMStaticRange[];
619
        }
620
    ) {
621
        const editor = this.editor;
×
622
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
623
        const { activeElement } = root;
×
624
        const { selection } = editor;
×
625
        const { inputType: type } = event;
×
626
        const data = event.dataTransfer || event.data || undefined;
×
627
        if (IS_ANDROID) {
×
628
            let targetRange: Range | null = null;
×
629
            let [nativeTargetRange] = event.getTargetRanges();
×
630
            if (nativeTargetRange) {
×
631
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange);
×
632
            }
633
            // COMPAT: SelectionChange event is fired after the action is performed, so we
634
            // have to manually get the selection here to ensure it's up-to-date.
635
            const window = AngularEditor.getWindow(editor);
×
636
            const domSelection = window.getSelection();
×
637
            if (!targetRange && domSelection) {
×
638
                targetRange = AngularEditor.toSlateRange(editor, domSelection);
×
639
            }
640
            targetRange = targetRange ?? editor.selection;
×
641
            if (type === 'insertCompositionText') {
×
642
                if (data && data.toString().includes('\n')) {
×
643
                    restoreDom(editor, () => {
×
644
                        Editor.insertBreak(editor);
×
645
                    });
646
                } else {
647
                    if (targetRange) {
×
648
                        if (data) {
×
649
                            restoreDom(editor, () => {
×
650
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
651
                            });
652
                        } else {
653
                            restoreDom(editor, () => {
×
654
                                Transforms.delete(editor, { at: targetRange });
×
655
                            });
656
                        }
657
                    }
658
                }
659
                return;
×
660
            }
661
            if (type === 'deleteContentBackward') {
×
662
                // gboard can not prevent default action, so must use restoreDom,
663
                // sougou Keyboard can prevent default action(only in Chinese input mode).
664
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
665
                if (!Range.isCollapsed(targetRange)) {
×
666
                    restoreDom(editor, () => {
×
667
                        Transforms.delete(editor, { at: targetRange });
×
668
                    });
669
                    return;
×
670
                }
671
            }
672
            if (type === 'insertText') {
×
673
                restoreDom(editor, () => {
×
674
                    if (typeof data === 'string') {
×
675
                        Editor.insertText(editor, data);
×
676
                    }
677
                });
678
                return;
×
679
            }
680
        }
681
        if (
×
682
            !this.readonly &&
×
683
            hasEditableTarget(editor, event.target) &&
684
            !isTargetInsideVoid(editor, activeElement) &&
685
            !this.isDOMEventHandled(event, this.beforeInput)
686
        ) {
687
            try {
×
688
                event.preventDefault();
×
689

690
                // COMPAT: If the selection is expanded, even if the command seems like
691
                // a delete forward/backward command it should delete the selection.
692
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
693
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
694
                    Editor.deleteFragment(editor, { direction });
×
695
                    return;
×
696
                }
697

698
                switch (type) {
×
699
                    case 'deleteByComposition':
700
                    case 'deleteByCut':
701
                    case 'deleteByDrag': {
702
                        Editor.deleteFragment(editor);
×
703
                        break;
×
704
                    }
705

706
                    case 'deleteContent':
707
                    case 'deleteContentForward': {
708
                        Editor.deleteForward(editor);
×
709
                        break;
×
710
                    }
711

712
                    case 'deleteContentBackward': {
713
                        Editor.deleteBackward(editor);
×
714
                        break;
×
715
                    }
716

717
                    case 'deleteEntireSoftLine': {
718
                        Editor.deleteBackward(editor, { unit: 'line' });
×
719
                        Editor.deleteForward(editor, { unit: 'line' });
×
720
                        break;
×
721
                    }
722

723
                    case 'deleteHardLineBackward': {
724
                        Editor.deleteBackward(editor, { unit: 'block' });
×
725
                        break;
×
726
                    }
727

728
                    case 'deleteSoftLineBackward': {
729
                        Editor.deleteBackward(editor, { unit: 'line' });
×
730
                        break;
×
731
                    }
732

733
                    case 'deleteHardLineForward': {
734
                        Editor.deleteForward(editor, { unit: 'block' });
×
735
                        break;
×
736
                    }
737

738
                    case 'deleteSoftLineForward': {
739
                        Editor.deleteForward(editor, { unit: 'line' });
×
740
                        break;
×
741
                    }
742

743
                    case 'deleteWordBackward': {
744
                        Editor.deleteBackward(editor, { unit: 'word' });
×
745
                        break;
×
746
                    }
747

748
                    case 'deleteWordForward': {
749
                        Editor.deleteForward(editor, { unit: 'word' });
×
750
                        break;
×
751
                    }
752

753
                    case 'insertLineBreak':
754
                    case 'insertParagraph': {
755
                        Editor.insertBreak(editor);
×
756
                        break;
×
757
                    }
758

759
                    case 'insertFromComposition': {
760
                        // COMPAT: in safari, `compositionend` event is dispatched after
761
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
762
                        // https://www.w3.org/TR/input-events-2/
763
                        // so the following code is the right logic
764
                        // because DOM selection in sync will be exec before `compositionend` event
765
                        // isComposing is true will prevent DOM selection being update correctly.
766
                        this.isComposing = false;
×
767
                        preventInsertFromComposition(event, this.editor);
×
768
                    }
769
                    case 'insertFromDrop':
770
                    case 'insertFromPaste':
771
                    case 'insertFromYank':
772
                    case 'insertReplacementText':
773
                    case 'insertText': {
774
                        // use a weak comparison instead of 'instanceof' to allow
775
                        // programmatic access of paste events coming from external windows
776
                        // like cypress where cy.window does not work realibly
777
                        if (data?.constructor.name === 'DataTransfer') {
×
778
                            AngularEditor.insertData(editor, data as DataTransfer);
×
779
                        } else if (typeof data === 'string') {
×
780
                            Editor.insertText(editor, data);
×
781
                        }
782
                        break;
×
783
                    }
784
                }
785
            } catch (error) {
786
                this.editor.onError({
×
787
                    code: SlateErrorCode.OnDOMBeforeInputError,
788
                    nativeError: error
789
                });
790
            }
791
        }
792
    }
793

794
    private onDOMBlur(event: FocusEvent) {
795
        if (
×
796
            this.readonly ||
×
797
            this.isUpdatingSelection ||
798
            !hasEditableTarget(this.editor, event.target) ||
799
            this.isDOMEventHandled(event, this.blur)
800
        ) {
801
            return;
×
802
        }
803

804
        const window = AngularEditor.getWindow(this.editor);
×
805

806
        // COMPAT: If the current `activeElement` is still the previous
807
        // one, this is due to the window being blurred when the tab
808
        // itself becomes unfocused, so we want to abort early to allow to
809
        // editor to stay focused when the tab becomes focused again.
810
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
811
        if (this.latestElement === root.activeElement) {
×
812
            return;
×
813
        }
814

815
        const { relatedTarget } = event;
×
816
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
817

818
        // COMPAT: The event should be ignored if the focus is returning
819
        // to the editor from an embedded editable element (eg. an <input>
820
        // element inside a void node).
821
        if (relatedTarget === el) {
×
822
            return;
×
823
        }
824

825
        // COMPAT: The event should be ignored if the focus is moving from
826
        // the editor to inside a void node's spacer element.
827
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
828
            return;
×
829
        }
830

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

837
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
838
                return;
×
839
            }
840
        }
841

842
        IS_FOCUSED.delete(this.editor);
×
843
    }
844

845
    private onDOMClick(event: MouseEvent) {
846
        if (
×
847
            !this.readonly &&
×
848
            hasTarget(this.editor, event.target) &&
849
            !this.isDOMEventHandled(event, this.click) &&
850
            isDOMNode(event.target)
851
        ) {
852
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
853
            const path = AngularEditor.findPath(this.editor, node);
×
854
            const start = Editor.start(this.editor, path);
×
855
            const end = Editor.end(this.editor, path);
×
856

857
            const startVoid = Editor.void(this.editor, { at: start });
×
858
            const endVoid = Editor.void(this.editor, { at: end });
×
859

860
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
861
                let blockPath = path;
×
862
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
863
                    const block = Editor.above(this.editor, {
×
864
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
865
                        at: path
866
                    });
867

868
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
869
                }
870

871
                const range = Editor.range(this.editor, blockPath);
×
872
                Transforms.select(this.editor, range);
×
873
                return;
×
874
            }
875

876
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
877
                const range = Editor.range(this.editor, start);
×
878
                Transforms.select(this.editor, range);
×
879
            }
880
        }
881
    }
882

883
    private onDOMCompositionStart(event: CompositionEvent) {
884
        const { selection } = this.editor;
1✔
885
        if (selection) {
1!
886
            // solve the problem of cross node Chinese input
887
            if (Range.isExpanded(selection)) {
×
888
                Editor.deleteFragment(this.editor);
×
889
                this.forceRender();
×
890
            }
891
        }
892
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
893
            this.isComposing = true;
1✔
894
        }
895
        this.render();
1✔
896
    }
897

898
    private onDOMCompositionUpdate(event: CompositionEvent) {
899
        this.isDOMEventHandled(event, this.compositionUpdate);
×
900
    }
901

902
    private onDOMCompositionEnd(event: CompositionEvent) {
903
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
904
            Transforms.delete(this.editor);
×
905
        }
906
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
907
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
908
            // aren't correct and never fire the "insertFromComposition"
909
            // type that we need. So instead, insert whenever a composition
910
            // ends since it will already have been committed to the DOM.
911
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
912
                preventInsertFromComposition(event, this.editor);
×
913
                Editor.insertText(this.editor, event.data);
×
914
            }
915

916
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
917
            // so we need avoid repeat isnertText by isComposing === true,
918
            this.isComposing = false;
×
919
        }
920
        this.render();
×
921
    }
922

923
    private onDOMCopy(event: ClipboardEvent) {
924
        const window = AngularEditor.getWindow(this.editor);
×
925
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
926
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
927
            event.preventDefault();
×
928
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
929
        }
930
    }
931

932
    private onDOMCut(event: ClipboardEvent) {
933
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
934
            event.preventDefault();
×
935
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
936
            const { selection } = this.editor;
×
937

938
            if (selection) {
×
939
                AngularEditor.deleteCutData(this.editor);
×
940
            }
941
        }
942
    }
943

944
    private onDOMDragOver(event: DragEvent) {
945
        if (hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
946
            // Only when the target is void, call `preventDefault` to signal
947
            // that drops are allowed. Editable content is droppable by
948
            // default, and calling `preventDefault` hides the cursor.
949
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
950

951
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
952
                event.preventDefault();
×
953
            }
954
        }
955
    }
956

957
    private onDOMDragStart(event: DragEvent) {
958
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
959
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
960
            const path = AngularEditor.findPath(this.editor, node);
×
961
            const voidMatch =
962
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
963

964
            // If starting a drag on a void node, make sure it is selected
965
            // so that it shows up in the selection's fragment.
966
            if (voidMatch) {
×
967
                const range = Editor.range(this.editor, path);
×
968
                Transforms.select(this.editor, range);
×
969
            }
970

971
            this.isDraggingInternally = true;
×
972

973
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
974
        }
975
    }
976

977
    private onDOMDrop(event: DragEvent) {
978
        const editor = this.editor;
×
979
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
980
            event.preventDefault();
×
981
            // Keep a reference to the dragged range before updating selection
982
            const draggedRange = editor.selection;
×
983

984
            // Find the range where the drop happened
985
            const range = AngularEditor.findEventRange(editor, event);
×
986
            const data = event.dataTransfer;
×
987

988
            Transforms.select(editor, range);
×
989

990
            if (this.isDraggingInternally) {
×
991
                if (draggedRange) {
×
992
                    Transforms.delete(editor, {
×
993
                        at: draggedRange
994
                    });
995
                }
996

997
                this.isDraggingInternally = false;
×
998
            }
999

1000
            AngularEditor.insertData(editor, data);
×
1001

1002
            // When dragging from another source into the editor, it's possible
1003
            // that the current editor does not have focus.
1004
            if (!AngularEditor.isFocused(editor)) {
×
1005
                AngularEditor.focus(editor);
×
1006
            }
1007
        }
1008
    }
1009

1010
    private onDOMDragEnd(event: DragEvent) {
1011
        if (
×
1012
            !this.readonly &&
×
1013
            this.isDraggingInternally &&
1014
            hasTarget(this.editor, event.target) &&
1015
            !this.isDOMEventHandled(event, this.dragEnd)
1016
        ) {
1017
            this.isDraggingInternally = false;
×
1018
        }
1019
    }
1020

1021
    private onDOMFocus(event: Event) {
1022
        if (
2✔
1023
            !this.readonly &&
8✔
1024
            !this.isUpdatingSelection &&
1025
            hasEditableTarget(this.editor, event.target) &&
1026
            !this.isDOMEventHandled(event, this.focus)
1027
        ) {
1028
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1029
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1030
            this.latestElement = root.activeElement;
2✔
1031

1032
            // COMPAT: If the editor has nested editable elements, the focus
1033
            // can go to them. In Firefox, this must be prevented because it
1034
            // results in issues with keyboard navigation. (2017/03/30)
1035
            if (IS_FIREFOX && event.target !== el) {
2!
1036
                el.focus();
×
1037
                return;
×
1038
            }
1039

1040
            IS_FOCUSED.set(this.editor, true);
2✔
1041
        }
1042
    }
1043

1044
    private onDOMKeydown(event: KeyboardEvent) {
1045
        const editor = this.editor;
×
1046
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1047
        const { activeElement } = root;
×
1048
        if (
×
1049
            !this.readonly &&
×
1050
            hasEditableTarget(editor, event.target) &&
1051
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1052
            !this.isComposing &&
1053
            !this.isDOMEventHandled(event, this.keydown)
1054
        ) {
1055
            const nativeEvent = event;
×
1056
            const { selection } = editor;
×
1057

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

1061
            try {
×
1062
                // COMPAT: Since we prevent the default behavior on
1063
                // `beforeinput` events, the browser doesn't think there's ever
1064
                // any history stack to undo or redo, so we have to manage these
1065
                // hotkeys ourselves. (2019/11/06)
1066
                if (Hotkeys.isRedo(nativeEvent)) {
×
1067
                    event.preventDefault();
×
1068

1069
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1070
                        editor.redo();
×
1071
                    }
1072

1073
                    return;
×
1074
                }
1075

1076
                if (Hotkeys.isUndo(nativeEvent)) {
×
1077
                    event.preventDefault();
×
1078

1079
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1080
                        editor.undo();
×
1081
                    }
1082

1083
                    return;
×
1084
                }
1085

1086
                // COMPAT: Certain browsers don't handle the selection updates
1087
                // properly. In Chrome, the selection isn't properly extended.
1088
                // And in Firefox, the selection isn't properly collapsed.
1089
                // (2017/10/17)
1090
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1091
                    event.preventDefault();
×
1092
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1093
                    return;
×
1094
                }
1095

1096
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1097
                    event.preventDefault();
×
1098
                    Transforms.move(editor, { unit: 'line' });
×
1099
                    return;
×
1100
                }
1101

1102
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1103
                    event.preventDefault();
×
1104
                    Transforms.move(editor, {
×
1105
                        unit: 'line',
1106
                        edge: 'focus',
1107
                        reverse: true
1108
                    });
1109
                    return;
×
1110
                }
1111

1112
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1113
                    event.preventDefault();
×
1114
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1115
                    return;
×
1116
                }
1117

1118
                // COMPAT: If a void node is selected, or a zero-width text node
1119
                // adjacent to an inline is selected, we need to handle these
1120
                // hotkeys manually because browsers won't be able to skip over
1121
                // the void node with the zero-width space not being an empty
1122
                // string.
1123
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1124
                    event.preventDefault();
×
1125

1126
                    if (selection && Range.isCollapsed(selection)) {
×
1127
                        Transforms.move(editor, { reverse: !isRTL });
×
1128
                    } else {
1129
                        Transforms.collapse(editor, { edge: 'start' });
×
1130
                    }
1131

1132
                    return;
×
1133
                }
1134

1135
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1136
                    event.preventDefault();
×
1137

1138
                    if (selection && Range.isCollapsed(selection)) {
×
1139
                        Transforms.move(editor, { reverse: isRTL });
×
1140
                    } else {
1141
                        Transforms.collapse(editor, { edge: 'end' });
×
1142
                    }
1143

1144
                    return;
×
1145
                }
1146

1147
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1148
                    event.preventDefault();
×
1149

1150
                    if (selection && Range.isExpanded(selection)) {
×
1151
                        Transforms.collapse(editor, { edge: 'focus' });
×
1152
                    }
1153

1154
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1155
                    return;
×
1156
                }
1157

1158
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1159
                    event.preventDefault();
×
1160

1161
                    if (selection && Range.isExpanded(selection)) {
×
1162
                        Transforms.collapse(editor, { edge: 'focus' });
×
1163
                    }
1164

1165
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1166
                    return;
×
1167
                }
1168

1169
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1170
                // fall back to guessing at the input intention for hotkeys.
1171
                // COMPAT: In iOS, some of these hotkeys are handled in the
1172
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1173
                    // We don't have a core behavior for these, but they change the
1174
                    // DOM if we don't prevent them, so we have to.
1175
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1176
                        event.preventDefault();
×
1177
                        return;
×
1178
                    }
1179

1180
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1181
                        event.preventDefault();
×
1182
                        Editor.insertBreak(editor);
×
1183
                        return;
×
1184
                    }
1185

1186
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1187
                        event.preventDefault();
×
1188

1189
                        if (selection && Range.isExpanded(selection)) {
×
1190
                            Editor.deleteFragment(editor, {
×
1191
                                direction: 'backward'
1192
                            });
1193
                        } else {
1194
                            Editor.deleteBackward(editor);
×
1195
                        }
1196

1197
                        return;
×
1198
                    }
1199

1200
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1201
                        event.preventDefault();
×
1202

1203
                        if (selection && Range.isExpanded(selection)) {
×
1204
                            Editor.deleteFragment(editor, {
×
1205
                                direction: 'forward'
1206
                            });
1207
                        } else {
1208
                            Editor.deleteForward(editor);
×
1209
                        }
1210

1211
                        return;
×
1212
                    }
1213

1214
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1215
                        event.preventDefault();
×
1216

1217
                        if (selection && Range.isExpanded(selection)) {
×
1218
                            Editor.deleteFragment(editor, {
×
1219
                                direction: 'backward'
1220
                            });
1221
                        } else {
1222
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1223
                        }
1224

1225
                        return;
×
1226
                    }
1227

1228
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1229
                        event.preventDefault();
×
1230

1231
                        if (selection && Range.isExpanded(selection)) {
×
1232
                            Editor.deleteFragment(editor, {
×
1233
                                direction: 'forward'
1234
                            });
1235
                        } else {
1236
                            Editor.deleteForward(editor, { unit: 'line' });
×
1237
                        }
1238

1239
                        return;
×
1240
                    }
1241

1242
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1243
                        event.preventDefault();
×
1244

1245
                        if (selection && Range.isExpanded(selection)) {
×
1246
                            Editor.deleteFragment(editor, {
×
1247
                                direction: 'backward'
1248
                            });
1249
                        } else {
1250
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1251
                        }
1252

1253
                        return;
×
1254
                    }
1255

1256
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1257
                        event.preventDefault();
×
1258

1259
                        if (selection && Range.isExpanded(selection)) {
×
1260
                            Editor.deleteFragment(editor, {
×
1261
                                direction: 'forward'
1262
                            });
1263
                        } else {
1264
                            Editor.deleteForward(editor, { unit: 'word' });
×
1265
                        }
1266

1267
                        return;
×
1268
                    }
1269
                } else {
1270
                    if (IS_CHROME || IS_SAFARI) {
×
1271
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1272
                        // an event when deleting backwards in a selected void inline node
1273
                        if (
×
1274
                            selection &&
×
1275
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1276
                            Range.isCollapsed(selection)
1277
                        ) {
1278
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1279
                            if (
×
1280
                                Element.isElement(currentNode) &&
×
1281
                                Editor.isVoid(editor, currentNode) &&
1282
                                Editor.isInline(editor, currentNode)
1283
                            ) {
1284
                                event.preventDefault();
×
1285
                                Editor.deleteBackward(editor, {
×
1286
                                    unit: 'block'
1287
                                });
1288
                                return;
×
1289
                            }
1290
                        }
1291
                    }
1292
                }
1293
            } catch (error) {
1294
                this.editor.onError({
×
1295
                    code: SlateErrorCode.OnDOMKeydownError,
1296
                    nativeError: error
1297
                });
1298
            }
1299
        }
1300
    }
1301

1302
    private onDOMPaste(event: ClipboardEvent) {
1303
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1304
        // fall back to React's `onPaste` here instead.
1305
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1306
        // when "paste without formatting" option is used.
1307
        // This unfortunately needs to be handled with paste events instead.
1308
        if (
×
1309
            !this.isDOMEventHandled(event, this.paste) &&
×
1310
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1311
            !this.readonly &&
1312
            hasEditableTarget(this.editor, event.target)
1313
        ) {
1314
            event.preventDefault();
×
1315
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1316
        }
1317
    }
1318

1319
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1320
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1321
        // fall back to React's leaky polyfill instead just for it. It
1322
        // only works for the `insertText` input type.
1323
        if (
×
1324
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1325
            !this.readonly &&
1326
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1327
            hasEditableTarget(this.editor, event.nativeEvent.target)
1328
        ) {
1329
            event.nativeEvent.preventDefault();
×
1330
            try {
×
1331
                const text = event.data;
×
1332
                if (!Range.isCollapsed(this.editor.selection)) {
×
1333
                    Editor.deleteFragment(this.editor);
×
1334
                }
1335
                // just handle Non-IME input
1336
                if (!this.isComposing) {
×
1337
                    Editor.insertText(this.editor, text);
×
1338
                }
1339
            } catch (error) {
1340
                this.editor.onError({
×
1341
                    code: SlateErrorCode.ToNativeSelectionError,
1342
                    nativeError: error
1343
                });
1344
            }
1345
        }
1346
    }
1347

1348
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1349
        if (!handler) {
3✔
1350
            return false;
3✔
1351
        }
1352
        handler(event);
×
1353
        return event.defaultPrevented;
×
1354
    }
1355
    //#endregion
1356

1357
    ngOnDestroy() {
1358
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1359
        this.manualListeners.forEach(manualListener => {
22✔
1360
            manualListener();
462✔
1361
        });
1362
        this.destroy$.complete();
22✔
1363
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1364
    }
1365
}
1366

1367
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1368
    // This was affecting the selection of multiple blocks and dragging behavior,
1369
    // so enabled only if the selection has been collapsed.
1370
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1371
        const leafEl = domRange.startContainer.parentElement!;
×
1372
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1373
        scrollIntoView(leafEl, {
×
1374
            scrollMode: 'if-needed'
1375
        });
1376
        delete leafEl.getBoundingClientRect;
×
1377
    }
1378
};
1379

1380
/**
1381
 * Check if the target is editable and in the editor.
1382
 */
1383

1384
export const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1385
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
3✔
1386
};
1387

1388
/**
1389
 * Check if two DOM range objects are equal.
1390
 */
1391
const isRangeEqual = (a: DOMRange, b: DOMRange) => {
1✔
1392
    return (
×
1393
        (a.startContainer === b.startContainer &&
×
1394
            a.startOffset === b.startOffset &&
1395
            a.endContainer === b.endContainer &&
1396
            a.endOffset === b.endOffset) ||
1397
        (a.startContainer === b.endContainer &&
1398
            a.startOffset === b.endOffset &&
1399
            a.endContainer === b.startContainer &&
1400
            a.endOffset === b.startOffset)
1401
    );
1402
};
1403

1404
/**
1405
 * Check if the target is in the editor.
1406
 */
1407

1408
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1409
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
1✔
1410
};
1411

1412
/**
1413
 * Check if the target is inside void and in the editor.
1414
 */
1415

1416
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1417
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1418
    return Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1419
};
1420

1421
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1422
    return (
3✔
1423
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
6!
1424
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1425
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1426
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1427
    );
1428
};
1429

1430
/**
1431
 * remove default insert from composition
1432
 * @param text
1433
 */
1434
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1435
    const types = ['compositionend', 'insertFromComposition'];
×
1436
    if (!types.includes(event.type)) {
×
1437
        return;
×
1438
    }
1439
    const insertText = (event as CompositionEvent).data;
×
1440
    const window = AngularEditor.getWindow(editor);
×
1441
    const domSelection = window.getSelection();
×
1442
    // ensure text node insert composition input text
1443
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1444
        const textNode = domSelection.anchorNode;
×
1445
        textNode.splitText(textNode.length - insertText.length).remove();
×
1446
    }
1447
};
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