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

worktile / slate-angular / f7c0666e-a081-4060-ae3d-d888bb5b7343

08 Dec 2025 02:17AM UTC coverage: 43.584% (-0.07%) from 43.653%
f7c0666e-a081-4060-ae3d-d888bb5b7343

Pull #312

circleci

Xwatson
fix: optimize
Pull Request #312: fix(virtual): fix scrolling lag

384 of 1117 branches covered (34.38%)

Branch coverage included in aggregate %.

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

166 existing lines in 1 file now uncovered.

1056 of 2187 relevant lines covered (48.29%)

29.74 hits per line

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

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

69
export const JUST_NOW_UPDATED_VIRTUAL_VIEW = new WeakMap<AngularEditor, boolean>();
1✔
70

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

74
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
75

76
@Component({
77
    selector: 'slate-editable',
78
    host: {
79
        class: 'slate-editable-container',
80
        '[attr.contenteditable]': 'readonly ? undefined : true',
81
        '[attr.role]': `readonly ? undefined : 'textbox'`,
82
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
83
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
84
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
85
    },
86
    template: '',
87
    changeDetection: ChangeDetectionStrategy.OnPush,
88
    providers: [
89
        {
90
            provide: NG_VALUE_ACCESSOR,
91
            useExisting: forwardRef(() => SlateEditable),
23✔
92
            multi: true
93
        }
94
    ],
95
    imports: []
96
})
97
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
98
    viewContext: SlateViewContext;
99
    context: SlateChildrenContext;
100

101
    private destroy$ = new Subject();
23✔
102

103
    isComposing = false;
23✔
104
    isDraggingInternally = false;
23✔
105
    isUpdatingSelection = false;
23✔
106
    latestElement = null as DOMElement | null;
23✔
107

108
    protected manualListeners: (() => void)[] = [];
23✔
109

110
    private initialized: boolean;
111

112
    private onTouchedCallback: () => void = () => {};
23✔
113

114
    private onChangeCallback: (_: any) => void = () => {};
23✔
115

116
    @Input() editor: AngularEditor;
117

118
    @Input() renderElement: (element: Element) => ViewType | null;
119

120
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
121

122
    @Input() renderText: (text: SlateText) => ViewType | null;
123

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

126
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
127

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

130
    @Input() isStrictDecorate: boolean = true;
23✔
131

132
    @Input() trackBy: (node: Element) => any = () => null;
206✔
133

134
    @Input() readonly = false;
23✔
135

136
    @Input() placeholder: string;
137

138
    @Input()
139
    set virtualScroll(config: SlateVirtualScrollConfig) {
140
        this.virtualConfig = config;
×
141
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
142
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
143
            let virtualView = this.refreshVirtualView();
×
144
            let diff = this.diffVirtualView(virtualView);
×
145
            if (!diff.isDiff) {
×
146
                return;
×
147
            }
148
            if (diff.isMissingTop) {
×
NEW
149
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
150
                if (result) {
×
151
                    virtualView = this.refreshVirtualView();
×
152
                    diff = this.diffVirtualView(virtualView, 'second');
×
153
                    if (!diff.isDiff) {
×
154
                        return;
×
155
                    }
156
                }
157
            }
158
            this.applyVirtualView(virtualView);
×
159
            if (this.listRender.initialized) {
×
160
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
161
            }
162
            this.scheduleMeasureVisibleHeights();
×
163
        });
164
    }
165

166
    //#region input event handler
167
    @Input() beforeInput: (event: Event) => void;
168
    @Input() blur: (event: Event) => void;
169
    @Input() click: (event: MouseEvent) => void;
170
    @Input() compositionEnd: (event: CompositionEvent) => void;
171
    @Input() compositionUpdate: (event: CompositionEvent) => void;
172
    @Input() compositionStart: (event: CompositionEvent) => void;
173
    @Input() copy: (event: ClipboardEvent) => void;
174
    @Input() cut: (event: ClipboardEvent) => void;
175
    @Input() dragOver: (event: DragEvent) => void;
176
    @Input() dragStart: (event: DragEvent) => void;
177
    @Input() dragEnd: (event: DragEvent) => void;
178
    @Input() drop: (event: DragEvent) => void;
179
    @Input() focus: (event: Event) => void;
180
    @Input() keydown: (event: KeyboardEvent) => void;
181
    @Input() paste: (event: ClipboardEvent) => void;
182
    //#endregion
183

184
    //#region DOM attr
185
    @Input() spellCheck = false;
23✔
186
    @Input() autoCorrect = false;
23✔
187
    @Input() autoCapitalize = false;
23✔
188

189
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
190
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
191
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
192

193
    get hasBeforeInputSupport() {
194
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
195
    }
196
    //#endregion
197

198
    viewContainerRef = inject(ViewContainerRef);
23✔
199

200
    getOutletParent = () => {
23✔
201
        return this.elementRef.nativeElement;
43✔
202
    };
203

204
    getOutletElement = () => {
23✔
205
        if (this.virtualScrollInitialized) {
23!
206
            return this.virtualCenterOutlet;
×
207
        } else {
208
            return null;
23✔
209
        }
210
    };
211

212
    listRender: ListRender;
213

214
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
215
        enabled: false,
216
        scrollTop: 0,
217
        viewportHeight: 0
218
    };
219
    private renderedChildren: Element[] = [];
23✔
220
    private virtualVisibleIndexes = new Set<number>();
23✔
221
    private measuredHeights = new Map<string, number>();
23✔
222
    private refreshVirtualViewAnimId: number;
223
    private measureVisibleHeightsAnimId: number;
224

225
    constructor(
226
        public elementRef: ElementRef,
23✔
227
        public renderer2: Renderer2,
23✔
228
        public cdr: ChangeDetectorRef,
23✔
229
        private ngZone: NgZone,
23✔
230
        private injector: Injector
23✔
231
    ) {}
232

233
    ngOnInit() {
234
        this.editor.injector = this.injector;
23✔
235
        this.editor.children = [];
23✔
236
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
237
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
238
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
239
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
240
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
241
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
242
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
243
            this.ngZone.run(() => {
13✔
244
                this.onChange();
13✔
245
            });
246
        });
