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

worktile / slate-angular / 0105ae4b-f4d1-4346-9167-d573854df6d4

24 Dec 2025 03:53AM UTC coverage: 36.686%. Remained the same
0105ae4b-f4d1-4346-9167-d573854df6d4

push

circleci

pubuzhixing8
refactor(virtual-scroll): rename diffResult

382 of 1244 branches covered (30.71%)

Branch coverage included in aggregate %.

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

1 existing line in 1 file now uncovered.

1077 of 2733 relevant lines covered (39.41%)

23.92 hits per line

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

21.94
/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: 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
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
297
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
298
                }
299
                this.tryMeasureInViewportChildrenHeights();
×
300
            } else {
301
                if (!this.listRender.initialized) {
26✔
302
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
303
                } else {
304
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
305
                }
306
            }
307
            this.cdr.markForCheck();
26✔
308
        }
309
    }
310

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

483
    ngAfterViewChecked() {}
484

485
    ngDoCheck() {}
486

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

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

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

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

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

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

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

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

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

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

631
    virtualScrollInitialized = false;
23✔
632

633
    virtualTopHeightElement: HTMLElement;
634

635
    virtualBottomHeightElement: HTMLElement;
636

637
    virtualCenterOutlet: HTMLElement;
638

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

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

683
    getVirtualTopHeight() {
684
        if (!this.virtualScrollInitialized) {
×
685
            return 0;
×
686
        }
687
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
688
    }
689

690
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
691
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
692
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
693
    }
694

695
    handlePreRendering() {
696
        let preRenderingCount = 1;
×
697
        const childrenWithPreRendering = [...this.inViewportChildren];
×
698
        if (this.inViewportIndics[0] !== 0) {
×
699
            childrenWithPreRendering.unshift(this.editor.children[this.inViewportIndics[0] - 1] as Element);
×
700
        } else {
701
            preRenderingCount = 0;
×
702
        }
703
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
704
        if (lastIndex !== this.editor.children.length - 1) {
×
705
            childrenWithPreRendering.push(this.editor.children[lastIndex + 1] as Element);
×
706
        }
707
        return { preRenderingCount, childrenWithPreRendering };
×
708
    }
709

710
    private tryUpdateVirtualViewport() {
711
        if (isDebug) {
×
712
            this.debugLog('log', 'tryUpdateVirtualViewport');
×
713
        }
714
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
715
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
716
            if (isDebug) {
×
717
                this.debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
718
            }
719
            let virtualView = this.calculateVirtualViewport();
×
720
            let diff = this.diffVirtualViewport(virtualView);
×
NEW
721
            if (diff.isDifferent) {
×
722
                this.applyVirtualView(virtualView);
×
723
                if (this.listRender.initialized) {
×
724
                    const { preRenderingCount, childrenWithPreRendering } = this.handlePreRendering();
×
725
                    this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount);
×
726
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
727
                        this.toNativeSelection();
×
728
                    }
729
                }
