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

worktile / slate-angular / 69fe0099-5d8b-4249-8c40-f33e6ce7f3d6

20 Nov 2023 07:25AM UTC coverage: 48.5% (+2.4%) from 46.148%
69fe0099-5d8b-4249-8c40-f33e6ce7f3d6

Pull #242

circleci

pubuzhixing8
chore: enter prerelease mode
Pull Request #242: List render

378 of 964 branches covered (0.0%)

Branch coverage included in aggregate %.

284 of 334 new or added lines in 12 files covered. (85.03%)

8 existing lines in 3 files now uncovered.

948 of 1770 relevant lines covered (53.56%)

39.84 hits per line

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

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

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

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

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

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

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

127
    private initialized: boolean;
128

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

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

133
    @Input() editor: AngularEditor;
134

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

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

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

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

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

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

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

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

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

153
    @Input() placeholder: string;
154

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

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

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

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

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

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

193
    viewContainerRef = inject(ViewContainerRef);
20✔
194

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

199
    listRender: ListRender;
200

201
    private throttleRAF: ThrottleRAF;
202

203
    constructor(
204
        public elementRef: ElementRef,
20✔
205
        public renderer2: Renderer2,
20✔
206
        public cdr: ChangeDetectorRef,
20✔
207
        private ngZone: NgZone,
20✔
208
        private injector: Injector,
20✔
209
        @Inject(SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN)
210
        public defaultElement: ComponentType<BaseElementComponent>,
20✔
211
        @Inject(SLATE_DEFAULT_TEXT_COMPONENT_TOKEN)
212
        public defaultText: ComponentType<BaseTextComponent>,
20✔
213
        @Inject(SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN)
214
        public defaultVoidText: ComponentType<BaseTextComponent>,
20✔
215
        @Inject(SLATE_DEFAULT_LEAF_COMPONENT_TOKEN)
216
        public defaultLeaf: ComponentType<BaseLeafComponent>
20✔
217
    ) {
218
        this.throttleRAF = createThrottleRAF();
20✔
219
    }
220

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

241
        // remove unused DOM, just keep templateComponent instance
242
        this.templateElementRef.nativeElement.remove();
20✔
243

244
        // add browser class
245
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
20!
246
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
20!
247
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletElement);
20✔
248
    }
249

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

270
    registerOnChange(fn: any) {
271
        this.onChangeCallback = fn;
20✔
272
    }
273
    registerOnTouched(fn: any) {
274
        this.onTouchedCallback = fn;
20✔
275
    }
276

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

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

331
    toNativeSelection() {
332
        try {
14✔
333
            const { selection } = this.editor;
14✔
334
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
14✔
335
            const { activeElement } = root;
14✔
336
            const domSelection = (root as Document).getSelection();
14✔
337

338
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
14!
339
                return;
12✔
340
            }
341

342
            const hasDomSelection = domSelection.type !== 'None';
2✔
343

344
            // If the DOM selection is properly unset, we're done.
345
            if (!selection && !hasDomSelection) {
2!
346
                return;
×
347
            }
348

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

357
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
358
            if (
2✔
359
                hasDomSelection &&
10✔
360
                hasDomSelectionInEditor &&
361
                selection &&
362
                hasStringTarget(domSelection) &&
363
                Range.equals(AngularEditor.toSlateRange(this.editor, domSelection), selection)
364
            ) {
365
                return;
1✔
366
            }
367

368
            // prevent updating native selection when active element is void element
369
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
370
                return;
×
371
            }
372

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

382
            // Otherwise the DOM selection is out of sync, so update it.
383
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
384
            this.isUpdatingSelection = true;
1✔
385

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

388
            if (newDomRange) {
1!
389
                // COMPAT: Since the DOM range has no concept of backwards/forwards
390
                // we need to check and do the right thing here.
391
                if (Range.isBackward(selection)) {
1!
392
                    // eslint-disable-next-line max-len
NEW
393
                    this.throttleRAF(() => {
×
NEW
394
                        domSelection.setBaseAndExtent(
×
395
                            newDomRange.endContainer,
396
                            newDomRange.endOffset,
397
                            newDomRange.startContainer,
398
                            newDomRange.startOffset
399
                        );
400
                    });
401
                    
402
                } else {
403
                    // eslint-disable-next-line max-len
404
                    this.throttleRAF(() => {
1✔
NEW
405
                        domSelection.setBaseAndExtent(
×
406
                            newDomRange.startContainer,
407
                            newDomRange.startOffset,
408
                            newDomRange.endContainer,
409
                            newDomRange.endOffset
410
                        );
411
                    });
412
                }
413
            } else {
414
                domSelection.removeAllRanges();
×
415
            }
416

417
            newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
418

