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

worktile / slate-angular / c3b70b25-6ca6-4aa8-8c87-7d255610ab6b

03 Nov 2023 06:45AM UTC coverage: 44.222% (-1.9%) from 46.148%
c3b70b25-6ca6-4aa8-8c87-7d255610ab6b

Pull #241

circleci

pubuzhixing8
feat: xxx
Pull Request #241: View loop manager

380 of 1042 branches covered (0.0%)

Branch coverage included in aggregate %.

244 of 330 new or added lines in 7 files covered. (73.94%)

111 existing lines in 6 files now uncovered.

925 of 1909 relevant lines covered (48.45%)

38.02 hits per line

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

32.21
/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
    ViewContainerRef
21
} from '@angular/core';
22
import {
23
    NODE_TO_ELEMENT,
24
    IS_FOCUSED,
25
    EDITOR_TO_ELEMENT,
26
    ELEMENT_TO_NODE,
27
    IS_READONLY,
28
    EDITOR_TO_ON_CHANGE,
29
    EDITOR_TO_WINDOW
30
} from '../../utils/weak-maps';
31
import { Text as SlateText, Element, Transforms, Editor, Range, Path, NodeEntry, Node } from 'slate';
32
import { direction } from 'direction';
33
import scrollIntoView from 'scroll-into-view-if-needed';
34
import { AngularEditor } from '../../plugins/angular-editor';
35
import {
36
    DOMElement,
37
    DOMNode,
38
    isDOMNode,
39
    DOMStaticRange,
40
    DOMRange,
41
    isDOMElement,
42
    isPlainTextOnlyPaste,
43
    DOMSelection,
44
    getDefaultView
45
} from '../../utils/dom';
46
import { Subject } from 'rxjs';
47
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
48
import Hotkeys from '../../utils/hotkeys';
49
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
50
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
51
import { SlateErrorCode } from '../../types/error';
52
import { SlateStringTemplate } from '../string/template.component';
53
import { NG_VALUE_ACCESSOR } from '@angular/forms';
54
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
55
import { ComponentType, ViewType } from '../../types/view';
56
import { HistoryEditor } from 'slate-history';
57
import { isDecoratorRangeListEqual, check, normalize } from '../../utils';
58
import { SlatePlaceholder } from '../../types/feature';
59
import { restoreDom } from '../../utils/restore-dom';
60
import { SlateChildren } from '../children/children.component';
61
import { SLATE_DEFAULT_ELEMENT_COMPONENT_TOKEN } from '../element/default-element.component.token';
62
import { SLATE_DEFAULT_TEXT_COMPONENT_TOKEN, SLATE_DEFAULT_VOID_TEXT_COMPONENT_TOKEN } from '../text/token';
63
import { SlateVoidText } from '../text/void-text.component';
64
import { SlateDefaultText } from '../text/default-text.component';
65
import { SlateDefaultElement } from '../element/default-element.component';
66
import { ViewLevel, ViewLoopManager, createLoopManager } from '../../view/loop-manager';
67
import { BaseElementComponent, BaseLeafComponent, BaseTextComponent } from '../../view/base';
68
import { SlateDefaultLeaf } from '../leaf/default-leaf.component';
69
import { SLATE_DEFAULT_LEAF_COMPONENT_TOKEN } from '../leaf/token';
70

71
// not correctly clipboardData on beforeinput
72
const forceOnDOMPaste = IS_SAFARI;
1✔
73

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

121
    protected manualListeners: (() => void)[] = [];
20✔
122

123
    private initialized: boolean;
124

125
    private onTouchedCallback: () => void = () => {};
20✔
126

127
    private onChangeCallback: (_: any) => void = () => {};
20✔
128

129
    @Input() editor: AngularEditor;
130

131
    @Input() renderElement: (element: Element) => ViewType | null;
132

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

135
    @Input() renderText: (text: SlateText) => ViewType | null;
136

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

139
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
140

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

143
    @Input() isStrictDecorate: boolean = true;
20✔
144

145
    @Input() trackBy: (node: Element) => any = () => null;
196✔
146

147
    @Input() readonly = false;
20✔
148

149
    @Input() placeholder: string;
150

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

169
    //#region DOM attr
170
    @Input() spellCheck = false;
20✔
171
    @Input() autoCorrect = false;
20✔
172
    @Input() autoCapitalize = false;