NEW
730
                if (diff.needAddOnTop) {
×
NEW
731
                    const remeasureAddedIndics = diff.changedIndexesOfTop;
×
732
                    if (isDebug) {
×
NEW
733
                        this.debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
734
                    }
NEW
735
                    const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
736
                    const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
737
                    const result = this.remeasureHeightByIndics(remeasureAddedIndics);
×
738
                    if (result) {
×
739
                        const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
740
                        const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
741
                        const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
742
                        this.setVirtualSpaceHeight(newTopHeight);
×
743
                        this.debugLog(
×
744
                            'log',
745
                            `update top height cause added element in top, 减去: ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
746
                        );
747
                    }
748
                }
749
                this.tryMeasureInViewportChildrenHeights();
×
750
            } else {
751
                const topHeight = this.getVirtualTopHeight();
×
752
                if (virtualView.top !== topHeight) {
×
753
                    this.debugLog('log', 'update top height: ', virtualView.top - topHeight, 'start index', this.inViewportIndics[0]);
×
754
                    this.setVirtualSpaceHeight(virtualView.top);
×
755
                }
756
            }
757
            if (isDebug) {
×
758
                this.debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
759
            }
760
        });
761
    }
762

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

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

827
        if (visibleStartIndex === -1 && elementLength) {
×
828
            visibleStartIndex = elementLength - 1;
×
829
            visible.push(children[visibleStartIndex]);
×
830
            visibleIndexes.push(visibleStartIndex);
×
831
        }
832

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

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

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

967
    private tryMeasureInViewportChildrenHeights() {
968
        if (!this.isEnabledVirtualScroll()) {
×
969
            return;
×
970
        }
971
        this.tryMeasureInViewportChildrenHeightsAnimId && cancelAnimationFrame(this.tryMeasureInViewportChildrenHeightsAnimId);
×
972
        this.tryMeasureInViewportChildrenHeightsAnimId = requestAnimationFrame(() => {
×
973
            this.measureVisibleHeights();
×
974
        });
975
    }
976

977
    private measureVisibleHeights() {
978
        const children = (this.editor.children || []) as Element[];
×
979
        const inViewportIndics = [...this.inViewportIndics];
×
980
        inViewportIndics.forEach(index => {
×
981
            const node = children[index];
×
982
            if (!node) {
×
983
                return;
×
984
            }
985
            const key = AngularEditor.findKey(this.editor, node);
×
986
            // 跳过已测过的块,除非强制测量
987
            if (this.keyHeightMap.has(key.id)) {
×
988
                return;
×
989
            }
990
            const view = ELEMENT_TO_COMPONENT.get(node);
×
991
            if (!view) {
×
992
                return;
×
993
            }
994
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
995
            if (ret instanceof Promise) {
×
996
                ret.then(height => {
×
997
                    this.keyHeightMap.set(key.id, height);
×
998
                });
999
            } else {
1000
                this.keyHeightMap.set(key.id, ret);
×
1001
            }
1002
        });
1003
    }
1004

1005
    private remeasureHeightByIndics(indics: number[]): boolean {
1006
        const children = (this.editor.children || []) as Element[];
×
1007
        let isHeightChanged = false;
×
1008
        indics.forEach((index, i) => {
×
1009
            const node = children[index];
×
1010
            if (!node) {
×
1011
                return;
×
1012
            }
1013
            const key = AngularEditor.findKey(this.editor, node);
×
1014
            const view = ELEMENT_TO_COMPONENT.get(node);
×
1015
            if (!view) {
×
1016
                return;
×
1017
            }
1018
            const prevHeight = this.keyHeightMap.get(key.id);
×
1019
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
1020
            if (ret instanceof Promise) {
×
1021
                ret.then(height => {
×
1022
                    this.keyHeightMap.set(key.id, height);
×
1023
                    if (height !== prevHeight) {
×
1024
                        isHeightChanged = true;
×
1025
                        if (isDebug) {
×
1026
                            this.debugLog(
×
1027
                                'log',
1028
                                `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`
1029
                            );
1030
                        }
1031
                    }
1032
                });
1033
            } else {
1034
                this.keyHeightMap.set(key.id, ret);
×
1035
                if (ret !== prevHeight) {
×
1036
                    isHeightChanged = true;
×
1037
                    if (isDebug) {
×
1038
                        this.debugLog('log', `remeasure element height, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
1039
                    }
1040
                }
1041
            }
1042
        });
1043
        return isHeightChanged;
×
1044
    }
1045

1046
    //#region event proxy
1047
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1048
        this.manualListeners.push(
483✔
1049
            this.renderer2.listen(target, eventName, (event: Event) => {
1050
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1051
                if (beforeInputEvent) {
5!
1052
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1053
                }
1054
                listener(event);
5✔
1055
            })
1056
        );
1057
    }
1058

1059
    private toSlateSelection() {
1060
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1061
            try {
1✔
1062
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1063
                const { activeElement } = root;
1✔
1064
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1065
                const domSelection = (root as Document).getSelection();
1✔
1066

1067
                if (activeElement === el) {
1!
1068
                    this.latestElement = activeElement;
1✔
1069
                    IS_FOCUSED.set(this.editor, true);
1✔
1070
                } else {
1071
                    IS_FOCUSED.delete(this.editor);
×
1072
                }
1073

1074
                if (!domSelection) {
1!
1075
                    return Transforms.deselect(this.editor);
×
1076
                }
1077

1078
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1079
                const hasDomSelectionInEditor =
1080
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1081
                if (!hasDomSelectionInEditor) {
1!
1082
                    Transforms.deselect(this.editor);
×
1083
                    return;
×
1084
                }
1085

1086
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1087
                // for example, double-click the last cell of the table to select a non-editable DOM
1088
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1089
                if (range) {
1✔
1090
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1091
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1092
                            // force adjust DOMSelection
1093
                            this.toNativeSelection();
×
1094
                        }
1095
                    } else {
1096
                        Transforms.select(this.editor, range);
1✔
1097
                    }
1098
                }