247
        this.ngZone.runOutsideAngular(() => {
23✔
248
            this.initialize();
23✔
249
        });
250
        this.initializeViewContext();
23✔
251
        this.initializeContext();
23✔
252

253
        // add browser class
254
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
255
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
256
        this.initializeVirtualScrolling();
23✔
257
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
258
    }
259

260
    ngOnChanges(simpleChanges: SimpleChanges) {
261
        if (!this.initialized) {
30✔
262
            return;
23✔
263
        }
264
        const decorateChange = simpleChanges['decorate'];
7✔
265
        if (decorateChange) {
7✔
266
            this.forceRender();
2✔
267
        }
268
        const placeholderChange = simpleChanges['placeholder'];
7✔
269
        if (placeholderChange) {
7✔
270
            this.render();
1✔
271
        }
272
        const readonlyChange = simpleChanges['readonly'];
7✔
273
        if (readonlyChange) {
7!
274
            IS_READ_ONLY.set(this.editor, this.readonly);
×
275
            this.render();
×
276
            this.toSlateSelection();
×
277
        }
278
    }
279

280
    registerOnChange(fn: any) {
281
        this.onChangeCallback = fn;
23✔
282
    }
283
    registerOnTouched(fn: any) {
284
        this.onTouchedCallback = fn;
23✔
285
    }
286

287
    writeValue(value: Element[]) {
288
        if (value && value.length) {
49✔
289
            this.editor.children = value;
26✔
290
            this.initializeContext();
26✔
291
            const virtualView = this.refreshVirtualView();
26✔
292
            this.applyVirtualView(virtualView);
26✔
293
            const childrenForRender = virtualView.renderedChildren;
26✔
294
            if (!this.listRender.initialized) {
26✔
295
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
296
            } else {
297
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
298
            }
299
            this.scheduleMeasureVisibleHeights();
26✔
300
            this.cdr.markForCheck();
26✔
301
        }
302
    }
303

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

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

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

347
            const hasDomSelection = domSelection.type !== 'None';
1✔
348

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

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

362
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
363
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
364
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
365
                    exactMatch: false,
366
                    suppressThrow: true
367
                });
368
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
369
                    return;
×
370
                }
371
            }
372

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

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

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

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

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

417
            setTimeout(() => {
1✔
418
                // handle scrolling in setTimeout because of
419
                // dom should not have updated immediately after listRender's updating
420
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
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.forceRender();
13✔
440
        this.onChangeCallback(this.editor.children);
13✔
441
    }
442

443
    ngAfterViewChecked() {}
444

445
    ngDoCheck() {}
446

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

489
    render() {
490
        const changed = this.updateContext();
2✔
491
        if (changed) {
2✔
492
            const virtualView = this.refreshVirtualView();
2✔
493
            this.applyVirtualView(virtualView);
2✔
494
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
495
            this.scheduleMeasureVisibleHeights();
2✔
496
        }
497
    }
498

499
    updateContext() {
500
        const decorations = this.generateDecorations();
17✔
501
        if (
17✔
502
            this.context.selection !== this.editor.selection ||
46✔
503
            this.context.decorate !== this.decorate ||
504
            this.context.readonly !== this.readonly ||
505
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
506
        ) {
507
            this.context = {
10✔
508
                parent: this.editor,
509
                selection: this.editor.selection,
510
                decorations: decorations,
511
                decorate: this.decorate,
512
                readonly: this.readonly
513
            };
514
            return true;
10✔
515
        }
516
        return false;
7✔
517
    }
518

519
    initializeContext() {
520
        this.context = {
49✔
521
            parent: this.editor,
522
            selection: this.editor.selection,
523
            decorations: this.generateDecorations(),
524
            decorate: this.decorate,
525
            readonly: this.readonly
526
        };
527
    }
528

529
    initializeViewContext() {
530
        this.viewContext = {
23✔
531
            editor: this.editor,
532
            renderElement: this.renderElement,
533
            renderLeaf: this.renderLeaf,
534
            renderText: this.renderText,
535
            trackBy: this.trackBy,
536
            isStrictDecorate: this.isStrictDecorate
537
        };
538
    }
539

540
    composePlaceholderDecorate(editor: Editor) {
541
        if (this.placeholderDecorate) {
64!
542
            return this.placeholderDecorate(editor) || [];
×
543
        }
544

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

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

566
    private shouldUseVirtual() {
567
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
568
    }
569

570
    // the height from scroll container top to editor top height element
571
    private businessHeight: number = 0;
23✔
572

573
    virtualScrollInitialized = false;
23✔
574

575
    virtualTopHeightElement: HTMLElement;
576

577
    virtualBottomHeightElement: HTMLElement;
578

579
    virtualCenterOutlet: HTMLElement;
580

581
    initializeVirtualScrolling() {
582
        if (this.virtualScrollInitialized) {
23!
583
            return;
×
584
        }
585
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
586
            this.virtualScrollInitialized = true;
×
587
            this.virtualTopHeightElement = document.createElement('div');
×
588
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
589
            this.virtualBottomHeightElement = document.createElement('div');
×
590
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
591
            this.virtualCenterOutlet = document.createElement('div');
×
592
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
593
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
594
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
595
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
596
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
597
        }
598
    }
599

600
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
601
        if (!this.virtualScrollInitialized) {
43✔
602
            return;
43✔
603
        }
604
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
605
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
606
    }
607