419
            setTimeout(() => {
1✔
420
                // COMPAT: In Firefox, it's not enough to create a range, you also need
421
                // to focus the contenteditable element too. (2016/11/16)
422
                if (newDomRange && IS_FIREFOX) {
1!
423
                    el.focus();
×
424
                }
425

426
                this.isUpdatingSelection = false;
1✔
427
            });
428
        } catch (error) {
429
            this.editor.onError({
×
430
                code: SlateErrorCode.ToNativeSelectionError,
431
                nativeError: error
432
            });
433
            this.isUpdatingSelection = false;
×
434
        }
435
    }
436

437
    onChange() {
438
        this.forceRender();
12✔
439
        this.onChangeCallback(this.editor.children);
12✔
440
    }
441

442
    ngAfterViewChecked() {}
443

444
    ngDoCheck() {}
445

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

485
    render() {
486
        const changed = this.updateContext();
2✔
487
        if (changed) {
2✔
488
            this.listRender.update(this.editor.children, this.editor, [], this.context);
2✔
489
        }
490
    }
491

492
    updateContext() {
493
        const decorations = this.generateDecorations();
16✔
494
        if (
16✔
495
            this.context.selection !== this.editor.selection ||
39✔
496
            this.context.decorate !== this.decorate ||
497
            this.context.readonly !== this.readonly ||
498
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
499
        ) {
500
            this.context = {
11✔
501
                parent: this.editor,
502
                selection: this.editor.selection,
503
                decorations: decorations,
504
                decorate: this.decorate,
505
                readonly: this.readonly
506
            };
507
            return true;
11✔
508
        }
509
        return false;
5✔
510
    }
511

512
    initializeContext() {
513
        this.context = {
43✔
514
            parent: this.editor,
515
            selection: this.editor.selection,
516
            decorations: this.generateDecorations(),
517
            decorate: this.decorate,
518
            readonly: this.readonly
519
        };
520
    }
521

522
    initializeViewContext() {
523
        this.viewContext = {
20✔
524
            editor: this.editor,
525
            renderElement: this.renderElement,
526
            renderLeaf: this.renderLeaf,
527
            renderText: this.renderText,
528
            trackBy: this.trackBy,
529
            isStrictDecorate: this.isStrictDecorate,
530
            templateComponent: this.templateComponent,
531
            defaultElement: this.defaultElement,
532
            defaultText: this.defaultText,
533
            defaultVoidText: this.defaultVoidText,
534
            defaultLeaf: this.defaultLeaf
535
        };
536
    }
537

538
    composePlaceholderDecorate(editor: Editor) {
539
        if (this.placeholderDecorate) {
57!
540
            return this.placeholderDecorate(editor) || [];
×
541
        }
542

543
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
57✔
544
            const start = Editor.start(editor, []);
3✔
545
            return [
3✔
546
                {
547
                    placeholder: this.placeholder,
548
                    anchor: start,
549
                    focus: start
550
                }
551
            ];
552
        } else {
553
            return [];
54✔
554
        }
555
    }
556

557
    generateDecorations() {
558
        const decorations = this.decorate([this.editor, []]);
59✔
559
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
59✔
560
        decorations.push(...placeholderDecorations);
59✔
561
        return decorations;
59✔
562
    }
563

564
    //#region event proxy
565
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
400✔
566
        this.manualListeners.push(
420✔
567
            this.renderer2.listen(target, eventName, (event: Event) => {
568
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
569
                if (beforeInputEvent) {
5!
570
                    this.onFallbackBeforeInput(beforeInputEvent);
×
571
                }
572
                listener(event);
5✔
573
            })
574
        );
575
    }
576

577
    private toSlateSelection() {
578
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
579
            try {
1✔
580
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
581
                const { activeElement } = root;
1✔
582
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
583
                const domSelection = (root as Document).getSelection();
1✔
584

585
                if (activeElement === el) {
1!
586
                    this.latestElement = activeElement;
1✔
587
                    IS_FOCUSED.set(this.editor, true);
1✔
588
                } else {
589
                    IS_FOCUSED.delete(this.editor);
×
590
                }
591

592
                if (!domSelection) {
1!
593
                    return Transforms.deselect(this.editor);
×
594
                }
595

596
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
597
                const hasDomSelectionInEditor =
598
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
599
                if (!hasDomSelectionInEditor) {
1!
600
                    Transforms.deselect(this.editor);
×
601
                    return;
×
602
                }
603

604
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
605
                // for example, double-click the last cell of the table to select a non-editable DOM
606
                const range = AngularEditor.toSlateRange(this.editor, domSelection);
1✔
607
                if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
608
                    if (!isTargetInsideVoid(this.editor, activeElement)) {
×
609
                        // force adjust DOMSelection
610
                        this.toNativeSelection();
×
611
                    }
612
                } else {
613
                    Transforms.select(this.editor, range);
1✔
614
                }
615
            } catch (error) {
616
                this.editor.onError({
×
617
                    code: SlateErrorCode.ToSlateSelectionError,
618
                    nativeError: error
619
                });
620
            }
