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

worktile / slate-angular / 0786bfb0-2da6-4a02-b2d0-80c01cd79276

12 Nov 2025 03:33AM UTC coverage: 47.244% (+0.4%) from 46.877%
0786bfb0-2da6-4a02-b2d0-80c01cd79276

push

circleci

web-flow
feat(flavour): support extendable flavour(based dom) to improve performance (#300)

* feat(flavour): support extendable flavour(based dom) to improve performance
1. Support angular-component, angular-template, flavour(dom) three kinds extendable view
2. Implement string render based native dom
3. Remove default-element, default-text, default-string, default-leaf and so on angular components
- [x] placeholder is right
- [x] void-string, empty-string, compatible-string, line-break-string are right
- [x] outline-parent is right
- [x] custom flavours are right

* fix(flavour): element support rerender and add void-text.flavour

* feat: revert SlateString component to avoid throwing error(other components need to use this component and need to bump latest slate-angular)

* chore: support flavour view(based native dom) to improve performance

* chore: enter pre

* fix: unit test

373 of 992 branches covered (37.6%)

Branch coverage included in aggregate %.

234 of 291 new or added lines in 17 files covered. (80.41%)

24 existing lines in 3 files now uncovered.

1007 of 1929 relevant lines covered (52.2%)

32.86 hits per line

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

29.95
/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 { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
24
import { direction } from 'direction';
25
import scrollIntoView from 'scroll-into-view-if-needed';
26
import { AngularEditor } from '../../plugins/angular-editor';
27
import {
28
    DOMElement,
29
    isDOMNode,
30
    DOMStaticRange,
31
    DOMRange,
32
    isDOMElement,
33
    isPlainTextOnlyPaste,
34
    DOMSelection,
35
    getDefaultView,
36
    EDITOR_TO_WINDOW,
37
    EDITOR_TO_ELEMENT,
38
    NODE_TO_ELEMENT,
39
    ELEMENT_TO_NODE,
40
    IS_FOCUSED,
41
    IS_READ_ONLY
42
} from 'slate-dom';
43
import { Subject } from 'rxjs';
44
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
45
import Hotkeys from '../../utils/hotkeys';
46
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
47
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
48
import { SlateErrorCode } from '../../types/error';
49
import { NG_VALUE_ACCESSOR } from '@angular/forms';
50
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
51
import { ViewType } from '../../types/view';
52
import { HistoryEditor } from 'slate-history';
53
import { isDecoratorRangeListEqual } from '../../utils';
54
import { SlatePlaceholder } from '../../types/feature';
55
import { restoreDom } from '../../utils/restore-dom';
56
import { ListRender } from '../../view/render/list-render';
57
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
58

59
// not correctly clipboardData on beforeinput
60
const forceOnDOMPaste = IS_SAFARI;
1✔
61

62
@Component({
63
    selector: 'slate-editable',
64
    host: {
65
        class: 'slate-editable-container',
66
        '[attr.contenteditable]': 'readonly ? undefined : true',
67
        '[attr.role]': `readonly ? undefined : 'textbox'`,
68
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
69
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
70
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
71
    },
72
    templateUrl: 'editable.component.html',
73
    changeDetection: ChangeDetectionStrategy.OnPush,
74
    providers: [
75
        {
76
            provide: NG_VALUE_ACCESSOR,
77
            useExisting: forwardRef(() => SlateEditable),
23✔
78
            multi: true
79
        }
80
    ],
81
    imports: []
82
})
83
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
84
    viewContext: SlateViewContext;
85
    context: SlateChildrenContext;
86

87
    private destroy$ = new Subject();
23✔
88

89
    isComposing = false;
23✔
90
    isDraggingInternally = false;
23✔
91
    isUpdatingSelection = false;
23✔
92
    latestElement = null as DOMElement | null;
23✔
93

94
    protected manualListeners: (() => void)[] = [];
23✔
95

96
    private initialized: boolean;
97

98
    private onTouchedCallback: () => void = () => {};
23✔
99

100
    private onChangeCallback: (_: any) => void = () => {};
23✔
101

102
    @Input() editor: AngularEditor;
103

104
    @Input() renderElement: (element: Element) => ViewType | null;
105

106
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
107

108
    @Input() renderText: (text: SlateText) => ViewType | null;
109

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

112
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
113

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

116
    @Input() isStrictDecorate: boolean = true;
23✔
117

118
    @Input() trackBy: (node: Element) => any = () => null;
206✔
119

120
    @Input() readonly = false;
23✔
121

122
    @Input() placeholder: string;
123

124
    //#region input event handler
125
    @Input() beforeInput: (event: Event) => void;
126
    @Input() blur: (event: Event) => void;
127
    @Input() click: (event: MouseEvent) => void;
128
    @Input() compositionEnd: (event: CompositionEvent) => void;
129
    @Input() compositionUpdate: (event: CompositionEvent) => void;
130
    @Input() compositionStart: (event: CompositionEvent) => void;
131
    @Input() copy: (event: ClipboardEvent) => void;
132
    @Input() cut: (event: ClipboardEvent) => void;
133
    @Input() dragOver: (event: DragEvent) => void;
134
    @Input() dragStart: (event: DragEvent) => void;
135
    @Input() dragEnd: (event: DragEvent) => void;
136
    @Input() drop: (event: DragEvent) => void;
137
    @Input() focus: (event: Event) => void;
138
    @Input() keydown: (event: KeyboardEvent) => void;
139
    @Input() paste: (event: ClipboardEvent) => void;
140
    //#endregion
141

142
    //#region DOM attr
143
    @Input() spellCheck = false;
23✔
144
    @Input() autoCorrect = false;
23✔
145
    @Input() autoCapitalize = false;
23✔
146

147
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
148
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
149
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
150

151
    get hasBeforeInputSupport() {
152
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
153
    }
154
    //#endregion
155

156
    viewContainerRef = inject(ViewContainerRef);
23✔
157

158
    getOutletParent = () => {
23✔
159
        return this.elementRef.nativeElement;
43✔
160
    };
161

162
    listRender: ListRender;
163

164
    constructor(
165
        public elementRef: ElementRef,
23✔
166
        public renderer2: Renderer2,
23✔
167
        public cdr: ChangeDetectorRef,
23✔
168
        private ngZone: NgZone,
23✔
169
        private injector: Injector
23✔
170
    ) {}
171

172
    ngOnInit() {
173
        this.editor.injector = this.injector;
23✔
174
        this.editor.children = [];
23✔
175
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
176
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
177
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
178
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
179
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
180
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
181
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
182
            this.ngZone.run(() => {
13✔
183
                this.onChange();
13✔
184
            });
185
        });
186
        this.ngZone.runOutsideAngular(() => {
23✔
187
            this.initialize();
23✔
188
        });
189
        this.initializeViewContext();
23✔
190
        this.initializeContext();
23✔
191

192
        // add browser class
193
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
194
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
195
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, () => null);
23✔
196
    }