20✔
173

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

178
    get hasBeforeInputSupport() {
179
        return HAS_BEFORE_INPUT_SUPPORT;
396✔
180
    }
181
    //#endregion
182

183
    @ViewChild('templateComponent', { static: true })
184
    templateComponent: SlateStringTemplate;
185

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

189
    viewLoopManager: ViewLoopManager;
190

191
    getHost = () => {
20✔
192
        return this.elementRef.nativeElement;
41✔
193
    }
194

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

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

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

237
        // add browser class
238
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
20!
239
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
20!
240
        this.viewLoopManager = createLoopManager(ViewLevel.node, this.viewContext, this.viewContainerRef, this.getHost);
20✔
241
    }
242

243
    ngOnChanges(simpleChanges: SimpleChanges) {
244
        if (!this.initialized) {
23✔
245
            return;
20✔
246
        }
247
        const decorateChange = simpleChanges['decorate'];
3✔
248
        if (decorateChange) {
3✔
249
            this.forceFlush();
2✔
250
            this.ngZone.run(() => {
2✔
251
                this.viewLoopManager.doCheck(this.editor.children, this.editor, [], this.context);
2✔
252
            });
253
        }
254
        const placeholderChange = simpleChanges['placeholder'];
3✔
255
        if (placeholderChange) {
3✔
256
            this.detectContext();
1✔
257
            this.ngZone.run(() => {
1✔
258
                this.viewLoopManager.doCheck(this.editor.children, this.editor, [], this.context);
1✔
259
            });
260
        }
261
        const readonlyChange = simpleChanges['readonly'];
3✔
262
        if (readonlyChange) {
3!
263
            IS_READONLY.set(this.editor, this.readonly);
×
264
            this.detectContext();
×
265
            this.toSlateSelection();
×
NEW
266
            this.ngZone.run(() => {
×
NEW
267
                this.viewLoopManager.doCheck(this.editor.children, this.editor, [], this.context);
×
268
            });
269
        }
270
    }
271

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

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

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

335
    toNativeSelection() {
336
        try {
14✔
337
            const { selection } = this.editor;
14✔
338
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
14✔
339
            const { activeElement } = root;
14✔
340
            const domSelection = (root as Document).getSelection();
14✔
341

342
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
14!
343
                return;
12✔
344
            }
345

346
            const hasDomSelection = domSelection.type !== 'None';
2✔
347

348
            // If the DOM selection is properly unset, we're done.
349
            if (!selection && !hasDomSelection) {
2!
350
                return;
×
351
            }
352

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

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

372
            // prevent updating native selection when active element is void element
373
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
374
                return;
×
375
            }
376

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

386
            // Otherwise the DOM selection is out of sync, so update it.
387
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
388
            this.isUpdatingSelection = true;
1✔
389

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

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

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

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

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

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

443
    ngAfterViewChecked() {
444
        if (this.viewLoopManager.initialized && !this.viewLoopManager.mounted) {
66!
NEW
445
            this.viewLoopManager.mount();
×
446
        }
447
    }
448

449
    ngDoCheck() {}
450

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

493
    initializeContext() {
494
        this.context = {
43✔
495
            parent: this.editor,
496
            selection: this.editor.selection,
497
            decorations: this.generateDecorations(),
498
            decorate: this.decorate,
499
            readonly: this.readonly
500
        };
501
    }
502

503
    initializeViewContext() {
504
        this.viewContext = {
20✔
505
            editor: this.editor,
506
            renderElement: this.renderElement,
507
            renderLeaf: this.renderLeaf,
508
            renderText: this.renderText,
509
            trackBy: this.trackBy,
510
            isStrictDecorate: this.isStrictDecorate,
511
            templateComponent: this.templateComponent,
512
            defaultElement: this.defaultElement,
513
            defaultText: this.defaultText,
514
            defaultVoidText: this.defaultVoidText,
515
            defaultLeaf: this.defaultLeaf
516
        };
517
    }
518

519
    detectContext() {
520
        const decorations = this.generateDecorations();
16✔
521
        if (
16✔
522
            this.context.selection !== this.editor.selection ||
39✔
523
            this.context.decorate !== this.decorate ||
524
            this.context.readonly !== this.readonly ||
525
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
526
        ) {
527
            this.context = {
11✔
528
                parent: this.editor,
529
                selection: this.editor.selection,
530
                decorations: decorations,
531
                decorate: this.decorate,
532
                readonly: this.readonly
533
            };
534
        }
535
    }
