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

worktile / slate-angular / 89c6c773-c37c-41f9-99ac-aa880f3a24f1

19 Dec 2025 03:35AM UTC coverage: 36.878%. Remained the same
89c6c773-c37c-41f9-99ac-aa880f3a24f1

push

circleci

pubuzhixing8
fix(virtual-scroll): remove business top when calculate view bottom

380 of 1237 branches covered (30.72%)

Branch coverage included in aggregate %.

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

1073 of 2703 relevant lines covered (39.7%)

24.06 hits per line

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

22.22
/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
    ELEMENT_TO_COMPONENT,
65
    getBusinessTop,
66
    getRealHeightByElement,
67
    IS_ENABLED_VIRTUAL_SCROLL,
68
    isDecoratorRangeListEqual
69
} from '../../utils';
70
import { SlatePlaceholder } from '../../types/feature';
71
import { restoreDom } from '../../utils/restore-dom';
72
import { ListRender } from '../../view/render/list-render';
73
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
74
import { BaseElementComponent } from '../../view/base';
75
import { BaseElementFlavour } from '../../view/flavour/element';
76
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
77
import { isKeyHotkey } from 'is-hotkey';
78
import { VirtualScrollDebugOverlay } from './debug';
79

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

83
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
1✔
84
const isDebugScrollTop = localStorage.getItem(SLATE_DEBUG_KEY_SCROLL_TOP) === 'true';
1✔
85

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

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

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

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

120
    private initialized: boolean;
121

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

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

126
    @Input() editor: AngularEditor;
127

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

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

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

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

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

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

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

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

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

146
    @Input() placeholder: string;
147

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

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

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

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

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

192
    viewContainerRef = inject(ViewContainerRef);
23✔
193

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

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

206
    listRender: ListRender;
207

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

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

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

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

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

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

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

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

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

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

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

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

386
            const hasDomSelection = domSelection.type !== 'None';
1✔
387

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

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

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

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

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

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

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

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

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

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

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

482
    ngAfterViewChecked() {}
483

484
    ngDoCheck() {}
485

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

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

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

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

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

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

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

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

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

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

630
    virtualScrollInitialized = false;
23✔
631

632
    virtualTopHeightElement: HTMLElement;
633

634
    virtualBottomHeightElement: HTMLElement;
635

636
    virtualCenterOutlet: HTMLElement;
637

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

672
    setVirtualSpaceHeight(topHeight: number, bottomHeight: number) {
673
        if (!this.virtualScrollInitialized) {
×
674
            return;
×
675
        }
676
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
677
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
678
    }
679

680
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
681
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
682
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
683
    }
684

685
    private tryUpdateVirtualViewport() {
686
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
687
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
688
            let virtualView = this.calculateVirtualViewport();
×
689
            let diff = this.diffVirtualViewport(virtualView);
×
690
            if (!diff.isDiff) {
×
691
                return;
×
692
            }
693
            // diff.isAddedTop
694
            if (diff.isMissingTop) {
×
695
                const remeasureIndics = diff.diffTopRenderedIndexes;
×
696
                const result = this.remeasureHeightByIndics(remeasureIndics);
×
697
                if (result) {
×
698
                    virtualView = this.calculateVirtualViewport();
×
699
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
700
                    if (!diff.isDiff) {
×
701
                        return;
×
702
                    }
703
                }
704
            }
705
            this.applyVirtualView(virtualView);
×
706
            if (this.listRender.initialized) {
×
707
                this.listRender.update(virtualView.inViewportChildren, this.editor, this.context);
×
708
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
709
                    this.toNativeSelection();
×
710
                }
711
            }
712
            if (diff.isAddedTop) {
×
713
                const remeasureAddedIndics = diff.diffTopRenderedIndexes;
×
714
                if (isDebug) {
×
715
                    this.debugLog('log', 'isAddedTop to remeasure heights: ', remeasureAddedIndics);
×
716
                }
717
                const startIndexBeforeAdd = diff.diffTopRenderedIndexes[diff.diffTopRenderedIndexes.length - 1] + 1;
×
718
                const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
719
                const result = this.remeasureHeightByIndics(remeasureAddedIndics);
×
720
                if (result) {
×
721
                    const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
722
                    const visibleStartIndex = diff.diffTopRenderedIndexes[0];
×
723
                    const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
724
                    const adjustedTopHeight =
725
                        (visibleStartIndex === -1 ? 0 : newHeights.accumulatedHeights[visibleStartIndex]) -
×
726
                        (actualTopHeightAfterAdd - topHeightBeforeAdd);
727
                    if (adjustedTopHeight !== virtualView.top) {
×
728
                        if (isDebug) {
×
729
                            this.debugLog(
×
730
                                'log',
731
                                `update top height cause added element in top: ${adjustedTopHeight}, old height: ${virtualView.top}`
732
                            );
733
                        }
734
                        this.virtualTopHeightElement.style.height = `${adjustedTopHeight}px`;
×
735
                    }
736
                }
737
            }
738
            this.tryMeasureInViewportChildrenHeights();
×
739
        });
740
    }
741