197

198
    ngOnChanges(simpleChanges: SimpleChanges) {
199
        if (!this.initialized) {
30✔
200
            return;
23✔
201
        }
202
        const decorateChange = simpleChanges['decorate'];
7✔
203
        if (decorateChange) {
7✔
204
            this.forceRender();
2✔
205
        }
206
        const placeholderChange = simpleChanges['placeholder'];
7✔
207
        if (placeholderChange) {
7✔
208
            this.render();
1✔
209
        }
210
        const readonlyChange = simpleChanges['readonly'];
7✔
211
        if (readonlyChange) {
7!
212
            IS_READ_ONLY.set(this.editor, this.readonly);
×
213
            this.render();
×
214
            this.toSlateSelection();
×
215
        }
216
    }
217

218
    registerOnChange(fn: any) {
219
        this.onChangeCallback = fn;
23✔
220
    }
221
    registerOnTouched(fn: any) {
222
        this.onTouchedCallback = fn;
23✔
223
    }
224

225
    writeValue(value: Element[]) {
226
        if (value && value.length) {
49✔
227
            this.editor.children = value;
26✔
228
            this.initializeContext();
26✔
229
            if (!this.listRender.initialized) {
26✔
230
                console.time('initialize list render');
23✔
231
                this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
232
                console.timeEnd('initialize list render');
23✔
233
            } else {
234
                this.listRender.update(this.editor.children, this.editor, this.context);
3✔
235
            }
236
            this.cdr.markForCheck();
26✔
237
        }
238
    }
239

240
    initialize() {
241
        this.initialized = true;
23✔
242
        const window = AngularEditor.getWindow(this.editor);
23✔
243
        this.addEventListener(
23✔
244
            'selectionchange',
245
            event => {
246
                this.toSlateSelection();
2✔
247
            },
248
            window.document
249
        );
250
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
251
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
252
        }
253
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
254
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
255
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
256
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
257
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
258
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
259
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
260
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
261
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
262
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
263
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
264
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
265
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
266
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
267
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
268
            this.addEventListener(event.name, () => {});
115✔
269
        });
270
    }
271

272
    toNativeSelection() {
273
        try {
15✔
274
            const { selection } = this.editor;
15✔
275
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
276
            const { activeElement } = root;
15✔
277
            const domSelection = (root as Document).getSelection();
15✔
278

279
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
280
                return;
14✔
281
            }
282

283
            const hasDomSelection = domSelection.type !== 'None';
1✔
284

285
            // If the DOM selection is properly unset, we're done.
286
            if (!selection && !hasDomSelection) {
1!
287
                return;
×
288
            }
289

290
            // If the DOM selection is already correct, we're done.
291
            // verify that the dom selection is in the editor
292
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
293
            let hasDomSelectionInEditor = false;
1✔
294
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
295
                hasDomSelectionInEditor = true;
1✔
296
            }
297

298
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
299
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
300
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
301
                    exactMatch: false,
302
                    suppressThrow: true
303
                });
304
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
305
                    return;
×
306
                }
307
            }
308

309
            // prevent updating native selection when active element is void element
310
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
311
                return;
×
312
            }
313

314
            // when <Editable/> is being controlled through external value
315
            // then its children might just change - DOM responds to it on its own
316
            // but Slate's value is not being updated through any operation
317
            // and thus it doesn't transform selection on its own
318
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
319
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
320
                return;
×
321
            }
322

323
            // Otherwise the DOM selection is out of sync, so update it.
324
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
325
            this.isUpdatingSelection = true;
1✔
326

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

