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

worktile / slate-angular / 9a41e977-85ac-413a-9c4b-a9ac0b00358a

28 May 2024 03:35AM UTC coverage: 46.748% (-0.006%) from 46.754%
9a41e977-85ac-413a-9c4b-a9ac0b00358a

push

circleci

pubuzhixing8
build: release 17.2.0

406 of 1083 branches covered (37.49%)

Branch coverage included in aggregate %.

1017 of 1961 relevant lines covered (51.86%)

44.65 hits per line

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

30.75
/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
    standalone: true,
111
    imports: [SlateStringTemplate]
112
})
113
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
114
    viewContext: SlateViewContext;
115
    context: SlateChildrenContext;
116

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

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

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

126
    private initialized: boolean;
127

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

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

132
    @Input() editor: AngularEditor;
133

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

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

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

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

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

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

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

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

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

152
    @Input() placeholder: string;
153

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

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

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

198
    listRender: ListRender;
199

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

395
            newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
396

397
            setTimeout(() => {
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);
6✔
547
                if (beforeInputEvent) {
6!
548
                    this.onFallbackBeforeInput(beforeInputEvent);
×
549
                }
550
                listener(event);
6✔
551
            })
552
        );
553
    }
554

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

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

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

574
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
2✔
575
                const hasDomSelectionInEditor =
576
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
2✔
577
                if (!hasDomSelectionInEditor) {
2!
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);
2✔
585
                if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
2!
586
                    if (!isTargetInsideVoid(this.editor, activeElement)) {
×
587
                        // force adjust DOMSelection
588
                        this.toNativeSelection();
×
589
                    }
590
                } else {
591
                    Transforms.select(this.editor, range);
2✔
592
                }
593
            } catch (error) {
594
                this.editor.onError({
×
595
                    code: SlateErrorCode.ToSlateSelectionError,
596
                    nativeError: error
597
                });
598
            }
599
        }
600
    }
601

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

794
        const window = AngularEditor.getWindow(this.editor);
×
795

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

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

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

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

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

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

832
        IS_FOCUSED.delete(this.editor);
×
833
    }
834

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

966
            this.isDraggingInternally = true;
×
967

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

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

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

983
            Transforms.select(editor, range);
×
984

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

992
                this.isDraggingInternally = false;
×
993
            }
994

995
            AngularEditor.insertData(editor, data);
×
996

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

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

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

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

1035
            IS_FOCUSED.set(this.editor, true);
2✔
1036
        }
1037
    }
1038

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

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

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

1064
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1065
                        editor.redo();
×
1066
                    }
1067

1068
                    return;
×
1069
                }
1070

1071
                if (Hotkeys.isUndo(nativeEvent)) {
×
1072
                    event.preventDefault();
×
1073

1074
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1075
                        editor.undo();
×
1076
                    }
1077

1078
                    return;
×
1079
                }
1080

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

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

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

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

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

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

1127
                    return;
×
1128
                }
1129

1130
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1131
                    event.preventDefault();
×
1132

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

1139
                    return;
×
1140
                }
1141

1142
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1143
                    event.preventDefault();
×
1144

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

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

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

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

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

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

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

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

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

1192
                        return;
×
1193
                    }
1194

1195
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1196
                        event.preventDefault();
×
1197

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

1206
                        return;
×
1207
                    }
1208

1209
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1210
                        event.preventDefault();
×
1211

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

1220
                        return;
×
1221
                    }
1222

1223
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1224
                        event.preventDefault();
×
1225

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

1234
                        return;
×
1235
                    }
1236

1237
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1238
                        event.preventDefault();
×
1239

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

1248
                        return;
×
1249
                    }
1250

1251
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1252
                        event.preventDefault();
×
1253

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

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

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

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

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

1352
    ngOnDestroy() {
1353
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1354
        this.manualListeners.forEach(manualListener => {
23✔
1355
            manualListener();
483✔
1356
        });
1357
        this.destroy$.complete();
23✔
1358
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1359
    }
1360
}
1361

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

1375
/**
1376
 * Check if the target is editable and in the editor.
1377
 */
1378

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

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

1399
/**
1400
 * Check if the target is in the editor.
1401
 */
1402

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

1407
/**
1408
 * Check if the target is inside void and in the editor.
1409
 */
1410

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

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

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