1099
            } catch (error) {
1100
                this.editor.onError({
×
1101
                    code: SlateErrorCode.ToSlateSelectionError,
1102
                    nativeError: error
1103
                });
1104
            }
1105
        }
1106
    }
1107

1108
    private onDOMBeforeInput(
1109
        event: Event & {
1110
            inputType: string;
1111
            isComposing: boolean;
1112
            data: string | null;
1113
            dataTransfer: DataTransfer | null;
1114
            getTargetRanges(): DOMStaticRange[];
1115
        }
1116
    ) {
1117
        const editor = this.editor;
×
1118
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1119
        const { activeElement } = root;
×
1120
        const { selection } = editor;
×
1121
        const { inputType: type } = event;
×
1122
        const data = event.dataTransfer || event.data || undefined;
×
1123
        if (IS_ANDROID) {
×
1124
            let targetRange: Range | null = null;
×
1125
            let [nativeTargetRange] = event.getTargetRanges();
×
1126
            if (nativeTargetRange) {
×
1127
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1128
            }
1129
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1130
            // have to manually get the selection here to ensure it's up-to-date.
1131
            const window = AngularEditor.getWindow(editor);
×
1132
            const domSelection = window.getSelection();
×
1133
            if (!targetRange && domSelection) {
×
1134
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1135
            }
1136
            targetRange = targetRange ?? editor.selection;
×
1137
            if (type === 'insertCompositionText') {
×
1138
                if (data && data.toString().includes('\n')) {
×
1139
                    restoreDom(editor, () => {
×
1140
                        Editor.insertBreak(editor);
×
1141
                    });
1142
                } else {
1143
                    if (targetRange) {
×
1144
                        if (data) {
×
1145
                            restoreDom(editor, () => {
×
1146
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1147
                            });
1148
                        } else {
1149
                            restoreDom(editor, () => {
×
1150
                                Transforms.delete(editor, { at: targetRange });
×
1151
                            });
1152
                        }
1153
                    }
1154
                }
1155
                return;
×
1156
            }
1157
            if (type === 'deleteContentBackward') {
×
1158
                // gboard can not prevent default action, so must use restoreDom,
1159
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1160
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1161
                if (!Range.isCollapsed(targetRange)) {
×
1162
                    restoreDom(editor, () => {
×
1163
                        Transforms.delete(editor, { at: targetRange });
×
1164
                    });
1165
                    return;
×
1166
                }
1167
            }
1168
            if (type === 'insertText') {
×
1169
                restoreDom(editor, () => {
×
1170
                    if (typeof data === 'string') {
×
1171
                        Editor.insertText(editor, data);
×
1172
                    }
1173
                });
1174
                return;
×
1175
            }
1176
        }
1177
        if (
×
1178
            !this.readonly &&
×
1179
            AngularEditor.hasEditableTarget(editor, event.target) &&
1180
            !isTargetInsideVoid(editor, activeElement) &&
1181
            !this.isDOMEventHandled(event, this.beforeInput)
1182
        ) {
1183
            try {
×
1184
                event.preventDefault();
×
1185

1186
                // COMPAT: If the selection is expanded, even if the command seems like
1187
                // a delete forward/backward command it should delete the selection.
1188
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1189
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1190
                    Editor.deleteFragment(editor, { direction });
×
1191
                    return;
×
1192
                }
1193

1194
                switch (type) {
×
1195
                    case 'deleteByComposition':
1196
                    case 'deleteByCut':
1197
                    case 'deleteByDrag': {
1198
                        Editor.deleteFragment(editor);
×
1199
                        break;
×
1200
                    }
1201

1202
                    case 'deleteContent':
1203
                    case 'deleteContentForward': {
1204
                        Editor.deleteForward(editor);
×
1205
                        break;
×
1206
                    }
1207

1208
                    case 'deleteContentBackward': {
1209
                        Editor.deleteBackward(editor);
×
1210
                        break;
×
1211
                    }
1212

1213
                    case 'deleteEntireSoftLine': {
1214
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1215
                        Editor.deleteForward(editor, { unit: 'line' });
×
1216
                        break;
×
1217
                    }
1218

1219
                    case 'deleteHardLineBackward': {
1220
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1221
                        break;
×
1222
                    }
1223

1224
                    case 'deleteSoftLineBackward': {
1225
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1226
                        break;
×
1227
                    }
1228

1229
                    case 'deleteHardLineForward': {
1230
                        Editor.deleteForward(editor, { unit: 'block' });
×
1231
                        break;
×
1232
                    }
1233

1234
                    case 'deleteSoftLineForward': {
1235
                        Editor.deleteForward(editor, { unit: 'line' });
×
1236
                        break;
×
1237
                    }
1238

1239
                    case 'deleteWordBackward': {
1240
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1241
                        break;
×
1242
                    }
1243

1244
                    case 'deleteWordForward': {
1245
                        Editor.deleteForward(editor, { unit: 'word' });
×
1246
                        break;
×
1247
                    }
1248

1249
                    case 'insertLineBreak':
1250
                    case 'insertParagraph': {
1251
                        Editor.insertBreak(editor);
×
1252
                        break;
×
1253
                    }
1254

1255
                    case 'insertFromComposition': {
1256
                        // COMPAT: in safari, `compositionend` event is dispatched after
1257
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1258
                        // https://www.w3.org/TR/input-events-2/
1259
                        // so the following code is the right logic
1260
                        // because DOM selection in sync will be exec before `compositionend` event
1261
                        // isComposing is true will prevent DOM selection being update correctly.
1262
                        this.isComposing = false;
×
1263
                        preventInsertFromComposition(event, this.editor);
×
1264
                    }
1265
                    case 'insertFromDrop':
1266
                    case 'insertFromPaste':
1267
                    case 'insertFromYank':
1268
                    case 'insertReplacementText':
1269
                    case 'insertText': {
1270
                        // use a weak comparison instead of 'instanceof' to allow
1271
                        // programmatic access of paste events coming from external windows
1272
                        // like cypress where cy.window does not work realibly
1273
                        if (data?.constructor.name === 'DataTransfer') {
×
1274
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1275
                        } else if (typeof data === 'string') {
×
1276
                            Editor.insertText(editor, data);
×
1277
                        }
1278
                        break;
×
1279
                    }
1280
                }
1281
            } catch (error) {
1282
                this.editor.onError({
×
1283
                    code: SlateErrorCode.OnDOMBeforeInputError,
1284
                    nativeError: error
1285
                });
1286
            }
1287
        }
