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

worktile / slate-angular / 914163ea-6ee0-42d0-9f61-7488a0f53348

24 Dec 2025 05:34PM UTC coverage: 37.097% (+0.03%) from 37.072%
914163ea-6ee0-42d0-9f61-7488a0f53348

push

circleci

pubuzhixing8
feat(virtual-scroll): add debugLog and move debugLog to virtual-scroll

382 of 1231 branches covered (31.03%)

Branch coverage included in aggregate %.

3 of 30 new or added lines in 2 files covered. (10.0%)

1 existing line in 1 file now uncovered.

1080 of 2710 relevant lines covered (39.85%)

24.12 hits per line

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

22.93
/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, Selection } 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
    SLATE_DEBUG_KEY,
49
    SLATE_DEBUG_KEY_SCROLL_TOP
50
} from '../../utils/environment';
51
import Hotkeys from '../../utils/hotkeys';
52
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
53
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
54
import { SlateErrorCode } from '../../types/error';
55
import { NG_VALUE_ACCESSOR } from '@angular/forms';
56
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
57
import { ViewType } from '../../types/view';
58
import { HistoryEditor } from 'slate-history';
59
import {
60
    buildHeightsAndAccumulatedHeights,
61
    EDITOR_TO_BUSINESS_TOP,
62
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
63
    ELEMENT_KEY_TO_HEIGHTS,
64
    getBusinessTop,
65
    getRealHeightByElement,
66
    IS_ENABLED_VIRTUAL_SCROLL,
67
    isDebug,
68
    isDebugScrollTop,
69
    isDecoratorRangeListEqual,
70
    measureHeightByIndics
71
} from '../../utils';
72
import { SlatePlaceholder } from '../../types/feature';
73
import { restoreDom } from '../../utils/restore-dom';
74
import { ListRender } from '../../view/render/list-render';
75
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
76
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
77
import { isKeyHotkey } from 'is-hotkey';
78
import { debugLog } from '../../utils/virtual-scroll';
79
import { VirtualScrollDebugOverlay } from './debug';
80

81
// not correctly clipboardData on beforeinput
82
const forceOnDOMPaste = IS_SAFARI;
1✔
83

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

109
    private destroy$ = new Subject();
23✔
110

111
    isComposing = false;
23✔
112
    isDraggingInternally = false;
23✔
113
    isUpdatingSelection = false;
23✔
114
    latestElement = null as DOMElement | null;
23✔
115

116
    protected manualListeners: (() => void)[] = [];
23✔
117

118
    private initialized: boolean;
119

120
    private onTouchedCallback: () => void = () => {};
23✔
121

122
    private onChangeCallback: (_: any) => void = () => {};
23✔
123

124
    @Input() editor: AngularEditor;
125

126
    @Input() renderElement: (element: Element) => ViewType | null;
127

128
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
129

130
    @Input() renderText: (text: SlateText) => ViewType | null;
131

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

134
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
135

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

138
    @Input() isStrictDecorate: boolean = true;
23✔
139

140
    @Input() trackBy: (node: Element) => any = () => null;
206✔
141

142
    @Input() readonly = false;
23✔
143

144
    @Input() placeholder: string;
145

146
    @Input()
147
    set virtualScroll(config: SlateVirtualScrollConfig) {
148
        this.virtualScrollConfig = config;
×
149
        if (isDebugScrollTop) {
×
NEW
150
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
151
        }
152
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
153
        if (this.isEnabledVirtualScroll()) {
×
154
            this.tryUpdateVirtualViewport();
×
155
        }
156
    }
157

158
    //#region input event handler
159
    @Input() beforeInput: (event: Event) => void;
160
    @Input() blur: (event: Event) => void;
161
    @Input() click: (event: MouseEvent) => void;
162
    @Input() compositionEnd: (event: CompositionEvent) => void;
163
    @Input() compositionUpdate: (event: CompositionEvent) => void;
164
    @Input() compositionStart: (event: CompositionEvent) => void;
165
    @Input() copy: (event: ClipboardEvent) => void;
166
    @Input() cut: (event: ClipboardEvent) => void;
167
    @Input() dragOver: (event: DragEvent) => void;
168
    @Input() dragStart: (event: DragEvent) => void;
169
    @Input() dragEnd: (event: DragEvent) => void;
170
    @Input() drop: (event: DragEvent) => void;
171
    @Input() focus: (event: Event) => void;
172
    @Input() keydown: (event: KeyboardEvent) => void;
173
    @Input() paste: (event: ClipboardEvent) => void;
174
    //#endregion
175

176
    //#region DOM attr
177
    @Input() spellCheck = false;
23✔
178
    @Input() autoCorrect = false;
23✔
179
    @Input() autoCapitalize = false;
23✔
180

181
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
182
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
183
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
184

185
    get hasBeforeInputSupport() {
186
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
187
    }
188
    //#endregion
189

190
    viewContainerRef = inject(ViewContainerRef);
23✔
191

192
    getOutletParent = () => {
23✔
193
        return this.elementRef.nativeElement;
43✔
194
    };
195

196
    getOutletElement = () => {
23✔
197
        if (this.virtualScrollInitialized) {
23!
198
            return this.virtualCenterOutlet;
×
199
        } else {
200
            return null;
23✔
201
        }
202
    };
203

204
    listRender: ListRender;
205

206
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
207
        enabled: false,
208
        scrollTop: 0,
209
        viewportHeight: 0,
210
        viewportBoundingTop: 0
211
    };
212

213
    private inViewportChildren: Element[] = [];
23✔
214
    private inViewportIndics: number[] = [];
23✔
215
    private keyHeightMap = new Map<string, number>();
23✔
216
    private tryUpdateVirtualViewportAnimId: number;
217
    private tryMeasureInViewportChildrenHeightsAnimId: number;
218
    private editorResizeObserver?: ResizeObserver;
219

220
    constructor(
221
        public elementRef: ElementRef,
23✔
222
        public renderer2: Renderer2,
23✔
223
        public cdr: ChangeDetectorRef,
23✔
224
        private ngZone: NgZone,
23✔
225
        private injector: Injector
23✔
226
    ) {}
227

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

249
        // add browser class
250
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
251
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
252
        this.initializeVirtualScroll();
23✔
253
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
254
    }
255

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

276
    registerOnChange(fn: any) {
277
        this.onChangeCallback = fn;
23✔
278
    }
279
    registerOnTouched(fn: any) {
280
        this.onTouchedCallback = fn;
23✔
281
    }
282