329
            if (newDomRange) {
1!
330
                // COMPAT: Since the DOM range has no concept of backwards/forwards
331
                // we need to check and do the right thing here.
332
                if (Range.isBackward(selection)) {
1!
333
                    // eslint-disable-next-line max-len
334
                    domSelection.setBaseAndExtent(
×
335
                        newDomRange.endContainer,
336
                        newDomRange.endOffset,
337
                        newDomRange.startContainer,
338
                        newDomRange.startOffset
339
                    );
340
                } else {
341
                    // eslint-disable-next-line max-len
342
                    domSelection.setBaseAndExtent(
1✔
343
                        newDomRange.startContainer,
344
                        newDomRange.startOffset,
345
                        newDomRange.endContainer,
346
                        newDomRange.endOffset
347
                    );
348
                }
349
            } else {
350
                domSelection.removeAllRanges();
×
351
            }
352

353
            setTimeout(() => {
1✔
354
                // handle scrolling in setTimeout because of
355
                // dom should not have updated immediately after listRender's updating
356
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
357
                // COMPAT: In Firefox, it's not enough to create a range, you also need
358
                // to focus the contenteditable element too. (2016/11/16)
359
                if (newDomRange && IS_FIREFOX) {
1!
360
                    el.focus();
×
361
                }
362

363
                this.isUpdatingSelection = false;
1✔
364
            });
365
        } catch (error) {
366
            this.editor.onError({
×
367
                code: SlateErrorCode.ToNativeSelectionError,
368
                nativeError: error
369
            });
370
            this.isUpdatingSelection = false;
×
371
        }
372
    }
373

374
    onChange() {
375
        this.forceRender();
13✔
376
        this.onChangeCallback(this.editor.children);
13✔
377
    }
378

379
    ngAfterViewChecked() {}
380

381
    ngDoCheck() {}
382

383
    forceRender() {
384
        this.updateContext();
15✔
385
        this.listRender.update(this.editor.children, this.editor, this.context);
15✔
386
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
387
        // when the DOMElement where the selection is located is removed
388
        // the compositionupdate and compositionend events will no longer be fired
389
        // so isComposing needs to be corrected
390
        // need exec after this.cdr.detectChanges() to render HTML
391
        // need exec before this.toNativeSelection() to correct native selection
392
        if (this.isComposing) {
15!
393
            // Composition input text be not rendered when user composition input with selection is expanded
394
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
395
            // this time condition is true and isComposing is assigned false
396
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
397
            setTimeout(() => {
×
398
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
399
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
400
                let textContent = '';
×
401
                // skip decorate text
402
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
403
                    let text = stringDOMNode.textContent;
×
404
                    const zeroChar = '\uFEFF';
×
405
                    // remove zero with char
406
                    if (text.startsWith(zeroChar)) {
×
407
                        text = text.slice(1);
×
408
                    }
409
                    if (text.endsWith(zeroChar)) {
×
410
                        text = text.slice(0, text.length - 1);
×
411
                    }
412
                    textContent += text;
×
413
                });
414
                if (Node.string(textNode).endsWith(textContent)) {
×
415
                    this.isComposing = false;
×
416
                }
417
            }, 0);
418
        }
419
        this.toNativeSelection();
15✔
420
    }
421

422
    render() {
423
        const changed = this.updateContext();
2✔
424
        if (changed) {
2✔
425
            this.listRender.update(this.editor.children, this.editor, this.context);
2✔
426
        }
427
    }
428

429
    updateContext() {
430
        const decorations = this.generateDecorations();
17✔
431
        if (
17✔
432
            this.context.selection !== this.editor.selection ||
46✔
433
            this.context.decorate !== this.decorate ||
434
            this.context.readonly !== this.readonly ||
435
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
436
        ) {
437
            this.context = {
10✔
438
                parent: this.editor,
439
                selection: this.editor.selection,
440
                decorations: decorations,
441
                decorate: this.decorate,
442
                readonly: this.readonly
443
            };
444
            return true;
10✔
445
        }
446
        return false;
7✔
447
    }
448

449
    initializeContext() {
450
        this.context = {
49✔
451
            parent: this.editor,
452
            selection: this.editor.selection,
453
            decorations: this.generateDecorations(),
454
            decorate: this.decorate,
455
            readonly: this.readonly
456
        };
457
    }
458

459
    initializeViewContext() {
460
        this.viewContext = {
23✔
461
            editor: this.editor,
462
            renderElement: this.renderElement,
463
            renderLeaf: this.renderLeaf,
464
            renderText: this.renderText,
465
            trackBy: this.trackBy,
466
            isStrictDecorate: this.isStrictDecorate
467
        };
468
    }
469

470
    composePlaceholderDecorate(editor: Editor) {
471
        if (this.placeholderDecorate) {
64!
472
            return this.placeholderDecorate(editor) || [];
×
473
        }
474

475
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
476
            const start = Editor.start(editor, []);
3✔
477
            return [
3✔
478
                {
479
                    placeholder: this.placeholder,
480
                    anchor: start,
481
                    focus: start
482
                }
483
            ];
484
        } else {
485
            return [];
61✔
486
        }
487
    }
488

489
    generateDecorations() {
490
        const decorations = this.decorate([this.editor, []]);
66✔
491
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
492
        decorations.push(...placeholderDecorations);
66✔
493
        return decorations;
66✔
494
    }
495

496
    //#region event proxy
