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

worktile / slate-angular / 9a27298f-a275-46e4-9430-02f192e8aae9

06 Nov 2023 09:44AM UTC coverage: 48.372% (+2.2%) from 46.148%
9a27298f-a275-46e4-9430-02f192e8aae9

push

circleci

pubuzhixing8
performance(render): initialize list render and leaves render to optimized rendering performance

371 of 953 branches covered (0.0%)

Branch coverage included in aggregate %.

270 of 309 new or added lines in 10 files covered. (87.38%)

8 existing lines in 3 files now uncovered.

936 of 1749 relevant lines covered (53.52%)

42.56 hits per line

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

31.27
/packages/src/components/editable/editable.component.ts
1
import {
2
    Component,
3
    OnInit,
4
    Input,
5
    ViewChild,
6
    HostBinding,
7
    Renderer2,
8
    ElementRef,
9
    ChangeDetectionStrategy,
10
    OnDestroy,
11
    ChangeDetectorRef,
12
    NgZone,
13
    Injector,
14
    forwardRef,
15
    OnChanges,
16
    SimpleChanges,
17
    AfterViewChecked,
18
    DoCheck,
19
    Inject,
20
    inject,
21
    ViewContainerRef
22
} from '@angular/core';
23
import {
24
    NODE_TO_ELEMENT,
25
    IS_FOCUSED,
26
    EDITOR_TO_ELEMENT,
27
    ELEMENT_TO_NODE,
28
    IS_READONLY,
29
    EDITOR_TO_ON_CHANGE,
30
    EDITOR_TO_WINDOW
31
} from '../../utils/weak-maps';
32
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
33
import { direction } from 'direction';
34
import scrollIntoView from 'scroll-into-view-if-needed';
35
import { AngularEditor } from '../../plugins/angular-editor';
36
import {
37
    DOMElement,
38
    DOMNode,
39
    isDOMNode,
40
    DOMStaticRange,
41
    DOMRange,
42
    isDOMElement,
43
    isPlainTextOnlyPaste,
44
    DOMSelection,
45
    getDefaultView
46
} from '../../utils/dom';
47
import { Subject } from 'rxjs';
48
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
49
import Hotkeys from '../../utils/hotkeys';
50
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
51
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
52
import { SlateErrorCode } from '../../types/error';
53
import { SlateStringTemplate } from '../string/template.component';
54
import { NG_VALUE_ACCESSOR } from '@angular/forms';
55
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
56
import { ComponentType, ViewType } from '../../types/view';
57
import { HistoryEditor } from 'slate-history';
58
import { isDecoratorRangeListEqual, check, normalize } from '../../utils';
59
import { SlatePlaceholder } from '../../types/feature';
60
import { restoreDom } from '../../utils/restore-dom';
61
import { SlateChildren } from '../children/children.component';
62
import { SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN } from '../element/default-element.component.token';
63
import { SLATE_DEFAULT_TEXT_COMPONENT_TOKEN, SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN } from '../text/token';
64
import { SlateVoidText } from '../text/void-text.component';
65
import { SlateDefaultText } from '../text/default-text.component';
66
import { SlateDefaultElement } from '../element/default-element.component';
67
import { SlateDefaultLeaf } from '../leaf/default-leaf.component';
68
import { SLATE_DEFAULT_LEAF_COMPONENT_TOKEN } from '../leaf/token';
69
import { BaseElementComponent, BaseLeafComponent, BaseTextComponent } from '../../view/base';
70
import { ListRender } from '../../view/render/list-render';
71

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),
20✔
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: [SlateChildren, 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();
20✔
118

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

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

126
    private initialized: boolean;
127

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

130
    private onChangeCallback: (_: any) => void = () => {};
20✔
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[] = () => [];
213✔
141

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

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

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

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

150
    @Input() readonly = false;
20✔
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;
20✔
174
    @Input() autoCorrect = false;
20✔
175
    @Input() autoCapitalize = false;
20✔
176

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

181
    get hasBeforeInputSupport() {
182
        return HAS_BEFORE_INPUT_SUPPORT;
396✔
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);
20✔
193

194
    getOutletElement = () => {
20✔
195
        return this.elementRef.nativeElement;
38✔
196
    };
197

198
    listRender: ListRender;
199

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

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

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

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

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

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

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

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

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

333
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
13!
334
                return;
12✔
335
            }
336

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

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

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

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

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

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

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

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

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

407
            newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
408

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

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