1288
    }
1289

1290
    private onDOMBlur(event: FocusEvent) {
1291
        if (
×
1292
            this.readonly ||
×
1293
            this.isUpdatingSelection ||
1294
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1295
            this.isDOMEventHandled(event, this.blur)
1296
        ) {
1297
            return;
×
1298
        }
1299

1300
        const window = AngularEditor.getWindow(this.editor);
×
1301

1302
        // COMPAT: If the current `activeElement` is still the previous
1303
        // one, this is due to the window being blurred when the tab
1304
        // itself becomes unfocused, so we want to abort early to allow to
1305
        // editor to stay focused when the tab becomes focused again.
1306
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1307
        if (this.latestElement === root.activeElement) {
×
1308
            return;
×
1309
        }
1310

1311
        const { relatedTarget } = event;
×
1312
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1313

1314
        // COMPAT: The event should be ignored if the focus is returning
1315
        // to the editor from an embedded editable element (eg. an <input>
1316
        // element inside a void node).
1317
        if (relatedTarget === el) {
×
1318
            return;
×
1319
        }
1320

1321
        // COMPAT: The event should be ignored if the focus is moving from
1322
        // the editor to inside a void node's spacer element.
1323
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1324
            return;
×
1325
        }
1326

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

1333
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1334
                return;
×
1335
            }
1336
        }
1337

1338
        IS_FOCUSED.delete(this.editor);
×
1339
    }
1340