283
    writeValue(value: Element[]) {
284
        if (value && value.length) {
49✔
285
            this.editor.children = value;
26✔
286
            this.initializeContext();
26✔
287
            if (this.isEnabledVirtualScroll()) {
26!
288
                const virtualView = this.calculateVirtualViewport();
×
289
                this.applyVirtualView(virtualView);
×
290
                const childrenForRender = virtualView.inViewportChildren;
×
291
                if (!this.listRender.initialized) {
×
292
                    this.listRender.initialize(childrenForRender, this.editor, this.context);
×
293
                } else {
294
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
295
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
296
                }
297
            } else {
298
                if (!this.listRender.initialized) {
26✔
299
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
300
                } else {
301
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
302
                }
303
            }
304
            this.cdr.markForCheck();
26✔
305
        }
306
    }
307

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

340
    calculateVirtualScrollSelection(selection: Selection) {
341
        if (selection) {
×
342
            const indics = this.inViewportIndics;
×
343
            if (indics.length > 0) {
×
344
                const currentVisibleRange: Range = {
×
345
                    anchor: Editor.start(this.editor, [indics[0]]),
346
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
347
                };
348
                const [start, end] = Range.edges(selection);
×
349
                const forwardSelection = { anchor: start, focus: end };
×
350
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
351
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
352
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
353
                    if (isDebug) {
×
NEW
354
                        debugLog(
×
355
                            'log',
356
                            `selection is not in visible range, selection: ${JSON.stringify(
357
                                selection
358
                            )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
359
                        );
360
                    }
361
                    return intersectedSelection;
×
362
                }
363
                return selection;
×
364
            }
365
        }
366
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
367
        return selection;
×
368
    }
369

370
    toNativeSelection() {
371
        try {
15✔
372
            let { selection } = this.editor;
15✔
373
            if (this.isEnabledVirtualScroll()) {
15!
374
                selection = this.calculateVirtualScrollSelection(selection);
×
375
            }
376
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
377
            const { activeElement } = root;
15✔
378
            const domSelection = (root as Document).getSelection();
15✔
379

380
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
381
                return;
14✔
382
            }
383

384
            const hasDomSelection = domSelection.type !== 'None';
1✔
385

386
            // If the DOM selection is properly unset, we're done.
387
            if (!selection && !hasDomSelection) {
1!
388
                return;
×
389
            }
390

391
            // If the DOM selection is already correct, we're done.
392
            // verify that the dom selection is in the editor
393
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
394
            let hasDomSelectionInEditor = false;
1✔
395
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
396
                hasDomSelectionInEditor = true;
1✔
397
            }
398

399
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
400
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
401
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
402
                    exactMatch: false,
403
                    suppressThrow: true
404
                });
405
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
406
                    return;
×
407
                }
408
            }
409

410
            // prevent updating native selection when active element is void element
411
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
412
                return;
×
413
            }
414

415
            // when <Editable/> is being controlled through external value
416
            // then its children might just change - DOM responds to it on its own
417
            // but Slate's value is not being updated through any operation
418
            // and thus it doesn't transform selection on its own
419
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
420
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
421
                return;
×
422
            }
423

424
            // Otherwise the DOM selection is out of sync, so update it.
425
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
426
            this.isUpdatingSelection = true;
1✔
427

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

430
            if (newDomRange) {
1!
431
                // COMPAT: Since the DOM range has no concept of backwards/forwards
432
                // we need to check and do the right thing here.
433
                if (Range.isBackward(selection)) {
1!
434
                    // eslint-disable-next-line max-len
435
                    domSelection.setBaseAndExtent(
×
436
                        newDomRange.endContainer,
437
                        newDomRange.endOffset,
438
                        newDomRange.startContainer,
439
                        newDomRange.startOffset
440
                    );
441
                } else {
442
                    // eslint-disable-next-line max-len
443
                    domSelection.setBaseAndExtent(
1✔
444
                        newDomRange.startContainer,
445
                        newDomRange.startOffset,
446
                        newDomRange.endContainer,
447
                        newDomRange.endOffset
448
                    );
449
                }
450
            } else {
451
                domSelection.removeAllRanges();
×
452
            }
453

454
            setTimeout(() => {
1✔
455
                // handle scrolling in setTimeout because of
456
                // dom should not have updated immediately after listRender's updating
457
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
458
                // COMPAT: In Firefox, it's not enough to create a range, you also need
459
                // to focus the contenteditable element too. (2016/11/16)
460
                if (newDomRange && IS_FIREFOX) {
1!
461
                    el.focus();
×
462
                }
463

464
                this.isUpdatingSelection = false;
1✔
465
            });
466
        } catch (error) {
467
            this.editor.onError({
×
468
                code: SlateErrorCode.ToNativeSelectionError,
469
                nativeError: error
470
            });
471
            this.isUpdatingSelection = false;
×
472
        }
473
    }
474

475
    onChange() {
476
        this.forceRender();
13✔
477
        this.onChangeCallback(this.editor.children);
13✔
478
    }
479

480
    ngAfterViewChecked() {}
481

482
    ngDoCheck() {}
483

484
    forceRender() {
485
        this.updateContext();
15✔
486
        if (this.isEnabledVirtualScroll()) {
15!
487
            this.updateListRenderAndRemeasureHeights();
×
488
        } else {
489
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
490
        }
491
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
492
        // when the DOMElement where the selection is located is removed
493
        // the compositionupdate and compositionend events will no longer be fired
494
        // so isComposing needs to be corrected
495
        // need exec after this.cdr.detectChanges() to render HTML
496
        // need exec before this.toNativeSelection() to correct native selection
497
        if (this.isComposing) {
15!
498
            // Composition input text be not rendered when user composition input with selection is expanded
499
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
500
            // this time condition is true and isComposing is assigned false
501
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
502
            setTimeout(() => {
×
503
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
504
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
505
                let textContent = '';
×
506
                // skip decorate text
507
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
508
                    let text = stringDOMNode.textContent;
×
509
                    const zeroChar = '\uFEFF';
×
510
                    // remove zero with char
511
                    if (text.startsWith(zeroChar)) {
×
512
                        text = text.slice(1);
×
513
                    }
514
                    if (text.endsWith(zeroChar)) {
×
515
                        text = text.slice(0, text.length - 1);
×
516
                    }
517
                    textContent += text;
×
518
                });
519
                if (Node.string(textNode).endsWith(textContent)) {
×
520
                    this.isComposing = false;
×
521
                }
522
            }, 0);
523
        }
524
        this.toNativeSelection();
15✔
525
    }
526

527
    render() {
528
        const changed = this.updateContext();
2✔
529
        if (changed) {
2✔
530
            if (this.isEnabledVirtualScroll()) {
2!
531
                this.updateListRenderAndRemeasureHeights();
×
532
            } else {
533
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
534
            }
535
        }
536
    }
537

538
    updateListRenderAndRemeasureHeights() {
539
        const virtualView = this.calculateVirtualViewport();
×
540
        const oldInViewportChildren = this.inViewportChildren;
×
541
        this.applyVirtualView(virtualView);
×
542
        const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
543
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
544
        // 新增或者修改的才需要重算,计算出这个结果
545
        const remeasureIndics = [];
×
546
        this.inViewportChildren.forEach((child, index) => {
×
547
            if (oldInViewportChildren.indexOf(child) === -1) {
×
548
                remeasureIndics.push(this.inViewportIndics[index]);
×
549
            }
550
        });
551
        if (isDebug && remeasureIndics.length > 0) {
×
552
            console.log('remeasure height by indics: ', remeasureIndics);
×
553
        }
554
        measureHeightByIndics(this.editor, remeasureIndics, true);
×
555
    }
556

557
    updateContext() {
558
        const decorations = this.generateDecorations();
17✔
559
        if (
17✔
560
            this.context.selection !== this.editor.selection ||
46✔
561
            this.context.decorate !== this.decorate ||
562
            this.context.readonly !== this.readonly ||
563
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
564
        ) {
565
            this.context = {
10✔
566
                parent: this.editor,
567
                selection: this.editor.selection,
568
                decorations: decorations,
569
                decorate: this.decorate,
570
                readonly: this.readonly
571
            };
572
            return true;
10✔
573
        }
574
        return false;
7✔
575
    }
576

577
    initializeContext() {
578
        this.context = {
49✔
579
            parent: this.editor,
580
            selection: this.editor.selection,
581
            decorations: this.generateDecorations(),
582
            decorate: this.decorate,
583
            readonly: this.readonly
584
        };
585
    }
586

587
    initializeViewContext() {
588
        this.viewContext = {
23✔
589
            editor: this.editor,
590
            renderElement: this.renderElement,
591
            renderLeaf: this.renderLeaf,
592
            renderText: this.renderText,
593
            trackBy: this.trackBy,
594
            isStrictDecorate: this.isStrictDecorate
595
        };
596
    }
597

598
    composePlaceholderDecorate(editor: Editor) {
599
        if (this.placeholderDecorate) {
64!
600
            return this.placeholderDecorate(editor) || [];
×
601
        }
602

603
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
604
            const start = Editor.start(editor, []);
3✔
605
            return [
3✔
606
                {
607
                    placeholder: this.placeholder,
608
                    anchor: start,
609
                    focus: start
610
                }
611
            ];
612
        } else {
613
            return [];
61✔
614
        }
615
    }
616

617
    generateDecorations() {
618
        const decorations = this.decorate([this.editor, []]);
66✔
619
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
620
        decorations.push(...placeholderDecorations);
66✔
621
        return decorations;
66✔
622
    }
623

624
    private isEnabledVirtualScroll() {
625
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
81✔
626
    }
627

628
    virtualScrollInitialized = false;
23✔
629

630
    virtualTopHeightElement: HTMLElement;
631

632
    virtualBottomHeightElement: HTMLElement;
633

634
    virtualCenterOutlet: HTMLElement;
635

636
    initializeVirtualScroll() {
637
        if (this.virtualScrollInitialized) {
23!
638
            return;
×
639
        }
640
        if (this.isEnabledVirtualScroll()) {
23!
641
            this.virtualScrollInitialized = true;
×
642
            this.virtualTopHeightElement = document.createElement('div');
×
643
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
644
            this.virtualTopHeightElement.contentEditable = 'false';
×
645
            this.virtualBottomHeightElement = document.createElement('div');
×
646
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
647
            this.virtualBottomHeightElement.contentEditable = 'false';
×
648
            this.virtualCenterOutlet = document.createElement('div');
×
649
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
650
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
651
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
652
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
653
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
654
            this.editorResizeObserver = new ResizeObserver(entries => {
×
655
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
656
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
657
                    this.keyHeightMap.clear();
×
658
                    const remeasureIndics = this.inViewportIndics;
×
NEW
659
                    measureHeightByIndics(this.editor, remeasureIndics, true);
×
660
                }
661
            });
662
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
663
        }
664
    }
665

666
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
667
        if (!this.virtualScrollInitialized) {
×
668
            return;
×
669
        }
670
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
671
        if (bottomHeight !== undefined) {
×
672
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
673
        }
674
    }
675

676
    getVirtualTopHeight() {
677
        if (!this.virtualScrollInitialized) {
×
678
            return 0;
×
679
        }
680
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
681
    }
682

683
    handlePreRendering() {
684
        let preRenderingCount = 1;
×
685
        const childrenWithPreRendering = [...this.inViewportChildren];
×
686
        if (this.inViewportIndics[0] !== 0) {
×
687
            childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
688
        } else {
689
            preRenderingCount = 0;
×
690
        }
691
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
692
        if (lastIndex !== this.editor.children.length - 1) {
×
693
            childrenWithPreRendering.push(this.editor.children[lastIndex + 1] as Element);
×
694
        }
695
        return { preRenderingCount, childrenWithPreRendering };
×
696
    }
697

698
    private tryUpdateVirtualViewport() {
699
        if (isDebug) {
×
NEW
700
            debugLog('log', 'tryUpdateVirtualViewport');
×
701
        }
702
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
703
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
704
            if (isDebug) {
×
NEW
705
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
706
            }
707
            let virtualView = this.calculateVirtualViewport();
×
708
            let diff = this.diffVirtualViewport(virtualView);
×
709
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
710
                const remeasureIndics = diff.changedIndexesOfTop;
×
711
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
712
                if (changed) {
×
713
                    virtualView = this.calculateVirtualViewport();
×
714
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
715
                }
716
            }
717
            if (diff.isDifferent) {
×
718
                this.applyVirtualView(virtualView);
×
719
                if (this.listRender.initialized) {
×
720
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
721
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
722
                    if (diff.needAddOnTop) {
×
723
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
724
                        if (isDebug) {
×
NEW
725
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
726
                        }
727
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
728
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
NEW
729
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
NEW
730
                        if (changed) {
×
731
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
732
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
733
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
734
                            this.setVirtualSpaceHeight(newTopHeight);
×
735
                            if (isDebug) {
×
NEW
736
                                debugLog(
×
737
                                    'log',
738
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
739
                                );
740
                            }
741
                        }
742
                    }
743
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
744
                        this.toNativeSelection();
×
745
                    }
746
                }
747
            } else {
748
                const topHeight = this.getVirtualTopHeight();
×
749
                if (virtualView.top !== topHeight) {
×
NEW
750
                    if (isDebug) {
×
NEW
751
                        debugLog(
×
752
                            'log',
753
                            'update top height since invalid status(正数减去高度,负数代表增加高度): ',
754
                            topHeight - virtualView.top
755
                        );
756
                    }
UNCOV
757
                    this.setVirtualSpaceHeight(virtualView.top);
×
758
                }
759
            }
760
            if (isDebug) {
×
NEW
761
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
762
            }
763
        });
764
    }
765

766
    private calculateVirtualViewport() {
767
        const children = (this.editor.children || []) as Element[];
×
768
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
769
            return {
×
770
                inViewportChildren: children,
771
                visibleIndexes: [],
772
                top: 0,
773
                bottom: 0,
774
                heights: []
775
            };
776
        }
777
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
778
        if (isDebug) {
×
779
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
780
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
781
        }
782
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
783
        if (!viewportHeight) {
×
784
            return {
×
785
                inViewportChildren: [],
786
                visibleIndexes: [],
787
                top: 0,
788
                bottom: 0,
789
                heights: []
790
            };
791
        }
792
        const elementLength = children.length;
×
793
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
794
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
795
            setTimeout(() => {
×
796
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
797
                const businessTop =
798
                    Math.ceil(virtualTopBoundingTop) +
×
799
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
800
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
801
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
802
                if (isDebug) {
×
NEW
803
                    debugLog('log', 'businessTop', businessTop);
×
804
                }
805
            }, 100);
806
        }
807
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
808
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
809
        const totalHeight = accumulatedHeights[elementLength];
×
810
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
811
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
812
        const viewBottom = limitedScrollTop + viewportHeight;
×
813
        let accumulatedOffset = 0;
×
814
        let visibleStartIndex = -1;
×
815
        const visible: Element[] = [];
×
816
        const visibleIndexes: number[] = [];
×
817

818
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
819
            const currentHeight = heights[i];
×
820
            const nextOffset = accumulatedOffset + currentHeight;
×
821
            // 可视区域有交集,加入渲染
822
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
823
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
824
                visible.push(children[i]);
×
825
                visibleIndexes.push(i);
×
826
            }
827
            accumulatedOffset = nextOffset;
×
828
        }
829

830
        if (visibleStartIndex === -1 && elementLength) {
×
831
            visibleStartIndex = elementLength - 1;
×
832
            visible.push(children[visibleStartIndex]);
×
833
            visibleIndexes.push(visibleStartIndex);
×
834
        }
835

836
        const visibleEndIndex =
837
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
838
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
839
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
840
        return {
×
841
            inViewportChildren: visible.length ? visible : children,
×
842
            visibleIndexes,
843
            top,
844
            bottom,
845
            heights,
846
            accumulatedHeights
847
        };
848
    }
849

850
    private applyVirtualView(virtualView: VirtualViewResult) {
851
        this.inViewportChildren = virtualView.inViewportChildren;
×
852
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
853
        this.inViewportIndics = virtualView.visibleIndexes;
×
854
    }
855

856
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
857
        if (!this.inViewportChildren.length) {
×
858
            return {
×
859
                isDifferent: true,
860
                changedIndexesOfTop: [],
861
                changedIndexesOfBottom: []
862
            };
863
        }
864
        const oldIndexesInViewport = [...this.inViewportIndics];
×
865
        const newIndexesInViewport = [...virtualView.visibleIndexes];
×
866
        const firstNewIndex = newIndexesInViewport[0];
×
867
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
868
        const firstOldIndex = oldIndexesInViewport[0];
×
869
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
870
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
871
            const changedIndexesOfTop = [];
×
872
            const changedIndexesOfBottom = [];
×
873
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
874
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
875
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
876
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
877
            if (needRemoveOnTop || needAddOnBottom) {
×
878
                // 向下
879
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
880
                    const element = oldIndexesInViewport[index];
×
881
                    if (!newIndexesInViewport.includes(element)) {
×
882
                        changedIndexesOfTop.push(element);
×
883
                    } else {
884
                        break;
×
885
                    }
886
                }
887
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
888
                    const element = newIndexesInViewport[index];
×
889
                    if (!oldIndexesInViewport.includes(element)) {
×
890
                        changedIndexesOfBottom.push(element);
×
891
                    } else {
892
                        break;
×
893
                    }
894
                }
895
            } else if (needAddOnTop || needRemoveOnBottom) {
×
896
                // 向上
897
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
898
                    const element = newIndexesInViewport[index];
×
899
                    if (!oldIndexesInViewport.includes(element)) {
×
900
                        changedIndexesOfTop.push(element);
×
901
                    } else {
902
                        break;
×
903
                    }
904
                }
905
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
906
                    const element = oldIndexesInViewport[index];
×
907
                    if (!newIndexesInViewport.includes(element)) {
×
908
                        changedIndexesOfBottom.push(element);
×
909
                    } else {
910
                        break;
×
911
                    }
912
                }
913
            }
914
            if (isDebug) {
×
NEW
915
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
NEW
916
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
NEW
917
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
NEW
918
                debugLog(
×
919
                    'log',
920
                    'changedIndexesOfTop:',
921
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
922
                    changedIndexesOfTop,
923
                    changedIndexesOfTop.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
924
                );
NEW
925
                debugLog(
×
926
                    'log',
927
                    'changedIndexesOfBottom:',
928
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
929
                    changedIndexesOfBottom,
930
                    changedIndexesOfBottom.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
931
                );
932
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
933
                const needBottom = virtualView.heights
×
934
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
935
                    .reduce((acc, height) => acc + height, 0);
×
NEW
936
                debugLog(
×
937
                    'log',
938
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
939
                    'newTopHeight:',
940
                    needTop,
941
                    'prevTopHeight:',
942
                    parseFloat(this.virtualTopHeightElement.style.height)
943
                );
NEW
944
                debugLog(
×
945
                    'log',
946
                    'newBottomHeight:',
947
                    needBottom,
948
                    'prevBottomHeight:',
949
                    parseFloat(this.virtualBottomHeightElement.style.height)
950
                );
NEW
951
                debugLog('warn', '=========== Dividing line ===========');
×
952
            }
953
            return {
×
954
                isDifferent: true,
955
                needRemoveOnTop,
956
                needAddOnTop,
957
                needRemoveOnBottom,
958
                needAddOnBottom,
959
                changedIndexesOfTop,
960
                changedIndexesOfBottom
961
            };
962
        }
963
        return {
×
964
            isDifferent: false,
965
            changedIndexesOfTop: [],
966
            changedIndexesOfBottom: []
967
        };
968
    }
969

970
    //#region event proxy
971
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
972
        this.manualListeners.push(
483✔
973
            this.renderer2.listen(target, eventName, (event: Event) => {
974
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
975
                if (beforeInputEvent) {
5!
976
                    this.onFallbackBeforeInput(beforeInputEvent);
×
977
                }
978
                listener(event);
5✔
979
            })
980
        );
981
    }
982

983
    private toSlateSelection() {
984
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
985
            try {
1✔
986
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
987
                const { activeElement } = root;
1✔
988
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
989
                const domSelection = (root as Document).getSelection();
1✔
990

991
                if (activeElement === el) {
1!
992
                    this.latestElement = activeElement;
1✔
993
                    IS_FOCUSED.set(this.editor, true);
1✔
994
                } else {
995
                    IS_FOCUSED.delete(this.editor);
×
996
                }
997

998
                if (!domSelection) {
1!
999
                    return Transforms.deselect(this.editor);
×
1000
                }
1001

1002
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1003
                const hasDomSelectionInEditor =
1004
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1005
                if (!hasDomSelectionInEditor) {
1!
1006
                    Transforms.deselect(this.editor);
×
1007
                    return;
×
1008
                }
1009

1010
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1011
                // for example, double-click the last cell of the table to select a non-editable DOM
1012
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1013
                if (range) {
1✔
1014
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1015
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1016
                            // force adjust DOMSelection
1017
                            this.toNativeSelection();
×
1018
                        }
1019
                    } else {
1020
                        Transforms.select(this.editor, range);
1✔
1021
                    }
1022
                }
1023
            } catch (error) {
1024
                this.editor.onError({
×
1025
                    code: SlateErrorCode.ToSlateSelectionError,
1026
                    nativeError: error
1027
                });
1028
            }
1029
        }
1030
    }
1031

1032
    private onDOMBeforeInput(
1033
        event: Event & {
1034
            inputType: string;
1035
            isComposing: boolean;
1036
            data: string | null;
1037
            dataTransfer: DataTransfer | null;
1038
            getTargetRanges(): DOMStaticRange[];
1039
        }
1040
    ) {
1041
        const editor = this.editor;
×
1042
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1043
        const { activeElement } = root;
×
1044
        const { selection } = editor;
×
1045
        const { inputType: type } = event;
×
1046
        const data = event.dataTransfer || event.data || undefined;
×
1047
        if (IS_ANDROID) {
×
1048
            let targetRange: Range | null = null;
×
1049
            let [nativeTargetRange] = event.getTargetRanges();
×
1050
            if (nativeTargetRange) {
×
1051
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1052
            }
1053
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1054
            // have to manually get the selection here to ensure it's up-to-date.
1055
            const window = AngularEditor.getWindow(editor);
×
1056
            const domSelection = window.getSelection();
×
1057
            if (!targetRange && domSelection) {
×
1058
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1059
            }
1060
            targetRange = targetRange ?? editor.selection;
×
1061
            if (type === 'insertCompositionText') {
×
1062
                if (data && data.toString().includes('\n')) {
×
1063
                    restoreDom(editor, () => {
×
1064
                        Editor.insertBreak(editor);
×
1065
                    });
1066
                } else {
1067
                    if (targetRange) {
×
1068
                        if (data) {
×
1069
                            restoreDom(editor, () => {
×
1070
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1071
                            });
1072
                        } else {
1073
                            restoreDom(editor, () => {
×
1074
                                Transforms.delete(editor, { at: targetRange });
×
1075
                            });
1076
                        }
1077
                    }
1078
                }
1079
                return;
×
1080
            }
1081
            if (type === 'deleteContentBackward') {
×
1082
                // gboard can not prevent default action, so must use restoreDom,
1083
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1084
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1085
                if (!Range.isCollapsed(targetRange)) {
×
1086
                    restoreDom(editor, () => {
×
1087
                        Transforms.delete(editor, { at: targetRange });
×
1088
                    });
1089
                    return;
×
1090
                }
1091
            }
1092
            if (type === 'insertText') {
×
1093
                restoreDom(editor, () => {
×
1094
                    if (typeof data === 'string') {
×
1095
                        Editor.insertText(editor, data);
×
1096
                    }
1097
                });
1098
                return;
×
1099
            }
1100
        }
1101
        if (
×
1102
            !this.readonly &&
×
1103
            AngularEditor.hasEditableTarget(editor, event.target) &&
1104
            !isTargetInsideVoid(editor, activeElement) &&
1105
            !this.isDOMEventHandled(event, this.beforeInput)
1106
        ) {
1107
            try {
×
1108
                event.preventDefault();
×
1109

1110
                // COMPAT: If the selection is expanded, even if the command seems like
1111
                // a delete forward/backward command it should delete the selection.
1112
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1113
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1114
                    Editor.deleteFragment(editor, { direction });
×
1115
                    return;
×
1116
                }
1117

1118
                switch (type) {
×
1119
                    case 'deleteByComposition':
1120
                    case 'deleteByCut':
1121
                    case 'deleteByDrag': {
1122
                        Editor.deleteFragment(editor);
×
1123
                        break;
×
1124
                    }
1125

1126
                    case 'deleteContent':
1127
                    case 'deleteContentForward': {
1128
                        Editor.deleteForward(editor);
×
1129
                        break;
×
1130
                    }
1131

1132
                    case 'deleteContentBackward': {
1133
                        Editor.deleteBackward(editor);
×
1134
                        break;
×
1135
                    }
1136

1137
                    case 'deleteEntireSoftLine': {
1138
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1139
                        Editor.deleteForward(editor, { unit: 'line' });
×
1140
                        break;
×
1141
                    }
1142

1143
                    case 'deleteHardLineBackward': {
1144
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1145
                        break;
×
1146
                    }
1147

1148
                    case 'deleteSoftLineBackward': {
1149
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1150
                        break;
×
1151
                    }
1152

1153
                    case 'deleteHardLineForward': {
1154
                        Editor.deleteForward(editor, { unit: 'block' });
×
1155
                        break;
×
1156
                    }
1157

1158
                    case 'deleteSoftLineForward': {
1159
                        Editor.deleteForward(editor, { unit: 'line' });
×
1160
                        break;
×
1161
                    }
1162

1163
                    case 'deleteWordBackward': {
1164
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1165
                        break;
×
1166
                    }
1167

1168
                    case 'deleteWordForward': {
1169
                        Editor.deleteForward(editor, { unit: 'word' });
×
1170
                        break;
×
1171
                    }
1172

1173
                    case 'insertLineBreak':
1174
                    case 'insertParagraph': {
1175
                        Editor.insertBreak(editor);
×
1176
                        break;
×
1177
                    }
1178

1179
                    case 'insertFromComposition': {
1180
                        // COMPAT: in safari, `compositionend` event is dispatched after
1181
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1182
                        // https://www.w3.org/TR/input-events-2/
1183
                        // so the following code is the right logic
1184
                        // because DOM selection in sync will be exec before `compositionend` event
1185
                        // isComposing is true will prevent DOM selection being update correctly.
1186
                        this.isComposing = false;
×
1187
                        preventInsertFromComposition(event, this.editor);
×
1188
                    }
1189
                    case 'insertFromDrop':
1190
                    case 'insertFromPaste':
1191
                    case 'insertFromYank':
1192
                    case 'insertReplacementText':
1193
                    case 'insertText': {
1194
                        // use a weak comparison instead of 'instanceof' to allow
1195
                        // programmatic access of paste events coming from external windows
1196
                        // like cypress where cy.window does not work realibly
1197
                        if (data?.constructor.name === 'DataTransfer') {
×
1198
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1199
                        } else if (typeof data === 'string') {
×
1200
                            Editor.insertText(editor, data);
×
1201
                        }
1202
                        break;
×
1203
                    }
1204
                }
1205
            } catch (error) {
1206
                this.editor.onError({
×
1207
                    code: SlateErrorCode.OnDOMBeforeInputError,
1208
                    nativeError: error
1209
                });
1210
            }
1211
        }
1212
    }
1213

1214
    private onDOMBlur(event: FocusEvent) {
1215
        if (
×
1216
            this.readonly ||
×
1217
            this.isUpdatingSelection ||
1218
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1219
            this.isDOMEventHandled(event, this.blur)
1220
        ) {
1221
            return;
×
1222
        }
1223

1224
        const window = AngularEditor.getWindow(this.editor);
×
1225

1226
        // COMPAT: If the current `activeElement` is still the previous
1227
        // one, this is due to the window being blurred when the tab
1228
        // itself becomes unfocused, so we want to abort early to allow to
1229
        // editor to stay focused when the tab becomes focused again.
1230
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1231
        if (this.latestElement === root.activeElement) {
×
1232
            return;
×
1233
        }
1234

1235
        const { relatedTarget } = event;
×
1236
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1237

1238
        // COMPAT: The event should be ignored if the focus is returning
1239
        // to the editor from an embedded editable element (eg. an <input>
1240
        // element inside a void node).
1241
        if (relatedTarget === el) {
×
1242
            return;
×
1243
        }
1244

1245
        // COMPAT: The event should be ignored if the focus is moving from
1246
        // the editor to inside a void node's spacer element.
1247
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1248
            return;
×
1249
        }
1250

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

1257
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1258
                return;
×
1259
            }
1260
        }
1261

1262
        IS_FOCUSED.delete(this.editor);
×
1263
    }
1264

1265
    private onDOMClick(event: MouseEvent) {
1266
        if (
×
1267
            !this.readonly &&
×
1268
            AngularEditor.hasTarget(this.editor, event.target) &&
1269
            !this.isDOMEventHandled(event, this.click) &&
1270
            isDOMNode(event.target)
1271
        ) {
1272
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1273
            const path = AngularEditor.findPath(this.editor, node);
×
1274
            const start = Editor.start(this.editor, path);
×
1275
            const end = Editor.end(this.editor, path);
×
1276

1277
            const startVoid = Editor.void(this.editor, { at: start });
×
1278
            const endVoid = Editor.void(this.editor, { at: end });
×
1279

1280
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1281
                let blockPath = path;
×
1282
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1283
                    const block = Editor.above(this.editor, {
×
1284
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1285
                        at: path
1286
                    });
1287

1288
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1289
                }
1290

1291
                const range = Editor.range(this.editor, blockPath);
×
1292
                Transforms.select(this.editor, range);
×
1293
                return;
×
1294
            }
1295

1296
            if (
×
1297
                startVoid &&
×
1298
                endVoid &&
1299
                Path.equals(startVoid[1], endVoid[1]) &&
1300
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1301
            ) {
1302
                const range = Editor.range(this.editor, start);
×
1303
                Transforms.select(this.editor, range);
×
1304
            }
1305
        }
1306
    }
1307

1308
    private onDOMCompositionStart(event: CompositionEvent) {
1309
        const { selection } = this.editor;
1✔
1310
        if (selection) {
1!
1311
            // solve the problem of cross node Chinese input
1312
            if (Range.isExpanded(selection)) {
×
1313
                Editor.deleteFragment(this.editor);
×
1314
                this.forceRender();
×
1315
            }
1316
        }
1317
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1318
            this.isComposing = true;
1✔
1319
        }
1320
        this.render();
1✔
1321
    }
1322

1323
    private onDOMCompositionUpdate(event: CompositionEvent) {
1324
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1325
    }
1326

1327
    private onDOMCompositionEnd(event: CompositionEvent) {
1328
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1329
            Transforms.delete(this.editor);
×
1330
        }
1331
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1332
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1333
            // aren't correct and never fire the "insertFromComposition"
1334
            // type that we need. So instead, insert whenever a composition
1335
            // ends since it will already have been committed to the DOM.
1336
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1337
                preventInsertFromComposition(event, this.editor);
×
1338
                Editor.insertText(this.editor, event.data);
×
1339
            }
1340

1341
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1342
            // so we need avoid repeat isnertText by isComposing === true,
1343
            this.isComposing = false;
×
1344
        }
1345
        this.render();
×
1346
    }
1347

1348
    private onDOMCopy(event: ClipboardEvent) {
1349
        const window = AngularEditor.getWindow(this.editor);
×
1350
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1351
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1352
            event.preventDefault();
×
1353
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1354
        }
1355
    }
1356

1357
    private onDOMCut(event: ClipboardEvent) {
1358
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1359
            event.preventDefault();
×
1360
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1361
            const { selection } = this.editor;
×
1362

1363
            if (selection) {
×
1364
                AngularEditor.deleteCutData(this.editor);
×
1365
            }
1366
        }
1367
    }
1368

1369
    private onDOMDragOver(event: DragEvent) {
1370
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1371
            // Only when the target is void, call `preventDefault` to signal
1372
            // that drops are allowed. Editable content is droppable by
1373
            // default, and calling `preventDefault` hides the cursor.
1374
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1375

1376
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1377
                event.preventDefault();
×
1378
            }
1379
        }
1380
    }
1381

1382
    private onDOMDragStart(event: DragEvent) {
1383
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1384
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1385
            const path = AngularEditor.findPath(this.editor, node);
×
1386
            const voidMatch =
1387
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1388

1389
            // If starting a drag on a void node, make sure it is selected
1390
            // so that it shows up in the selection's fragment.
1391
            if (voidMatch) {
×
1392
                const range = Editor.range(this.editor, path);
×
1393
                Transforms.select(this.editor, range);
×
1394
            }
1395

1396
            this.isDraggingInternally = true;
×
1397

1398
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1399
        }
1400
    }
1401

1402
    private onDOMDrop(event: DragEvent) {
1403
        const editor = this.editor;
×
1404
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1405
            event.preventDefault();
×
1406
            // Keep a reference to the dragged range before updating selection
1407
            const draggedRange = editor.selection;
×
1408

1409
            // Find the range where the drop happened
1410
            const range = AngularEditor.findEventRange(editor, event);
×
1411
            const data = event.dataTransfer;
×
1412

1413
            Transforms.select(editor, range);
×
1414

1415
            if (this.isDraggingInternally) {
×
1416
                if (draggedRange) {
×
1417
                    Transforms.delete(editor, {
×
1418
                        at: draggedRange
1419
                    });
1420
                }
1421

1422
                this.isDraggingInternally = false;
×
1423
            }
1424

1425
            AngularEditor.insertData(editor, data);
×
1426

1427
            // When dragging from another source into the editor, it's possible
1428
            // that the current editor does not have focus.
1429
            if (!AngularEditor.isFocused(editor)) {
×
1430
                AngularEditor.focus(editor);
×
1431
            }
1432
        }
1433
    }
1434

1435
    private onDOMDragEnd(event: DragEvent) {
1436
        if (
×
1437
            !this.readonly &&
×
1438
            this.isDraggingInternally &&
1439
            AngularEditor.hasTarget(this.editor, event.target) &&
1440
            !this.isDOMEventHandled(event, this.dragEnd)
1441
        ) {
1442
            this.isDraggingInternally = false;
×
1443
        }
1444
    }
1445

1446
    private onDOMFocus(event: Event) {
1447
        if (
2✔
1448
            !this.readonly &&
8✔
1449
            !this.isUpdatingSelection &&
1450
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1451
            !this.isDOMEventHandled(event, this.focus)
1452
        ) {
1453
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1454
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1455
            this.latestElement = root.activeElement;
2✔
1456

1457
            // COMPAT: If the editor has nested editable elements, the focus
1458
            // can go to them. In Firefox, this must be prevented because it
1459
            // results in issues with keyboard navigation. (2017/03/30)
1460
            if (IS_FIREFOX && event.target !== el) {
2!
1461
                el.focus();
×
1462
                return;
×
1463
            }
1464

1465
            IS_FOCUSED.set(this.editor, true);
2✔
1466
        }
1467
    }
1468

1469
    private onDOMKeydown(event: KeyboardEvent) {
1470
        const editor = this.editor;
×
1471
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1472
        const { activeElement } = root;
×
1473
        if (
×
1474
            !this.readonly &&
×
1475
            AngularEditor.hasEditableTarget(editor, event.target) &&
1476
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1477
            !this.isComposing &&
1478
            !this.isDOMEventHandled(event, this.keydown)
1479
        ) {
1480
            const nativeEvent = event;
×
1481
            const { selection } = editor;
×
1482

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

1486
            try {
×
1487
                // COMPAT: Since we prevent the default behavior on
1488
                // `beforeinput` events, the browser doesn't think there's ever
1489
                // any history stack to undo or redo, so we have to manage these
1490
                // hotkeys ourselves. (2019/11/06)
1491
                if (Hotkeys.isRedo(nativeEvent)) {
×
1492
                    event.preventDefault();
×
1493

1494
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1495
                        editor.redo();
×
1496
                    }
1497

1498
                    return;
×
1499
                }
1500

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

1504
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1505
                        editor.undo();
×
1506
                    }
1507

1508
                    return;
×
1509
                }
1510

1511
                // COMPAT: Certain browsers don't handle the selection updates
1512
                // properly. In Chrome, the selection isn't properly extended.
1513
                // And in Firefox, the selection isn't properly collapsed.
1514
                // (2017/10/17)
1515
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1516
                    event.preventDefault();
×
1517
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1518
                    return;
×
1519
                }
1520

1521
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1522
                    event.preventDefault();
×
1523
                    Transforms.move(editor, { unit: 'line' });
×
1524
                    return;
×
1525
                }
1526

1527
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1528
                    event.preventDefault();
×
1529
                    Transforms.move(editor, {
×
1530
                        unit: 'line',
1531
                        edge: 'focus',
1532
                        reverse: true
1533
                    });
1534
                    return;
×
1535
                }
1536

1537
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1538
                    event.preventDefault();
×
1539
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1540
                    return;
×
1541
                }
1542

1543
                // COMPAT: If a void node is selected, or a zero-width text node
1544
                // adjacent to an inline is selected, we need to handle these
1545
                // hotkeys manually because browsers won't be able to skip over
1546
                // the void node with the zero-width space not being an empty
1547
                // string.
1548
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1549
                    event.preventDefault();
×
1550

1551
                    if (selection && Range.isCollapsed(selection)) {
×
1552
                        Transforms.move(editor, { reverse: !isRTL });
×
1553
                    } else {
1554
                        Transforms.collapse(editor, { edge: 'start' });
×
1555
                    }
1556

1557
                    return;
×
1558
                }
1559

1560
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1561
                    event.preventDefault();
×
1562
                    if (selection && Range.isCollapsed(selection)) {
×
1563
                        Transforms.move(editor, { reverse: isRTL });
×
1564
                    } else {
1565
                        Transforms.collapse(editor, { edge: 'end' });
×
1566
                    }
1567

1568
                    return;
×
1569
                }
1570

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

1574
                    if (selection && Range.isExpanded(selection)) {
×
1575
                        Transforms.collapse(editor, { edge: 'focus' });
×
1576
                    }
1577

1578
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1579
                    return;
×
1580
                }
1581

1582
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1583
                    event.preventDefault();
×
1584

1585
                    if (selection && Range.isExpanded(selection)) {
×
1586
                        Transforms.collapse(editor, { edge: 'focus' });
×
1587
                    }
1588

1589
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1590
                    return;
×
1591
                }
1592

1593
                if (isKeyHotkey('mod+a', event)) {
×
1594
                    this.editor.selectAll();
×
1595
                    event.preventDefault();
×
1596
                    return;
×
1597
                }
1598

1599
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1600
                // fall back to guessing at the input intention for hotkeys.
1601
                // COMPAT: In iOS, some of these hotkeys are handled in the
1602
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1603
                    // We don't have a core behavior for these, but they change the
1604
                    // DOM if we don't prevent them, so we have to.
1605
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1606
                        event.preventDefault();
×
1607
                        return;
×
1608
                    }
1609

1610
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1611
                        event.preventDefault();
×
1612
                        Editor.insertBreak(editor);
×
1613
                        return;
×
1614
                    }
1615

1616
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1617
                        event.preventDefault();
×
1618

1619
                        if (selection && Range.isExpanded(selection)) {
×
1620
                            Editor.deleteFragment(editor, {
×
1621
                                direction: 'backward'
1622
                            });
1623
                        } else {
1624
                            Editor.deleteBackward(editor);
×
1625
                        }
1626

1627
                        return;
×
1628
                    }
1629

1630
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1631
                        event.preventDefault();
×
1632

1633
                        if (selection && Range.isExpanded(selection)) {
×
1634
                            Editor.deleteFragment(editor, {
×
1635
                                direction: 'forward'
1636
                            });
1637
                        } else {
1638
                            Editor.deleteForward(editor);
×
1639
                        }
1640

1641
                        return;
×
1642
                    }
1643

1644
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1645
                        event.preventDefault();
×
1646

1647
                        if (selection && Range.isExpanded(selection)) {
×
1648
                            Editor.deleteFragment(editor, {
×
1649
                                direction: 'backward'
1650
                            });
1651
                        } else {
1652
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1653
                        }
1654

1655
                        return;
×
1656
                    }
1657

1658
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1659
                        event.preventDefault();
×
1660

1661
                        if (selection && Range.isExpanded(selection)) {
×
1662
                            Editor.deleteFragment(editor, {
×
1663
                                direction: 'forward'
1664
                            });
1665
                        } else {
1666
                            Editor.deleteForward(editor, { unit: 'line' });
×
1667
                        }
1668

1669
                        return;
×
1670
                    }
1671

1672
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1673
                        event.preventDefault();
×
1674

1675
                        if (selection && Range.isExpanded(selection)) {
×
1676
                            Editor.deleteFragment(editor, {
×
1677
                                direction: 'backward'
1678
                            });
1679
                        } else {
1680
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1681
                        }
1682

1683
                        return;
×
1684
                    }
1685

1686
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1687
                        event.preventDefault();
×
1688

1689
                        if (selection && Range.isExpanded(selection)) {
×
1690
                            Editor.deleteFragment(editor, {
×
1691
                                direction: 'forward'
1692
                            });
1693
                        } else {
1694
                            Editor.deleteForward(editor, { unit: 'word' });
×
1695
                        }
1696

1697
                        return;
×
1698
                    }
1699
                } else {
1700
                    if (IS_CHROME || IS_SAFARI) {
×
1701
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1702
                        // an event when deleting backwards in a selected void inline node
1703
                        if (
×
1704
                            selection &&
×
1705
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1706
                            Range.isCollapsed(selection)
1707
                        ) {
1708
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1709
                            if (
×
1710
                                Element.isElement(currentNode) &&
×
1711
                                Editor.isVoid(editor, currentNode) &&
1712
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1713
                            ) {
1714
                                event.preventDefault();
×
1715
                                Editor.deleteBackward(editor, {
×
1716
                                    unit: 'block'
1717
                                });
1718
                                return;
×
1719
                            }
1720
                        }
1721
                    }
1722
                }
1723
            } catch (error) {
1724
                this.editor.onError({
×
1725
                    code: SlateErrorCode.OnDOMKeydownError,
1726
                    nativeError: error
1727
                });
1728
            }
1729
        }
1730
    }
1731

1732
    private onDOMPaste(event: ClipboardEvent) {
1733
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1734
        // fall back to React's `onPaste` here instead.
1735
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1736
        // when "paste without formatting" option is used.
1737
        // This unfortunately needs to be handled with paste events instead.
1738
        if (
×
1739
            !this.isDOMEventHandled(event, this.paste) &&
×
1740
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1741
            !this.readonly &&
1742
            AngularEditor.hasEditableTarget(this.editor, event.target)
1743
        ) {
1744
            event.preventDefault();
×
1745
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1746
        }
1747
    }
1748

1749
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1750
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1751
        // fall back to React's leaky polyfill instead just for it. It
1752
        // only works for the `insertText` input type.
1753
        if (
×
1754
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1755
            !this.readonly &&
1756
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1757
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1758
        ) {
1759
            event.nativeEvent.preventDefault();
×
1760
            try {
×
1761
                const text = event.data;
×
1762
                if (!Range.isCollapsed(this.editor.selection)) {
×
1763
                    Editor.deleteFragment(this.editor);
×
1764
                }
1765
                // just handle Non-IME input
1766
                if (!this.isComposing) {
×
1767
                    Editor.insertText(this.editor, text);
×
1768
                }
1769
            } catch (error) {
1770
                this.editor.onError({
×
1771
                    code: SlateErrorCode.ToNativeSelectionError,
1772
                    nativeError: error
1773
                });
1774
            }
1775
        }
1776
    }
1777

1778
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1779
        if (!handler) {
3✔
1780
            return false;
3✔
1781
        }
1782
        handler(event);
×
1783
        return event.defaultPrevented;
×
1784
    }
1785
    //#endregion
1786

1787
    ngOnDestroy() {
1788
        this.editorResizeObserver?.disconnect();
23✔
1789
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1790
        this.manualListeners.forEach(manualListener => {
23✔
1791
            manualListener();
483✔
1792
        });
1793
        this.destroy$.complete();
23✔
1794
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1795
    }
1796
}
1797

1798
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1799
    // This was affecting the selection of multiple blocks and dragging behavior,
1800
    // so enabled only if the selection has been collapsed.
1801
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1802
        const leafEl = domRange.startContainer.parentElement!;
×
1803

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

1809
        if (isZeroDimensionRect) {
×
1810
            const leafRect = leafEl.getBoundingClientRect();
×
1811
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1812

1813
            if (leafHasDimensions) {
×
1814
                return;
×
1815
            }
1816
        }
1817

1818
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1819
        scrollIntoView(leafEl, {
×
1820
            scrollMode: 'if-needed'
1821
        });
1822
        delete leafEl.getBoundingClientRect;
×
1823
    }
1824
};
1825

1826
/**
1827
 * Check if the target is inside void and in the editor.
1828
 */
1829

1830
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1831
    let slateNode: Node | null = null;
1✔
1832
    try {
1✔
1833
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1834
    } catch (error) {}
1835
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1836
};
1837

1838
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1839
    return (
2✔
1840
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1841
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1842
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1843
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1844
    );
1845
};
1846

1847
/**
1848
 * remove default insert from composition
1849
 * @param text
1850
 */
1851
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1852
    const types = ['compositionend', 'insertFromComposition'];
×
1853
    if (!types.includes(event.type)) {
×
1854
        return;
×
1855
    }
1856
    const insertText = (event as CompositionEvent).data;
×
1857
    const window = AngularEditor.getWindow(editor);
×
1858
    const domSelection = window.getSelection();
×
1859
    // ensure text node insert composition input text
1860
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1861
        const textNode = domSelection.anchorNode;
×
1862
        textNode.splitText(textNode.length - insertText.length).remove();
×
1863
    }
1864
};
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