608
    private refreshVirtualView() {
609
        const children = (this.editor.children || []) as Element[];
43!
610
        if (!children.length || !this.shouldUseVirtual()) {
43✔
611
            return {
43✔
612
                renderedChildren: children,
613
                visibleIndexes: new Set<number>(),
614
                top: 0,
615
                bottom: 0,
616
                heights: []
617
            };
618
        }
619
        const scrollTop = this.virtualConfig.scrollTop;
×
620
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
621
        if (!viewportHeight) {
×
622
            return {
×
623
                renderedChildren: [],
624
                visibleIndexes: new Set<number>(),
625
                top: 0,
626
                bottom: 0,
627
                heights: []
628
            };
629
        }
630
        const elementLength = children.length;
×
631
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
NEW
632
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
NEW
633
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
NEW
634
        const totalHeight = accumulatedHeights[elementLength];
×
NEW
635
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
NEW
636
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
NEW
637
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
638
        let accumulatedOffset = 0;
×
639
        let visibleStartIndex = -1;
×
640
        const visible: Element[] = [];
×
641
        const visibleIndexes: number[] = [];
×
642

643
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
NEW
644
            const currentHeight = heights[i];
×
645
            const nextOffset = accumulatedOffset + currentHeight;
×
646
            // 可视区域有交集,加入渲染
NEW
647
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
648
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
649
                visible.push(children[i]);
×
650
                visibleIndexes.push(i);
×
651
            }
652
            accumulatedOffset = nextOffset;
×
653
        }
654

NEW
655
        if (visibleStartIndex === -1 && elementLength) {
×
NEW
656
            visibleStartIndex = elementLength - 1;
×
NEW
657
            visible.push(children[visibleStartIndex]);
×
NEW
658
            visibleIndexes.push(visibleStartIndex);
×
659
        }
660

661
        const visibleEndIndex =
NEW
662
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
663
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
NEW
664
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
665

666
        return {
×
667
            renderedChildren: visible.length ? visible : children,
×
668
            visibleIndexes: new Set(visibleIndexes),
669
            top,
670
            bottom,
671
            heights
672
        };
673
    }
674

675
    private applyVirtualView(virtualView: VirtualViewResult) {
676
        this.renderedChildren = virtualView.renderedChildren;
43✔
677
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
678
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
679
    }
680

681
    private diffVirtualView(virtualView: VirtualViewResult, stage: 'first' | 'second' = 'first') {
×
682
        if (!this.renderedChildren.length) {
×
683
            return {
×
684
                isDiff: true,
685
                diffTopRenderedIndexes: [],
686
                diffBottomRenderedIndexes: []
687
            };
688
        }
689
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
690
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
691
        const firstNewIndex = newVisibleIndexes[0];
×
692
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
693
        const firstOldIndex = oldVisibleIndexes[0];
×
694
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
695
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
696
            const diffTopRenderedIndexes = [];
×
697
            const diffBottomRenderedIndexes = [];
×
698
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
699
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
700
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
701
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
702
            if (isMissingTop || isAddedBottom) {
×
703
                // 向下
704
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
705
                    const element = oldVisibleIndexes[index];
×
706
                    if (!newVisibleIndexes.includes(element)) {
×
707
                        diffTopRenderedIndexes.push(element);
×
708
                    } else {
709
                        break;
×
710
                    }
711
                }
712
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
713
                    const element = newVisibleIndexes[index];
×
714
                    if (!oldVisibleIndexes.includes(element)) {
×
715
                        diffBottomRenderedIndexes.push(element);
×
716
                    } else {
717
                        break;
×
718
                    }
719
                }
720
            } else if (isAddedTop || isMissingBottom) {
×
721
                // 向上
722
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
723
                    const element = newVisibleIndexes[index];
×
724
                    if (!oldVisibleIndexes.includes(element)) {
×
725
                        diffTopRenderedIndexes.push(element);
×
726
                    } else {
727
                        break;
×
728
                    }
729
                }
730
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
731
                    const element = oldVisibleIndexes[index];
×
732
                    if (!newVisibleIndexes.includes(element)) {
×
733
                        diffBottomRenderedIndexes.push(element);
×
734
                    } else {
735
                        break;
×
736
                    }
737
                }
738
            }
739
            if (isDebug) {
×
740
                console.log(`====== diffVirtualView stage: ${stage} ======`);
×
741
                console.log('oldVisibleIndexes:', oldVisibleIndexes);
×
742
                console.log('newVisibleIndexes:', newVisibleIndexes);
×
743
                console.log(
×
744
                    'diffTopRenderedIndexes:',
745
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
746
                    diffTopRenderedIndexes,
747
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
748
                );
749
                console.log(
×
750
                    'diffBottomRenderedIndexes:',
751
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
752
                    diffBottomRenderedIndexes,
753
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
754
                );
755
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
756
                const needBottom = virtualView.heights
×
757
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
758
                    .reduce((acc, height) => acc + height, 0);
×
759
                console.log('newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
760
                console.log('newBottomHeight:', needBottom, 'prevBottomHeight:', parseFloat(this.virtualBottomHeightElement.style.height));
×
761
                console.warn('=========== Dividing line ===========');
×
762
            }
763
            return {
×
764
                isDiff: true,
765
                isMissingTop,
766
                isAddedTop,
767
                isMissingBottom,
768
                isAddedBottom,
769
                diffTopRenderedIndexes,
770
                diffBottomRenderedIndexes
771
            };
772
        }
773
        return {
×
774
            isDiff: false,
775
            diffTopRenderedIndexes: [],
776
            diffBottomRenderedIndexes: []
777
        };
778
    }
779

780
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
781
        const node = this.editor.children[index];
×
782
        if (!node) {
×
783
            return defaultHeight;
×
784
        }
785
        const key = AngularEditor.findKey(this.editor, node);
×
786
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
787
    }
788

789
    private buildAccumulatedHeight(heights: number[]) {
790
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
791
        for (let i = 0; i < heights.length; i++) {
×
792
            // 存储前 i 个的累计高度
793
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
794
        }
795
        return accumulatedHeights;
×
796
    }
797

798
    private scheduleMeasureVisibleHeights() {
799
        if (!this.shouldUseVirtual()) {
43✔
800
            return;
43✔
801
        }
802
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
803
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
804
            this.measureVisibleHeights();
×
805
        });
806
    }
807