1341
    private onDOMClick(event: MouseEvent) {
1342
        if (
×
1343
            !this.readonly &&
×
1344
            AngularEditor.hasTarget(this.editor, event.target) &&
1345
            !this.isDOMEventHandled(event, this.click) &&
1346
            isDOMNode(event.target)
1347
        ) {
1348
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1349
            const path = AngularEditor.findPath(this.editor, node);
×
1350
            const start = Editor.start(this.editor, path);
×
1351
            const end = Editor.end(this.editor, path);
×
1352

1353
            const startVoid = Editor.void(this.editor, { at: start });
×
1354
            const endVoid = Editor.void(this.editor, { at: end });
×
1355

1356
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1357
                let blockPath = path;
×
1358
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1359
                    const block = Editor.above(this.editor, {
×
1360
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1361
                        at: path
1362
                    });
1363

1364
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1365
                }
1366

1367
                const range = Editor.range(this.editor, blockPath);
×
1368
                Transforms.select(this.editor, range);
×
1369
                return;
×
1370
            }
1371

1372
            if (
×
1373
                startVoid &&
×
1374
                endVoid &&
1375
                Path.equals(startVoid[1], endVoid[1]) &&
1376
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1377
            ) {
1378
                const range = Editor.range(this.editor, start);
×
1379
                Transforms.select(this.editor, range);
×
1380
            }
1381
        }
1382
    }
1383

1384
    private onDOMCompositionStart(event: CompositionEvent) {
1385
        const { selection } = this.editor;
1✔
1386
        if (selection) {
1!
1387
            // solve the problem of cross node Chinese input
1388
            if (Range.isExpanded(selection)) {
×
1389
                Editor.deleteFragment(this.editor);
×
1390
                this.forceRender();
×
1391
            }
1392
        }
1393
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1394
            this.isComposing = true;
1✔
1395
        }
1396
        this.render();
1✔
1397
    }
1398

1399
    private onDOMCompositionUpdate(event: CompositionEvent) {
1400
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1401
    }
1402

1403
    private onDOMCompositionEnd(event: CompositionEvent) {
1404
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1405
            Transforms.delete(this.editor);
×
1406
        }
1407
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1408
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1409
            // aren't correct and never fire the "insertFromComposition"
1410
            // type that we need. So instead, insert whenever a composition
1411
            // ends since it will already have been committed to the DOM.
1412
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1413
                preventInsertFromComposition(event, this.editor);
×
1414
                Editor.insertText(this.editor, event.data);
×
1415
            }
1416

1417
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1418
            // so we need avoid repeat isnertText by isComposing === true,
1419
            this.isComposing = false;
×
1420
        }
1421
        this.render();
×
1422
    }
1423

1424
    private onDOMCopy(event: ClipboardEvent) {
1425
        const window = AngularEditor.getWindow(this.editor);
×
1426
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1427
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1428
            event.preventDefault();
×
1429
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1430
        }
1431
    }
1432

1433
    private onDOMCut(event: ClipboardEvent) {
1434
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1435
            event.preventDefault();
×
1436
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1437
            const { selection } = this.editor;
×
1438

1439
            if (selection) {
×
1440
                AngularEditor.deleteCutData(this.editor);
×
1441
            }
1442
        }
1443
    }
1444

1445
    private onDOMDragOver(event: DragEvent) {
1446
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1447
            // Only when the target is void, call `preventDefault` to signal
1448
            // that drops are allowed. Editable content is droppable by
1449
            // default, and calling `preventDefault` hides the cursor.
1450
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1451

1452
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1453
                event.preventDefault();
×
1454
            }
1455
        }
1456
    }
1457

1458
    private onDOMDragStart(event: DragEvent) {
1459
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1460
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1461
            const path = AngularEditor.findPath(this.editor, node);
×
1462
            const voidMatch =
1463
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1464

1465
            // If starting a drag on a void node, make sure it is selected
1466
            // so that it shows up in the selection's fragment.
1467
            if (voidMatch) {
×
1468
                const range = Editor.range(this.editor, path);
×
1469
                Transforms.select(this.editor, range);
×
1470
            }
1471

1472
            this.isDraggingInternally = true;
×
1473

1474
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1475
        }
1476
    }
1477