427
    onChange() {
428
        this.forceRender();
11✔
429
        this.onChangeCallback(this.editor.children);
11✔
430
    }
431

432
    ngAfterViewChecked() {}
433

434
    ngDoCheck() {}
435

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

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

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

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

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

528
    composePlaceholderDecorate(editor: Editor) {
529
        if (this.placeholderDecorate) {
56!
530
            return this.placeholderDecorate(editor) || [];
×
531
        }
532

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

806
        const window = AngularEditor.getWindow(this.editor);
×
807

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

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

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

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

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

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

844
        IS_FOCUSED.delete(this.editor);
×
845
    }
846

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

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

862
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
863
                const range = Editor.range(this.editor, start);
×
864
                Transforms.select(this.editor, range);
×
865
            }
866
        }
867
    }
868

869
    private onDOMCompositionStart(event: CompositionEvent) {
870
        const { selection } = this.editor;
1✔
871
        if (selection) {
1!
872
            // solve the problem of cross node Chinese input
873
            if (Range.isExpanded(selection)) {
×
874
                Editor.deleteFragment(this.editor);
×
NEW
875
                this.forceRender();
×
876
            }
877
        }
878
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
879
            this.isComposing = true;
1✔
880
        }
881
        this.render();
1✔
882
    }
883

884
    private onDOMCompositionUpdate(event: CompositionEvent) {
885
        this.isDOMEventHandled(event, this.compositionUpdate);
×
886
    }
887

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

902
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
903
            // so we need avoid repeat isnertText by isComposing === true,
904
            this.isComposing = false;
×
905
        }
NEW
906
        this.render();
×
907
    }
908

909
    private onDOMCopy(event: ClipboardEvent) {
910
        const window = AngularEditor.getWindow(this.editor);
×
911
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
912
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
913
            event.preventDefault();
×
914
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
915
        }
916
    }
917

918
    private onDOMCut(event: ClipboardEvent) {
919
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
920
            event.preventDefault();
×
921
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
922
            const { selection } = this.editor;
×
923

924
            if (selection) {
×
925
                AngularEditor.deleteCutData(this.editor);
×
926
            }
927
        }
928
    }
929

930
    private onDOMDragOver(event: DragEvent) {
931
        if (hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
932
            // Only when the target is void, call `preventDefault` to signal
933
            // that drops are allowed. Editable content is droppable by
934
            // default, and calling `preventDefault` hides the cursor.
935
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
936

937
            if (Editor.isVoid(this.editor, node)) {
×
938
                event.preventDefault();
×
939
            }
940
        }
941
    }
942

943
    private onDOMDragStart(event: DragEvent) {
944
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
945
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
946
            const path = AngularEditor.findPath(this.editor, node);
×
947
            const voidMatch = Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true });
×
948

949
            // If starting a drag on a void node, make sure it is selected
950
            // so that it shows up in the selection's fragment.
951
            if (voidMatch) {
×
952
                const range = Editor.range(this.editor, path);
×
953
                Transforms.select(this.editor, range);
×
954
            }
955

956
            this.isDraggingInternally = true;
×
957

958
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
959
        }
960
    }
961

962
    private onDOMDrop(event: DragEvent) {
963
        const editor = this.editor;
×
964
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
965
            event.preventDefault();
×
966
            // Keep a reference to the dragged range before updating selection
967
            const draggedRange = editor.selection;
×
968

969
            // Find the range where the drop happened
970
            const range = AngularEditor.findEventRange(editor, event);
×
971
            const data = event.dataTransfer;
×
972

973
            Transforms.select(editor, range);
×
974

975
            if (this.isDraggingInternally) {
×
976
                if (draggedRange) {
×
977
                    Transforms.delete(editor, {
×
978
                        at: draggedRange
979
                    });
980
                }
981

982
                this.isDraggingInternally = false;
×
983
            }
984

985
            AngularEditor.insertData(editor, data);
×
986

987
            // When dragging from another source into the editor, it's possible
988
            // that the current editor does not have focus.
989
            if (!AngularEditor.isFocused(editor)) {
×
990
                AngularEditor.focus(editor);
×
991
            }
992
        }
993
    }
994

995
    private onDOMDragEnd(event: DragEvent) {
996
        if (
×
997
            !this.readonly &&
×
998
            this.isDraggingInternally &&
999
            hasTarget(this.editor, event.target) &&
1000
            !this.isDOMEventHandled(event, this.dragEnd)
1001
        ) {
1002
            this.isDraggingInternally = false;
×
1003
        }
1004
    }