808
    private measureVisibleHeights() {
809
        const children = (this.editor.children || []) as Element[];
×
810
        this.virtualVisibleIndexes.forEach(index => {
×
811
            const node = children[index];
×
812
            if (!node) {
×
813
                return;
×
814
            }
815
            const key = AngularEditor.findKey(this.editor, node);
×
816
            // 跳过已测过的块
817
            if (this.measuredHeights.has(key.id)) {
×
818
                return;
×
819
            }
820
            const view = ELEMENT_TO_COMPONENT.get(node);
×
821
            if (!view) {
×
822
                return;
×
823
            }
824
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
825
            if (ret instanceof Promise) {
×
826
                ret.then(height => {
×
827
                    this.measuredHeights.set(key.id, height);
×
828
                });
829
            } else {
830
                this.measuredHeights.set(key.id, ret);
×
831
            }
832
        });
833
    }
834

835
    private remeasureHeightByIndics(indics: number[]): boolean {
836
        const children = (this.editor.children || []) as Element[];
×
837
        let isHeightChanged = false;
×
838
        indics.forEach(index => {
×
839
            const node = children[index];
×
840
            if (!node) {
×
841
                return;
×
842
            }
843
            const key = AngularEditor.findKey(this.editor, node);
×
844
            const view = ELEMENT_TO_COMPONENT.get(node);
×
845
            if (!view) {
×
846
                return;
×
847
            }
NEW
848
            const slateView = view as BaseElementComponent | BaseElementFlavour;
×
849
            const prevHeight = this.measuredHeights.get(key.id);
×
NEW
850
            const ret = slateView.getRealHeight();
×
851
            if (ret instanceof Promise) {
×
852
                ret.then(height => {
×
853
                    if (height !== prevHeight) {
×
854
                        isHeightChanged = true;
×
855
                    }
NEW
856
                    this.measuredHeights.set(key.id, height);
×
NEW
UNCOV
857
                    if (isDebug) {
×
NEW
UNCOV
858
                        console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
859
                    }
860
                });
861
            } else {
862
                if (ret !== prevHeight) {
×
863
                    isHeightChanged = true;
×
864
                }
NEW
865
                this.measuredHeights.set(key.id, ret);
×
NEW
UNCOV
866
                if (isDebug) {
×
NEW
UNCOV
867
                    console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
868
                }
869
            }
870
        });
UNCOV
871
        return isHeightChanged;
×
872
    }
873

874
    //#region event proxy
875
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
876
        this.manualListeners.push(
483✔
877
            this.renderer2.listen(target, eventName, (event: Event) => {
878
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
879
                if (beforeInputEvent) {
5!
UNCOV
880
                    this.onFallbackBeforeInput(beforeInputEvent);
×
881
                }
882
                listener(event);
5✔
883
            })
884
        );
885
    }
886

887
    private toSlateSelection() {
888
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
889
            try {
1✔
890
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
891
                const { activeElement } = root;
1✔
892
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
893
                const domSelection = (root as Document).getSelection();
1✔
894

895
                if (activeElement === el) {
1!
896
                    this.latestElement = activeElement;
1✔
897
                    IS_FOCUSED.set(this.editor, true);
1✔
898
                } else {
UNCOV
899
                    IS_FOCUSED.delete(this.editor);
×
900
                }
901

902
                if (!domSelection) {
1!
UNCOV
903
                    return Transforms.deselect(this.editor);
×
904
                }
905

906
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
907
                const hasDomSelectionInEditor =
908
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
909
                if (!hasDomSelectionInEditor) {
1!
910
                    Transforms.deselect(this.editor);
×
UNCOV
911
                    return;
×
912
                }
913

914
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
915
                // for example, double-click the last cell of the table to select a non-editable DOM
916
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
917
                if (range) {
1✔
918
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
UNCOV
919
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
920
                            // force adjust DOMSelection
UNCOV
921
                            this.toNativeSelection();
×
922
                        }
923
                    } else {
924
                        Transforms.select(this.editor, range);
1✔
925
                    }
926
                }
927
            } catch (error) {
UNCOV
928
                this.editor.onError({
×
929
                    code: SlateErrorCode.ToSlateSelectionError,
930
                    nativeError: error
931
                });
932
            }
933
        }
934
    }
935