1478
    private onDOMDrop(event: DragEvent) {
1479
        const editor = this.editor;
×
1480
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1481
            event.preventDefault();
×
1482
            // Keep a reference to the dragged range before updating selection
1483
            const draggedRange = editor.selection;
×
1484

1485
            // Find the range where the drop happened
1486
            const range = AngularEditor.findEventRange(editor, event);
×
1487
            const data = event.dataTransfer;
×
1488

1489
            Transforms.select(editor, range);
×
1490

1491
            if (this.isDraggingInternally) {
×
1492
                if (draggedRange) {
×
1493
                    Transforms.delete(editor, {
×
1494
                        at: draggedRange
1495
                    });
1496
                }
1497

1498
                this.isDraggingInternally = false;
×
1499
            }
1500

1501
            AngularEditor.insertData(editor, data);
×
1502

1503
            // When dragging from another source into the editor, it's possible
1504
            // that the current editor does not have focus.
1505
            if (!AngularEditor.isFocused(editor)) {
×
1506
                AngularEditor.focus(editor);
×
1507
            }
1508
        }
1509
    }
1510

1511
    private onDOMDragEnd(event: DragEvent) {
1512
        if (
×
1513
            !this.readonly &&
×
1514
            this.isDraggingInternally &&
1515
            AngularEditor.hasTarget(this.editor, event.target) &&
1516
            !this.isDOMEventHandled(event, this.dragEnd)
1517
        ) {
1518
            this.isDraggingInternally = false;
×
1519
        }
1520
    }
1521

1522
    private onDOMFocus(event: Event) {
1523
        if (
2✔
1524
            !this.readonly &&
8✔
1525
            !this.isUpdatingSelection &&
1526
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1527
            !this.isDOMEventHandled(event, this.focus)
1528
        ) {
1529
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1530
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1531
            this.latestElement = root.activeElement;
2✔
1532

1533
            // COMPAT: If the editor has nested editable elements, the focus
1534
            // can go to them. In Firefox, this must be prevented because it
1535
            // results in issues with keyboard navigation. (2017/03/30)
1536
            if (IS_FIREFOX && event.target !== el) {
2!
1537
                el.focus();
×
1538
                return;
×
1539
            }
1540

1541
            IS_FOCUSED.set(this.editor, true);
2✔
1542
        }
1543
    }
1544

1545
    private onDOMKeydown(event: KeyboardEvent) {
1546
        const editor = this.editor;
×
1547
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1548
        const { activeElement } = root;
×
1549
        if (
×
1550
            !this.readonly &&
×
1551
            AngularEditor.hasEditableTarget(editor, event.target) &&
1552
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1553
            !this.isComposing &&
1554
            !this.isDOMEventHandled(event, this.keydown)
1555
        ) {
1556
            const nativeEvent = event;
×
1557
            const { selection } = editor;
×
1558

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

1562
            try {
×
1563
                // COMPAT: Since we prevent the default behavior on
1564
                // `beforeinput` events, the browser doesn't think there's ever
1565
                // any history stack to undo or redo, so we have to manage these
1566
                // hotkeys ourselves. (2019/11/06)
1567
                if (Hotkeys.isRedo(nativeEvent)) {
×
1568
                    event.preventDefault();
×
1569

1570
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1571
                        editor.redo();
×
1572
                    }
1573

1574
                    return;
×
1575
                }
1576

1577
                if (Hotkeys.isUndo(nativeEvent)) {
×
1578
                    event.preventDefault();
×
1579

1580
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1581
                        editor.undo();
×
1582
                    }
1583

1584
                    return;
×
1585
                }
1586

1587
                // COMPAT: Certain browsers don't handle the selection updates
1588
                // properly. In Chrome, the selection isn't properly extended.
1589
                // And in Firefox, the selection isn't properly collapsed.
1590
                // (2017/10/17)
1591
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1592
                    event.preventDefault();
×
1593
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1594
                    return;
×
1595
                }
1596

1597
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1598
                    event.preventDefault();
×
1599
                    Transforms.move(editor, { unit: 'line' });
×
1600
                    return;
×
1601
                }
1602

1603
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1604
                    event.preventDefault();
×
1605
                    Transforms.move(editor, {
×
1606
                        unit: 'line',
1607
                        edge: 'focus',
1608
                        reverse: true
1609
                    });