536

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

878
    private onDOMCompositionStart(event: CompositionEvent) {
879
        const { selection } = this.editor;
1✔
880

881
        if (selection) {
1!
882
            // solve the problem of cross node Chinese input
883
            if (Range.isExpanded(selection)) {
×
884
                Editor.deleteFragment(this.editor);
×
885
                this.forceFlush();
×
886
            }
887
        }
888
        if (hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
889
            this.isComposing = true;
1✔
890
        }
891
        this.detectContext();
1✔
892
        this.ngZone.run(() => {
1✔
893
            this.viewLoopManager.doCheck(this.editor.children, this.editor, [], this.context);
1✔
894
        });
895
        this.cdr.detectChanges();
1✔
896
    }
897

898
    private onDOMCompositionUpdate(event: CompositionEvent) {
899
        this.isDOMEventHandled(event, this.compositionUpdate);
×
900
    }
901

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

916
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
917
            // so we need avoid repeat isnertText by isComposing === true,
918
            this.isComposing = false;
×
919
        }
920
        this.detectContext();
×
921
        this.cdr.detectChanges();
×
922
    }
923

924
    private onDOMCopy(event: ClipboardEvent) {
925
        const window = AngularEditor.getWindow(this.editor);
×
926
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
927
        if (!isOutsideSlate && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
928
            event.preventDefault();
×
929
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
930
        }
931
    }
932

933
    private onDOMCut(event: ClipboardEvent) {
934
        if (!this.readonly && hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
935
            event.preventDefault();
×
936
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
937
            const { selection } = this.editor;
×
938

939
            if (selection) {
×
940
                AngularEditor.deleteCutData(this.editor);
×
941
            }
942
        }
943
    }
944

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

952
            if (Editor.isVoid(this.editor, node)) {
×
953
                event.preventDefault();
×
954
            }
955
        }
956
    }
957

958
    private onDOMDragStart(event: DragEvent) {
959
        if (!this.readonly && hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
960
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
961
            const path = AngularEditor.findPath(this.editor, node);
×
962
            const voidMatch = Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true });
×
963

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

971
            this.isDraggingInternally = true;
×
972

973
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
974
        }
975
    }
976

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

984
            // Find the range where the drop happened
985
            const range = AngularEditor.findEventRange(editor, event);
×
986
            const data = event.dataTransfer;
×
987

988
            Transforms.select(editor, range);
×
989

990
            if (this.isDraggingInternally) {
×
991
                if (draggedRange) {
×
992
                    Transforms.delete(editor, {
×
993
                        at: draggedRange
994
                    });
995
                }
996

997
                this.isDraggingInternally = false;
×
998
            }
999

1000
            AngularEditor.insertData(editor, data);
×
1001

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

1010
    private onDOMDragEnd(event: DragEvent) {
1011
        if (
×
1012
            !this.readonly &&
×
1013
            this.isDraggingInternally &&
1014
            hasTarget(this.editor, event.target) &&
1015
            !this.isDOMEventHandled(event, this.dragEnd)
1016
        ) {
1017
            this.isDraggingInternally = false;
×
1018
        }
1019
    }
1020

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

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

1040
            IS_FOCUSED.set(this.editor, true);
2✔
1041
        }
1042
    }
1043

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

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

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

1069
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1070
                        editor.redo();
×
1071
                    }
1072

1073
                    return;
×
1074
                }
1075

1076
                if (Hotkeys.isUndo(nativeEvent)) {
×
1077
                    event.preventDefault();
×
1078

1079
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1080
                        editor.undo();
×
1081
                    }
1082

1083
                    return;
×
1084
                }
1085

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

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

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

1112
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1113
                    event.preventDefault();
×
1114
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1115
                    return;
×
1116
                }
1117

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

1126
                    if (selection && Range.isCollapsed(selection)) {
×
1127
                        Transforms.move(editor, { reverse: !isRTL });
×
1128
                    } else {
1129
                        Transforms.collapse(editor, { edge: 'start' });
×
1130
                    }
1131

1132
                    return;
×
1133
                }
1134

1135
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1136
                    event.preventDefault();
×
1137