936
    private onDOMBeforeInput(
937
        event: Event & {
938
            inputType: string;
939
            isComposing: boolean;
940
            data: string | null;
941
            dataTransfer: DataTransfer | null;
942
            getTargetRanges(): DOMStaticRange[];
943
        }
944
    ) {
945
        const editor = this.editor;
×
946
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
947
        const { activeElement } = root;
×
948
        const { selection } = editor;
×
949
        const { inputType: type } = event;
×
950
        const data = event.dataTransfer || event.data || undefined;
×
951
        if (IS_ANDROID) {
×
952
            let targetRange: Range | null = null;
×
953
            let [nativeTargetRange] = event.getTargetRanges();
×
954
            if (nativeTargetRange) {
×
UNCOV
955
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
956
            }
957
            // COMPAT: SelectionChange event is fired after the action is performed, so we
958
            // have to manually get the selection here to ensure it's up-to-date.
959
            const window = AngularEditor.getWindow(editor);
×
960
            const domSelection = window.getSelection();
×
961
            if (!targetRange && domSelection) {
×
UNCOV
962
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
963
            }
964
            targetRange = targetRange ?? editor.selection;
×
965
            if (type === 'insertCompositionText') {
×
966
                if (data && data.toString().includes('\n')) {
×
967
                    restoreDom(editor, () => {
×
UNCOV
968
                        Editor.insertBreak(editor);
×
969
                    });
970
                } else {
971
                    if (targetRange) {
×
972
                        if (data) {
×
973
                            restoreDom(editor, () => {
×
UNCOV
974
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
975
                            });
976
                        } else {
977
                            restoreDom(editor, () => {
×
UNCOV
978
                                Transforms.delete(editor, { at: targetRange });
×
979
                            });
980
                        }
981
                    }
982
                }
UNCOV
983
                return;
×
984
            }
UNCOV
985
            if (type === 'deleteContentBackward') {
×
986
                // gboard can not prevent default action, so must use restoreDom,
987
                // sougou Keyboard can prevent default action(only in Chinese input mode).
988
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
989
                if (!Range.isCollapsed(targetRange)) {
×
990
                    restoreDom(editor, () => {
×
UNCOV
991
                        Transforms.delete(editor, { at: targetRange });
×
992
                    });
UNCOV
993
                    return;
×
994
                }
995
            }
996
            if (type === 'insertText') {
×
997
                restoreDom(editor, () => {
×
998
                    if (typeof data === 'string') {
×
UNCOV
999
                        Editor.insertText(editor, data);
×
1000
                    }
1001
                });
UNCOV
1002
                return;
×
1003
            }
1004
        }
UNCOV
1005
        if (
×
1006
            !this.readonly &&
×
1007
            AngularEditor.hasEditableTarget(editor, event.target) &&
1008
            !isTargetInsideVoid(editor, activeElement) &&
1009
            !this.isDOMEventHandled(event, this.beforeInput)
1010
        ) {
1011
            try {
×
UNCOV
1012
                event.preventDefault();
×
1013

1014
                // COMPAT: If the selection is expanded, even if the command seems like
1015
                // a delete forward/backward command it should delete the selection.
1016
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1017
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1018
                    Editor.deleteFragment(editor, { direction });
×
UNCOV
1019
                    return;
×
1020
                }
1021

UNCOV
1022
                switch (type) {
×
1023
                    case 'deleteByComposition':
1024
                    case 'deleteByCut':
1025
                    case 'deleteByDrag': {
1026
                        Editor.deleteFragment(editor);
×
UNCOV
1027
                        break;
×
1028
                    }
1029

1030
                    case 'deleteContent':
1031
                    case 'deleteContentForward': {
1032
                        Editor.deleteForward(editor);
×
UNCOV
1033
                        break;
×
1034
                    }
1035

1036
                    case 'deleteContentBackward': {
1037
                        Editor.deleteBackward(editor);
×
UNCOV
1038
                        break;
×
1039
                    }
1040

1041
                    case 'deleteEntireSoftLine': {
1042
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1043
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1044
                        break;
×
1045
                    }
1046

1047
                    case 'deleteHardLineBackward': {
1048
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
1049
                        break;
×
1050
                    }
1051

1052
                    case 'deleteSoftLineBackward': {
1053
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
1054
                        break;
×
1055
                    }
1056

1057
                    case 'deleteHardLineForward': {
1058
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
1059
                        break;
×
1060
                    }
1061

1062
                    case 'deleteSoftLineForward': {
1063
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
1064
                        break;
×
1065
                    }
1066

1067
                    case 'deleteWordBackward': {
1068
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
1069
                        break;
×
1070
                    }
1071

1072
                    case 'deleteWordForward': {
1073
                        Editor.deleteForward(editor, { unit: 'word' });
×
UNCOV
1074
                        break;
×
1075
                    }
1076

1077
                    case 'insertLineBreak':
1078
                    case 'insertParagraph': {
1079
                        Editor.insertBreak(editor);
×
UNCOV
1080
                        break;
×
1081
                    }
1082

1083
                    case 'insertFromComposition': {
1084
                        // COMPAT: in safari, `compositionend` event is dispatched after
1085
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1086
                        // https://www.w3.org/TR/input-events-2/
1087
                        // so the following code is the right logic
1088
                        // because DOM selection in sync will be exec before `compositionend` event
1089
                        // isComposing is true will prevent DOM selection being update correctly.
1090
                        this.isComposing = false;
×
UNCOV
1091
                        preventInsertFromComposition(event, this.editor);
×
1092
                    }
1093
                    case 'insertFromDrop':
1094
                    case 'insertFromPaste':
1095
                    case 'insertFromYank':
1096
                    case 'insertReplacementText':
1097
                    case 'insertText': {
1098
                        // use a weak comparison instead of 'instanceof' to allow
1099
                        // programmatic access of paste events coming from external windows
1100
                        // like cypress where cy.window does not work realibly
1101
                        if (data?.constructor.name === 'DataTransfer') {
×
1102
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1103
                        } else if (typeof data === 'string') {
×
UNCOV
1104
                            Editor.insertText(editor, data);
×
1105
                        }
UNCOV
1106
                        break;
×
1107
                    }
1108
                }
1109
            } catch (error) {
UNCOV
1110
                this.editor.onError({
×
1111
                    code: SlateErrorCode.OnDOMBeforeInputError,
1112
                    nativeError: error
1113
                });
1114
            }
1115
        }
1116
    }
1117

1118
    private onDOMBlur(event: FocusEvent) {
UNCOV
1119
        if (
×
1120
            this.readonly ||
×
1121
            this.isUpdatingSelection ||
1122
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1123
            this.isDOMEventHandled(event, this.blur)
1124
        ) {
UNCOV
1125
            return;
×
1126
        }
1127

UNCOV
1128
        const window = AngularEditor.getWindow(this.editor);
×
1129

1130
        // COMPAT: If the current `activeElement` is still the previous
1131
        // one, this is due to the window being blurred when the tab
1132
        // itself becomes unfocused, so we want to abort early to allow to
1133
        // editor to stay focused when the tab becomes focused again.
1134
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1135
        if (this.latestElement === root.activeElement) {
×
UNCOV
1136
            return;
×
1137
        }
1138

1139
        const { relatedTarget } = event;
×
UNCOV
1140
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1141

1142
        // COMPAT: The event should be ignored if the focus is returning
1143
        // to the editor from an embedded editable element (eg. an <input>
1144
        // element inside a void node).
1145
        if (relatedTarget === el) {
×
UNCOV
1146
            return;
×
1147
        }
1148

1149
        // COMPAT: The event should be ignored if the focus is moving from
1150
        // the editor to inside a void node's spacer element.
1151
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
UNCOV
1152
            return;
×
1153
        }
1154

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

1161
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
UNCOV
1162
                return;
×
1163
            }
1164
        }
1165

UNCOV
1166
        IS_FOCUSED.delete(this.editor);
×
1167
    }
1168