1610
                    return;
×
1611
                }
1612

1613
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1614
                    event.preventDefault();
×
1615
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1616
                    return;
×
1617
                }
1618

1619
                // COMPAT: If a void node is selected, or a zero-width text node
1620
                // adjacent to an inline is selected, we need to handle these
1621
                // hotkeys manually because browsers won't be able to skip over
1622
                // the void node with the zero-width space not being an empty
1623
                // string.
1624
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1625
                    event.preventDefault();
×
1626

1627
                    if (selection && Range.isCollapsed(selection)) {
×
1628
                        Transforms.move(editor, { reverse: !isRTL });
×
1629
                    } else {
1630
                        Transforms.collapse(editor, { edge: 'start' });
×
1631
                    }
1632

1633
                    return;
×
1634
                }
1635

1636
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1637
                    event.preventDefault();
×
1638
                    if (selection && Range.isCollapsed(selection)) {
×
1639
                        Transforms.move(editor, { reverse: isRTL });
×
1640
                    } else {
1641
                        Transforms.collapse(editor, { edge: 'end' });
×
1642
                    }
1643

1644
                    return;
×
1645
                }
1646

1647
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1648
                    event.preventDefault();
×
1649

1650
                    if (selection && Range.isExpanded(selection)) {
×
1651
                        Transforms.collapse(editor, { edge: 'focus' });
×
1652
                    }
1653

1654
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1655
                    return;
×
1656
                }
1657

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

1661
                    if (selection && Range.isExpanded(selection)) {
×
1662
                        Transforms.collapse(editor, { edge: 'focus' });
×
1663
                    }
1664

1665
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1666
                    return;
×
1667
                }
1668

1669
                if (isKeyHotkey('mod+a', event)) {
×
1670
                    this.editor.selectAll();
×
1671
                    event.preventDefault();
×
1672
                    return;
×
1673
                }
1674

1675
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1676
                // fall back to guessing at the input intention for hotkeys.
1677
                // COMPAT: In iOS, some of these hotkeys are handled in the
1678
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1679
                    // We don't have a core behavior for these, but they change the
1680
                    // DOM if we don't prevent them, so we have to.
1681
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1682
                        event.preventDefault();
×
1683
                        return;
×
1684
                    }
1685

1686
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1687
                        event.preventDefault();
×
1688
                        Editor.insertBreak(editor);
×
1689
                        return;
×
1690
                    }
1691

1692
                    if (Hotkeys.isDeleteBackward(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);
×
1701
                        }
1702

1703
                        return;
×
1704
                    }
1705

1706
                    if (Hotkeys.isDeleteForward(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);
×
1715
                        }
1716

1717
                        return;
×
1718
                    }
1719

1720
                    if (Hotkeys.isDeleteLineBackward(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: 'line' });
×
1729
                        }
1730

1731
                        return;
×
1732
                    }
1733

1734
                    if (Hotkeys.isDeleteLineForward(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: 'line' });
×
1743
                        }
1744

1745
                        return;
×
1746
                    }
1747

1748
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1749
                        event.preventDefault();
×
1750

1751
                        if (selection && Range.isExpanded(selection)) {
×
1752
                            Editor.deleteFragment(editor, {
×
1753
                                direction: 'backward'
1754
                            });
1755
                        } else {
1756
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1757
                        }
1758

1759
                        return;
×
1760
                    }
1761

1762
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1763
                        event.preventDefault();
×
1764

1765
                        if (selection && Range.isExpanded(selection)) {
×
1766
                            Editor.deleteFragment(editor, {
×
1767
                                direction: 'forward'
1768
                            });
1769
                        } else {
1770
                            Editor.deleteForward(editor, { unit: 'word' });
×
1771
                        }
1772

1773
                        return;
×
1774
                    }
1775
                } else {
1776
                    if (IS_CHROME || IS_SAFARI) {
×
1777
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1778
                        // an event when deleting backwards in a selected void inline node
1779
                        if (
×
1780
                            selection &&
×
1781
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1782
                            Range.isCollapsed(selection)
1783
                        ) {
1784
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1785
                            if (
×
1786
                                Element.isElement(currentNode) &&
×
1787
                                Editor.isVoid(editor, currentNode) &&
1788
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1789
                            ) {
1790
                                event.preventDefault();
×
1791
                                Editor.deleteBackward(editor, {
×
1792
                                    unit: 'block'
1793
                                });
1794
                                return;
×
1795
                            }
1796
                        }
1797
                    }
1798
                }
