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

worktile / slate-angular / 776886ea-20c4-4d4e-891f-a6ef584a0988

31 Mar 2025 01:48AM UTC coverage: 46.776%. Remained the same
776886ea-20c4-4d4e-891f-a6ef584a0988

push

circleci

pubuzhixing8
build: npx changeset pre exit

409 of 1075 branches covered (38.05%)

Branch coverage included in aggregate %.

1020 of 1980 relevant lines covered (51.52%)

43.97 hits per line

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

30.9
/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 } from '../../utils';
59
import { SlatePlaceholder } from '../../types/feature';
60
import { restoreDom } from '../../utils/restore-dom';
61
import { SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN } from '../element/default-element.component.token';
62
import { SLATE_DEFAULT_TEXT_COMPONENT_TOKEN, SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN } from '../text/token';
63
import { SlateVoidText } from '../text/void-text.component';
64
import { SlateDefaultText } from '../text/default-text.component';
65
import { SlateDefaultElement } from '../element/default-element.component';
66
import { SlateDefaultLeaf } from '../leaf/default-leaf.component';
67
import { SLATE_DEFAULT_LEAF_COMPONENT_TOKEN } from '../leaf/token';
68
import { BaseElementComponent, BaseLeafComponent, BaseTextComponent } from '../../view/base';
69
import { ListRender } from '../../view/render/list-render';
70
import { TRIPLE_CLICK } from '../../utils/constants';
71

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

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

116
    private destroy$ = new Subject();
23✔
117

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

123
    protected manualListeners: (() => void)[] = [];
23✔
124

125
    private initialized: boolean;
126

127
    private onTouchedCallback: () => void = () => {};
23✔
128

129
    private onChangeCallback: (_: any) => void = () => {};
23✔
130

131
    @Input() editor: AngularEditor;
132

133
    @Input() renderElement: (element: Element) => ViewType | null;
134

135
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
136

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

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

141
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
142

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

145
    @Input() isStrictDecorate: boolean = true;
23✔
146

147
    @Input() trackBy: (node: Element) => any = () => null;
206✔
148

149
    @Input() readonly = false;
23✔
150

151
    @Input() placeholder: string;
152

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

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

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

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

185
    @ViewChild('templateComponent', { static: true })
186
    templateComponent: SlateStringTemplate;
187

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

191
    viewContainerRef = inject(ViewContainerRef);
23✔
192

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

197
    listRender: ListRender;
198

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

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

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

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

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

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

271
    writeValue(value: Element[]) {
272
        if (value && value.length) {
49✔
273
            this.editor.children = value;
26✔
274
            this.initializeContext();
26✔
275
            if (!this.listRender.initialized) {
26✔
276
                this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
277
            } else {
278
                this.listRender.update(this.editor.children, this.editor, this.context);
3✔
279
            }
280
            this.cdr.markForCheck();
26✔
281
        }
282
    }
283

284
    initialize() {
285
        this.initialized = true;
23✔
286
        const window = AngularEditor.getWindow(this.editor);
23✔
287
        this.addEventListener(
23✔
288
            'selectionchange',
289
            event => {
290
                this.toSlateSelection();
2✔
291
            },
292
            window.document
293
        );
294
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
295
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
296
        }
297
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
298
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
299
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
300
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
301
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
302
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
303
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
304
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
305
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
306
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
307
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
308
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
309
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
310
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
311
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
312
            this.addEventListener(event.name, () => {});
115✔
313
        });
314
    }
315

316
    toNativeSelection() {
317
        try {
15✔
318
            const { selection } = this.editor;
15✔
319
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
320
            const { activeElement } = root;
15✔
321
            const domSelection = (root as Document).getSelection();
15✔
322

323
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
324
                return;
14✔
325
            }
326

327
            const hasDomSelection = domSelection.type !== 'None';
1✔
328

329
            // If the DOM selection is properly unset, we're done.
330
            if (!selection && !hasDomSelection) {
1!
331
                return;
×
332
            }
333

334
            // If the DOM selection is already correct, we're done.
335
            // verify that the dom selection is in the editor
336
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
337
            let hasDomSelectionInEditor = false;
1✔
338
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
339
                hasDomSelectionInEditor = true;
1✔
340
            }
341

342
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
343
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
344
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, { suppressThrow: true });
1✔
345
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
346
                    return;
×
347
                }
348
            }
349

350
            // prevent updating native selection when active element is void element
351
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
352
                return;
×
353
            }
354

355
            // when <Editable/> is being controlled through external value
356
            // then its children might just change - DOM responds to it on its own
357
            // but Slate's value is not being updated through any operation
358
            // and thus it doesn't transform selection on its own
359
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
360
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { suppressThrow: false });
×
361
                return;
×
362
            }
363

364
            // Otherwise the DOM selection is out of sync, so update it.