1169
    private onDOMClick(event: MouseEvent) {
UNCOV
1170
        if (
×
1171
            !this.readonly &&
×
1172
            AngularEditor.hasTarget(this.editor, event.target) &&
1173
            !this.isDOMEventHandled(event, this.click) &&
1174
            isDOMNode(event.target)
1175
        ) {
1176
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1177
            const path = AngularEditor.findPath(this.editor, node);
×
1178
            const start = Editor.start(this.editor, path);
×
UNCOV
1179
            const end = Editor.end(this.editor, path);
×
1180

1181
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
1182
            const endVoid = Editor.void(this.editor, { at: end });
×
1183

1184
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1185
                let blockPath = path;
×
1186
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1187
                    const block = Editor.above(this.editor, {
×
UNCOV
1188
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1189
                        at: path
1190
                    });
1191

UNCOV
1192
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1193
                }
1194

1195
                const range = Editor.range(this.editor, blockPath);
×
1196
                Transforms.select(this.editor, range);
×
UNCOV
1197
                return;
×
1198
            }
1199

UNCOV
1200
            if (
×
1201
                startVoid &&
×
1202
                endVoid &&
1203
                Path.equals(startVoid[1], endVoid[1]) &&
1204
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1205
            ) {
1206
                const range = Editor.range(this.editor, start);
×
UNCOV
1207
                Transforms.select(this.editor, range);
×
1208
            }
1209
        }
1210
    }
1211

1212
    private onDOMCompositionStart(event: CompositionEvent) {
1213
        const { selection } = this.editor;
1✔
1214
        if (selection) {
1!
1215
            // solve the problem of cross node Chinese input
1216
            if (Range.isExpanded(selection)) {
×
1217
                Editor.deleteFragment(this.editor);
×
UNCOV
1218
                this.forceRender();
×
1219
            }
1220
        }
1221
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1222
            this.isComposing = true;
1✔
1223
        }
1224
        this.render();
1✔
1225
    }
1226

1227
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1228
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1229
    }
1230

1231
    private onDOMCompositionEnd(event: CompositionEvent) {
1232
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1233
            Transforms.delete(this.editor);
×
1234
        }
UNCOV
1235
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1236
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1237
            // aren't correct and never fire the "insertFromComposition"
1238
            // type that we need. So instead, insert whenever a composition
1239
            // ends since it will already have been committed to the DOM.
1240
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1241
                preventInsertFromComposition(event, this.editor);
×
UNCOV
1242
                Editor.insertText(this.editor, event.data);
×
1243
            }
1244

1245
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1246
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1247
            this.isComposing = false;
×
1248
        }
UNCOV
1249
        this.render();
×
1250
    }
1251

1252
    private onDOMCopy(event: ClipboardEvent) {
1253
        const window = AngularEditor.getWindow(this.editor);
×
1254
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1255
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1256
            event.preventDefault();
×
UNCOV
1257
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1258
        }
1259
    }
1260

1261
    private onDOMCut(event: ClipboardEvent) {
1262
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1263
            event.preventDefault();
×
1264
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
UNCOV
1265
            const { selection } = this.editor;
×
1266

1267
            if (selection) {
×
UNCOV
1268
                AngularEditor.deleteCutData(this.editor);
×
1269
            }
1270
        }
1271
    }
1272

1273
    private onDOMDragOver(event: DragEvent) {
UNCOV
1274
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1275
            // Only when the target is void, call `preventDefault` to signal
1276
            // that drops are allowed. Editable content is droppable by
1277
            // default, and calling `preventDefault` hides the cursor.
UNCOV
1278
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1279

1280
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1281
                event.preventDefault();
×
1282
            }
1283
        }
1284
    }
1285

1286
    private onDOMDragStart(event: DragEvent) {
1287
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1288
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1289
            const path = AngularEditor.findPath(this.editor, node);
×
1290
            const voidMatch =
UNCOV
1291
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1292

1293
            // If starting a drag on a void node, make sure it is selected
1294
            // so that it shows up in the selection's fragment.
1295
            if (voidMatch) {
×
1296
                const range = Editor.range(this.editor, path);
×
UNCOV
1297
                Transforms.select(this.editor, range);
×
1298
            }
1299

UNCOV
1300
            this.isDraggingInternally = true;
×
1301

UNCOV
1302
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1303
        }
1304
    }
1305

1306
    private onDOMDrop(event: DragEvent) {
1307
        const editor = this.editor;
×
1308
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
UNCOV
1309
            event.preventDefault();
×
1310
            // Keep a reference to the dragged range before updating selection
UNCOV
1311
            const draggedRange = editor.selection;
×
1312

1313
            // Find the range where the drop happened
1314
            const range = AngularEditor.findEventRange(editor, event);
×
UNCOV
1315
            const data = event.dataTransfer;
×
1316

UNCOV
1317
            Transforms.select(editor, range);
×
1318

1319
            if (this.isDraggingInternally) {
×
1320
                if (draggedRange) {
×
UNCOV
1321
                    Transforms.delete(editor, {
×
1322
                        at: draggedRange
1323
                    });
1324
                }
1325

UNCOV
1326
                this.isDraggingInternally = false;
×
1327
            }
1328

UNCOV
1329
            AngularEditor.insertData(editor, data);
×
1330

1331
            // When dragging from another source into the editor, it's possible
1332
            // that the current editor does not have focus.
1333
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1334
                AngularEditor.focus(editor);
×
1335
            }
1336
        }
1337
    }
1338

1339
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1340
        if (
×
1341
            !this.readonly &&
×
1342
            this.isDraggingInternally &&
1343
            AngularEditor.hasTarget(this.editor, event.target) &&
1344
            !this.isDOMEventHandled(event, this.dragEnd)
1345
        ) {
UNCOV
1346
            this.isDraggingInternally = false;
×
1347
        }
1348
    }
1349