621
        }
622
    }
623

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

702
                // COMPAT: If the selection is expanded, even if the command seems like
703
                // a delete forward/backward command it should delete the selection.
704
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
705
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
706
                    Editor.deleteFragment(editor, { direction });
×
707
                    return;
×
708
                }
709

710
                switch (type) {
×
711
                    case 'deleteByComposition':
712
                    case 'deleteByCut':
713
                    case 'deleteByDrag': {
714
                        Editor.deleteFragment(editor);
×
715
                        break;
×
716
                    }
717

718
                    case 'deleteContent':
719
                    case 'deleteContentForward': {
720
                        Editor.deleteForward(editor);
×
721
                        break;
×
722
                    }
723

724
                    case 'deleteContentBackward': {
725
                        Editor.deleteBackward(editor);
×
726
                        break;
×
727
                    }
728

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

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

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

745
                    case 'deleteHardLineForward': {
746
                        Editor.deleteForward(editor, { unit: 'block' });
×
747
                        break;
×
748
                    }
749

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

755
                    case 'deleteWordBackward': {
756
                        Editor.deleteBackward(editor, { unit: 'word' });
×
757
                        break;
×
758
                    }
759

760
                    case 'deleteWordForward': {
761
                        Editor.deleteForward(editor, { unit: 'word' });
×
762
                        break;
×
763
                    }
764

765
                    case 'insertLineBreak':
766
                    case 'insertParagraph': {
767
                        Editor.insertBreak(editor);
×
768
                        break;
×
769
                    }
770

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

806
    private onDOMBlur(event: FocusEvent) {
807
        if (
×
808
            this.readonly ||
×
809
            this.isUpdatingSelection ||
810
            !hasEditableTarget(this.editor, event.target) ||
811
            this.isDOMEventHandled(event, this.blur)
812
        ) {
813
            return;
×
814
        }
815

816
        const window = AngularEditor.getWindow(this.editor);
×
817

818
        // COMPAT: If the current `activeElement` is still the previous
819
        // one, this is due to the window being blurred when the tab
820
        // itself becomes unfocused, so we want to abort early to allow to
821
        // editor to stay focused when the tab becomes focused again.
822
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
823
        if (this.latestElement === root.activeElement) {
×
824
            return;
×
825
        }
826

827
        const { relatedTarget } = event;
×
828
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
829

830
        // COMPAT: The event should be ignored if the focus is returning
831
        // to the editor from an embedded editable element (eg. an <input>
832
        // element inside a void node).
833
        if (relatedTarget === el) {
×
834
            return;
×
835
        }
836

837
        // COMPAT: The event should be ignored if the focus is moving from
838
        // the editor to inside a void node's spacer element.
839
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
840
            return;
×
841
        }
842

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

849
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
850
                return;
×
851
            }
852
        }
853

854
        IS_FOCUSED.delete(this.editor);
×
855
    }
856

857
    private onDOMClick(event: MouseEvent) {
858
        if (
×
859
            !this.readonly &&
×
860
            hasTarget(this.editor, event.target) &&
861
            !this.isDOMEventHandled(event, this.click) &&
862
            isDOMNode(event.target)
863
        ) {
864
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
865
            const path = AngularEditor.findPath(this.editor, node);
×
866
            const start = Editor.start(this.editor, path);
×
867
            const end = Editor.end(this.editor, path);
×
868

869
            const startVoid = Editor.void(this.editor, { at: start });
×
870
            const endVoid = Editor.void(this.editor, { at: end });
×
871

872
            if (startVoid && endVoid && Path.equals(startVoid[1], endVoid[1])) {
×
873
                const range = Editor.range(this.editor, start);
×
874
                Transforms.select(this.editor, range);
×
875
            }
876
        }
877
    }
878

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

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

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

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

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

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

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

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

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

953
    private onDOMDragStart(event: DragEvent) {
954
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
955
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
956
            const path = AngularEditor.findPath(this.editor, node);
×
957
            const voidMatch = 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)
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);
19✔
1354
        this.manualListeners.forEach(manualListener => {
19✔
1355
            manualListener();
399✔
1356
        });
1357
        this.destroy$.complete();
19✔
1358
        EDITOR_TO_ON_CHANGE.delete(this.editor);
19✔
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);
1✔
1413
    return Editor.isVoid(editor, slateNode);
1✔
1414
};
1415

1416
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1417
    return (
2✔
1418
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
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