742
    private calculateVirtualViewport() {
743
        const children = (this.editor.children || []) as Element[];
×
744
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
745
            return {
×
746
                inViewportChildren: children,
747
                visibleIndexes: new Set<number>(),
748
                top: 0,
749
                bottom: 0,
750
                heights: []
751
            };
752
        }
753
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
754
        if (isDebug) {
×
755
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
756
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
757
        }
758
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
759
        if (!viewportHeight) {
×
760
            return {
×
761
                inViewportChildren: [],
762
                visibleIndexes: new Set<number>(),
763
                top: 0,
764
                bottom: 0,
765
                heights: []
766
            };
767
        }
768
        const elementLength = children.length;
×
769
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
770
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
771
            setTimeout(() => {
×
772
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
773
                const businessTop =
774
                    Math.ceil(virtualTopBoundingTop) +
×
775
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
776
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
777
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
778
                if (isDebug) {
×
779
                    this.debugLog('log', 'businessTop', businessTop);
×
780
                }
781
            }, 100);
782
        }
783
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
784
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor);
×
785
        const totalHeight = accumulatedHeights[elementLength];
×
786
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
787
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
NEW
788
        const viewBottom = limitedScrollTop + viewportHeight;
×
789
        let accumulatedOffset = 0;
×
790
        let visibleStartIndex = -1;
×
791
        const visible: Element[] = [];
×
792
        const visibleIndexes: number[] = [];
×
793

794
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
795
            const currentHeight = heights[i];
×
796
            const nextOffset = accumulatedOffset + currentHeight;
×
797
            // 可视区域有交集,加入渲染
798
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
799
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
800
                visible.push(children[i]);
×
801
                visibleIndexes.push(i);
×
802
            }
803
            accumulatedOffset = nextOffset;
×
804
        }
805

806
        if (visibleStartIndex === -1 && elementLength) {
×
807
            visibleStartIndex = elementLength - 1;
×
808
            visible.push(children[visibleStartIndex]);
×
809
            visibleIndexes.push(visibleStartIndex);
×
810
        }
811

812
        const visibleEndIndex =
813
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
814
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
815
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
816

817
        return {
×
818
            inViewportChildren: visible.length ? visible : children,
×
819
            visibleIndexes: new Set(visibleIndexes),
820
            top,
821
            bottom,
822
            heights,
823
            accumulatedHeights
824
        };
825
    }
826

827
    private applyVirtualView(virtualView: VirtualViewResult) {
828
        this.inViewportChildren = virtualView.inViewportChildren;
×
829
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
830
        this.inViewportIndics = virtualView.visibleIndexes;
×
831
    }
832

833
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
834
        if (!this.inViewportChildren.length) {
×
835
            return {
×
836
                isDiff: true,
837
                diffTopRenderedIndexes: [],
838
                diffBottomRenderedIndexes: []
839
            };
840
        }
841
        const oldVisibleIndexes = [...this.inViewportIndics];
×
842
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
843
        const firstNewIndex = newVisibleIndexes[0];
×
844
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
845
        const firstOldIndex = oldVisibleIndexes[0];
×
846
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
847
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
848
            const diffTopRenderedIndexes = [];
×
849
            const diffBottomRenderedIndexes = [];
×
850
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
851
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
852
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
853
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
854
            if (isMissingTop || isAddedBottom) {
×
855
                // 向下
856
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
857
                    const element = oldVisibleIndexes[index];
×
858
                    if (!newVisibleIndexes.includes(element)) {
×
859
                        diffTopRenderedIndexes.push(element);
×
860
                    } else {
861
                        break;
×
862
                    }
863
                }
864
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
865
                    const element = newVisibleIndexes[index];
×
866
                    if (!oldVisibleIndexes.includes(element)) {
×
867
                        diffBottomRenderedIndexes.push(element);
×
868
                    } else {
869
                        break;
×
870
                    }
871
                }
872
            } else if (isAddedTop || isMissingBottom) {
×
873
                // 向上
874
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
875
                    const element = newVisibleIndexes[index];
×
876
                    if (!oldVisibleIndexes.includes(element)) {
×
877
                        diffTopRenderedIndexes.push(element);
×
878
                    } else {
879
                        break;
×
880
                    }
881
                }
882
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
883
                    const element = oldVisibleIndexes[index];
×
884
                    if (!newVisibleIndexes.includes(element)) {
×
885
                        diffBottomRenderedIndexes.push(element);
×
886
                    } else {
887
                        break;
×
888
                    }
889
                }
890
            }
891
            if (isDebug) {
×
892
                this.debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
893
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
894
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
895
                this.debugLog(
×
896
                    'log',
897
                    'diffTopRenderedIndexes:',
898
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
899
                    diffTopRenderedIndexes,
900
                    diffTopRenderedIndexes.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
901
                );
902
                this.debugLog(
×
903
                    'log',
904
                    'diffBottomRenderedIndexes:',
905
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
906
                    diffBottomRenderedIndexes,
907
                    diffBottomRenderedIndexes.map(index => getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0))
×
908
                );
909
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
910
                const needBottom = virtualView.heights
×
911
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
912
                    .reduce((acc, height) => acc + height, 0);