1350
    private onDOMFocus(event: Event) {
1351
        if (
2✔
1352
            !this.readonly &&
8✔
1353
            !this.isUpdatingSelection &&
1354
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1355
            !this.isDOMEventHandled(event, this.focus)
1356
        ) {
1357
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1358
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1359
            this.latestElement = root.activeElement;
2✔
1360

1361
            // COMPAT: If the editor has nested editable elements, the focus
1362
            // can go to them. In Firefox, this must be prevented because it
1363
            // results in issues with keyboard navigation. (2017/03/30)
1364
            if (IS_FIREFOX && event.target !== el) {
2!
1365
                el.focus();
×
UNCOV
1366
                return;
×
1367
            }
1368

1369
            IS_FOCUSED.set(this.editor, true);
2✔
1370
        }
1371
    }
1372

1373
    private onDOMKeydown(event: KeyboardEvent) {
1374
        const editor = this.editor;
×
1375
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1376
        const { activeElement } = root;
×
UNCOV
1377
        if (
×
1378
            !this.readonly &&
×
1379
            AngularEditor.hasEditableTarget(editor, event.target) &&
1380
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1381
            !this.isComposing &&
1382
            !this.isDOMEventHandled(event, this.keydown)
1383
        ) {
1384
            const nativeEvent = event;
×
UNCOV
1385
            const { selection } = editor;
×
1386

1387
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
UNCOV
1388
            const isRTL = direction(Node.string(element)) === 'rtl';
×
1389

UNCOV
1390
            try {
×
1391
                // COMPAT: Since we prevent the default behavior on
1392
                // `beforeinput` events, the browser doesn't think there's ever
1393
                // any history stack to undo or redo, so we have to manage these
1394
                // hotkeys ourselves. (2019/11/06)
1395
                if (Hotkeys.isRedo(nativeEvent)) {
×
UNCOV
1396
                    event.preventDefault();
×
1397

1398
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1399
                        editor.redo();
×
1400
                    }
1401

UNCOV
1402
                    return;
×
1403
                }
1404

1405
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1406
                    event.preventDefault();
×
1407

1408
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1409
                        editor.undo();
×
1410
                    }
1411

UNCOV
1412
                    return;
×
1413
                }
1414

1415
                // COMPAT: Certain browsers don't handle the selection updates
1416
                // properly. In Chrome, the selection isn't properly extended.
1417
                // And in Firefox, the selection isn't properly collapsed.
1418
                // (2017/10/17)
1419
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1420
                    event.preventDefault();
×
1421
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
UNCOV
1422
                    return;
×
1423
                }
1424

1425
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1426
                    event.preventDefault();
×
1427
                    Transforms.move(editor, { unit: 'line' });
×
UNCOV
1428
                    return;
×
1429
                }
1430

1431
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1432
                    event.preventDefault();
×
UNCOV
1433
                    Transforms.move(editor, {
×
1434
                        unit: 'line',
1435
                        edge: 'focus',
1436
                        reverse: true
1437
                    });
UNCOV
1438
                    return;
×
1439
                }
1440

1441
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1442
                    event.preventDefault();
×
1443
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
UNCOV
1444
                    return;
×
1445
                }
1446

1447
                // COMPAT: If a void node is selected, or a zero-width text node
1448
                // adjacent to an inline is selected, we need to handle these
1449
                // hotkeys manually because browsers won't be able to skip over
1450
                // the void node with the zero-width space not being an empty
1451
                // string.
1452
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
UNCOV
1453
                    event.preventDefault();
×
1454

1455
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1456
                        Transforms.move(editor, { reverse: !isRTL });
×
1457
                    } else {
UNCOV
1458
                        Transforms.collapse(editor, { edge: 'start' });
×
1459
                    }
1460

UNCOV
1461
                    return;
×
1462
                }
1463

1464
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1465
                    event.preventDefault();
×
1466
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1467
                        Transforms.move(editor, { reverse: isRTL });
×
1468
                    } else {
UNCOV
1469
                        Transforms.collapse(editor, { edge: 'end' });
×
1470
                    }
1471

UNCOV
1472
                    return;
×
1473
                }
1474

1475
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1476
                    event.preventDefault();
×
1477

1478
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1479
                        Transforms.collapse(editor, { edge: 'focus' });
×
1480
                    }
1481

1482
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1483
                    return;
×
1484
                }
1485

1486
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1487
                    event.preventDefault();
×
1488

1489
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1490
                        Transforms.collapse(editor, { edge: 'focus' });
×
1491
                    }
1492

1493
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
UNCOV
1494
                    return;
×
1495
                }
1496

1497
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1498
                // fall back to guessing at the input intention for hotkeys.
1499
                // COMPAT: In iOS, some of these hotkeys are handled in the
UNCOV
1500
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1501
                    // We don't have a core behavior for these, but they change the
1502
                    // DOM if we don't prevent them, so we have to.
1503
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1504
                        event.preventDefault();
×
UNCOV
1505
                        return;
×
1506
                    }
1507

1508
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1509
                        event.preventDefault();
×
1510
                        Editor.insertBreak(editor);
×
UNCOV
1511
                        return;
×
1512
                    }
1513

1514
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1515
                        event.preventDefault();
×
1516

1517
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1518
                            Editor.deleteFragment(editor, {
×
1519
                                direction: 'backward'
1520
                            });
1521
                        } else {
UNCOV
1522
                            Editor.deleteBackward(editor);
×
1523
                        }
1524

UNCOV
1525
                        return;
×
1526
                    }
1527

1528
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1529
                        event.preventDefault();
×
1530

1531
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1532
                            Editor.deleteFragment(editor, {
×
1533
                                direction: 'forward'
1534
                            });
1535
                        } else {
UNCOV
1536
                            Editor.deleteForward(editor);
×
1537
                        }
1538

UNCOV
1539
                        return;
×
1540
                    }
1541

1542
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1543
                        event.preventDefault();
×
1544

1545
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1546
                            Editor.deleteFragment(editor, {
×
1547
                                direction: 'backward'
1548
                            });
1549
                        } else {
UNCOV
1550
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1551
                        }
1552

UNCOV
1553
                        return;
×
1554
                    }
1555

1556
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1557
                        event.preventDefault();
