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

worktile / slate-angular / 04498188-2f3f-4d67-8c06-98bae7e205ee

04 Sep 2025 07:25AM UTC coverage: 47.486% (-1.0%) from 48.475%
04498188-2f3f-4d67-8c06-98bae7e205ee

push

circleci

pubuzhixing8
fix: fix autoscroll to top on line break #WIK-18594
refer to https://github.com/ianstormtaylor/slate/issues/5900

360 of 938 branches covered (38.38%)

Branch coverage included in aggregate %.

0 of 7 new or added lines in 1 file covered. (0.0%)

14 existing lines in 1 file now uncovered.

934 of 1787 relevant lines covered (52.27%)

43.99 hits per line

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

30.17
/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 { SlateStringTemplate } from '../string/template.component';
50
import { NG_VALUE_ACCESSOR } from '@angular/forms';
51
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
52
import { ComponentType, ViewType } from '../../types/view';
53
import { HistoryEditor } from 'slate-history';
54
import { isDecoratorRangeListEqual } from '../../utils';
55
import { SlatePlaceholder } from '../../types/feature';
56
import { restoreDom } from '../../utils/restore-dom';
57
import { SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN } from '../element/default-element.component.token';
58
import { SLATE_DEFAULT_TEXT_COMPONENT_TOKEN, SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN } from '../text/token';
59
import { SlateVoidText } from '../text/void-text.component';
60
import { SlateDefaultText } from '../text/default-text.component';
61
import { SlateDefaultElement } from '../element/default-element.component';
62
import { SlateDefaultLeaf } from '../leaf/default-leaf.component';
63
import { SLATE_DEFAULT_LEAF_COMPONENT_TOKEN } from '../leaf/token';
64
import { BaseElementComponent, BaseLeafComponent, BaseTextComponent } from '../../view/base';
65
import { ListRender } from '../../view/render/list-render';
66
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
67

68
// not correctly clipboardData on beforeinput
69
const forceOnDOMPaste = IS_SAFARI;
1✔
70

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

112
    private destroy$ = new Subject();
23✔
113

114
    isComposing = false;
23✔
115
    isDraggingInternally = false;
23✔
116
    isUpdatingSelection = false;
23✔
117
    latestElement = null as DOMElement | null;
23✔
118

119
    protected manualListeners: (() => void)[] = [];
23✔
120

121
    private initialized: boolean;
122

123
    private onTouchedCallback: () => void = () => {};
23✔
124

125
    private onChangeCallback: (_: any) => void = () => {};
23✔
126

127
    @Input() editor: AngularEditor;
128

129
    @Input() renderElement: (element: Element) => ViewType | null;
130

131
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
132

133
    @Input() renderText: (text: SlateText) => ViewType | null;
134

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

137
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
138

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

141
    @Input() isStrictDecorate: boolean = true;
23✔
142

143
    @Input() trackBy: (node: Element) => any = () => null;
206✔
144

145
    @Input() readonly = false;
23✔
146

147
    @Input() placeholder: string;
148

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

167
    //#region DOM attr
168
    @Input() spellCheck = false;
23✔
169
    @Input() autoCorrect = false;
23✔
170
    @Input() autoCapitalize = false;
23✔
171

172
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
173
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
174
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
175

176
    get hasBeforeInputSupport() {
177
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
178
    }
179
    //#endregion
180

181
    @ViewChild('templateComponent', { static: true })
182
    templateComponent: SlateStringTemplate;
183

184
    @ViewChild('templateComponent', { static: true, read: ElementRef })
185
    templateElementRef: ElementRef<any>;
186

187
    viewContainerRef = inject(ViewContainerRef);
23✔
188

189
    getOutletParent = () => {
23✔
190
        return this.elementRef.nativeElement;
43✔
191
    };
192

193
    listRender: ListRender;
194

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

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

231
        // remove unused DOM, just keep templateComponent instance
232
        this.templateElementRef.nativeElement.remove();
23✔
233

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

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

260
    registerOnChange(fn: any) {
261
        this.onChangeCallback = fn;
23✔
262
    }
263
    registerOnTouched(fn: any) {
264
        this.onTouchedCallback = fn;
23✔
265
    }
266

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

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

312
    toNativeSelection() {
313
        try {
15✔
314
            const { selection } = this.editor;
15✔
315
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
316
            const { activeElement } = root;
15✔
317
            const domSelection = (root as Document).getSelection();
15✔
318

319
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
320
                return;
14✔
321
            }
322

323
            const hasDomSelection = domSelection.type !== 'None';
1✔
324

325
            // If the DOM selection is properly unset, we're done.
326
            if (!selection && !hasDomSelection) {
1!
327
                return;
×
328
            }
329

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

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

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

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

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

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

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

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

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

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

419
    ngAfterViewChecked() {}
420

421
    ngDoCheck() {}
422

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

867
            if (
×
868
                startVoid &&
×
869
                endVoid &&
870
                Path.equals(startVoid[1], endVoid[1]) &&
871
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
872
            ) {
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
UNCOV
883
            if (Range.isExpanded(selection)) {
×
884
                Editor.deleteFragment(this.editor);
×
885
                this.forceRender();
×
886
            }
887
        }
888
        if (AngularEditor.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 (AngularEditor.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
        }
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 && AngularEditor.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 && AngularEditor.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 (AngularEditor.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 (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
948
                event.preventDefault();
×
949
            }
950
        }
951
    }
952

953
    private onDOMDragStart(event: DragEvent) {
954
        if (!this.readonly && AngularEditor.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 =
958
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
959

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

967
            this.isDraggingInternally = true;
×
968

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

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

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

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

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

993
                this.isDraggingInternally = false;
×
994
            }
995

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

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

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

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

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

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

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

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

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

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

1069
                    return;
×
1070
                }
1071

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

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

1079
                    return;
×
1080
                }
1081

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

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

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

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

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

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

1128
                    return;
×
1129
                }
1130

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

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

1140
                    return;
×
1141
                }
1142

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

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

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

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

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

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

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

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

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

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

1193
                        return;
×
1194
                    }
1195

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

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

1207
                        return;
×
1208
                    }
1209

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

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

1221
                        return;
×
1222
                    }
1223

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

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

1235
                        return;
×
1236
                    }
1237

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

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

1249
                        return;
×
1250
                    }
1251

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

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

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

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

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

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

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

1363
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1364
    // This was affecting the selection of multiple blocks and dragging behavior,
1365
    // so enabled only if the selection has been collapsed.
1366
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1367
        const leafEl = domRange.startContainer.parentElement!;
×
1368

1369
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1370
        // When this happens, do not scroll like most editors do.
NEW
1371
        const domRect = domRange.getBoundingClientRect();
×
NEW
1372
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1373

NEW
1374
        if (isZeroDimensionRect) {
×
NEW
1375
            const leafRect = leafEl.getBoundingClientRect();
×
NEW
1376
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1377

NEW
1378
            if (leafHasDimensions) {
×
NEW
1379
                return;
×
1380
            }
1381
        }
1382

1383
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1384
        scrollIntoView(leafEl, {
×
1385
            scrollMode: 'if-needed'
1386
        });
1387
        delete leafEl.getBoundingClientRect;
×
1388
    }
1389
};
1390

1391
/**
1392
 * Check if the target is inside void and in the editor.
1393
 */
1394

1395
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1396
    let slateNode: Node | null = null;
1✔
1397
    try {
1✔
1398
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1399
    } catch (error) {}
1400
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1401
};
1402

1403
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1404
    return (
2✔
1405
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1406
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1407
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1408
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1409
    );
1410
};
1411

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