×
913
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
914
                this.debugLog(
×
915
                    'log',
916
                    'newBottomHeight:',
917
                    needBottom,
918
                    'prevBottomHeight:',
919
                    parseFloat(this.virtualBottomHeightElement.style.height)
920
                );
921
                this.debugLog('warn', '=========== Dividing line ===========');
×
922
            }
923
            return {
×
924
                isDiff: true,
925
                isMissingTop,
926
                isAddedTop,
927
                isMissingBottom,
928
                isAddedBottom,
929
                diffTopRenderedIndexes,
930
                diffBottomRenderedIndexes
931
            };
932
        }
933
        return {
×
934
            isDiff: false,
935
            diffTopRenderedIndexes: [],
936
            diffBottomRenderedIndexes: []
937
        };
938
    }
939

940
    private tryMeasureInViewportChildrenHeights() {
941
        if (!this.isEnabledVirtualScroll()) {
×
942
            return;
×
943
        }
944
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
945
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
946
            this.measureVisibleHeights();
×
947
        });
948
    }
949

950
    private measureVisibleHeights() {
951
        const children = (this.editor.children || []) as Element[];
×
952
        this.inViewportIndics.forEach(index => {
×
953
            const node = children[index];
×
954
            if (!node) {
×
955
                return;
×
956
            }
957
            const key = AngularEditor.findKey(this.editor, node);
×
958
            // 跳过已测过的块,除非强制测量
959
            if (this.keyHeightMap.has(key.id)) {
×
960
                return;
×
961
            }
962
            const view = ELEMENT_TO_COMPONENT.get(node);
×
963
            if (!view) {
×
964
                return;
×
965
            }
966
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
967
            if (ret instanceof Promise) {
×
968
                ret.then(height => {
×
969
                    this.keyHeightMap.set(key.id, height);
×
970
                });
971
            } else {
972
                this.keyHeightMap.set(key.id, ret);
×
973
            }
974
        });
975
    }
976