1799
            } catch (error) {
1800
                this.editor.onError({
×
1801
                    code: SlateErrorCode.OnDOMKeydownError,
1802
                    nativeError: error
1803
                });
1804
            }
1805
        }
1806
    }
1807

1808
    private onDOMPaste(event: ClipboardEvent) {
1809
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1810
        // fall back to React's `onPaste` here instead.
1811
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1812
        // when "paste without formatting" option is used.
1813
        // This unfortunately needs to be handled with paste events instead.
1814
        if (
×
1815
            !this.isDOMEventHandled(event, this.paste) &&
×
1816
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1817
            !this.readonly &&
1818
            AngularEditor.hasEditableTarget(this.editor, event.target)
1819
        ) {
1820
            event.preventDefault();
×
1821
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1822
        }
1823
    }
1824

1825
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1826
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1827
        // fall back to React's leaky polyfill instead just for it. It
1828
        // only works for the `insertText` input type.
1829
        if (
×
1830
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1831
            !this.readonly &&
1832
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1833
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1834
        ) {
1835
            event.nativeEvent.preventDefault();
×
1836
            try {
×
1837
                const text = event.data;
×
1838
                if (!Range.isCollapsed(this.editor.selection)) {
×
1839
                    Editor.deleteFragment(this.editor);
×
1840
                }
1841
                // just handle Non-IME input
1842
                if (!this.isComposing) {
×
1843
                    Editor.insertText(this.editor, text);
×
1844
                }
1845
            } catch (error) {
1846
                this.editor.onError({
×
1847
                    code: SlateErrorCode.ToNativeSelectionError,
1848
                    nativeError: error
1849
                });
1850
            }
1851
        }
1852
    }
1853

1854
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1855
        if (!handler) {
3✔
1856
            return false;
3✔
1857
        }
1858
        handler(event);
×
1859
        return event.defaultPrevented;
×
1860
    }
1861
    //#endregion
1862

1863
    ngOnDestroy() {
1864
        this.editorResizeObserver?.disconnect();
23✔
1865
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1866
        this.manualListeners.forEach(manualListener => {
23✔
1867
            manualListener();
483✔
1868
        });
1869
        this.destroy$.complete();
23✔
1870
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1871
    }
1872
}
1873

1874
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1875
    // This was affecting the selection of multiple blocks and dragging behavior,
1876
    // so enabled only if the selection has been collapsed.
1877
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1878
        const leafEl = domRange.startContainer.parentElement!;
×
1879

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

1885
        if (isZeroDimensionRect) {
×
1886
            const leafRect = leafEl.getBoundingClientRect();
×
1887
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1888

1889
            if (leafHasDimensions) {
×
1890
                return;
×
1891
            }
1892
        }
1893

1894
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1895
        scrollIntoView(leafEl, {
×
1896
            scrollMode: 'if-needed'
1897
        });
1898
        delete leafEl.getBoundingClientRect;
×
1899
    }
1900
};
1901

1902
/**
1903
 * Check if the target is inside void and in the editor.
1904
 */
1905

1906
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1907
    let slateNode: Node | null = null;
1✔
1908
    try {
1✔
1909
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1910
    } catch (error) {}
1911
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1912
};
1913

1914
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1915
    return (
2✔
1916
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1917
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1918
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1919
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1920
    );
1921
};
1922

1923
/**
1924
 * remove default insert from composition
1925
 * @param text
1926
 */
1927
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1928
    const types = ['compositionend', 'insertFromComposition'];
×
1929
    if (!types.includes(event.type)) {
×
1930
        return;
×
1931
    }
1932
    const insertText = (event as CompositionEvent).data;
×
1933
    const window = AngularEditor.getWindow(editor);
×
1934
    const domSelection = window.getSelection();
×
1935
    // ensure text node insert composition input text
1936
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1937
        const textNode = domSelection.anchorNode;
×
1938
        textNode.splitText(textNode.length - insertText.length).remove();
×
1939
    }
1940
};
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