1005

1006
    private onDOMFocus(event: Event) {
1007
        if (
2✔
1008
            !this.readonly &&
8✔
1009
            !this.isUpdatingSelection &&
1010
            hasEditableTarget(this.editor, event.target) &&
1011
            !this.isDOMEventHandled(event, this.focus)
1012
        ) {
1013
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1014
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1015
            this.latestElement = root.activeElement;
2✔
1016

1017
            // COMPAT: If the editor has nested editable elements, the focus
1018
            // can go to them. In Firefox, this must be prevented because it
1019
            // results in issues with keyboard navigation. (2017/03/30)
1020
            if (IS_FIREFOX && event.target !== el) {
2!
1021
                el.focus();
×
1022
                return;
×
1023
            }
1024

1025
            IS_FOCUSED.set(this.editor, true);
2✔
1026
        }
1027
    }
1028

1029
    private onDOMKeydown(event: KeyboardEvent) {
1030
        const editor = this.editor;
×
1031
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1032
        const { activeElement } = root;
×
1033
        if (
×
1034
            !this.readonly &&
×
1035
            hasEditableTarget(editor, event.target) &&
1036
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1037
            !this.isComposing &&
1038
            !this.isDOMEventHandled(event, this.keydown)
1039
        ) {
1040
            const nativeEvent = event;
×
1041
            const { selection } = editor;
×
1042

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

1046
            try {
×
1047
                // COMPAT: Since we prevent the default behavior on
1048
                // `beforeinput` events, the browser doesn't think there's ever
1049
                // any history stack to undo or redo, so we have to manage these
1050
                // hotkeys ourselves. (2019/11/06)
1051
                if (Hotkeys.isRedo(nativeEvent)) {
×
1052
                    event.preventDefault();
×
1053

1054
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1055
                        editor.redo();
×
1056
                    }
1057

1058
                    return;
×
1059
                }
1060

1061
                if (Hotkeys.isUndo(nativeEvent)) {
×
1062
                    event.preventDefault();
×
1063

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

1068
                    return;
×
1069
                }
1070

1071
                // COMPAT: Certain browsers don't handle the selection updates
1072
                // properly. In Chrome, the selection isn't properly extended.
1073
                // And in Firefox, the selection isn't properly collapsed.
1074
                // (2017/10/17)
1075
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1076
                    event.preventDefault();
×
1077
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1078
                    return;
×
1079
                }
1080

1081
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1082
                    event.preventDefault();
×
1083
                    Transforms.move(editor, { unit: 'line' });
×
1084
                    return;
×
1085
                }
1086

1087
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1088
                    event.preventDefault();
×
1089
                    Transforms.move(editor, {
×
1090
                        unit: 'line',
1091
                        edge: 'focus',
1092
                        reverse: true
1093
                    });
1094
                    return;
×
1095
                }
1096

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

1103
                // COMPAT: If a void node is selected, or a zero-width text node
1104
                // adjacent to an inline is selected, we need to handle these
1105
                // hotkeys manually because browsers won't be able to skip over
1106
                // the void node with the zero-width space not being an empty
1107
                // string.
1108
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1109
                    event.preventDefault();
×
1110

1111
                    if (selection && Range.isCollapsed(selection)) {
×
1112
                        Transforms.move(editor, { reverse: !isRTL });
×
1113
                    } else {
1114
                        Transforms.collapse(editor, { edge: 'start' });
×
1115
                    }
1116

1117
                    return;
×
1118
                }
1119

1120
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1121
                    event.preventDefault();
×
1122

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

1129
                    return;
×
1130
                }
1131

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

1135
                    if (selection && Range.isExpanded(selection)) {
×
1136
                        Transforms.collapse(editor, { edge: 'focus' });
×
1137
                    }
1138

1139
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1140
                    return;
×
1141
                }
1142

1143
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1144
                    event.preventDefault();
×
1145

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

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

1154
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1155
                // fall back to guessing at the input intention for hotkeys.
1156
                // COMPAT: In iOS, some of these hotkeys are handled in the
1157
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1158
                    // We don't have a core behavior for these, but they change the
1159
                    // DOM if we don't prevent them, so we have to.
1160
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1161
                        event.preventDefault();
×
1162
                        return;
×
1163
                    }
1164

1165
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1166
                        event.preventDefault();