365
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
366
            this.isUpdatingSelection = true;
1✔
367

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

370
            if (newDomRange) {
1!
371
                // COMPAT: Since the DOM range has no concept of backwards/forwards
372
                // we need to check and do the right thing here.
373
                if (Range.isBackward(selection)) {
1!
374
                    // eslint-disable-next-line max-len
375
                    domSelection.setBaseAndExtent(
×
376
                        newDomRange.endContainer,
377
                        newDomRange.endOffset,
378
                        newDomRange.startContainer,
379
                        newDomRange.startOffset
380
                    );
381
                } else {
382
                    // eslint-disable-next-line max-len
383
                    domSelection.setBaseAndExtent(
1✔
384
                        newDomRange.startContainer,
385
                        newDomRange.startOffset,
386
                        newDomRange.endContainer,
387
                        newDomRange.endOffset
388
                    );
389
                }
390
            } else {
391
                domSelection.removeAllRanges();
×
392
            }
393

394
            setTimeout(() => {
1✔
395
                // handle scrolling in setTimeout because of
396
                // dom should not have updated immediately after listRender's updating
397
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
398
                // COMPAT: In Firefox, it's not enough to create a range, you also need
399
                // to focus the contenteditable element too. (2016/11/16)
400
                if (newDomRange && IS_FIREFOX) {
1!
401
                    el.focus();
×
402
                }
403

404
                this.isUpdatingSelection = false;
1✔
405
            });
406
        } catch (error) {
407
            this.editor.onError({
×
408
                code: SlateErrorCode.ToNativeSelectionError,
409
                nativeError: error
410
            });
411
            this.isUpdatingSelection = false;
×
412
        }
413
    }
414

415
    onChange() {
416
        this.forceRender();
13✔
417
        this.onChangeCallback(this.editor.children);
13✔
418
    }
419

420
    ngAfterViewChecked() {}
421

422
    ngDoCheck() {}
423

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

463
    render() {
464
        const changed = this.updateContext();
2✔
465
        if (changed) {
2✔
466
            this.listRender.update(this.editor.children, this.editor, this.context);
2✔
467
        }
468
    }
469

470
    updateContext() {
471
        const decorations = this.generateDecorations();
17✔
472
        if (
17✔
473
            this.context.selection !== this.editor.selection ||
46✔
474
            this.context.decorate !== this.decorate ||
475
            this.context.readonly !== this.readonly ||
476
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
477
        ) {
478
            this.context = {
10✔
479
                parent: this.editor,
480
                selection: this.editor.selection,
481
                decorations: decorations,
482
                decorate: this.decorate,
483
                readonly: this.readonly
484
            };
485
            return true;
10✔
486
        }
487
        return false;
7✔
488
    }
489

490
    initializeContext() {
491
        this.context = {
49✔
492
            parent: this.editor,
493
            selection: this.editor.selection,
494
            decorations: this.generateDecorations(),
495
            decorate: this.decorate,
496
            readonly: this.readonly
497
        };
498
    }
499

500
    initializeViewContext() {
501
        this.viewContext = {
23✔
502
            editor: this.editor,
503
            renderElement: this.renderElement,
504
            renderLeaf: this.renderLeaf,
505
            renderText: this.renderText,
506
            trackBy: this.trackBy,
507
            isStrictDecorate: this.isStrictDecorate,
508
            templateComponent: this.templateComponent,
509
            defaultElement: this.defaultElement,
510
            defaultText: this.defaultText,
511
            defaultVoidText: this.defaultVoidText,
512
            defaultLeaf: this.defaultLeaf
513
        };
514
    }
515

516
    composePlaceholderDecorate(editor: Editor) {
517
        if (this.placeholderDecorate) {
64!
518
            return this.placeholderDecorate(editor) || [];
×
519
        }
520

521
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
522
            const start = Editor.start(editor, []);
3✔
523
            return [
3✔
524
                {
525
                    placeholder: this.placeholder,
526
                    anchor: start,
527
                    focus: start
528
                }
529
            ];
530
        } else {
531
            return [];
61✔
532
        }
533
    }
534

535
    generateDecorations() {
536
        const decorations = this.decorate([this.editor, []]);
66✔
537
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
538
        decorations.push(...placeholderDecorations);
66✔
539
        return decorations;
66✔
540
    }
541

542
    //#region event proxy
543
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
544
        this.manualListeners.push(
483✔
545
            this.renderer2.listen(target, eventName, (event: Event) => {
546
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
547
                if (beforeInputEvent) {
5!
548
                    this.onFallbackBeforeInput(beforeInputEvent);
×
549
                }
550
                listener(event);
5✔
551
            })
552
        );
553
    }
554