497
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
498
        this.manualListeners.push(
483✔
499
            this.renderer2.listen(target, eventName, (event: Event) => {
500
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
501
                if (beforeInputEvent) {
5!
502
                    this.onFallbackBeforeInput(beforeInputEvent);
×
503
                }
504
                listener(event);
5✔
505
            })
506
        );
507
    }
508

509
    private toSlateSelection() {
510
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
511
            try {
1✔
512
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
513
                const { activeElement } = root;
1✔
514
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
515
                const domSelection = (root as Document).getSelection();
1✔
516

517
                if (activeElement === el) {
1!
518
                    this.latestElement = activeElement;
1✔
519
                    IS_FOCUSED.set(this.editor, true);
1✔
520
                } else {
521
                    IS_FOCUSED.delete(this.editor);
×
522
                }
523

524
                if (!domSelection) {
1!
525
                    return Transforms.deselect(this.editor);
×
526
                }
527

528
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
529
                const hasDomSelectionInEditor =
530
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
531
                if (!hasDomSelectionInEditor) {
1!
532
                    Transforms.deselect(this.editor);
×
533
                    return;
×
534
                }
535

536
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
537
                // for example, double-click the last cell of the table to select a non-editable DOM
538
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
539
                if (range) {
1✔
540
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
541
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
542
                            // force adjust DOMSelection
543
                            this.toNativeSelection();
×
544
                        }
545
                    } else {
546
                        Transforms.select(this.editor, range);
1✔
547
                    }
548
                }
549
            } catch (error) {
550
                this.editor.onError({
×
551
                    code: SlateErrorCode.ToSlateSelectionError,
552
                    nativeError: error
553
                });
554
            }
555
        }
556
    }
557

558
    private onDOMBeforeInput(
559
        event: Event & {
560
            inputType: string;
561
            isComposing: boolean;
562
            data: string | null;
563
            dataTransfer: DataTransfer | null;
564
            getTargetRanges(): DOMStaticRange[];
565
        }
566
    ) {
567
        const editor = this.editor;
×
568
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
569
        const { activeElement } = root;
×
570
        const { selection } = editor;
×
571
        const { inputType: type } = event;
×
572
        const data = event.dataTransfer || event.data || undefined;
×
573
        if (IS_ANDROID) {
×
574
            let targetRange: Range | null = null;
×
575
            let [nativeTargetRange] = event.getTargetRanges();
×
576
            if (nativeTargetRange) {
×
577
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
578
            }
579
            // COMPAT: SelectionChange event is fired after the action is performed, so we
580
            // have to manually get the selection here to ensure it's up-to-date.
581
            const window = AngularEditor.getWindow(editor);
×
582
            const domSelection = window.getSelection();
×
583
            if (!targetRange && domSelection) {
×
584
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
585
            }
586
            targetRange = targetRange ?? editor.selection;
×
587
            if (type === 'insertCompositionText') {
×
588
                if (data && data.toString().includes('\n')) {
×
589
                    restoreDom(editor, () => {
×
590
                        Editor.insertBreak(editor);
×
591
                    });
592
                } else {
593
                    if (targetRange) {
×
594
                        if (data) {
×
595
                            restoreDom(editor, () => {
×
596
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
597
                            });
598
                        } else {
599
                            restoreDom(editor, () => {
×
600
                                Transforms.delete(editor, { at: targetRange });
×
601
                            });
602
                        }
603
                    }
604
                }
605
                return;
×
606
            }
607
            if (type === 'deleteContentBackward') {
×
608
                // gboard can not prevent default action, so must use restoreDom,
609
                // sougou Keyboard can prevent default action(only in Chinese input mode).
610
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
611
                if (!Range.isCollapsed(targetRange)) {
×
612
                    restoreDom(editor, () => {
×
613
                        Transforms.delete(editor, { at: targetRange });
×
614
                    });
615
                    return;
×
616
                }
617
            }
618
            if (type === 'insertText') {
×
619
                restoreDom(editor, () => {
×
620
                    if (typeof data === 'string') {
×
621
                        Editor.insertText(editor, data);
×
622
                    }
623
                });
624
                return;
×
625
            }
626
        }
627
        if (
×
628
            !this.readonly &&
×
629
            AngularEditor.hasEditableTarget(editor, event.target) &&
630
            !isTargetInsideVoid(editor, activeElement) &&
631
            !this.isDOMEventHandled(event, this.beforeInput)
632
        ) {
633
            try {
×
634
                event.preventDefault();
×
635

636
                // COMPAT: If the selection is expanded, even if the command seems like
637
                // a delete forward/backward command it should delete the selection.
638
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
639
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
640
                    Editor.deleteFragment(editor, { direction });
×
641
                    return;
×
642
                }
643

644
                switch (type) {
×
645
                    case 'deleteByComposition':
646
                    case 'deleteByCut':
647
                    case 'deleteByDrag': {
648
                        Editor.deleteFragment(editor);
×
649
                        break;
×
650
                    }
651

652
                    case 'deleteContent':
653
                    case 'deleteContentForward': {
654
                        Editor.deleteForward(editor);
×
655
                        break;
×
656
                    }
657

658
                    case 'deleteContentBackward': {
659
                        Editor.deleteBackward(editor);
×
660
                        break;
×
661
                    }
662

663
                    case 'deleteEntireSoftLine': {
664
                        Editor.deleteBackward(editor, { unit: 'line' });
×
665
                        Editor.deleteForward(editor, { unit: 'line' });
×
666
                        break;
×
667
                    }
668

669
                    case 'deleteHardLineBackward': {
670
                        Editor.deleteBackward(editor, { unit: 'block' });
×
671
                        break;
×
672
                    }
673

674
                    case 'deleteSoftLineBackward': {
675
                        Editor.deleteBackward(editor, { unit: 'line' });
×
676
                        break;
×
677
                    }
678

679
                    case 'deleteHardLineForward': {
680
                        Editor.deleteForward(editor, { unit: 'block' });
×
681
                        break;
×
682
                    }
683

684
                    case 'deleteSoftLineForward': {
685
                        Editor.deleteForward(editor, { unit: 'line' });
×
686
                        break;
×
687
                    }
688

689
                    case 'deleteWordBackward': {
690
                        Editor.deleteBackward(editor, { unit: 'word' });
×
691
                        break;
×
692
                    }
693

694
                    case 'deleteWordForward': {
695
                        Editor.deleteForward(editor, { unit: 'word' });
×
696
                        break;
×
697
                    }
698

699
                    case 'insertLineBreak':
700
                    case 'insertParagraph': {
701
                        Editor.insertBreak(editor);
×
702
                        break;
×
703
                    }
704

705
                    case 'insertFromComposition': {
706
                        // COMPAT: in safari, `compositionend` event is dispatched after
707
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
708
                        // https://www.w3.org/TR/input-events-2/
709
                        // so the following code is the right logic
710
                        // because DOM selection in sync will be exec before `compositionend` event
711
                        // isComposing is true will prevent DOM selection being update correctly.
712
                        this.isComposing = false;
×
713
                        preventInsertFromComposition(event, this.editor);
×
714
                    }
715
                    case 'insertFromDrop':
716
                    case 'insertFromPaste':
717
                    case 'insertFromYank':
718
                    case 'insertReplacementText':
719
                    case 'insertText': {
720
                        // use a weak comparison instead of 'instanceof' to allow
721
                        // programmatic access of paste events coming from external windows
722
                        // like cypress where cy.window does not work realibly
723
                        if (data?.constructor.name === 'DataTransfer') {
×
724
                            AngularEditor.insertData(editor, data as DataTransfer);
×
725
                        } else if (typeof data === 'string') {
×
726
                            Editor.insertText(editor, data);
×
727
                        }
728
                        break;
×
729
                    }
730
                }
731
            } catch (error) {
732
                this.editor.onError({
×
733
                    code: SlateErrorCode.OnDOMBeforeInputError,
734
                    nativeError: error
735
                });
736
            }
737
        }