×
1167
                        Editor.insertBreak(editor);
×
1168
                        return;
×
1169
                    }
1170

1171
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1172
                        event.preventDefault();
×
1173

1174
                        if (selection && Range.isExpanded(selection)) {
×
1175
                            Editor.deleteFragment(editor, {
×
1176
                                direction: 'backward'
1177
                            });
1178
                        } else {
1179
                            Editor.deleteBackward(editor);
×
1180
                        }
1181

1182
                        return;
×
1183
                    }
1184

1185
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1186
                        event.preventDefault();
×
1187

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

1196
                        return;
×
1197
                    }
1198

1199
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1200
                        event.preventDefault();
×
1201

1202
                        if (selection && Range.isExpanded(selection)) {
×
1203
                            Editor.deleteFragment(editor, {
×
1204
                                direction: 'backward'
1205
                            });
1206
                        } else {
1207
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1208
                        }
1209

1210
                        return;
×
1211
                    }
1212

1213
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1214
                        event.preventDefault();
×
1215

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

1224
                        return;
×
1225
                    }
1226

1227
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1228
                        event.preventDefault();
×
1229

1230
                        if (selection && Range.isExpanded(selection)) {
×
1231
                            Editor.deleteFragment(editor, {
×
1232
                                direction: 'backward'
1233
                            });
1234
                        } else {
1235
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1236
                        }
1237

1238
                        return;
×
1239
                    }
1240

1241
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1242
                        event.preventDefault();
×
1243

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

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

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

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

1333
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1334
        if (!handler) {
3✔
1335
            return false;
3✔
1336
        }
1337
        handler(event);
×
1338
        return event.defaultPrevented;
×
1339
    }
1340
    //#endregion
1341

1342
    ngOnDestroy() {
1343
        NODE_TO_ELEMENT.delete(this.editor);
19✔
1344
        this.manualListeners.forEach(manualListener => {
19✔
1345
            manualListener();
399✔
1346
        });
1347
        this.destroy$.complete();
19✔
1348
        EDITOR_TO_ON_CHANGE.delete(this.editor);
19✔
1349
    }
1350
}
1351

1352
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1353
    // This was affecting the selection of multiple blocks and dragging behavior,
1354
    // so enabled only if the selection has been collapsed.
1355
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1356
        const leafEl = domRange.startContainer.parentElement!;
×
1357
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1358
        scrollIntoView(leafEl, {
×
1359
            scrollMode: 'if-needed'
1360
        });
1361
        delete leafEl.getBoundingClientRect;
×
1362
    }
1363
};
1364

1365
/**
1366
 * Check if the target is editable and in the editor.
1367
 */
1368

1369
export const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1370
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
3✔
1371
};
1372

1373
/**
1374
 * Check if two DOM range objects are equal.
1375
 */
1376
const isRangeEqual = (a: DOMRange, b: DOMRange) => {
1✔
1377
    return (
×
1378
        (a.startContainer === b.startContainer &&
×
1379
            a.startOffset === b.startOffset &&
1380
            a.endContainer === b.endContainer &&
1381
            a.endOffset === b.endOffset) ||
1382
        (a.startContainer === b.endContainer &&
1383
            a.startOffset === b.endOffset &&
1384
            a.endContainer === b.startContainer &&
1385
            a.endOffset === b.startOffset)
1386
    );
1387
};
1388

1389
/**
1390
 * Check if the target is in the editor.
1391
 */
1392

1393
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1394
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
1✔
1395
};
1396

1397
/**
1398
 * Check if the target is inside void and in the editor.
1399
 */
1400

1401
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1402
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1403
    return Editor.isVoid(editor, slateNode);
1✔
1404
};
1405

1406
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1407
    return (
3✔
1408
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
6!
1409
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1410
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1411
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1412
    );
1413
};
1414

1415
/**
1416
 * remove default insert from composition
1417
 * @param text
1418
 */
1419
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1420
    const types = ['compositionend', 'insertFromComposition'];
×
1421
    if (!types.includes(event.type)) {
×
1422
        return;
×
1423
    }
1424
    const insertText = (event as CompositionEvent).data;
×
1425
    const window = AngularEditor.getWindow(editor);
×
1426
    const domSelection = window.getSelection();
×
1427
    // ensure text node insert composition input text
1428
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1429
        const textNode = domSelection.anchorNode;
×
1430
        textNode.splitText(textNode.length - insertText.length).remove();
×
1431
    }
1432
};
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