555
    private toSlateSelection() {
556
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
557
            try {
1✔
558
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
559
                const { activeElement } = root;
1✔
560
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
561
                const domSelection = (root as Document).getSelection();
1✔
562

563
                if (activeElement === el) {
1!
564
                    this.latestElement = activeElement;
1✔
565
                    IS_FOCUSED.set(this.editor, true);
1✔
566
                } else {
567
                    IS_FOCUSED.delete(this.editor);
×
568
                }
569

570
                if (!domSelection) {
1!
571
                    return Transforms.deselect(this.editor);
×
572
                }
573

574
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
575
                const hasDomSelectionInEditor =
576
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
577
                if (!hasDomSelectionInEditor) {
1!
578
                    Transforms.deselect(this.editor);
×
579
                    return;
×
580
                }
581

582
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
583
                // for example, double-click the last cell of the table to select a non-editable DOM
584
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
585
                if (range) {
1✔
586
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
587
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
588
                            // force adjust DOMSelection
589
                            this.toNativeSelection();
×
590
                        }
591
                    } else {
592
                        Transforms.select(this.editor, range);
1✔
593
                    }
594
                }
595
            } catch (error) {
596
                this.editor.onError({
×
597
                    code: SlateErrorCode.ToSlateSelectionError,
598
                    nativeError: error
599
                });
600
            }
601
        }
602
    }
603

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

682
                // COMPAT: If the selection is expanded, even if the command seems like
683
                // a delete forward/backward command it should delete the selection.
684
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
685
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
686
                    Editor.deleteFragment(editor, { direction });
×
687
                    return;
×
688
                }
689

690
                switch (type) {
×
691
                    case 'deleteByComposition':
692
                    case 'deleteByCut':
693
                    case 'deleteByDrag': {
694
                        Editor.deleteFragment(editor);
×
695
                        break;
×
696
                    }
697

698
                    case 'deleteContent':
699
                    case 'deleteContentForward': {
700
                        Editor.deleteForward(editor);
×
701
                        break;
×
702
                    }
703

704
                    case 'deleteContentBackward': {
705
                        Editor.deleteBackward(editor);
×
706
                        break;
×
707
                    }
708

709
                    case 'deleteEntireSoftLine': {
710
                        Editor.deleteBackward(editor, { unit: 'line' });
×
711
                        Editor.deleteForward(editor, { unit: 'line' });
×
712
                        break;
×
713
                    }
714

715
                    case 'deleteHardLineBackward': {
716
                        Editor.deleteBackward(editor, { unit: 'block' });
×
717
                        break;
×
718
                    }
719

720
                    case 'deleteSoftLineBackward': {
721
                        Editor.deleteBackward(editor, { unit: 'line' });
×
722
                        break;
×
723
                    }
724

725
                    case 'deleteHardLineForward': {
726
                        Editor.deleteForward(editor, { unit: 'block' });
×
727
                        break;
×
728
                    }
729

730
                    case 'deleteSoftLineForward': {
731
                        Editor.deleteForward(editor, { unit: 'line' });
×
732
                        break;
×
733
                    }
734

735
                    case 'deleteWordBackward': {
736
                        Editor.deleteBackward(editor, { unit: 'word' });
×
737
                        break;
×
738
                    }
739

740
                    case 'deleteWordForward': {
741
                        Editor.deleteForward(editor, { unit: 'word' });
×
742
                        break;
×
743
                    }
744

745
                    case 'insertLineBreak':
746
                    case 'insertParagraph': {
747
                        Editor.insertBreak(editor);
×
748
                        break;
×
749
                    }
750

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

786
    private onDOMBlur(event: FocusEvent) {
787
        if (
×
788
            this.readonly ||
×
789
            this.isUpdatingSelection ||
790
            !hasEditableTarget(this.editor, event.target) ||
791
            this.isDOMEventHandled(event, this.blur)
792
        ) {
793
            return;
×
794
        }
795

796
        const window = AngularEditor.getWindow(this.editor);
×
797

798
        // COMPAT: If the current `activeElement` is still the previous
799
        // one, this is due to the window being blurred when the tab
800
        // itself becomes unfocused, so we want to abort early to allow to
801
        // editor to stay focused when the tab becomes focused again.
802
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
803
        if (this.latestElement === root.activeElement) {
×
804
            return;
×
805
        }
806

807
        const { relatedTarget } = event;
×
808
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
809

810
        // COMPAT: The event should be ignored if the focus is returning
811
        // to the editor from an embedded editable element (eg. an <input>
812
        // element inside a void node).
813
        if (relatedTarget === el) {
×
814
            return;
×
815
        }
816

817
        // COMPAT: The event should be ignored if the focus is moving from
818
        // the editor to inside a void node's spacer element.
819
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
820
            return;
×
821
        }
822

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

829
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
830
                return;
×
831
            }
832
        }
833

834
        IS_FOCUSED.delete(this.editor);