738
    }
739

740
    private onDOMBlur(event: FocusEvent) {
741
        if (
×
742
            this.readonly ||
×
743
            this.isUpdatingSelection ||
744
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
745
            this.isDOMEventHandled(event, this.blur)
746
        ) {
747
            return;
×
748
        }
749

750
        const window = AngularEditor.getWindow(this.editor);
×
751

752
        // COMPAT: If the current `activeElement` is still the previous
753
        // one, this is due to the window being blurred when the tab
754
        // itself becomes unfocused, so we want to abort early to allow to
755
        // editor to stay focused when the tab becomes focused again.
756
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
757
        if (this.latestElement === root.activeElement) {
×
758
            return;
×
759
        }
760

761
        const { relatedTarget } = event;
×
762
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
763

764
        // COMPAT: The event should be ignored if the focus is returning
765
        // to the editor from an embedded editable element (eg. an <input>
766
        // element inside a void node).
767
        if (relatedTarget === el) {
×
768
            return;
×
769
        }
770

771
        // COMPAT: The event should be ignored if the focus is moving from
772
        // the editor to inside a void node's spacer element.
773
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
774
            return;
×
775
        }
776

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

783
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
784
                return;
×
785
            }
786
        }
787

788
        IS_FOCUSED.delete(this.editor);
×
789
    }
790

791
    private onDOMClick(event: MouseEvent) {
792
        if (
×
793
            !this.readonly &&
×
794
            AngularEditor.hasTarget(this.editor, event.target) &&
795
            !this.isDOMEventHandled(event, this.click) &&
796
            isDOMNode(event.target)
797
        ) {
798
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
799
            const path = AngularEditor.findPath(this.editor, node);
×
800
            const start = Editor.start(this.editor, path);
×
801
            const end = Editor.end(this.editor, path);
×
802

803
            const startVoid = Editor.void(this.editor, { at: start });
×
804
            const endVoid = Editor.void(this.editor, { at: end });
×
805

806
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
807
                let blockPath = path;
×
808
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
809
                    const block = Editor.above(this.editor, {
×
810
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
811
                        at: path
812
                    });
813

814
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
815
                }
816

817
                const range = Editor.range(this.editor, blockPath);
×
818
                Transforms.select(this.editor, range);
×
819
                return;
×
820
            }
821

822
            if (
×
823
                startVoid &&
×
824
                endVoid &&
825
                Path.equals(startVoid[1], endVoid[1]) &&
826
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
827
            ) {
828
                const range = Editor.range(this.editor, start);
×
829
                Transforms.select(this.editor, range);
×
830
            }
831
        }
832
    }
833

