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

worktile / slate-angular / 6a799e2c-4a36-4dc3-b3f2-c0d61a88cd6f

08 Dec 2025 01:23PM UTC coverage: 43.426% (-0.2%) from 43.597%
6a799e2c-4a36-4dc3-b3f2-c0d61a88cd6f

Pull #314

circleci

Xwatson
feat(virtual): set block minheight to reduce element loading jitter
Pull Request #314: feat(virtual): set block minheight to reduce element loading jitter

384 of 1122 branches covered (34.22%)

Branch coverage included in aggregate %.

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

33 existing lines in 3 files now uncovered.

1056 of 2194 relevant lines covered (48.13%)

29.66 hits per line

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

25.73
/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
import { getBlockCardByNativeElement } from '../block-card/block-card';
69

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

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

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

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

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

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

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

111
    private initialized: boolean;
112

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

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

117
    @Input() editor: AngularEditor;
118

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

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

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

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

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

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

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

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

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

137
    @Input() placeholder: string;
138

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

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

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

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

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

200
    viewContainerRef = inject(ViewContainerRef);
23✔
201

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

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

214
    listRender: ListRender;
215

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

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

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

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

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

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

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

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

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

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

349
            const hasDomSelection = domSelection.type !== 'None';
1✔
350

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

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

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

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

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

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

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

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

419
            setTimeout(() => {
1✔
420
                // handle scrolling in setTimeout because of
421
                // dom should not have updated immediately after listRender's updating
422
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
423
                // COMPAT: In Firefox, it's not enough to create a range, you also need
424
                // to focus the contenteditable element too. (2016/11/16)
425
                if (newDomRange && IS_FIREFOX) {
1!
426
                    el.focus();
×
427
                }
428

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

440
    onChange() {
441
        this.forceRender();
13✔
442
        this.onChangeCallback(this.editor.children);
13✔
443
    }
444

445
    ngAfterViewChecked() {}
446

447
    ngDoCheck() {}
448

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

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

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

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

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

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

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

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

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

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

575
    virtualScrollInitialized = false;
23✔
576

577
    virtualTopHeightElement: HTMLElement;
578

579
    virtualBottomHeightElement: HTMLElement;
580

581
    virtualCenterOutlet: HTMLElement;
582

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

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

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

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

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

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

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

677
    private updateBlockCardMinheight(virtualView: VirtualViewResult) {
NEW
678
        const children = (this.editor.children || []) as Element[];
×
NEW
679
        virtualView.visibleIndexes.forEach(index => {
×
NEW
680
            const node = children[index];
×
NEW
681
            const view = ELEMENT_TO_COMPONENT.get(node);
×
NEW
682
            const block = getBlockCardByNativeElement(
×
683
                (view as BaseElementComponent | BaseElementFlavour).viewContainerRef.element.nativeElement
684
            );
NEW
685
            if (block) {
×
NEW
686
                block.style.minHeight = virtualView.heights[index] + 'px';
×
687
            }
688
        });
689
    }
690

691
    private applyVirtualView(virtualView: VirtualViewResult) {
692
        this.renderedChildren = virtualView.renderedChildren;
43✔
693
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
694
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
695
    }
696

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

796
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
797
        const node = this.editor.children[index];
×
798
        if (!node) {
×
799
            return defaultHeight;
×
800
        }
801
        const key = AngularEditor.findKey(this.editor, node);
×
802
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
803
    }
804

805
    private buildAccumulatedHeight(heights: number[]) {
806
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
807
        for (let i = 0; i < heights.length; i++) {
×
808
            // 存储前 i 个的累计高度
809
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
810
        }
811
        return accumulatedHeights;
×
812
    }
813

814
    private scheduleMeasureVisibleHeights() {
815
        if (!this.shouldUseVirtual()) {
43✔
816
            return;
43✔
817
        }
818
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
819
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
820
            this.measureVisibleHeights();
×
821
        });
822
    }
823