×
835
    }
836

837
    private onDOMClick(event: MouseEvent) {
838
        if (
×
839
            !this.readonly &&
×
840
            hasTarget(this.editor, event.target) &&
841
            !this.isDOMEventHandled(event, this.click) &&
842
            isDOMNode(event.target)
843
        ) {
844
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
845
            const path = AngularEditor.findPath(this.editor, node);
×
846
            const start = Editor.start(this.editor, path);
×
847
            const end = Editor.end(this.editor, path);
×
848

849
            const startVoid = Editor.void(this.editor, { at: start });
×
850
            const endVoid = Editor.void(this.editor, { at: end });
×
851

852
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
853
                let blockPath = path;
×
854
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
855
                    const block = Editor.above(this.editor, {
×
856
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
857
                        at: path
858
                    });
859

860
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
861
                }
862

863
                const range = Editor.range(this.editor, blockPath);
×
864
                Transforms.select(this.editor, range);
×
865
                return;
×
866
            }
867

868
            if (
×
869
                startVoid &&
×
870
                endVoid &&
871
                Path.equals(startVoid[1], endVoid[1]) &&
872
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
873
            ) {
874
                const range = Editor.range(this.editor, start);
×
875
                Transforms.select(this.editor, range);
×
876
            }
877
        }
878
    }
879

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

895
    private onDOMCompositionUpdate(event: CompositionEvent) {
896
        this.isDOMEventHandled(event, this.compositionUpdate);
×
897
    }
898

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

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

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

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

935
            if (selection) {
×
936
                AngularEditor.deleteCutData(this.editor);
×
937
            }
938
        }
939
    }
940

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

948
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
949
                event.preventDefault();
×
950
            }
951
        }
952
    }
953

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

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

968
            this.isDraggingInternally = true;
×
969

970
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
971
        }
972
    }
973

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

981
            // Find the range where the drop happened
982
            const range = AngularEditor.findEventRange(editor, event);
×
983
            const data = event.dataTransfer;
×
984

985
            Transforms.select(editor, range);
×
986

987
            if (this.isDraggingInternally) {
×
988
                if (draggedRange) {
×
989
                    Transforms.delete(editor, {
×
990
                        at: draggedRange
991
                    });
992
                }
993

994
                this.isDraggingInternally = false;
×
995
            }
996

997
            AngularEditor.insertData(editor, data);
×
998

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

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

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

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

1037
            IS_FOCUSED.set(this.editor, true);
2✔
1038
        }
1039
    }
1040

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

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

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

1066
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1067
                        editor.redo();
×
1068
                    }
1069

1070
                    return;
×
1071
                }
1072

1073
                if (Hotkeys.isUndo(nativeEvent)) {
×
1074
                    event.preventDefault();
×
1075

1076
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1077
                        editor.undo();
×
1078
                    }
1079

1080
                    return;
×
1081
                }
1082

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

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

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

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

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

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

1129
                    return;
×
1130
                }
1131

1132
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1133
                    event.preventDefault();
×
1134

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

1141
                    return;
×
1142
                }
1143

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

1147
                    if (selection && Range.isExpanded(selection)) {
×
1148
                        Transforms.collapse(editor, { edge: 'focus' });
×
1149
                    }
1150

1151
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1152
                    return;
×
1153
                }
1154

1155
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1156
                    event.preventDefault();
×
1157

1158
                    if (selection && Range.isExpanded(selection)) {
×
1159
                        Transforms.collapse(editor, { edge: 'focus' });
×
1160
                    }
1161

1162
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1163
                    return;
×
1164
                }
1165

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

1177
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1178
                        event.preventDefault();
×
1179
                        Editor.insertBreak(editor);
×
1180
                        return;
×
1181
                    }
1182

1183
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1184
                        event.preventDefault();
×
1185

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

1194
                        return;
×
1195
                    }
1196

1197
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1198
                        event.preventDefault();
×
1199

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

1208
                        return;
×
1209
                    }
1210

1211
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1212
                        event.preventDefault();
×
1213

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

1222
                        return;
×
1223
                    }
1224

1225
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1226
                        event.preventDefault();
×
1227

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

1236
                        return;
×
1237
                    }
1238

1239
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1240
                        event.preventDefault();
×
1241

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

1250
                        return;
×
1251
                    }
1252

1253
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1254
                        event.preventDefault();
×
1255

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

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

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

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

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

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

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

1377
/**
1378
 * Check if the target is editable and in the editor.
1379
 */
1380

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

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

1401
/**
1402
 * Check if the target is in the editor.
1403
 */
1404

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

1409
/**
1410
 * Check if the target is inside void and in the editor.
1411
 */
1412

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

1418
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1419
    return (
2✔
1420
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1421
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1422
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1423
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1424
    );
1425
};
1426

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