977
    private remeasureHeightByIndics(indics: number[]): boolean {
978
        const children = (this.editor.children || []) as Element[];
×
979
        let isHeightChanged = false;
×
980
        indics.forEach((index, i) => {
×
981
            const node = children[index];
×
982
            if (!node) {
×
983
                return;
×
984
            }
985
            const key = AngularEditor.findKey(this.editor, node);
×
986
            const view = ELEMENT_TO_COMPONENT.get(node);
×
987
            if (!view) {
×
988
                return;
×
989
            }
990
            const prevHeight = this.keyHeightMap.get(key.id);
×
991
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
992
            if (ret instanceof Promise) {
×
993
                ret.then(height => {
×
994
                    this.keyHeightMap.set(key.id, height);
×
995
                    if (height !== prevHeight) {
×
996
                        isHeightChanged = true;
×
997
                        if (isDebug) {
×
998
                            this.debugLog(
×
999
                                'log',
1000
                                `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`
1001
                            );
1002
                        }
1003
                    }
1004
                });
1005
            } else {
1006
                this.keyHeightMap.set(key.id, ret);
×
1007
                if (ret !== prevHeight) {
×
1008
                    isHeightChanged = true;
×
1009
                    if (isDebug) {
×
1010
                        this.debugLog('log', `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
1011
                    }
1012
                }
1013
            }
1014
        });
1015
        return isHeightChanged;
×
1016
    }
1017

1018
    //#region event proxy
1019
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1020
        this.manualListeners.push(
483✔
1021
            this.renderer2.listen(target, eventName, (event: Event) => {
1022
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1023
                if (beforeInputEvent) {
5!
1024
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1025
                }
1026
                listener(event);
5✔
1027
            })
1028
        );
1029
    }
1030

1031
    private toSlateSelection() {
1032
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1033
            try {
1✔
1034
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1035
                const { activeElement } = root;
1✔
1036
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1037
                const domSelection = (root as Document).getSelection();
1✔
1038

1039
                if (activeElement === el) {
1!
1040
                    this.latestElement = activeElement;
1✔
1041
                    IS_FOCUSED.set(this.editor, true);
1✔
1042
                } else {
1043
                    IS_FOCUSED.delete(this.editor);
×
1044
                }
1045

1046
                if (!domSelection) {
1!
1047
                    return Transforms.deselect(this.editor);
×
1048
                }
1049

1050
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1051
                const hasDomSelectionInEditor =
1052
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1053
                if (!hasDomSelectionInEditor) {
1!
1054
                    Transforms.deselect(this.editor);
×
1055
                    return;
×
1056
                }
1057

1058
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1059
                // for example, double-click the last cell of the table to select a non-editable DOM
1060
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1061
                if (range) {
1✔
1062
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1063
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1064
                            // force adjust DOMSelection
1065
                            this.toNativeSelection();
×
1066
                        }
1067
                    } else {
1068
                        Transforms.select(this.editor, range);
1✔
1069
                    }
1070
                }
1071
            } catch (error) {
1072
                this.editor.onError({
×
1073
                    code: SlateErrorCode.ToSlateSelectionError,
1074
                    nativeError: error
1075
                });
1076
            }
1077
        }
1078
    }
1079

1080
    private onDOMBeforeInput(
1081
        event: Event & {
1082
            inputType: string;
1083
            isComposing: boolean;
1084
            data: string | null;
1085
            dataTransfer: DataTransfer | null;
1086
            getTargetRanges(): DOMStaticRange[];
1087
        }
1088
    ) {
1089
        const editor = this.editor;
×
1090
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1091
        const { activeElement } = root;
×
1092
        const { selection } = editor;
×
1093
        const { inputType: type } = event;
×
1094
        const data = event.dataTransfer || event.data || undefined;
×
1095
        if (IS_ANDROID) {
×
1096
            let targetRange: Range | null = null;
×
1097
            let [nativeTargetRange] = event.getTargetRanges();
×
1098
            if (nativeTargetRange) {
×
1099
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1100
            }
1101
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1102
            // have to manually get the selection here to ensure it's up-to-date.
1103
            const window = AngularEditor.getWindow(editor);
×
1104
            const domSelection = window.getSelection();
×
1105
            if (!targetRange && domSelection) {
×
1106
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1107
            }
1108
            targetRange = targetRange ?? editor.selection;
×
1109
            if (type === 'insertCompositionText') {
×
1110
                if (data && data.toString().includes('\n')) {
×
1111
                    restoreDom(editor, () => {
×
1112
                        Editor.insertBreak(editor);
×
1113
                    });
1114
                } else {
1115
                    if (targetRange) {
×
1116
                        if (data) {
×
1117
                            restoreDom(editor, () => {
×
1118
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1119
                            });
1120
                        } else {
1121
                            restoreDom(editor, () => {
×
1122
                                Transforms.delete(editor, { at: targetRange });
×
1123
                            });
1124
                        }
1125
                    }
1126
                }
1127
                return;
×
1128
            }
1129
            if (type === 'deleteContentBackward') {
×
1130
                // gboard can not prevent default action, so must use restoreDom,
1131
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1132
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1133
                if (!Range.isCollapsed(targetRange)) {
×
1134
                    restoreDom(editor, () => {
×
1135
                        Transforms.delete(editor, { at: targetRange });
×
1136
                    });
1137
                    return;
×
1138
                }
1139
            }
1140
            if (type === 'insertText') {
×
1141
                restoreDom(editor, () => {
×
1142
                    if (typeof data === 'string') {
×
1143
                        Editor.insertText(editor, data);
×
1144
                    }
1145
                });
1146
                return;
×
1147
            }
1148
        }
1149
        if (
×
1150
            !this.readonly &&
×
1151
            AngularEditor.hasEditableTarget(editor, event.target) &&
1152
            !isTargetInsideVoid(editor, activeElement) &&
1153
            !this.isDOMEventHandled(event, this.beforeInput)
1154
        ) {
1155
            try {
×
1156
                event.preventDefault();
×
1157

1158
                // COMPAT: If the selection is expanded, even if the command seems like
1159
                // a delete forward/backward command it should delete the selection.
1160
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1161
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1162
                    Editor.deleteFragment(editor, { direction });
×
1163
                    return;
×
1164
                }
1165

1166
                switch (type) {
×
1167
                    case 'deleteByComposition':
1168
                    case 'deleteByCut':
1169
                    case 'deleteByDrag': {
1170
                        Editor.deleteFragment(editor);
×
1171
                        break;
×
1172
                    }
1173

1174
                    case 'deleteContent':
1175
                    case 'deleteContentForward': {
1176
                        Editor.deleteForward(editor);
×
1177
                        break;
×
1178
                    }
1179

1180
                    case 'deleteContentBackward': {
1181
                        Editor.deleteBackward(editor);
×
1182
                        break;
×
1183
                    }
1184

1185
                    case 'deleteEntireSoftLine': {
1186
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1187
                        Editor.deleteForward(editor, { unit: 'line' });
×
1188
                        break;
×
1189
                    }
1190

1191
                    case 'deleteHardLineBackward': {
1192
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1193
                        break;
×
1194
                    }
1195

1196
                    case 'deleteSoftLineBackward': {
1197
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1198
                        break;
×
1199
                    }
1200

1201
                    case 'deleteHardLineForward': {
1202
                        Editor.deleteForward(editor, { unit: 'block' });
×
1203
                        break;
×
1204
                    }
1205

1206
                    case 'deleteSoftLineForward': {
1207
                        Editor.deleteForward(editor, { unit: 'line' });
×
1208
                        break;
×
1209
                    }
1210

1211
                    case 'deleteWordBackward': {
1212
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1213
                        break;
×
1214
                    }
1215

1216
                    case 'deleteWordForward': {
1217
                        Editor.deleteForward(editor, { unit: 'word' });
×
1218
                        break;
×
1219
                    }
1220

1221
                    case 'insertLineBreak':
1222
                    case 'insertParagraph': {
1223
                        Editor.insertBreak(editor);
×
1224
                        break;
×
1225
                    }
1226

1227
                    case 'insertFromComposition': {
1228
                        // COMPAT: in safari, `compositionend` event is dispatched after
1229
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1230
                        // https://www.w3.org/TR/input-events-2/
1231
                        // so the following code is the right logic
1232
                        // because DOM selection in sync will be exec before `compositionend` event
1233
                        // isComposing is true will prevent DOM selection being update correctly.
1234
                        this.isComposing = false;
×
1235
                        preventInsertFromComposition(event, this.editor);
×
1236
                    }
1237
                    case 'insertFromDrop':
1238
                    case 'insertFromPaste':
1239
                    case 'insertFromYank':
1240
                    case 'insertReplacementText':
1241
                    case 'insertText': {
1242
                        // use a weak comparison instead of 'instanceof' to allow
1243
                        // programmatic access of paste events coming from external windows
1244
                        // like cypress where cy.window does not work realibly
1245
                        if (data?.constructor.name === 'DataTransfer') {
×
1246
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1247
                        } else if (typeof data === 'string') {
×
1248
                            Editor.insertText(editor, data);
×
1249
                        }
1250
                        break;
×
1251
                    }
1252
                }
1253
            } catch (error) {
1254
                this.editor.onError({
×
1255
                    code: SlateErrorCode.OnDOMBeforeInputError,
1256
                    nativeError: error
1257
                });
1258
            }
1259
        }
1260
    }
1261

1262
    private onDOMBlur(event: FocusEvent) {
1263
        if (
×
1264
            this.readonly ||
×
1265
            this.isUpdatingSelection ||
1266
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1267
            this.isDOMEventHandled(event, this.blur)
1268
        ) {
1269
            return;
×
1270
        }
1271

1272
        const window = AngularEditor.getWindow(this.editor);
×
1273

1274
        // COMPAT: If the current `activeElement` is still the previous
1275
        // one, this is due to the window being blurred when the tab
1276
        // itself becomes unfocused, so we want to abort early to allow to
1277
        // editor to stay focused when the tab becomes focused again.
1278
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1279
        if (this.latestElement === root.activeElement) {
×
1280
            return;
×
1281
        }
1282

1283
        const { relatedTarget } = event;
×
1284
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1285

1286
        // COMPAT: The event should be ignored if the focus is returning
1287
        // to the editor from an embedded editable element (eg. an <input>
1288
        // element inside a void node).
1289
        if (relatedTarget === el) {
×
1290
            return;
×
1291
        }
1292

1293
        // COMPAT: The event should be ignored if the focus is moving from
1294
        // the editor to inside a void node's spacer element.
1295
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1296
            return;
×
1297
        }
1298

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

1305
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1306
                return;
×
1307
            }
1308
        }
1309

1310
        IS_FOCUSED.delete(this.editor);
×
1311
    }
1312

1313
    private onDOMClick(event: MouseEvent) {
1314
        if (
×
1315
            !this.readonly &&
×
1316
            AngularEditor.hasTarget(this.editor, event.target) &&
1317
            !this.isDOMEventHandled(event, this.click) &&
1318
            isDOMNode(event.target)
1319
        ) {
1320
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1321
            const path = AngularEditor.findPath(this.editor, node);
×
1322
            const start = Editor.start(this.editor, path);
×
1323
            const end = Editor.end(this.editor, path);
×
1324

1325
            const startVoid = Editor.void(this.editor, { at: start });
×
1326
            const endVoid = Editor.void(this.editor, { at: end });
×
1327

1328
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1329
                let blockPath = path;
×
1330
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1331
                    const block = Editor.above(this.editor, {
×
1332
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1333
                        at: path
1334
                    });
1335

1336
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1337
                }
1338

1339
                const range = Editor.range(this.editor, blockPath);
×
1340
                Transforms.select(this.editor, range);
×
1341
                return;
×
1342
            }
1343

1344
            if (
×
1345
                startVoid &&
×
1346
                endVoid &&
1347
                Path.equals(startVoid[1], endVoid[1]) &&
1348
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1349
            ) {
1350
                const range = Editor.range(this.editor, start);
×
1351
                Transforms.select(this.editor, range);
×
1352
            }
1353
        }
1354
    }
1355

1356
    private onDOMCompositionStart(event: CompositionEvent) {
1357
        const { selection } = this.editor;
1✔
1358
        if (selection) {
1!
1359
            // solve the problem of cross node Chinese input
1360
            if (Range.isExpanded(selection)) {
×
1361
                Editor.deleteFragment(this.editor);
×
1362
                this.forceRender();
×
1363
            }
1364
        }
1365
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1366
            this.isComposing = true;
1✔
1367
        }
1368
        this.render();
1✔
1369
    }
1370

1371
    private onDOMCompositionUpdate(event: CompositionEvent) {
1372
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1373
    }
1374

1375
    private onDOMCompositionEnd(event: CompositionEvent) {
1376
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1377
            Transforms.delete(this.editor);
×
1378
        }
1379
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1380
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1381
            // aren't correct and never fire the "insertFromComposition"
1382
            // type that we need. So instead, insert whenever a composition
1383
            // ends since it will already have been committed to the DOM.
1384
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1385
                preventInsertFromComposition(event, this.editor);
×
1386
                Editor.insertText(this.editor, event.data);
×
1387
            }
1388

1389
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1390
            // so we need avoid repeat isnertText by isComposing === true,
1391
            this.isComposing = false;
×
1392
        }
1393
        this.render();
×
1394
    }
1395

1396
    private onDOMCopy(event: ClipboardEvent) {
1397
        const window = AngularEditor.getWindow(this.editor);
×
1398
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1399
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1400
            event.preventDefault();
×
1401
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1402
        }
1403
    }
1404

1405
    private onDOMCut(event: ClipboardEvent) {
1406
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1407
            event.preventDefault();
×
1408
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1409
            const { selection } = this.editor;
×
1410

1411
            if (selection) {
×
1412
                AngularEditor.deleteCutData(this.editor);
×
1413
            }
1414
        }
1415
    }
1416

1417
    private onDOMDragOver(event: DragEvent) {
1418
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1419
            // Only when the target is void, call `preventDefault` to signal
1420
            // that drops are allowed. Editable content is droppable by
1421
            // default, and calling `preventDefault` hides the cursor.
1422
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1423

1424
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1425
                event.preventDefault();
×
1426
            }
1427
        }
1428
    }
1429

1430
    private onDOMDragStart(event: DragEvent) {
1431
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1432
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1433
            const path = AngularEditor.findPath(this.editor, node);
×
1434
            const voidMatch =
1435
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1436

1437
            // If starting a drag on a void node, make sure it is selected
1438
            // so that it shows up in the selection's fragment.
1439
            if (voidMatch) {
×
1440
                const range = Editor.range(this.editor, path);
×
1441
                Transforms.select(this.editor, range);
×
1442
            }
1443

1444
            this.isDraggingInternally = true;
×
1445

1446
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1447
        }
1448
    }
1449

1450
    private onDOMDrop(event: DragEvent) {
1451
        const editor = this.editor;
×
1452
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1453
            event.preventDefault();
×
1454
            // Keep a reference to the dragged range before updating selection
1455
            const draggedRange = editor.selection;
×
1456

1457
            // Find the range where the drop happened
1458
            const range = AngularEditor.findEventRange(editor, event);
×
1459
            const data = event.dataTransfer;
×
1460

1461
            Transforms.select(editor, range);
×
1462

1463
            if (this.isDraggingInternally) {
×
1464
                if (draggedRange) {
×
1465
                    Transforms.delete(editor, {
×
1466
                        at: draggedRange
1467
                    });
1468
                }
1469

1470
                this.isDraggingInternally = false;
×
1471
            }
1472

1473
            AngularEditor.insertData(editor, data);
×
1474

1475
            // When dragging from another source into the editor, it's possible
1476
            // that the current editor does not have focus.
1477
            if (!AngularEditor.isFocused(editor)) {
×
1478
                AngularEditor.focus(editor);
×
1479
            }
1480
        }
1481
    }
1482

1483
    private onDOMDragEnd(event: DragEvent) {
1484
        if (
×
1485
            !this.readonly &&
×
1486
            this.isDraggingInternally &&
1487
            AngularEditor.hasTarget(this.editor, event.target) &&
1488
            !this.isDOMEventHandled(event, this.dragEnd)
1489
        ) {
1490
            this.isDraggingInternally = false;
×
1491
        }
1492
    }
1493

1494
    private onDOMFocus(event: Event) {
1495
        if (
2✔
1496
            !this.readonly &&
8✔
1497
            !this.isUpdatingSelection &&
1498
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1499
            !this.isDOMEventHandled(event, this.focus)
1500
        ) {
1501
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1502
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1503
            this.latestElement = root.activeElement;
2✔
1504

1505
            // COMPAT: If the editor has nested editable elements, the focus
1506
            // can go to them. In Firefox, this must be prevented because it
1507
            // results in issues with keyboard navigation. (2017/03/30)
1508
            if (IS_FIREFOX && event.target !== el) {
2!
1509
                el.focus();
×
1510
                return;
×
1511
            }
1512

1513
            IS_FOCUSED.set(this.editor, true);
2✔
1514
        }
1515
    }
1516

1517
    private onDOMKeydown(event: KeyboardEvent) {
1518
        const editor = this.editor;
×
1519
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1520
        const { activeElement } = root;
×
1521
        if (
×
1522
            !this.readonly &&
×
1523
            AngularEditor.hasEditableTarget(editor, event.target) &&
1524
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1525
            !this.isComposing &&
1526
            !this.isDOMEventHandled(event, this.keydown)
1527
        ) {
1528
            const nativeEvent = event;
×
1529
            const { selection } = editor;
×
1530

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

1534
            try {
×
1535
                // COMPAT: Since we prevent the default behavior on
1536
                // `beforeinput` events, the browser doesn't think there's ever
1537
                // any history stack to undo or redo, so we have to manage these
1538
                // hotkeys ourselves. (2019/11/06)
1539
                if (Hotkeys.isRedo(nativeEvent)) {
×
1540
                    event.preventDefault();
×
1541

1542
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1543
                        editor.redo();
×
1544
                    }
1545

1546
                    return;
×
1547
                }
1548

1549
                if (Hotkeys.isUndo(nativeEvent)) {
×
1550
                    event.preventDefault();
×
1551

1552
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1553
                        editor.undo();
×
1554
                    }
1555

1556
                    return;
×
1557
                }
1558

1559
                // COMPAT: Certain browsers don't handle the selection updates
1560
                // properly. In Chrome, the selection isn't properly extended.
1561
                // And in Firefox, the selection isn't properly collapsed.
1562
                // (2017/10/17)
1563
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1564
                    event.preventDefault();
×
1565
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1566
                    return;
×
1567
                }
1568

1569
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1570
                    event.preventDefault();
×
1571
                    Transforms.move(editor, { unit: 'line' });
×
1572
                    return;
×
1573
                }
1574

1575
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1576
                    event.preventDefault();
×
1577
                    Transforms.move(editor, {
×
1578
                        unit: 'line',
1579
                        edge: 'focus',
1580
                        reverse: true
1581
                    });
1582
                    return;
×
1583
                }
1584

1585
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1586
                    event.preventDefault();
×
1587
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1588
                    return;
×
1589
                }
1590

1591
                // COMPAT: If a void node is selected, or a zero-width text node
1592
                // adjacent to an inline is selected, we need to handle these
1593
                // hotkeys manually because browsers won't be able to skip over
1594
                // the void node with the zero-width space not being an empty
1595
                // string.
1596
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1597
                    event.preventDefault();
×
1598

1599
                    if (selection && Range.isCollapsed(selection)) {
×
1600
                        Transforms.move(editor, { reverse: !isRTL });
×
1601
                    } else {
1602
                        Transforms.collapse(editor, { edge: 'start' });
×
1603
                    }
1604

1605
                    return;
×
1606
                }
1607

1608
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1609
                    event.preventDefault();
×
1610
                    if (selection && Range.isCollapsed(selection)) {
×
1611
                        Transforms.move(editor, { reverse: isRTL });
×
1612
                    } else {
1613
                        Transforms.collapse(editor, { edge: 'end' });
×
1614
                    }
1615

1616
                    return;
×
1617
                }
1618

1619
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1620
                    event.preventDefault();
×
1621

1622
                    if (selection && Range.isExpanded(selection)) {
×
1623
                        Transforms.collapse(editor, { edge: 'focus' });
×
1624
                    }
1625

1626
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1627
                    return;
×
1628
                }
1629

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

1633
                    if (selection && Range.isExpanded(selection)) {
×
1634
                        Transforms.collapse(editor, { edge: 'focus' });
×
1635
                    }
1636

1637
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1638
                    return;
×
1639
                }
1640

1641
                if (isKeyHotkey('mod+a', event)) {
×
1642
                    this.editor.selectAll();
×
1643
                    event.preventDefault();
×
1644
                    return;
×
1645
                }
1646

1647
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1648
                // fall back to guessing at the input intention for hotkeys.
1649
                // COMPAT: In iOS, some of these hotkeys are handled in the
1650
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1651
                    // We don't have a core behavior for these, but they change the
1652
                    // DOM if we don't prevent them, so we have to.
1653
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1654
                        event.preventDefault();
×
1655
                        return;
×
1656
                    }
1657

1658
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1659
                        event.preventDefault();
×
1660
                        Editor.insertBreak(editor);
×
1661
                        return;
×
1662
                    }
1663

1664
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1665
                        event.preventDefault();
×
1666

1667
                        if (selection && Range.isExpanded(selection)) {
×
1668
                            Editor.deleteFragment(editor, {
×
1669
                                direction: 'backward'
1670
                            });
1671
                        } else {
1672
                            Editor.deleteBackward(editor);
×
1673
                        }
1674

1675
                        return;
×
1676
                    }
1677

1678
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1679
                        event.preventDefault();
×
1680

1681
                        if (selection && Range.isExpanded(selection)) {
×
1682
                            Editor.deleteFragment(editor, {
×
1683
                                direction: 'forward'
1684
                            });
1685
                        } else {
1686
                            Editor.deleteForward(editor);
×
1687
                        }
1688

1689
                        return;
×
1690
                    }
1691

1692
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1693
                        event.preventDefault();
×
1694

1695
                        if (selection && Range.isExpanded(selection)) {
×
1696
                            Editor.deleteFragment(editor, {
×
1697
                                direction: 'backward'
1698
                            });
1699
                        } else {
1700
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1701
                        }
1702

1703
                        return;
×
1704
                    }
1705

1706
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1707
                        event.preventDefault();
×
1708

1709
                        if (selection && Range.isExpanded(selection)) {
×
1710
                            Editor.deleteFragment(editor, {
×
1711
                                direction: 'forward'
1712
                            });
1713
                        } else {
1714
                            Editor.deleteForward(editor, { unit: 'line' });
×
1715
                        }
1716

1717
                        return;
×
1718
                    }
1719

1720
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1721
                        event.preventDefault();
×
1722

1723
                        if (selection && Range.isExpanded(selection)) {
×
1724
                            Editor.deleteFragment(editor, {
×
1725
                                direction: 'backward'
1726
                            });
1727
                        } else {
1728
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1729
                        }
1730

1731
                        return;
×
1732
                    }
1733

1734
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1735
                        event.preventDefault();
×
1736

1737
                        if (selection && Range.isExpanded(selection)) {
×
1738
                            Editor.deleteFragment(editor, {
×
1739
                                direction: 'forward'
1740
                            });
1741
                        } else {
1742
                            Editor.deleteForward(editor, { unit: 'word' });
×
1743
                        }
1744

1745
                        return;
×
1746
                    }
1747
                } else {
1748
                    if (IS_CHROME || IS_SAFARI) {
×
1749
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1750
                        // an event when deleting backwards in a selected void inline node
1751
                        if (
×
1752
                            selection &&
×
1753
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1754
                            Range.isCollapsed(selection)
1755
                        ) {
1756
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1757
                            if (
×
1758
                                Element.isElement(currentNode) &&
×
1759
                                Editor.isVoid(editor, currentNode) &&
1760
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1761
                            ) {
1762
                                event.preventDefault();
×
1763
                                Editor.deleteBackward(editor, {
×
1764
                                    unit: 'block'
1765
                                });
1766
                                return;
×
1767
                            }
1768
                        }
1769
                    }
1770
                }
1771
            } catch (error) {
1772
                this.editor.onError({
×
1773
                    code: SlateErrorCode.OnDOMKeydownError,
1774
                    nativeError: error
1775
                });
1776
            }
1777
        }
1778
    }
1779

1780
    private onDOMPaste(event: ClipboardEvent) {
1781
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1782
        // fall back to React's `onPaste` here instead.
1783
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1784
        // when "paste without formatting" option is used.
1785
        // This unfortunately needs to be handled with paste events instead.
1786
        if (
×
1787
            !this.isDOMEventHandled(event, this.paste) &&
×
1788
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1789
            !this.readonly &&
1790
            AngularEditor.hasEditableTarget(this.editor, event.target)
1791
        ) {
1792
            event.preventDefault();
×
1793
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1794
        }
1795
    }
1796

1797
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1798
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1799
        // fall back to React's leaky polyfill instead just for it. It
1800
        // only works for the `insertText` input type.
1801
        if (
×
1802
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1803
            !this.readonly &&
1804
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1805
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1806
        ) {
1807
            event.nativeEvent.preventDefault();
×
1808
            try {
×
1809
                const text = event.data;
×
1810
                if (!Range.isCollapsed(this.editor.selection)) {
×
1811
                    Editor.deleteFragment(this.editor);
×
1812
                }
1813
                // just handle Non-IME input
1814
                if (!this.isComposing) {
×
1815
                    Editor.insertText(this.editor, text);
×
1816
                }
1817
            } catch (error) {
1818
                this.editor.onError({
×
1819
                    code: SlateErrorCode.ToNativeSelectionError,
1820
                    nativeError: error
1821
                });
1822
            }
1823
        }
1824
    }
1825

1826
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1827
        if (!handler) {
3✔
1828
            return false;
3✔
1829
        }
1830
        handler(event);
×
1831
        return event.defaultPrevented;
×
1832
    }
1833
    //#endregion
1834

1835
    ngOnDestroy() {
1836
        this.editorResizeObserver?.disconnect();
22✔
1837
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1838
        this.manualListeners.forEach(manualListener => {
22✔
1839
            manualListener();
462✔
1840
        });
1841
        this.destroy$.complete();
22✔
1842
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1843
    }
1844
}
1845

1846
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1847
    // This was affecting the selection of multiple blocks and dragging behavior,
1848
    // so enabled only if the selection has been collapsed.
1849
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1850
        const leafEl = domRange.startContainer.parentElement!;
×
1851

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

1857
        if (isZeroDimensionRect) {
×
1858
            const leafRect = leafEl.getBoundingClientRect();
×
1859
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1860

1861
            if (leafHasDimensions) {
×
1862
                return;
×
1863
            }
1864
        }
1865

1866
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1867
        scrollIntoView(leafEl, {
×
1868
            scrollMode: 'if-needed'
1869
        });
1870
        delete leafEl.getBoundingClientRect;
×
1871
    }
1872
};
1873

1874
/**
1875
 * Check if the target is inside void and in the editor.
1876
 */
1877

1878
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1879
    let slateNode: Node | null = null;
1✔
1880
    try {
1✔
1881
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1882
    } catch (error) {}
1883
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1884
};
1885

1886
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1887
    return (
2✔
1888
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1889
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1890
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1891
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1892
    );
1893
};
1894

1895
/**
1896
 * remove default insert from composition
1897
 * @param text
1898
 */
1899
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1900
    const types = ['compositionend', 'insertFromComposition'];
×
1901
    if (!types.includes(event.type)) {
×
1902
        return;
×
1903
    }
1904
    const insertText = (event as CompositionEvent).data;
×
1905
    const window = AngularEditor.getWindow(editor);
×
1906
    const domSelection = window.getSelection();
×
1907
    // ensure text node insert composition input text
1908
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1909
        const textNode = domSelection.anchorNode;
×
1910
        textNode.splitText(textNode.length - insertText.length).remove();
×
1911
    }
1912
};
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