×
1558

1559
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1560
                            Editor.deleteFragment(editor, {
×
1561
                                direction: 'forward'
1562
                            });
1563
                        } else {
UNCOV
1564
                            Editor.deleteForward(editor, { unit: 'line' });
×
1565
                        }
1566

UNCOV
1567
                        return;
×
1568
                    }
1569

1570
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1571
                        event.preventDefault();
×
1572

1573
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1574
                            Editor.deleteFragment(editor, {
×
1575
                                direction: 'backward'
1576
                            });
1577
                        } else {
UNCOV
1578
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1579
                        }
1580

UNCOV
1581
                        return;
×
1582
                    }
1583

1584
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1585
                        event.preventDefault();
×
1586

1587
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1588
                            Editor.deleteFragment(editor, {
×
1589
                                direction: 'forward'
1590
                            });
1591
                        } else {
UNCOV
1592
                            Editor.deleteForward(editor, { unit: 'word' });
×
1593
                        }
1594

UNCOV
1595
                        return;
×
1596
                    }
1597
                } else {
UNCOV
1598
                    if (IS_CHROME || IS_SAFARI) {
×
1599
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1600
                        // an event when deleting backwards in a selected void inline node
UNCOV
1601
                        if (
×
1602
                            selection &&
×
1603
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1604
                            Range.isCollapsed(selection)
1605
                        ) {
1606
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
UNCOV
1607
                            if (
×
1608
                                Element.isElement(currentNode) &&
×
1609
                                Editor.isVoid(editor, currentNode) &&
1610
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1611
                            ) {
1612
                                event.preventDefault();
×
UNCOV
1613
                                Editor.deleteBackward(editor, {
×
1614
                                    unit: 'block'
1615
                                });
UNCOV
1616
                                return;
×
1617
                            }
1618
                        }
1619
                    }
1620
                }
1621
            } catch (error) {
UNCOV
1622
                this.editor.onError({
×
1623
                    code: SlateErrorCode.OnDOMKeydownError,
1624
                    nativeError: error
1625
                });
1626
            }
1627
        }
1628
    }
1629

1630
    private onDOMPaste(event: ClipboardEvent) {
1631
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1632
        // fall back to React's `onPaste` here instead.
1633
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1634
        // when "paste without formatting" option is used.
1635
        // This unfortunately needs to be handled with paste events instead.
UNCOV
1636
        if (
×
1637
            !this.isDOMEventHandled(event, this.paste) &&
×
1638
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1639
            !this.readonly &&
1640
            AngularEditor.hasEditableTarget(this.editor, event.target)
1641
        ) {
1642
            event.preventDefault();
×
UNCOV
1643
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1644
        }
1645
    }
1646

1647
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1648
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1649
        // fall back to React's leaky polyfill instead just for it. It
1650
        // only works for the `insertText` input type.
UNCOV
1651
        if (
×
1652
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1653
            !this.readonly &&
1654
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1655
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1656
        ) {
1657
            event.nativeEvent.preventDefault();
×
1658
            try {
×
1659
                const text = event.data;
×
1660
                if (!Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1661
                    Editor.deleteFragment(this.editor);
×
1662
                }
1663
                // just handle Non-IME input
1664
                if (!this.isComposing) {
×
UNCOV
1665
                    Editor.insertText(this.editor, text);
×
1666
                }
1667
            } catch (error) {
UNCOV
1668
                this.editor.onError({
×
1669
                    code: SlateErrorCode.ToNativeSelectionError,
1670
                    nativeError: error
1671
                });
1672
            }
1673
        }
1674
    }
1675

1676
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1677
        if (!handler) {
3✔
1678
            return false;
3✔
1679
        }
1680
        handler(event);
×
UNCOV
1681
        return event.defaultPrevented;
×
1682
    }
1683
    //#endregion
1684

1685
    ngOnDestroy() {
1686
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1687
        this.manualListeners.forEach(manualListener => {
22✔
1688
            manualListener();
462✔
1689
        });
1690
        this.destroy$.complete();
22✔
1691
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1692
    }
1693
}
1694

1695
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1696
    // This was affecting the selection of multiple blocks and dragging behavior,
1697
    // so enabled only if the selection has been collapsed.
1698
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
UNCOV
1699
        const leafEl = domRange.startContainer.parentElement!;
×
1700

1701
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1702
        // When this happens, do not scroll like most editors do.
1703
        const domRect = domRange.getBoundingClientRect();
×
UNCOV
1704
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1705

1706
        if (isZeroDimensionRect) {
×
1707
            const leafRect = leafEl.getBoundingClientRect();
×
UNCOV
1708
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1709

1710
            if (leafHasDimensions) {
×
UNCOV
1711
                return;
×
1712
            }
1713
        }
1714

1715
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1716
        scrollIntoView(leafEl, {
×
1717
            scrollMode: 'if-needed'
1718
        });
UNCOV
1719
        delete leafEl.getBoundingClientRect;
×
1720
    }
1721
};
1722

1723
/**
1724
 * Check if the target is inside void and in the editor.
1725
 */
1726

1727
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1728
    let slateNode: Node | null = null;
1✔
1729
    try {
1✔
1730
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1731
    } catch (error) {}
1732
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1733
};
1734

1735
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1736
    return (
2✔
1737
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1738
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1739
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1740
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1741
    );
1742
};
1743

1744
/**
1745
 * remove default insert from composition
1746
 * @param text
1747
 */
1748
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1749
    const types = ['compositionend', 'insertFromComposition'];
×
1750
    if (!types.includes(event.type)) {
×
UNCOV
1751
        return;
×
1752
    }
1753
    const insertText = (event as CompositionEvent).data;
×
1754
    const window = AngularEditor.getWindow(editor);
×
UNCOV
1755
    const domSelection = window.getSelection();
×
1756
    // ensure text node insert composition input text
1757
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1758
        const textNode = domSelection.anchorNode;
×
UNCOV
1759
        textNode.splitText(textNode.length - insertText.length).remove();
×
1760
    }
1761
};
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