834
    private onDOMCompositionStart(event: CompositionEvent) {
835
        const { selection } = this.editor;
1✔
836
        if (selection) {
1!
837
            // solve the problem of cross node Chinese input
838
            if (Range.isExpanded(selection)) {
×
839
                Editor.deleteFragment(this.editor);
×
840
                this.forceRender();
×
841
            }
842
        }
843
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
844
            this.isComposing = true;
1✔
845
        }
846
        this.render();
1✔
847
    }
848

849
    private onDOMCompositionUpdate(event: CompositionEvent) {
850
        this.isDOMEventHandled(event, this.compositionUpdate);
×
851
    }
852

853
    private onDOMCompositionEnd(event: CompositionEvent) {
854
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
855
            Transforms.delete(this.editor);
×
856
        }
857
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
858
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
859
            // aren't correct and never fire the "insertFromComposition"
860
            // type that we need. So instead, insert whenever a composition
861
            // ends since it will already have been committed to the DOM.
862
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
863
                preventInsertFromComposition(event, this.editor);
×
864
                Editor.insertText(this.editor, event.data);
×
865
            }
866

867
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
868
            // so we need avoid repeat isnertText by isComposing === true,
869
            this.isComposing = false;
×
870
        }
871
        this.render();
×
872
    }
873

874
    private onDOMCopy(event: ClipboardEvent) {
875
        const window = AngularEditor.getWindow(this.editor);
×
876
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
877
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
878
            event.preventDefault();
×
879
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
880
        }
881
    }
882

883
    private onDOMCut(event: ClipboardEvent) {
884
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
885
            event.preventDefault();
×
886
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
887
            const { selection } = this.editor;
×
888

889
            if (selection) {
×
890
                AngularEditor.deleteCutData(this.editor);
×
891
            }
892
        }
893
    }
894

895
    private onDOMDragOver(event: DragEvent) {
896
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
897
            // Only when the target is void, call `preventDefault` to signal
898
            // that drops are allowed. Editable content is droppable by
899
            // default, and calling `preventDefault` hides the cursor.
900
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
901

902
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
903
                event.preventDefault();
×
904
            }
905
        }
906
    }
907

908
    private onDOMDragStart(event: DragEvent) {
909
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
910
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
911
            const path = AngularEditor.findPath(this.editor, node);
×
912
            const voidMatch =
913
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
914

915
            // If starting a drag on a void node, make sure it is selected
916
            // so that it shows up in the selection's fragment.
917
            if (voidMatch) {
×
918
                const range = Editor.range(this.editor, path);
×
919
                Transforms.select(this.editor, range);
×
920
            }
921

922
            this.isDraggingInternally = true;
×
923

924
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
925
        }
926
    }
927

928
    private onDOMDrop(event: DragEvent) {
929
        const editor = this.editor;
×
930
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
931
            event.preventDefault();
×
932
            // Keep a reference to the dragged range before updating selection
933
            const draggedRange = editor.selection;
×
934

935
            // Find the range where the drop happened
936
            const range = AngularEditor.findEventRange(editor, event);
×
937
            const data = event.dataTransfer;
×
938

939
            Transforms.select(editor, range);
×
940

941
            if (this.isDraggingInternally) {
×
942
                if (draggedRange) {
×
943
                    Transforms.delete(editor, {
×
944
                        at: draggedRange
945
                    });
946
                }
947

948
                this.isDraggingInternally = false;
×
949
            }
950

951
            AngularEditor.insertData(editor, data);
×
952

953
            // When dragging from another source into the editor, it's possible
954
            // that the current editor does not have focus.
955
            if (!AngularEditor.isFocused(editor)) {
×
956
                AngularEditor.focus(editor);
×
957
            }
958
        }
959
    }
960

961
    private onDOMDragEnd(event: DragEvent) {
962
        if (
×
963
            !this.readonly &&
×
964
            this.isDraggingInternally &&
965
            AngularEditor.hasTarget(this.editor, event.target) &&
966
            !this.isDOMEventHandled(event, this.dragEnd)
967
        ) {
968
            this.isDraggingInternally = false;
×
969
        }
970
    }
971

972
    private onDOMFocus(event: Event) {
973
        if (
2✔
974
            !this.readonly &&
8✔
975
            !this.isUpdatingSelection &&
976
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
977
            !this.isDOMEventHandled(event, this.focus)
978
        ) {
979
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
980
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
981
            this.latestElement = root.activeElement;
2✔
982

983
            // COMPAT: If the editor has nested editable elements, the focus
984
            // can go to them. In Firefox, this must be prevented because it
985
            // results in issues with keyboard navigation. (2017/03/30)
986
            if (IS_FIREFOX && event.target !== el) {
2!
987
                el.focus();
×
988
                return;
×
989
            }
990

991
            IS_FOCUSED.set(this.editor, true);
2✔
992
        }
993
    }
994