824
    private measureVisibleHeights() {
825
        const children = (this.editor.children || []) as Element[];
×
826
        this.virtualVisibleIndexes.forEach(index => {
×
827
            const node = children[index];
×
828
            if (!node) {
×
829
                return;
×
830
            }
831
            const key = AngularEditor.findKey(this.editor, node);
×
832
            // 跳过已测过的块
833
            if (this.measuredHeights.has(key.id)) {
×
834
                return;
×
835
            }
836
            const view = ELEMENT_TO_COMPONENT.get(node);
×
837
            if (!view) {
×
838
                return;
×
839
            }
840
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
841
            if (ret instanceof Promise) {
×
842
                ret.then(height => {
×
843
                    this.measuredHeights.set(key.id, height);
×
844
                });
845
            } else {
846
                this.measuredHeights.set(key.id, ret);
×
847
            }
848
        });
849
    }
850

851
    private remeasureHeightByIndics(indics: number[]): boolean {
852
        const children = (this.editor.children || []) as Element[];
×
853
        let isHeightChanged = false;
×
854
        indics.forEach(index => {
×
855
            const node = children[index];
×
856
            if (!node) {
×
857
                return;
×
858
            }
859
            const key = AngularEditor.findKey(this.editor, node);
×
860
            const view = ELEMENT_TO_COMPONENT.get(node);
×
861
            if (!view) {
×
862
                return;
×
863
            }
NEW
864
            const prevHeight = this.measuredHeights.get(key.id) ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
865
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
866
            if (ret instanceof Promise) {
×
867
                ret.then(height => {
×
868
                    if (height !== prevHeight) {
×
869
                        this.measuredHeights.set(key.id, height);
×
870
                        isHeightChanged = true;
×
871
                        if (isDebug) {
×
872
                            console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
873
                        }
874
                    }
875
                });
876
            } else {
877
                if (ret !== prevHeight) {
×
878
                    this.measuredHeights.set(key.id, ret);
×
879
                    isHeightChanged = true;
×
880
                    if (isDebug) {
×
881
                        console.log(`remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
882
                    }
883
                }
884
            }
885
        });
886
        return isHeightChanged;
×
887
    }
888

889
    //#region event proxy
890
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
891
        this.manualListeners.push(
483✔
892
            this.renderer2.listen(target, eventName, (event: Event) => {
893
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
894
                if (beforeInputEvent) {
5!
895
                    this.onFallbackBeforeInput(beforeInputEvent);
×
896
                }
897
                listener(event);
5✔
898
            })
899
        );
900
    }
901

902
    private toSlateSelection() {
903
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
904
            try {
1✔
905
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
906
                const { activeElement } = root;
1✔
907
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
908
                const domSelection = (root as Document).getSelection();
1✔
909

910
                if (activeElement === el) {
1!
911
                    this.latestElement = activeElement;
1✔
912
                    IS_FOCUSED.set(this.editor, true);
1✔
913
                } else {
914
                    IS_FOCUSED.delete(this.editor);
×
915
                }
916

917
                if (!domSelection) {
1!
918
                    return Transforms.deselect(this.editor);
×
919
                }
920

921
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
922
                const hasDomSelectionInEditor =
923
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
924
                if (!hasDomSelectionInEditor) {
1!
925
                    Transforms.deselect(this.editor);
×
926
                    return;
×
927
                }
928

929
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
930
                // for example, double-click the last cell of the table to select a non-editable DOM
931
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
932
                if (range) {
1✔
933
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
934
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
935
                            // force adjust DOMSelection
936
                            this.toNativeSelection();
×
937
                        }
938
                    } else {
939
                        Transforms.select(this.editor, range);
1✔
940
                    }
941
                }
942
            } catch (error) {
943
                this.editor.onError({
×
944
                    code: SlateErrorCode.ToSlateSelectionError,
945
                    nativeError: error
946
                });
947
            }
948
        }
949
    }
950

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

1029
                // COMPAT: If the selection is expanded, even if the command seems like
1030
                // a delete forward/backward command it should delete the selection.
1031
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1032
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1033
                    Editor.deleteFragment(editor, { direction });
×
1034
                    return;
×
1035
                }
1036

1037
                switch (type) {
×
1038
                    case 'deleteByComposition':
1039
                    case 'deleteByCut':
1040
                    case 'deleteByDrag': {
1041
                        Editor.deleteFragment(editor);
×
1042
                        break;
×
1043
                    }
1044

1045
                    case 'deleteContent':
1046
                    case 'deleteContentForward': {
1047
                        Editor.deleteForward(editor);
×
1048
                        break;
×
1049
                    }
1050

1051
                    case 'deleteContentBackward': {
1052
                        Editor.deleteBackward(editor);
×
1053
                        break;
×
1054
                    }
1055

1056
                    case 'deleteEntireSoftLine': {
1057
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1058
                        Editor.deleteForward(editor, { unit: 'line' });
×
1059
                        break;
×
1060
                    }
1061

1062
                    case 'deleteHardLineBackward': {
1063
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1064
                        break;
×
1065
                    }
1066

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

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

1077
                    case 'deleteSoftLineForward': {
1078
                        Editor.deleteForward(editor, { unit: 'line' });
×
1079
                        break;
×
1080
                    }
1081

1082
                    case 'deleteWordBackward': {
1083
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1084
                        break;
×
1085
                    }
1086

1087
                    case 'deleteWordForward': {
1088
                        Editor.deleteForward(editor, { unit: 'word' });
×
1089
                        break;
×
1090
                    }
1091

1092
                    case 'insertLineBreak':
1093
                    case 'insertParagraph': {
1094
                        Editor.insertBreak(editor);
×
1095
                        break;
×
1096
                    }
1097

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

1133
    private onDOMBlur(event: FocusEvent) {
1134
        if (
×
1135
            this.readonly ||
×
1136
            this.isUpdatingSelection ||
1137
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1138
            this.isDOMEventHandled(event, this.blur)
1139
        ) {
1140
            return;
×
1141
        }
1142

1143
        const window = AngularEditor.getWindow(this.editor);
×
1144

1145
        // COMPAT: If the current `activeElement` is still the previous
1146
        // one, this is due to the window being blurred when the tab
1147
        // itself becomes unfocused, so we want to abort early to allow to
1148
        // editor to stay focused when the tab becomes focused again.
1149
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1150
        if (this.latestElement === root.activeElement) {
×
1151
            return;
×
1152
        }
1153

1154
        const { relatedTarget } = event;
×
1155
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1156

1157
        // COMPAT: The event should be ignored if the focus is returning
1158
        // to the editor from an embedded editable element (eg. an <input>
1159
        // element inside a void node).
1160
        if (relatedTarget === el) {
×
1161
            return;
×
1162
        }
1163

1164
        // COMPAT: The event should be ignored if the focus is moving from
1165
        // the editor to inside a void node's spacer element.
1166
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1167
            return;
×
1168
        }
1169

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

1176
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1177
                return;
×
1178
            }
1179
        }
1180

1181
        IS_FOCUSED.delete(this.editor);
×
1182
    }
1183

1184
    private onDOMClick(event: MouseEvent) {
1185
        if (
×
1186
            !this.readonly &&
×
1187
            AngularEditor.hasTarget(this.editor, event.target) &&
1188
            !this.isDOMEventHandled(event, this.click) &&
1189
            isDOMNode(event.target)
1190
        ) {
1191
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1192
            const path = AngularEditor.findPath(this.editor, node);
×
1193
            const start = Editor.start(this.editor, path);
×
1194
            const end = Editor.end(this.editor, path);
×
1195

1196
            const startVoid = Editor.void(this.editor, { at: start });
×
1197
            const endVoid = Editor.void(this.editor, { at: end });
×
1198

1199
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1200
                let blockPath = path;
×
1201
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1202
                    const block = Editor.above(this.editor, {
×
1203
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1204
                        at: path
1205
                    });
1206

1207
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1208
                }
1209

1210
                const range = Editor.range(this.editor, blockPath);
×
1211
                Transforms.select(this.editor, range);
×
1212
                return;
×
1213
            }
1214

1215
            if (
×
1216
                startVoid &&
×
1217
                endVoid &&
1218
                Path.equals(startVoid[1], endVoid[1]) &&
1219
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1220
            ) {
1221
                const range = Editor.range(this.editor, start);
×
1222
                Transforms.select(this.editor, range);
×
1223
            }
1224
        }
1225
    }
1226

1227
    private onDOMCompositionStart(event: CompositionEvent) {
1228
        const { selection } = this.editor;
1✔
1229
        if (selection) {
1!
1230
            // solve the problem of cross node Chinese input
1231
            if (Range.isExpanded(selection)) {
×
1232
                Editor.deleteFragment(this.editor);
×
1233
                this.forceRender();
×
1234
            }
1235
        }
1236
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1237
            this.isComposing = true;
1✔
1238
        }
1239
        this.render();
1✔
1240
    }
1241

1242
    private onDOMCompositionUpdate(event: CompositionEvent) {
1243
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1244
    }
1245

1246
    private onDOMCompositionEnd(event: CompositionEvent) {
1247
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1248
            Transforms.delete(this.editor);
×
1249
        }
1250
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1251
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1252
            // aren't correct and never fire the "insertFromComposition"
1253
            // type that we need. So instead, insert whenever a composition
1254
            // ends since it will already have been committed to the DOM.
1255
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1256
                preventInsertFromComposition(event, this.editor);
×
1257
                Editor.insertText(this.editor, event.data);
×
1258
            }
1259

1260
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1261
            // so we need avoid repeat isnertText by isComposing === true,
1262
            this.isComposing = false;
×
1263
        }
1264
        this.render();
×
1265
    }
1266

1267
    private onDOMCopy(event: ClipboardEvent) {
1268
        const window = AngularEditor.getWindow(this.editor);
×
1269
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1270
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1271
            event.preventDefault();
×
1272
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1273
        }
1274
    }
1275

1276
    private onDOMCut(event: ClipboardEvent) {
1277
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1278
            event.preventDefault();
×
1279
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1280
            const { selection } = this.editor;
×
1281

1282
            if (selection) {
×
1283
                AngularEditor.deleteCutData(this.editor);
×
1284
            }
1285
        }
1286
    }
1287

1288
    private onDOMDragOver(event: DragEvent) {
1289
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1290
            // Only when the target is void, call `preventDefault` to signal
1291
            // that drops are allowed. Editable content is droppable by
1292
            // default, and calling `preventDefault` hides the cursor.
1293
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1294

1295
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1296
                event.preventDefault();
×
1297
            }
1298
        }
1299
    }
1300

1301
    private onDOMDragStart(event: DragEvent) {
1302
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1303
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1304
            const path = AngularEditor.findPath(this.editor, node);
×
1305
            const voidMatch =
1306
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1307

1308
            // If starting a drag on a void node, make sure it is selected
1309
            // so that it shows up in the selection's fragment.
1310
            if (voidMatch) {
×
1311
                const range = Editor.range(this.editor, path);
×
1312
                Transforms.select(this.editor, range);
×
1313
            }
1314

1315
            this.isDraggingInternally = true;
×
1316

1317
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1318
        }
1319
    }
1320

1321
    private onDOMDrop(event: DragEvent) {
1322
        const editor = this.editor;
×
1323
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1324
            event.preventDefault();
×
1325
            // Keep a reference to the dragged range before updating selection
1326
            const draggedRange = editor.selection;
×
1327

1328
            // Find the range where the drop happened
1329
            const range = AngularEditor.findEventRange(editor, event);
×
1330
            const data = event.dataTransfer;
×
1331

1332
            Transforms.select(editor, range);
×
1333

1334
            if (this.isDraggingInternally) {
×
1335
                if (draggedRange) {
×
1336
                    Transforms.delete(editor, {
×
1337
                        at: draggedRange
1338
                    });
1339
                }
1340

1341
                this.isDraggingInternally = false;
×
1342
            }
1343

1344
            AngularEditor.insertData(editor, data);
×
1345

1346
            // When dragging from another source into the editor, it's possible
1347
            // that the current editor does not have focus.
1348
            if (!AngularEditor.isFocused(editor)) {
×
1349
                AngularEditor.focus(editor);
×
1350
            }
1351
        }
1352
    }
1353

1354
    private onDOMDragEnd(event: DragEvent) {
1355
        if (
×
1356
            !this.readonly &&
×
1357
            this.isDraggingInternally &&
1358
            AngularEditor.hasTarget(this.editor, event.target) &&
1359
            !this.isDOMEventHandled(event, this.dragEnd)
1360
        ) {
1361
            this.isDraggingInternally = false;
×
1362
        }
1363
    }
1364

1365
    private onDOMFocus(event: Event) {
1366
        if (
2✔
1367
            !this.readonly &&
8✔
1368
            !this.isUpdatingSelection &&
1369
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1370
            !this.isDOMEventHandled(event, this.focus)
1371
        ) {
1372
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1373
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1374
            this.latestElement = root.activeElement;
2✔
1375

1376
            // COMPAT: If the editor has nested editable elements, the focus
1377
            // can go to them. In Firefox, this must be prevented because it
1378
            // results in issues with keyboard navigation. (2017/03/30)
1379
            if (IS_FIREFOX && event.target !== el) {
2!
1380
                el.focus();
×
1381
                return;
×
1382
            }
1383

1384
            IS_FOCUSED.set(this.editor, true);
2✔
1385
        }
1386
    }
1387

1388
    private onDOMKeydown(event: KeyboardEvent) {
1389
        const editor = this.editor;
×
1390
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1391
        const { activeElement } = root;
×
1392
        if (
×
1393
            !this.readonly &&
×
1394
            AngularEditor.hasEditableTarget(editor, event.target) &&
1395
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1396
            !this.isComposing &&
1397
            !this.isDOMEventHandled(event, this.keydown)
1398
        ) {
1399
            const nativeEvent = event;
×
1400
            const { selection } = editor;
×
1401

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

1405
            try {
×
1406
                // COMPAT: Since we prevent the default behavior on
1407
                // `beforeinput` events, the browser doesn't think there's ever
1408
                // any history stack to undo or redo, so we have to manage these
1409
                // hotkeys ourselves. (2019/11/06)
1410
                if (Hotkeys.isRedo(nativeEvent)) {
×
1411
                    event.preventDefault();
×
1412

1413
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1414
                        editor.redo();
×
1415
                    }
1416

1417
                    return;
×
1418
                }
1419

1420
                if (Hotkeys.isUndo(nativeEvent)) {
×
1421
                    event.preventDefault();
×
1422

1423
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1424
                        editor.undo();
×
1425
                    }
1426

1427
                    return;
×
1428
                }
1429

1430
                // COMPAT: Certain browsers don't handle the selection updates
1431
                // properly. In Chrome, the selection isn't properly extended.
1432
                // And in Firefox, the selection isn't properly collapsed.
1433
                // (2017/10/17)
1434
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1435
                    event.preventDefault();
×
1436
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1437
                    return;
×
1438
                }
1439

1440
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1441
                    event.preventDefault();
×
1442
                    Transforms.move(editor, { unit: 'line' });
×
1443
                    return;
×
1444
                }
1445

1446
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1447
                    event.preventDefault();
×
1448
                    Transforms.move(editor, {
×
1449
                        unit: 'line',
1450
                        edge: 'focus',
1451
                        reverse: true
1452
                    });
1453
                    return;
×
1454
                }
1455

1456
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1457
                    event.preventDefault();
×
1458
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1459
                    return;
×
1460
                }
1461

1462
                // COMPAT: If a void node is selected, or a zero-width text node
1463
                // adjacent to an inline is selected, we need to handle these
1464
                // hotkeys manually because browsers won't be able to skip over
1465
                // the void node with the zero-width space not being an empty
1466
                // string.
1467
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1468
                    event.preventDefault();
×
1469

1470
                    if (selection && Range.isCollapsed(selection)) {
×
1471
                        Transforms.move(editor, { reverse: !isRTL });
×
1472
                    } else {
1473
                        Transforms.collapse(editor, { edge: 'start' });
×
1474
                    }
1475

1476
                    return;
×
1477
                }
1478

1479
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1480
                    event.preventDefault();
×
1481
                    if (selection && Range.isCollapsed(selection)) {
×
1482
                        Transforms.move(editor, { reverse: isRTL });
×
1483
                    } else {
1484
                        Transforms.collapse(editor, { edge: 'end' });
×
1485
                    }
1486

1487
                    return;
×
1488
                }
1489

1490
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1491
                    event.preventDefault();
×
1492

1493
                    if (selection && Range.isExpanded(selection)) {
×
1494
                        Transforms.collapse(editor, { edge: 'focus' });
×
1495
                    }
1496

1497
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1498
                    return;
×
1499
                }
1500

1501
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1502
                    event.preventDefault();
×
1503

1504
                    if (selection && Range.isExpanded(selection)) {
×
1505
                        Transforms.collapse(editor, { edge: 'focus' });
×
1506
                    }
1507

1508
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1509
                    return;
×
1510
                }
1511

1512
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1513
                // fall back to guessing at the input intention for hotkeys.
1514
                // COMPAT: In iOS, some of these hotkeys are handled in the
1515
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1516
                    // We don't have a core behavior for these, but they change the
1517
                    // DOM if we don't prevent them, so we have to.
1518
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1519
                        event.preventDefault();
×
1520
                        return;
×
1521
                    }
1522

1523
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1524
                        event.preventDefault();
×
1525
                        Editor.insertBreak(editor);
×
1526
                        return;
×
1527
                    }
1528

1529
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1530
                        event.preventDefault();
×
1531

1532
                        if (selection && Range.isExpanded(selection)) {
×
1533
                            Editor.deleteFragment(editor, {
×
1534
                                direction: 'backward'
1535
                            });
1536
                        } else {
1537
                            Editor.deleteBackward(editor);
×
1538
                        }
1539

1540
                        return;
×
1541
                    }
1542

1543
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1544
                        event.preventDefault();
×
1545

1546
                        if (selection && Range.isExpanded(selection)) {
×
1547
                            Editor.deleteFragment(editor, {
×
1548
                                direction: 'forward'
1549
                            });
1550
                        } else {
1551
                            Editor.deleteForward(editor);
×
1552
                        }
1553

1554
                        return;
×
1555
                    }
1556

1557
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1558
                        event.preventDefault();
×
1559

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

1568
                        return;
×
1569
                    }
1570

1571
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1572
                        event.preventDefault();
×
1573

1574
                        if (selection && Range.isExpanded(selection)) {
×
1575
                            Editor.deleteFragment(editor, {
×
1576
                                direction: 'forward'
1577
                            });
1578
                        } else {
1579
                            Editor.deleteForward(editor, { unit: 'line' });
×
1580
                        }
1581

1582
                        return;
×
1583
                    }
1584

1585
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1586
                        event.preventDefault();
×
1587

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

1596
                        return;
×
1597
                    }
1598

1599
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1600
                        event.preventDefault();
×
1601

1602
                        if (selection && Range.isExpanded(selection)) {
×
1603
                            Editor.deleteFragment(editor, {
×
1604
                                direction: 'forward'
1605
                            });
1606
                        } else {
1607
                            Editor.deleteForward(editor, { unit: 'word' });
×
1608
                        }
1609

1610
                        return;
×
1611
                    }
1612
                } else {
1613
                    if (IS_CHROME || IS_SAFARI) {
×
1614
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1615
                        // an event when deleting backwards in a selected void inline node
1616
                        if (
×
1617
                            selection &&
×
1618
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1619
                            Range.isCollapsed(selection)
1620
                        ) {
1621
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1622
                            if (
×
1623
                                Element.isElement(currentNode) &&
×
1624
                                Editor.isVoid(editor, currentNode) &&
1625
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1626
                            ) {
1627
                                event.preventDefault();
×
1628
                                Editor.deleteBackward(editor, {
×
1629
                                    unit: 'block'
1630
                                });
1631
                                return;
×
1632
                            }
1633
                        }
1634
                    }
1635
                }
1636
            } catch (error) {
1637
                this.editor.onError({
×
1638
                    code: SlateErrorCode.OnDOMKeydownError,
1639
                    nativeError: error
1640
                });
1641
            }
1642
        }
1643
    }
1644

1645
    private onDOMPaste(event: ClipboardEvent) {
1646
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1647
        // fall back to React's `onPaste` here instead.
1648
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1649
        // when "paste without formatting" option is used.
1650
        // This unfortunately needs to be handled with paste events instead.
1651
        if (
×
1652
            !this.isDOMEventHandled(event, this.paste) &&
×
1653
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1654
            !this.readonly &&
1655
            AngularEditor.hasEditableTarget(this.editor, event.target)
1656
        ) {
1657
            event.preventDefault();
×
1658
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1659
        }
1660
    }
1661

1662
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1663
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1664
        // fall back to React's leaky polyfill instead just for it. It
1665
        // only works for the `insertText` input type.
1666
        if (
×
1667
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1668
            !this.readonly &&
1669
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1670
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1671
        ) {
1672
            event.nativeEvent.preventDefault();
×
1673
            try {
×
1674
                const text = event.data;
×
1675
                if (!Range.isCollapsed(this.editor.selection)) {
×
1676
                    Editor.deleteFragment(this.editor);
×
1677
                }
1678
                // just handle Non-IME input
1679
                if (!this.isComposing) {
×
1680
                    Editor.insertText(this.editor, text);
×
1681
                }
1682
            } catch (error) {
1683
                this.editor.onError({
×
1684
                    code: SlateErrorCode.ToNativeSelectionError,
1685
                    nativeError: error
1686
                });
1687
            }
1688
        }
1689
    }
1690

1691
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1692
        if (!handler) {
3✔
1693
            return false;
3✔
1694
        }
1695
        handler(event);
×
1696
        return event.defaultPrevented;
×
1697
    }
1698
    //#endregion
1699

1700
    ngOnDestroy() {
1701
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1702
        this.manualListeners.forEach(manualListener => {
23✔
1703
            manualListener();
483✔
1704
        });
1705
        this.destroy$.complete();
23✔
1706
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1707
    }
1708
}
1709

1710
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1711
    // This was affecting the selection of multiple blocks and dragging behavior,
1712
    // so enabled only if the selection has been collapsed.
1713
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1714
        const leafEl = domRange.startContainer.parentElement!;
×
1715

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

1721
        if (isZeroDimensionRect) {
×
1722
            const leafRect = leafEl.getBoundingClientRect();
×
1723
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1724

1725
            if (leafHasDimensions) {
×
1726
                return;
×
1727
            }
1728
        }
1729

1730
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1731
        scrollIntoView(leafEl, {
×
1732
            scrollMode: 'if-needed'
1733
        });
1734
        delete leafEl.getBoundingClientRect;
×
1735
    }
1736
};
1737

1738
/**
1739
 * Check if the target is inside void and in the editor.
1740
 */
1741

1742
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1743
    let slateNode: Node | null = null;
1✔
1744
    try {
1✔
1745
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1746
    } catch (error) {}
1747
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1748
};
1749

1750
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1751
    return (
2✔
1752
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1753
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1754
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1755
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1756
    );
1757
};
1758

1759
/**
1760
 * remove default insert from composition
1761
 * @param text
1762
 */
1763
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1764
    const types = ['compositionend', 'insertFromComposition'];
×
1765
    if (!types.includes(event.type)) {
×
1766
        return;
×
1767
    }
1768
    const insertText = (event as CompositionEvent).data;
×
1769
    const window = AngularEditor.getWindow(editor);
×
1770
    const domSelection = window.getSelection();
×
1771
    // ensure text node insert composition input text
1772
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1773
        const textNode = domSelection.anchorNode;
×
1774
        textNode.splitText(textNode.length - insertText.length).remove();
×
1775
    }
1776
};
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