1138
                    if (selection && Range.isCollapsed(selection)) {
×
1139
                        Transforms.move(editor, { reverse: isRTL });
×
1140
                    } else {
1141
                        Transforms.collapse(editor, { edge: 'end' });
×
1142
                    }
1143

1144
                    return;
×
1145
                }
1146

1147
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1148
                    event.preventDefault();
×
1149

1150
                    if (selection && Range.isExpanded(selection)) {
×
1151
                        Transforms.collapse(editor, { edge: 'focus' });
×
1152
                    }
1153

1154
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1155
                    return;
×
1156
                }
1157

1158
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1159
                    event.preventDefault();
×
1160

1161
                    if (selection && Range.isExpanded(selection)) {
×
1162
                        Transforms.collapse(editor, { edge: 'focus' });
×
1163
                    }
1164

1165
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1166
                    return;
×
1167
                }
1168

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

1180
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1181
                        event.preventDefault();
×
1182
                        Editor.insertBreak(editor);
×
1183
                        return;
×
1184
                    }
1185

1186
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1187
                        event.preventDefault();
×
1188

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

1197
                        return;
×
1198
                    }
1199

1200
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1201
                        event.preventDefault();
×
1202

1203
                        if (selection && Range.isExpanded(selection)) {
×
1204
                            Editor.deleteFragment(editor, {
×
1205
                                direction: 'forward'
1206
                            });
1207
                        } else {
1208
                            Editor.deleteForward(editor);
×
1209
                        }
1210

1211
                        return;
×
1212
                    }
1213

1214
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1215
                        event.preventDefault();
×
1216

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

1225
                        return;
×
1226
                    }
1227

1228
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1229
                        event.preventDefault();
×
1230

1231
                        if (selection && Range.isExpanded(selection)) {
×
1232
                            Editor.deleteFragment(editor, {
×
1233
                                direction: 'forward'
1234
                            });
1235
                        } else {
1236
                            Editor.deleteForward(editor, { unit: 'line' });
×
1237
                        }
1238

1239
                        return;
×
1240
                    }
1241

1242
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1243
                        event.preventDefault();
×
1244

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

1253
                        return;
×
1254
                    }
1255

1256
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1257
                        event.preventDefault();
×
1258

1259
                        if (selection && Range.isExpanded(selection)) {
×
1260
                            Editor.deleteFragment(editor, {
×
1261
                                direction: 'forward'
1262
                            });
1263
                        } else {
1264
                            Editor.deleteForward(editor, { unit: 'word' });
×
1265
                        }
1266

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

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

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

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

1357
    ngOnDestroy() {
1358
        NODE_TO_ELEMENT.delete(this.editor);
20✔
1359
        this.manualListeners.forEach(manualListener => {
20✔
1360
            manualListener();
420✔
1361
        });
1362
        this.destroy$.complete();
20✔
1363
        EDITOR_TO_ON_CHANGE.delete(this.editor);
20✔
1364
    }
1365
}
1366

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

1380
/**
1381
 * Check if the target is editable and in the editor.
1382
 */
1383

1384
export const hasEditableTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1385
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target, { editable: true });
3✔
1386
};
1387

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

1404
/**
1405
 * Check if the target is in the editor.
1406
 */
1407

1408
const hasTarget = (editor: AngularEditor, target: EventTarget | null): target is DOMNode => {
1✔
1409
    return isDOMNode(target) && AngularEditor.hasDOMNode(editor, target);
1✔
1410
};
1411

1412
/**
1413
 * Check if the target is inside void and in the editor.
1414
 */
1415

1416
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1417
    const slateNode = hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1418
    return Editor.isVoid(editor, slateNode);
1✔
1419
};
1420

1421
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1422
    return (
2✔
1423
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1424
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1425
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1426
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1427
    );
1428
};
1429

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

1449
let timerId: number | null = null;
1✔
1450

1451
export const throttleRAF = (fn: () => void) => {
1✔
1452
    const scheduleFunc = () => {
1✔
1453
        timerId = requestAnimationFrame(() => {
1✔
NEW
1454
            timerId = null;
×
NEW
1455
            fn();
×
1456
        });
1457
    };
1458
    if (timerId !== null) {
1!
NEW
1459
        cancelAnimationFrame(timerId);
×
NEW
1460
        timerId = null;
×
1461
    }
1462
    scheduleFunc();
1✔
1463
};
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