995
    private onDOMKeydown(event: KeyboardEvent) {
996
        const editor = this.editor;
×
997
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
998
        const { activeElement } = root;
×
999
        if (
×
1000
            !this.readonly &&
×
1001
            AngularEditor.hasEditableTarget(editor, event.target) &&
1002
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1003
            !this.isComposing &&
1004
            !this.isDOMEventHandled(event, this.keydown)
1005
        ) {
1006
            const nativeEvent = event;
×
1007
            const { selection } = editor;
×
1008

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

1012
            try {
×
1013
                // COMPAT: Since we prevent the default behavior on
1014
                // `beforeinput` events, the browser doesn't think there's ever
1015
                // any history stack to undo or redo, so we have to manage these
1016
                // hotkeys ourselves. (2019/11/06)
1017
                if (Hotkeys.isRedo(nativeEvent)) {
×
1018
                    event.preventDefault();
×
1019

1020
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1021
                        editor.redo();
×
1022
                    }
1023

1024
                    return;
×
1025
                }
1026

1027
                if (Hotkeys.isUndo(nativeEvent)) {
×
1028
                    event.preventDefault();
×
1029

1030
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1031
                        editor.undo();
×
1032
                    }
1033

1034
                    return;
×
1035
                }
1036

1037
                // COMPAT: Certain browsers don't handle the selection updates
1038
                // properly. In Chrome, the selection isn't properly extended.
1039
                // And in Firefox, the selection isn't properly collapsed.
1040
                // (2017/10/17)
1041
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1042
                    event.preventDefault();
×
1043
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1044
                    return;
×
1045
                }
1046

1047
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1048
                    event.preventDefault();
×
1049
                    Transforms.move(editor, { unit: 'line' });
×
1050
                    return;
×
1051
                }
1052

1053
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1054
                    event.preventDefault();
×
1055
                    Transforms.move(editor, {
×
1056
                        unit: 'line',
1057
                        edge: 'focus',
1058
                        reverse: true
1059
                    });
1060
                    return;
×
1061
                }
1062

1063
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1064
                    event.preventDefault();
×
1065
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1066
                    return;
×
1067
                }
1068

1069
                // COMPAT: If a void node is selected, or a zero-width text node
1070
                // adjacent to an inline is selected, we need to handle these
1071
                // hotkeys manually because browsers won't be able to skip over
1072
                // the void node with the zero-width space not being an empty
1073
                // string.
1074
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1075
                    event.preventDefault();
×
1076

1077
                    if (selection && Range.isCollapsed(selection)) {
×
1078
                        Transforms.move(editor, { reverse: !isRTL });
×
1079
                    } else {
1080
                        Transforms.collapse(editor, { edge: 'start' });
×
1081
                    }
1082

1083
                    return;
×
1084
                }
1085

1086
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1087
                    event.preventDefault();
×
UNCOV
1088
                    if (selection && Range.isCollapsed(selection)) {
×
1089
                        Transforms.move(editor, { reverse: isRTL });
×
1090
                    } else {
1091
                        Transforms.collapse(editor, { edge: 'end' });
×
1092
                    }
1093

1094
                    return;
×
1095
                }
1096

1097
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1098
                    event.preventDefault();
×
1099

1100
                    if (selection && Range.isExpanded(selection)) {
×
1101
                        Transforms.collapse(editor, { edge: 'focus' });
×
1102
                    }
1103

1104
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1105
                    return;
×
1106
                }
1107

1108
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1109
                    event.preventDefault();
×
1110

1111
                    if (selection && Range.isExpanded(selection)) {
×
1112
                        Transforms.collapse(editor, { edge: 'focus' });
×
1113
                    }
1114

1115
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1116
                    return;
×
1117
                }
1118

1119
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1120
                // fall back to guessing at the input intention for hotkeys.
1121
                // COMPAT: In iOS, some of these hotkeys are handled in the
1122
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1123
                    // We don't have a core behavior for these, but they change the
1124
                    // DOM if we don't prevent them, so we have to.
1125
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1126
                        event.preventDefault();
×
1127
                        return;
×
1128
                    }
1129

1130
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1131
                        event.preventDefault();
×
1132
                        Editor.insertBreak(editor);
×
1133
                        return;
×
1134
                    }
1135

1136
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1137
                        event.preventDefault();
×
1138

1139
                        if (selection && Range.isExpanded(selection)) {
×
1140
                            Editor.deleteFragment(editor, {
×
1141
                                direction: 'backward'
1142
                            });
1143
                        } else {
1144
                            Editor.deleteBackward(editor);
×
1145
                        }
1146

1147
                        return;
×
1148
                    }
1149

1150
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1151
                        event.preventDefault();
×
1152

1153
                        if (selection && Range.isExpanded(selection)) {
×
1154
                            Editor.deleteFragment(editor, {
×
1155
                                direction: 'forward'
1156
                            });
1157
                        } else {
1158
                            Editor.deleteForward(editor);
×
1159
                        }
1160

1161
                        return;
×
1162
                    }
1163

1164
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1165
                        event.preventDefault();
×
1166

1167
                        if (selection && Range.isExpanded(selection)) {
×
1168
                            Editor.deleteFragment(editor, {
×
1169
                                direction: 'backward'
1170
                            });
1171
                        } else {
1172
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1173
                        }
1174

1175
                        return;
×
1176
                    }
1177

1178
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1179
                        event.preventDefault();
×
1180

1181
                        if (selection && Range.isExpanded(selection)) {
×
1182
                            Editor.deleteFragment(editor, {
×
1183
                                direction: 'forward'
1184
                            });
1185
                        } else {
1186
                            Editor.deleteForward(editor, { unit: 'line' });
×
1187
                        }
1188

1189
                        return;
×
1190
                    }
1191

1192
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1193
                        event.preventDefault();
×
1194

1195
                        if (selection && Range.isExpanded(selection)) {
×
1196
                            Editor.deleteFragment(editor, {
×
1197
                                direction: 'backward'
1198
                            });
1199
                        } else {
1200
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1201
                        }
1202

1203
                        return;
×
1204
                    }
1205

1206
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1207
                        event.preventDefault();
×
1208

1209
                        if (selection && Range.isExpanded(selection)) {
×
1210
                            Editor.deleteFragment(editor, {
×
1211
                                direction: 'forward'
1212
                            });
1213
                        } else {
1214
                            Editor.deleteForward(editor, { unit: 'word' });
×
1215
                        }
1216

1217
                        return;
×
1218
                    }
1219
                } else {
1220
                    if (IS_CHROME || IS_SAFARI) {
×
1221
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1222
                        // an event when deleting backwards in a selected void inline node
1223
                        if (
×
1224
                            selection &&
×
1225
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1226
                            Range.isCollapsed(selection)
1227
                        ) {
1228
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1229
                            if (
×
1230
                                Element.isElement(currentNode) &&
×
1231
                                Editor.isVoid(editor, currentNode) &&
1232
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1233
                            ) {
1234
                                event.preventDefault();
×
1235
                                Editor.deleteBackward(editor, {
×
1236
                                    unit: 'block'
1237
                                });
1238
                                return;
×
1239
                            }
1240
                        }
1241
                    }
1242
                }
1243
            } catch (error) {
1244
                this.editor.onError({
×
1245
                    code: SlateErrorCode.OnDOMKeydownError,
1246
                    nativeError: error
1247
                });
1248
            }
1249
        }
1250
    }
1251

1252
    private onDOMPaste(event: ClipboardEvent) {
1253
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1254
        // fall back to React's `onPaste` here instead.
1255
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1256
        // when "paste without formatting" option is used.
1257
        // This unfortunately needs to be handled with paste events instead.
1258
        if (
×
1259
            !this.isDOMEventHandled(event, this.paste) &&
×
1260
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1261
            !this.readonly &&
1262
            AngularEditor.hasEditableTarget(this.editor, event.target)
1263
        ) {
1264
            event.preventDefault();
×
1265
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1266
        }
1267
    }
1268

1269
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1270
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1271
        // fall back to React's leaky polyfill instead just for it. It
1272
        // only works for the `insertText` input type.
1273
        if (
×
1274
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1275
            !this.readonly &&
1276
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1277
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1278
        ) {
1279
            event.nativeEvent.preventDefault();
×
1280
            try {
×
1281
                const text = event.data;
×
1282
                if (!Range.isCollapsed(this.editor.selection)) {
×
1283
                    Editor.deleteFragment(this.editor);
×
1284
                }
1285
                // just handle Non-IME input
1286
                if (!this.isComposing) {
×
1287
                    Editor.insertText(this.editor, text);
×
1288
                }
1289
            } catch (error) {
1290
                this.editor.onError({
×
1291
                    code: SlateErrorCode.ToNativeSelectionError,
1292
                    nativeError: error
1293
                });
1294
            }
1295
        }
1296
    }
1297

1298
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1299
        if (!handler) {
3✔
1300
            return false;
3✔
1301
        }
1302
        handler(event);
×
1303
        return event.defaultPrevented;
×
1304
    }
1305
    //#endregion
1306

1307
    ngOnDestroy() {
1308
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1309
        this.manualListeners.forEach(manualListener => {
23✔
1310
            manualListener();
483✔
1311
        });
1312
        this.destroy$.complete();
23✔
1313
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1314
    }
1315
}
1316

1317
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1318
    // This was affecting the selection of multiple blocks and dragging behavior,
1319
    // so enabled only if the selection has been collapsed.
1320
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1321
        const leafEl = domRange.startContainer.parentElement!;
×
1322

1323
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1324
        // When this happens, do not scroll like most editors do.
1325
        const domRect = domRange.getBoundingClientRect();
×
1326
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1327

1328
        if (isZeroDimensionRect) {
×
1329
            const leafRect = leafEl.getBoundingClientRect();
×
1330
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1331

1332
            if (leafHasDimensions) {
×
1333
                return;
×
1334
            }
1335
        }
1336

1337
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1338
        scrollIntoView(leafEl, {
×
1339
            scrollMode: 'if-needed'
1340
        });
1341
        delete leafEl.getBoundingClientRect;
×
1342
    }
1343
};
1344

1345
/**
1346
 * Check if the target is inside void and in the editor.
1347
 */
1348

1349
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1350
    let slateNode: Node | null = null;
1✔
1351
    try {
1✔
1352
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1353
    } catch (error) {}
1354
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1355
};
1356

1357
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1358
    return (
2✔
1359
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1360
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1361
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1362
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1363
    );
1364
};
1365

1366
/**
1367
 * remove default insert from composition
1368
 * @param text
1369
 */
1370
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1371
    const types = ['compositionend', 'insertFromComposition'];
×
1372
    if (!types.includes(event.type)) {
×
1373
        return;
×
1374
    }
1375
    const insertText = (event as CompositionEvent).data;
×
1376
    const window = AngularEditor.getWindow(editor);
×
1377
    const domSelection = window.getSelection();
×
1378
    // ensure text node insert composition input text
1379
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1380
        const textNode = domSelection.anchorNode;
×
1381
        textNode.splitText(textNode.length - insertText.length).remove();
×
1382
    }
1383
};
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