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

worktile / slate-angular / 56ae9a51-fae9-480f-a03e-425c4c359d73

08 Jan 2026 07:33AM UTC coverage: 36.73% (-0.2%) from 36.883%
56ae9a51-fae9-480f-a03e-425c4c359d73

push

circleci

pubuzhixing8
fix(virtual-scroll): need to measure element height when diff is different and need remove on top in onChange scenario #WIK-19747

401 of 1290 branches covered (31.09%)

Branch coverage included in aggregate %.

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

1 existing line in 1 file now uncovered.

1102 of 2802 relevant lines covered (39.33%)

23.94 hits per line

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

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

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

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

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

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

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

117
    private initialized: boolean;
118

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

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

123
    @Input() editor: AngularEditor;
124

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

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

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

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

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

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

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

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

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

143
    @Input() placeholder: string;
144

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

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

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

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

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

189
    viewContainerRef = inject(ViewContainerRef);
23✔
190

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

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

203
    listRender: ListRender;
204

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

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

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

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

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

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

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

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

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

349
    calculateVirtualScrollSelection(selection: Selection) {
350
        if (selection) {
×
351
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
352
            const indics = this.inViewportIndics;
×
353
            if (indics.length > 0) {
×
354
                const currentVisibleRange: Range = {
×
355
                    anchor: Editor.start(this.editor, [indics[0]]),
356
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
357
                };
358
                const [start, end] = Range.edges(selection);
×
359
                let forwardSelection = { anchor: start, focus: end };
×
360
                if (!isBlockCardCursor) {
×
361
                    forwardSelection = { anchor: start, focus: end };
×
362
                } else {
363
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
364
                }
365
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
366
                if (intersectedSelection && isBlockCardCursor) {
×
367
                    return selection;
×
368
                }
369
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
370
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
371
                    if (isDebug) {
×
372
                        debugLog(
×
373
                            'log',
374
                            `selection is not in visible range, selection: ${JSON.stringify(
375
                                selection
376
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
377
                        );
378
                    }
379
                    return intersectedSelection;
×
380
                }
381
                return selection;
×
382
            }
383
        }
384
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
385
        return selection;
×
386
    }
387

388
    private isSelectionInvisible(selection: Selection) {
389
        const anchorIndex = selection.anchor.path[0];
6✔
390
        const focusIndex = selection.focus.path[0];
6✔
391
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
392
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
393
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
394
    }
395

396
    toNativeSelection(autoScroll = true) {
15✔
397
        try {
15✔
398
            let { selection } = this.editor;
15✔
399

400
            if (this.isEnabledVirtualScroll()) {
15!
401
                selection = this.calculateVirtualScrollSelection(selection);
×
402
            }
403

404
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
405
            const { activeElement } = root;
15✔
406
            const domSelection = (root as Document).getSelection();
15✔
407

408
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
409
                return;
14✔
410
            }
411

412
            const hasDomSelection = domSelection.type !== 'None';
1✔
413

414
            // If the DOM selection is properly unset, we're done.
415
            if (!selection && !hasDomSelection) {
1!
416
                return;
×
417
            }
418

419
            // If the DOM selection is already correct, we're done.
420
            // verify that the dom selection is in the editor
421
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
422
            let hasDomSelectionInEditor = false;
1✔
423
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
424
                hasDomSelectionInEditor = true;
1✔
425
            }
426

427
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
428
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
429
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
430
                    exactMatch: false,
431
                    suppressThrow: true
432
                });
433
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
434
                    return;
×
435
                }
436
            }
437

438
            // prevent updating native selection when active element is void element
439
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
440
                return;
×
441
            }
442

443
            // when <Editable/> is being controlled through external value
444
            // then its children might just change - DOM responds to it on its own
445
            // but Slate's value is not being updated through any operation
446
            // and thus it doesn't transform selection on its own
447
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
448
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
449
                return;
×
450
            }
451

452
            // Otherwise the DOM selection is out of sync, so update it.
453
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
454
            this.isUpdatingSelection = true;
1✔
455

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

458
            if (newDomRange) {
1!
459
                // COMPAT: Since the DOM range has no concept of backwards/forwards
460
                // we need to check and do the right thing here.
461
                if (Range.isBackward(selection)) {
1!
462
                    // eslint-disable-next-line max-len
463
                    domSelection.setBaseAndExtent(
×
464
                        newDomRange.endContainer,
465
                        newDomRange.endOffset,
466
                        newDomRange.startContainer,
467
                        newDomRange.startOffset
468
                    );
469
                } else {
470
                    // eslint-disable-next-line max-len
471
                    domSelection.setBaseAndExtent(
1✔
472
                        newDomRange.startContainer,
473
                        newDomRange.startOffset,
474
                        newDomRange.endContainer,
475
                        newDomRange.endOffset
476
                    );
477
                }
478
            } else {
479
                domSelection.removeAllRanges();
×
480
            }
481

482
            setTimeout(() => {
1✔
483
                if (
1!
484
                    this.isEnabledVirtualScroll() &&
1!
485
                    !selection &&
486
                    this.editor.selection &&
487
                    autoScroll &&
488
                    this.virtualScrollConfig.scrollContainer
489
                ) {
490
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
491
                    this.isUpdatingSelection = false;
×
492
                    return;
×
493
                } else {
494
                    // handle scrolling in setTimeout because of
495
                    // dom should not have updated immediately after listRender's updating
496
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
497
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
498
                    // to focus the contenteditable element too. (2016/11/16)
499
                    if (newDomRange && IS_FIREFOX) {
1!
500
                        el.focus();
×
501
                    }
502
                }
503
                this.isUpdatingSelection = false;
1✔
504
            });
505
        } catch (error) {
506
            this.editor.onError({
×
507
                code: SlateErrorCode.ToNativeSelectionError,
508
                nativeError: error
509
            });
510
            this.isUpdatingSelection = false;
×
511
        }
512
    }
513

514
    onChange() {
515
        this.forceRender();
13✔
516
        this.onChangeCallback(this.editor.children);
13✔
517
    }
518

519
    ngAfterViewChecked() {}
520

521
    ngDoCheck() {}
522

523
    forceRender() {
524
        this.updateContext();
15✔
525
        if (this.isEnabledVirtualScroll()) {
15!
526
            this.updateListRenderAndRemeasureHeights();
×
527
        } else {
528
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
529
        }
530
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
531
        // when the DOMElement where the selection is located is removed
532
        // the compositionupdate and compositionend events will no longer be fired
533
        // so isComposing needs to be corrected
534
        // need exec after this.cdr.detectChanges() to render HTML
535
        // need exec before this.toNativeSelection() to correct native selection
536
        if (this.isComposing) {
15!
537
            // Composition input text be not rendered when user composition input with selection is expanded
538
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
539
            // this time condition is true and isComposing is assigned false
540
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
541
            setTimeout(() => {
×
542
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
543
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
544
                let textContent = '';
×
545
                // skip decorate text
546
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
547
                    let text = stringDOMNode.textContent;
×
548
                    const zeroChar = '\uFEFF';
×
549
                    // remove zero with char
550
                    if (text.startsWith(zeroChar)) {
×
551
                        text = text.slice(1);
×
552
                    }
553
                    if (text.endsWith(zeroChar)) {
×
554
                        text = text.slice(0, text.length - 1);
×
555
                    }
556
                    textContent += text;
×
557
                });
558
                if (Node.string(textNode).endsWith(textContent)) {
×
559
                    this.isComposing = false;
×
560
                }
561
            }, 0);
562
        }
563
        if (this.editor.selection && this.isSelectionInvisible(this.editor.selection)) {
15!
564
            Transforms.deselect(this.editor);
×
565
            return;
×
566
        } else {
567
            this.toNativeSelection();
15✔
568
        }
569
    }
570

571
    render() {
572
        const changed = this.updateContext();
2✔
573
        if (changed) {
2✔
574
            if (this.isEnabledVirtualScroll()) {
2!
575
                this.updateListRenderAndRemeasureHeights();
×
576
            } else {
577
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
578
            }
579
        }
580
    }
581

582
    updateListRenderAndRemeasureHeights() {
NEW
583
        let virtualView = this.calculateVirtualViewport();
×
NEW
584
        let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
NEW
585
        if (diff.isDifferent && diff.needRemoveOnTop) {
×
NEW
586
            const remeasureIndics = diff.changedIndexesOfTop;
×
NEW
587
            const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
NEW
588
            if (changed) {
×
NEW
589
                virtualView = this.calculateVirtualViewport();
×
NEW
590
                diff = this.diffVirtualViewport(virtualView, 'second');
×
591
            }
592
        }
593
        const oldInViewportChildren = this.inViewportChildren;
×
594
        this.applyVirtualView(virtualView);
×
595
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
596
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
597
        // 新增或者修改的才需要重算,计算出这个结果
598
        const remeasureIndics = [];
×
599
        this.inViewportChildren.forEach((child, index) => {
×
600
            if (oldInViewportChildren.indexOf(child) === -1) {
×
601
                remeasureIndics.push(this.inViewportIndics[index]);
×
602
            }
603
        });
604
    }
605

606
    updateContext() {
607
        const decorations = this.generateDecorations();
17✔
608
        if (
17✔
609
            this.context.selection !== this.editor.selection ||
46✔
610
            this.context.decorate !== this.decorate ||
611
            this.context.readonly !== this.readonly ||
612
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
613
        ) {
614
            this.context = {
10✔
615
                parent: this.editor,
616
                selection: this.editor.selection,
617
                decorations: decorations,
618
                decorate: this.decorate,
619
                readonly: this.readonly
620
            };
621
            return true;
10✔
622
        }
623
        return false;
7✔
624
    }
625

626
    initializeContext() {
627
        this.context = {
49✔
628
            parent: this.editor,
629
            selection: this.editor.selection,
630
            decorations: this.generateDecorations(),
631
            decorate: this.decorate,
632
            readonly: this.readonly
633
        };
634
    }
635

636
    initializeViewContext() {
637
        this.viewContext = {
23✔
638
            editor: this.editor,
639
            renderElement: this.renderElement,
640
            renderLeaf: this.renderLeaf,
641
            renderText: this.renderText,
642
            trackBy: this.trackBy,
643
            isStrictDecorate: this.isStrictDecorate
644
        };
645
    }
646

647
    composePlaceholderDecorate(editor: Editor) {
648
        if (this.placeholderDecorate) {
64!
649
            return this.placeholderDecorate(editor) || [];
×
650
        }
651

652
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
653
            const start = Editor.start(editor, []);
3✔
654
            return [
3✔
655
                {
656
                    placeholder: this.placeholder,
657
                    anchor: start,
658
                    focus: start
659
                }
660
            ];
661
        } else {
662
            return [];
61✔
663
        }
664
    }
665

666
    generateDecorations() {
667
        const decorations = this.decorate([this.editor, []]);
66✔
668
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
669
        decorations.push(...placeholderDecorations);
66✔
670
        return decorations;
66✔
671
    }
672

673
    private isEnabledVirtualScroll() {
674
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
675
    }
676

677
    virtualScrollInitialized = false;
23✔
678

679
    virtualTopHeightElement: HTMLElement;
680

681
    virtualBottomHeightElement: HTMLElement;
682

683
    virtualCenterOutlet: HTMLElement;
684

685
    initializeVirtualScroll() {
686
        if (this.virtualScrollInitialized) {
23!
687
            return;
×
688
        }
689
        if (this.isEnabledVirtualScroll()) {
23!
690
            this.virtualScrollInitialized = true;
×
691
            this.virtualTopHeightElement = document.createElement('div');
×
692
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
693
            this.virtualTopHeightElement.contentEditable = 'false';
×
694
            this.virtualBottomHeightElement = document.createElement('div');
×
695
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
696
            this.virtualBottomHeightElement.contentEditable = 'false';
×
697
            this.virtualCenterOutlet = document.createElement('div');
×
698
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
699
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
700
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
701
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
702
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
703
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
704
            this.editorResizeObserver = new ResizeObserver(entries => {
×
705
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
706
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
707
                    this.keyHeightMap.clear();
×
708
                    const remeasureIndics = this.inViewportIndics;
×
709
                    measureHeightByIndics(this.editor, remeasureIndics, true);
×
710
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
711
                    if (isDebug) {
×
712
                        debugLog(
×
713
                            'log',
714
                            'editorResizeObserverRectWidth: ',
715
                            editorResizeObserverRectWidth,
716
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
717
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
718
                        );
719
                    }
720
                }
721
            });
722
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
723
        }
724
    }
725

726
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
727
        if (!this.virtualScrollInitialized) {
×
728
            return;
×
729
        }
730
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
731
        if (bottomHeight !== undefined) {
×
732
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
733
        }
734
    }
735

736
    getActualVirtualTopHeight() {
737
        if (!this.virtualScrollInitialized) {
×
738
            return 0;
×
739
        }
740
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
741
    }
742

743
    handlePreRendering() {
744
        let preRenderingCount = 0;
×
745
        const childrenWithPreRendering = [...this.inViewportChildren];
×
746
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
747
        const firstIndex = this.inViewportIndics[0];
×
748
        for (let index = firstIndex - 1; index >= 0; index--) {
×
749
            const element = this.editor.children[index] as Element;
×
750
            if (this.editor.isVisible(element)) {
×
751
                childrenWithPreRendering.unshift(element);
×
752
                childrenWithPreRenderingIndics.unshift(index);
×
753
                preRenderingCount = 1;
×
754
                break;
×
755
            }
756
        }
757
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
758
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
759
            const element = this.editor.children[index] as Element;
×
760
            if (this.editor.isVisible(element)) {
×
761
                childrenWithPreRendering.push(element);
×
762
                childrenWithPreRenderingIndics.push(index);
×
763
                break;
×
764
            }
765
        }
766
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
767
    }
768

769
    private tryUpdateVirtualViewport() {
770
        if (isDebug) {
×
771
            debugLog('log', 'tryUpdateVirtualViewport');
×
772
        }
773
        if (this.inViewportIndics.length > 0) {
×
774
            const topHeight = this.getActualVirtualTopHeight();
×
775
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0]);
×
776
            if (topHeight !== refreshVirtualTopHeight) {
×
777
                if (isDebug) {
×
778
                    debugLog(
×
779
                        'log',
780
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
781
                        topHeight - refreshVirtualTopHeight
782
                    );
783
                }
784
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
785
                return;
×
786
            }
787
        }
788
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
789
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
790
            if (isDebug) {
×
791
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
792
            }
793
            let virtualView = this.calculateVirtualViewport();
×
794
            let diff = this.diffVirtualViewport(virtualView);
×
795
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
796
                const remeasureIndics = diff.changedIndexesOfTop;
×
797
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
798
                if (changed) {
×
799
                    virtualView = this.calculateVirtualViewport();
×
800
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
801
                }
802
            }
803
            if (diff.isDifferent) {
×
804
                this.applyVirtualView(virtualView);
×
805
                if (this.listRender.initialized) {
×
806
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
807
                    this.listRender.update(
×
808
                        childrenWithPreRendering,
809
                        this.editor,
810
                        this.context,
811
                        preRenderingCount,
812
                        childrenWithPreRenderingIndics
813
                    );
814
                    if (diff.needAddOnTop) {
×
815
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
816
                        if (isDebug) {
×
817
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
818
                        }
819
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
820
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
821
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
822
                        if (changed) {
×
823
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
824
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
825
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
826
                            this.setVirtualSpaceHeight(newTopHeight);
×
827
                            if (isDebug) {
×
828
                                debugLog(
×
829
                                    'log',
830
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
831
                                );
832
                            }
833
                        }
834
                    }
835
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
836
                        this.toNativeSelection(false);
×
837
                    }
838
                }
839
            }
840
            if (isDebug) {
×
841
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
842
            }
843
        });
844
    }
845

846
    private calculateVirtualViewport() {
847
        const children = (this.editor.children || []) as Element[];
×
848
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
849
            return {
×
850
                inViewportChildren: children,
851
                inViewportIndics: [],
852
                top: 0,
853
                bottom: 0,
854
                heights: []
855
            };
856
        }
857
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
858
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
859
        if (!viewportHeight) {
×
860
            return {
×
861
                inViewportChildren: [],
862
                inViewportIndics: [],
863
                top: 0,
864
                bottom: 0,
865
                heights: []
866
            };
867
        }
868
        const elementLength = children.length;
×
869
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
870
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
871
            setTimeout(() => {
×
872
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
873
                const businessTop =
874
                    Math.ceil(virtualTopBoundingTop) +
×
875
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
876
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
877
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
878
                if (isDebug) {
×
879
                    debugLog('log', 'businessTop', businessTop);
×
880
                }
881
            }, 100);
882
        }
883
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
884
        const { heights, accumulatedHeights, visibleStates } = buildHeightsAndAccumulatedHeights(this.editor);
×
885
        const totalHeight = accumulatedHeights[elementLength];
×
886
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
887
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
888
        const viewBottom = limitedScrollTop + viewportHeight;
×
889
        let accumulatedOffset = 0;
×
890
        let inViewportStartIndex = -1;
×
891
        const visible: Element[] = [];
×
892
        const inViewportIndics: number[] = [];
×
893

894
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
895
            const currentHeight = heights[i];
×
896
            const nextOffset = accumulatedOffset + currentHeight;
×
897
            if (!visibleStates[i]) {
×
898
                accumulatedOffset = nextOffset;
×
899
                continue;
×
900
            }
901
            // 可视区域有交集,加入渲染
902
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
903
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
904
                visible.push(children[i]);
×
905
                inViewportIndics.push(i);
×
906
            }
907
            accumulatedOffset = nextOffset;
×
908
        }
909

910
        const inViewportEndIndex =
911
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
912
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
913
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
914
        return {
×
915
            inViewportChildren: visible.length ? visible : children,
×
916
            inViewportIndics,
917
            top,
918
            bottom,
919
            heights,
920
            accumulatedHeights
921
        };
922
    }
923

924
    private applyVirtualView(virtualView: VirtualViewResult) {
925
        this.inViewportChildren = virtualView.inViewportChildren;
×
926
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
927
        this.inViewportIndics = virtualView.inViewportIndics;
×
928
    }
929

930
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
931
        if (!this.inViewportChildren.length) {
×
932
            if (isDebug) {
×
933
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
934
            }
935
            return {
×
936
                isDifferent: true,
937
                changedIndexesOfTop: [],
938
                changedIndexesOfBottom: []
939
            };
940
        }
941
        const oldIndexesInViewport = [...this.inViewportIndics];
×
942
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
943
        const firstNewIndex = newIndexesInViewport[0];
×
944
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
945
        const firstOldIndex = oldIndexesInViewport[0];
×
946
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
947
        const isSameViewport =
948
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
949
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
950
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
951
            return {
×
952
                isDifferent: !isSameViewport,
953
                changedIndexesOfTop: [],
954
                changedIndexesOfBottom: []
955
            };
956
        }
957
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
958
            const changedIndexesOfTop = [];
×
959
            const changedIndexesOfBottom = [];
×
960
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
961
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
962
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
963
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
964
            if (needRemoveOnTop || needAddOnBottom) {
×
965
                // 向下
966
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
967
                    const element = oldIndexesInViewport[index];
×
968
                    if (!newIndexesInViewport.includes(element)) {
×
969
                        changedIndexesOfTop.push(element);
×
970
                    } else {
971
                        break;
×
972
                    }
973
                }
974
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
975
                    const element = newIndexesInViewport[index];
×
976
                    if (!oldIndexesInViewport.includes(element)) {
×
977
                        changedIndexesOfBottom.push(element);
×
978
                    } else {
979
                        break;
×
980
                    }
981
                }
982
            } else if (needAddOnTop || needRemoveOnBottom) {
×
983
                // 向上
984
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
985
                    const element = newIndexesInViewport[index];
×
986
                    if (!oldIndexesInViewport.includes(element)) {
×
987
                        changedIndexesOfTop.push(element);
×
988
                    } else {
989
                        break;
×
990
                    }
991
                }
992
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
993
                    const element = oldIndexesInViewport[index];
×
994
                    if (!newIndexesInViewport.includes(element)) {
×
995
                        changedIndexesOfBottom.push(element);
×
996
                    } else {
997
                        break;
×
998
                    }
999
                }
1000
            }
1001
            if (isDebug) {
×
1002
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
1003
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
1004
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
1005
                // this.editor.children[index] will be undefined when it is removed
UNCOV
1006
                debugLog(
×
1007
                    'log',
1008
                    'changedIndexesOfTop:',
1009
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
1010
                    changedIndexesOfTop,
1011
                    changedIndexesOfTop.map(
1012
                        index =>
NEW
1013
                            (this.editor.children[index] &&
×
1014
                                getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0)) ||
1015
                            0
1016
                    )
1017
                );
1018
                debugLog(
×
1019
                    'log',
1020
                    'changedIndexesOfBottom:',
1021
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
1022
                    changedIndexesOfBottom,
1023
                    changedIndexesOfBottom.map(
1024
                        index =>
NEW
1025
                            (this.editor.children[index] &&
×
1026
                                getRealHeightByElement(this.editor, this.editor.children[index] as Element, 0)) ||
1027
                            0
1028
                    )
1029
                );
1030
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
1031
                const needBottom = virtualView.heights
×
1032
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
1033
                    .reduce((acc, height) => acc + height, 0);
×
1034
                debugLog(
×
1035
                    'log',
1036
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
1037
                    'newTopHeight:',
1038
                    needTop,
1039
                    'prevTopHeight:',
1040
                    parseFloat(this.virtualTopHeightElement.style.height)
1041
                );
1042
                debugLog(
×
1043
                    'log',
1044
                    'newBottomHeight:',
1045
                    needBottom,
1046
                    'prevBottomHeight:',
1047
                    parseFloat(this.virtualBottomHeightElement.style.height)
1048
                );
1049
                debugLog('warn', '=========== Dividing line ===========');
×
1050
            }
1051
            return {
×
1052
                isDifferent: true,
1053
                needRemoveOnTop,
1054
                needAddOnTop,
1055
                needRemoveOnBottom,
1056
                needAddOnBottom,
1057
                changedIndexesOfTop,
1058
                changedIndexesOfBottom
1059
            };
1060
        }
1061
        return {
×
1062
            isDifferent: false,
1063
            changedIndexesOfTop: [],
1064
            changedIndexesOfBottom: []
1065
        };
1066
    }
1067

1068
    //#region event proxy
1069
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1070
        this.manualListeners.push(
483✔
1071
            this.renderer2.listen(target, eventName, (event: Event) => {
1072
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1073
                if (beforeInputEvent) {
5!
1074
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1075
                }
1076
                listener(event);
5✔
1077
            })
1078
        );
1079
    }
1080

1081
    private toSlateSelection() {
1082
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1083
            try {
1✔
1084
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1085
                const { activeElement } = root;
1✔
1086
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1087
                const domSelection = (root as Document).getSelection();
1✔
1088

1089
                if (activeElement === el) {
1!
1090
                    this.latestElement = activeElement;
1✔
1091
                    IS_FOCUSED.set(this.editor, true);
1✔
1092
                } else {
1093
                    IS_FOCUSED.delete(this.editor);
×
1094
                }
1095

1096
                if (!domSelection) {
1!
1097
                    return Transforms.deselect(this.editor);
×
1098
                }
1099

1100
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1101
                const hasDomSelectionInEditor =
1102
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1103
                if (!hasDomSelectionInEditor) {
1!
1104
                    Transforms.deselect(this.editor);
×
1105
                    return;
×
1106
                }
1107

1108
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1109
                // for example, double-click the last cell of the table to select a non-editable DOM
1110
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1111
                if (range) {
1✔
1112
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1113
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1114
                            // force adjust DOMSelection
1115
                            this.toNativeSelection(false);
×
1116
                        }
1117
                    } else {
1118
                        Transforms.select(this.editor, range);
1✔
1119
                    }
1120
                }
1121
            } catch (error) {
1122
                this.editor.onError({
×
1123
                    code: SlateErrorCode.ToSlateSelectionError,
1124
                    nativeError: error
1125
                });
1126
            }
1127
        }
1128
    }
1129

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

1208
                // COMPAT: If the selection is expanded, even if the command seems like
1209
                // a delete forward/backward command it should delete the selection.
1210
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1211
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1212
                    Editor.deleteFragment(editor, { direction });
×
1213
                    return;
×
1214
                }
1215

1216
                switch (type) {
×
1217
                    case 'deleteByComposition':
1218
                    case 'deleteByCut':
1219
                    case 'deleteByDrag': {
1220
                        Editor.deleteFragment(editor);
×
1221
                        break;
×
1222
                    }
1223

1224
                    case 'deleteContent':
1225
                    case 'deleteContentForward': {
1226
                        Editor.deleteForward(editor);
×
1227
                        break;
×
1228
                    }
1229

1230
                    case 'deleteContentBackward': {
1231
                        Editor.deleteBackward(editor);
×
1232
                        break;
×
1233
                    }
1234

1235
                    case 'deleteEntireSoftLine': {
1236
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1237
                        Editor.deleteForward(editor, { unit: 'line' });
×
1238
                        break;
×
1239
                    }
1240

1241
                    case 'deleteHardLineBackward': {
1242
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1243
                        break;
×
1244
                    }
1245

1246
                    case 'deleteSoftLineBackward': {
1247
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1248
                        break;
×
1249
                    }
1250

1251
                    case 'deleteHardLineForward': {
1252
                        Editor.deleteForward(editor, { unit: 'block' });
×
1253
                        break;
×
1254
                    }
1255

1256
                    case 'deleteSoftLineForward': {
1257
                        Editor.deleteForward(editor, { unit: 'line' });
×
1258
                        break;
×
1259
                    }
1260

1261
                    case 'deleteWordBackward': {
1262
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1263
                        break;
×
1264
                    }
1265

1266
                    case 'deleteWordForward': {
1267
                        Editor.deleteForward(editor, { unit: 'word' });
×
1268
                        break;
×
1269
                    }
1270

1271
                    case 'insertLineBreak':
1272
                    case 'insertParagraph': {
1273
                        Editor.insertBreak(editor);
×
1274
                        break;
×
1275
                    }
1276

1277
                    case 'insertFromComposition': {
1278
                        // COMPAT: in safari, `compositionend` event is dispatched after
1279
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1280
                        // https://www.w3.org/TR/input-events-2/
1281
                        // so the following code is the right logic
1282
                        // because DOM selection in sync will be exec before `compositionend` event
1283
                        // isComposing is true will prevent DOM selection being update correctly.
1284
                        this.isComposing = false;
×
1285
                        preventInsertFromComposition(event, this.editor);
×
1286
                    }
1287
                    case 'insertFromDrop':
1288
                    case 'insertFromPaste':
1289
                    case 'insertFromYank':
1290
                    case 'insertReplacementText':
1291
                    case 'insertText': {
1292
                        // use a weak comparison instead of 'instanceof' to allow
1293
                        // programmatic access of paste events coming from external windows
1294
                        // like cypress where cy.window does not work realibly
1295
                        if (data?.constructor.name === 'DataTransfer') {
×
1296
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1297
                        } else if (typeof data === 'string') {
×
1298
                            Editor.insertText(editor, data);
×
1299
                        }
1300
                        break;
×
1301
                    }
1302
                }
1303
            } catch (error) {
1304
                this.editor.onError({
×
1305
                    code: SlateErrorCode.OnDOMBeforeInputError,
1306
                    nativeError: error
1307
                });
1308
            }
1309
        }
1310
    }
1311

1312
    private onDOMBlur(event: FocusEvent) {
1313
        if (
×
1314
            this.readonly ||
×
1315
            this.isUpdatingSelection ||
1316
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1317
            this.isDOMEventHandled(event, this.blur)
1318
        ) {
1319
            return;
×
1320
        }
1321

1322
        const window = AngularEditor.getWindow(this.editor);
×
1323

1324
        // COMPAT: If the current `activeElement` is still the previous
1325
        // one, this is due to the window being blurred when the tab
1326
        // itself becomes unfocused, so we want to abort early to allow to
1327
        // editor to stay focused when the tab becomes focused again.
1328
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1329
        if (this.latestElement === root.activeElement) {
×
1330
            return;
×
1331
        }
1332

1333
        const { relatedTarget } = event;
×
1334
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1335

1336
        // COMPAT: The event should be ignored if the focus is returning
1337
        // to the editor from an embedded editable element (eg. an <input>
1338
        // element inside a void node).
1339
        if (relatedTarget === el) {
×
1340
            return;
×
1341
        }
1342

1343
        // COMPAT: The event should be ignored if the focus is moving from
1344
        // the editor to inside a void node's spacer element.
1345
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1346
            return;
×
1347
        }
1348

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

1355
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1356
                return;
×
1357
            }
1358
        }
1359

1360
        IS_FOCUSED.delete(this.editor);
×
1361
    }
1362

1363
    private onDOMClick(event: MouseEvent) {
1364
        if (
×
1365
            !this.readonly &&
×
1366
            AngularEditor.hasTarget(this.editor, event.target) &&
1367
            !this.isDOMEventHandled(event, this.click) &&
1368
            isDOMNode(event.target)
1369
        ) {
1370
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1371
            const path = AngularEditor.findPath(this.editor, node);
×
1372
            const start = Editor.start(this.editor, path);
×
1373
            const end = Editor.end(this.editor, path);
×
1374

1375
            const startVoid = Editor.void(this.editor, { at: start });
×
1376
            const endVoid = Editor.void(this.editor, { at: end });
×
1377

1378
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1379
                let blockPath = path;
×
1380
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1381
                    const block = Editor.above(this.editor, {
×
1382
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1383
                        at: path
1384
                    });
1385

1386
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1387
                }
1388

1389
                const range = Editor.range(this.editor, blockPath);
×
1390
                Transforms.select(this.editor, range);
×
1391
                return;
×
1392
            }
1393

1394
            if (
×
1395
                startVoid &&
×
1396
                endVoid &&
1397
                Path.equals(startVoid[1], endVoid[1]) &&
1398
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1399
            ) {
1400
                const range = Editor.range(this.editor, start);
×
1401
                Transforms.select(this.editor, range);
×
1402
            }
1403
        }
1404
    }
1405

1406
    private onDOMCompositionStart(event: CompositionEvent) {
1407
        const { selection } = this.editor;
1✔
1408
        if (selection) {
1!
1409
            // solve the problem of cross node Chinese input
1410
            if (Range.isExpanded(selection)) {
×
1411
                Editor.deleteFragment(this.editor);
×
1412
                this.forceRender();
×
1413
            }
1414
        }
1415
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1416
            this.isComposing = true;
1✔
1417
        }
1418
        this.render();
1✔
1419
    }
1420

1421
    private onDOMCompositionUpdate(event: CompositionEvent) {
1422
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1423
    }
1424

1425
    private onDOMCompositionEnd(event: CompositionEvent) {
1426
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1427
            Transforms.delete(this.editor);
×
1428
        }
1429
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1430
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1431
            // aren't correct and never fire the "insertFromComposition"
1432
            // type that we need. So instead, insert whenever a composition
1433
            // ends since it will already have been committed to the DOM.
1434
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1435
                preventInsertFromComposition(event, this.editor);
×
1436
                Editor.insertText(this.editor, event.data);
×
1437
            }
1438

1439
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1440
            // so we need avoid repeat isnertText by isComposing === true,
1441
            this.isComposing = false;
×
1442
        }
1443
        this.render();
×
1444
    }
1445

1446
    private onDOMCopy(event: ClipboardEvent) {
1447
        const window = AngularEditor.getWindow(this.editor);
×
1448
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1449
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1450
            event.preventDefault();
×
1451
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1452
        }
1453
    }
1454

1455
    private onDOMCut(event: ClipboardEvent) {
1456
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1457
            event.preventDefault();
×
1458
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1459
            const { selection } = this.editor;
×
1460

1461
            if (selection) {
×
1462
                AngularEditor.deleteCutData(this.editor);
×
1463
            }
1464
        }
1465
    }
1466

1467
    private onDOMDragOver(event: DragEvent) {
1468
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1469
            // Only when the target is void, call `preventDefault` to signal
1470
            // that drops are allowed. Editable content is droppable by
1471
            // default, and calling `preventDefault` hides the cursor.
1472
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1473

1474
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1475
                event.preventDefault();
×
1476
            }
1477
        }
1478
    }
1479

1480
    private onDOMDragStart(event: DragEvent) {
1481
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1482
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1483
            const path = AngularEditor.findPath(this.editor, node);
×
1484
            const voidMatch =
1485
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1486

1487
            // If starting a drag on a void node, make sure it is selected
1488
            // so that it shows up in the selection's fragment.
1489
            if (voidMatch) {
×
1490
                const range = Editor.range(this.editor, path);
×
1491
                Transforms.select(this.editor, range);
×
1492
            }
1493

1494
            this.isDraggingInternally = true;
×
1495

1496
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1497
        }
1498
    }
1499

1500
    private onDOMDrop(event: DragEvent) {
1501
        const editor = this.editor;
×
1502
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1503
            event.preventDefault();
×
1504
            // Keep a reference to the dragged range before updating selection
1505
            const draggedRange = editor.selection;
×
1506

1507
            // Find the range where the drop happened
1508
            const range = AngularEditor.findEventRange(editor, event);
×
1509
            const data = event.dataTransfer;
×
1510

1511
            Transforms.select(editor, range);
×
1512

1513
            if (this.isDraggingInternally) {
×
1514
                if (draggedRange) {
×
1515
                    Transforms.delete(editor, {
×
1516
                        at: draggedRange
1517
                    });
1518
                }
1519

1520
                this.isDraggingInternally = false;
×
1521
            }
1522

1523
            AngularEditor.insertData(editor, data);
×
1524

1525
            // When dragging from another source into the editor, it's possible
1526
            // that the current editor does not have focus.
1527
            if (!AngularEditor.isFocused(editor)) {
×
1528
                AngularEditor.focus(editor);
×
1529
            }
1530
        }
1531
    }
1532

1533
    private onDOMDragEnd(event: DragEvent) {
1534
        if (
×
1535
            !this.readonly &&
×
1536
            this.isDraggingInternally &&
1537
            AngularEditor.hasTarget(this.editor, event.target) &&
1538
            !this.isDOMEventHandled(event, this.dragEnd)
1539
        ) {
1540
            this.isDraggingInternally = false;
×
1541
        }
1542
    }
1543

1544
    private onDOMFocus(event: Event) {
1545
        if (
2✔
1546
            !this.readonly &&
8✔
1547
            !this.isUpdatingSelection &&
1548
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1549
            !this.isDOMEventHandled(event, this.focus)
1550
        ) {
1551
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1552
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1553
            this.latestElement = root.activeElement;
2✔
1554

1555
            // COMPAT: If the editor has nested editable elements, the focus
1556
            // can go to them. In Firefox, this must be prevented because it
1557
            // results in issues with keyboard navigation. (2017/03/30)
1558
            if (IS_FIREFOX && event.target !== el) {
2!
1559
                el.focus();
×
1560
                return;
×
1561
            }
1562

1563
            IS_FOCUSED.set(this.editor, true);
2✔
1564
        }
1565
    }
1566

1567
    private onDOMKeydown(event: KeyboardEvent) {
1568
        const editor = this.editor;
×
1569
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1570
        const { activeElement } = root;
×
1571
        if (
×
1572
            !this.readonly &&
×
1573
            AngularEditor.hasEditableTarget(editor, event.target) &&
1574
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1575
            !this.isComposing &&
1576
            !this.isDOMEventHandled(event, this.keydown)
1577
        ) {
1578
            const nativeEvent = event;
×
1579
            const { selection } = editor;
×
1580

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

1584
            try {
×
1585
                // COMPAT: Since we prevent the default behavior on
1586
                // `beforeinput` events, the browser doesn't think there's ever
1587
                // any history stack to undo or redo, so we have to manage these
1588
                // hotkeys ourselves. (2019/11/06)
1589
                if (Hotkeys.isRedo(nativeEvent)) {
×
1590
                    event.preventDefault();
×
1591

1592
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1593
                        editor.redo();
×
1594
                    }
1595

1596
                    return;
×
1597
                }
1598

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

1602
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1603
                        editor.undo();
×
1604
                    }
1605

1606
                    return;
×
1607
                }
1608

1609
                // COMPAT: Certain browsers don't handle the selection updates
1610
                // properly. In Chrome, the selection isn't properly extended.
1611
                // And in Firefox, the selection isn't properly collapsed.
1612
                // (2017/10/17)
1613
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1614
                    event.preventDefault();
×
1615
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1616
                    return;
×
1617
                }
1618

1619
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1620
                    event.preventDefault();
×
1621
                    Transforms.move(editor, { unit: 'line' });
×
1622
                    return;
×
1623
                }
1624

1625
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1626
                    event.preventDefault();
×
1627
                    Transforms.move(editor, {
×
1628
                        unit: 'line',
1629
                        edge: 'focus',
1630
                        reverse: true
1631
                    });
1632
                    return;
×
1633
                }
1634

1635
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1636
                    event.preventDefault();
×
1637
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1638
                    return;
×
1639
                }
1640

1641
                // COMPAT: If a void node is selected, or a zero-width text node
1642
                // adjacent to an inline is selected, we need to handle these
1643
                // hotkeys manually because browsers won't be able to skip over
1644
                // the void node with the zero-width space not being an empty
1645
                // string.
1646
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1647
                    event.preventDefault();
×
1648

1649
                    if (selection && Range.isCollapsed(selection)) {
×
1650
                        Transforms.move(editor, { reverse: !isRTL });
×
1651
                    } else {
1652
                        Transforms.collapse(editor, { edge: 'start' });
×
1653
                    }
1654

1655
                    return;
×
1656
                }
1657

1658
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1659
                    event.preventDefault();
×
1660
                    if (selection && Range.isCollapsed(selection)) {
×
1661
                        Transforms.move(editor, { reverse: isRTL });
×
1662
                    } else {
1663
                        Transforms.collapse(editor, { edge: 'end' });
×
1664
                    }
1665

1666
                    return;
×
1667
                }
1668

1669
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1670
                    event.preventDefault();
×
1671

1672
                    if (selection && Range.isExpanded(selection)) {
×
1673
                        Transforms.collapse(editor, { edge: 'focus' });
×
1674
                    }
1675

1676
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1677
                    return;
×
1678
                }
1679

1680
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1681
                    event.preventDefault();
×
1682

1683
                    if (selection && Range.isExpanded(selection)) {
×
1684
                        Transforms.collapse(editor, { edge: 'focus' });
×
1685
                    }
1686

1687
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1688
                    return;
×
1689
                }
1690

1691
                if (isKeyHotkey('mod+a', event)) {
×
1692
                    this.editor.selectAll();
×
1693
                    event.preventDefault();
×
1694
                    return;
×
1695
                }
1696

1697
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1698
                // fall back to guessing at the input intention for hotkeys.
1699
                // COMPAT: In iOS, some of these hotkeys are handled in the
1700
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1701
                    // We don't have a core behavior for these, but they change the
1702
                    // DOM if we don't prevent them, so we have to.
1703
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1704
                        event.preventDefault();
×
1705
                        return;
×
1706
                    }
1707

1708
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1709
                        event.preventDefault();
×
1710
                        Editor.insertBreak(editor);
×
1711
                        return;
×
1712
                    }
1713

1714
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1715
                        event.preventDefault();
×
1716

1717
                        if (selection && Range.isExpanded(selection)) {
×
1718
                            Editor.deleteFragment(editor, {
×
1719
                                direction: 'backward'
1720
                            });
1721
                        } else {
1722
                            Editor.deleteBackward(editor);
×
1723
                        }
1724

1725
                        return;
×
1726
                    }
1727

1728
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1729
                        event.preventDefault();
×
1730

1731
                        if (selection && Range.isExpanded(selection)) {
×
1732
                            Editor.deleteFragment(editor, {
×
1733
                                direction: 'forward'
1734
                            });
1735
                        } else {
1736
                            Editor.deleteForward(editor);
×
1737
                        }
1738

1739
                        return;
×
1740
                    }
1741

1742
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1743
                        event.preventDefault();
×
1744

1745
                        if (selection && Range.isExpanded(selection)) {
×
1746
                            Editor.deleteFragment(editor, {
×
1747
                                direction: 'backward'
1748
                            });
1749
                        } else {
1750
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1751
                        }
1752

1753
                        return;
×
1754
                    }
1755

1756
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1757
                        event.preventDefault();
×
1758

1759
                        if (selection && Range.isExpanded(selection)) {
×
1760
                            Editor.deleteFragment(editor, {
×
1761
                                direction: 'forward'
1762
                            });
1763
                        } else {
1764
                            Editor.deleteForward(editor, { unit: 'line' });
×
1765
                        }
1766

1767
                        return;
×
1768
                    }
1769

1770
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1771
                        event.preventDefault();
×
1772

1773
                        if (selection && Range.isExpanded(selection)) {
×
1774
                            Editor.deleteFragment(editor, {
×
1775
                                direction: 'backward'
1776
                            });
1777
                        } else {
1778
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1779
                        }
1780

1781
                        return;
×
1782
                    }
1783

1784
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1785
                        event.preventDefault();
×
1786

1787
                        if (selection && Range.isExpanded(selection)) {
×
1788
                            Editor.deleteFragment(editor, {
×
1789
                                direction: 'forward'
1790
                            });
1791
                        } else {
1792
                            Editor.deleteForward(editor, { unit: 'word' });
×
1793
                        }
1794

1795
                        return;
×
1796
                    }
1797
                } else {
1798
                    if (IS_CHROME || IS_SAFARI) {
×
1799
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1800
                        // an event when deleting backwards in a selected void inline node
1801
                        if (
×
1802
                            selection &&
×
1803
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1804
                            Range.isCollapsed(selection)
1805
                        ) {
1806
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1807
                            if (
×
1808
                                Element.isElement(currentNode) &&
×
1809
                                Editor.isVoid(editor, currentNode) &&
1810
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1811
                            ) {
1812
                                event.preventDefault();
×
1813
                                Editor.deleteBackward(editor, {
×
1814
                                    unit: 'block'
1815
                                });
1816
                                return;
×
1817
                            }
1818
                        }
1819
                    }
1820
                }
1821
            } catch (error) {
1822
                this.editor.onError({
×
1823
                    code: SlateErrorCode.OnDOMKeydownError,
1824
                    nativeError: error
1825
                });
1826
            }
1827
        }
1828
    }
1829

1830
    private onDOMPaste(event: ClipboardEvent) {
1831
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1832
        // fall back to React's `onPaste` here instead.
1833
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1834
        // when "paste without formatting" option is used.
1835
        // This unfortunately needs to be handled with paste events instead.
1836
        if (
×
1837
            !this.isDOMEventHandled(event, this.paste) &&
×
1838
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1839
            !this.readonly &&
1840
            AngularEditor.hasEditableTarget(this.editor, event.target)
1841
        ) {
1842
            event.preventDefault();
×
1843
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1844
        }
1845
    }
1846

1847
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1848
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1849
        // fall back to React's leaky polyfill instead just for it. It
1850
        // only works for the `insertText` input type.
1851
        if (
×
1852
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1853
            !this.readonly &&
1854
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1855
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1856
        ) {
1857
            event.nativeEvent.preventDefault();
×
1858
            try {
×
1859
                const text = event.data;
×
1860
                if (!Range.isCollapsed(this.editor.selection)) {
×
1861
                    Editor.deleteFragment(this.editor);
×
1862
                }
1863
                // just handle Non-IME input
1864
                if (!this.isComposing) {
×
1865
                    Editor.insertText(this.editor, text);
×
1866
                }
1867
            } catch (error) {
1868
                this.editor.onError({
×
1869
                    code: SlateErrorCode.ToNativeSelectionError,
1870
                    nativeError: error
1871
                });
1872
            }
1873
        }
1874
    }
1875

1876
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1877
        if (!handler) {
3✔
1878
            return false;
3✔
1879
        }
1880
        handler(event);
×
1881
        return event.defaultPrevented;
×
1882
    }
1883
    //#endregion
1884

1885
    ngOnDestroy() {
1886
        this.editorResizeObserver?.disconnect();
23✔
1887
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1888
        this.manualListeners.forEach(manualListener => {
23✔
1889
            manualListener();
483✔
1890
        });
1891
        this.destroy$.complete();
23✔
1892
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1893
    }
1894
}
1895

1896
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1897
    // This was affecting the selection of multiple blocks and dragging behavior,
1898
    // so enabled only if the selection has been collapsed.
1899
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1900
        const leafEl = domRange.startContainer.parentElement!;
×
1901

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

1907
        if (isZeroDimensionRect) {
×
1908
            const leafRect = leafEl.getBoundingClientRect();
×
1909
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1910

1911
            if (leafHasDimensions) {
×
1912
                return;
×
1913
            }
1914
        }
1915

1916
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1917
        scrollIntoView(leafEl, {
×
1918
            scrollMode: 'if-needed'
1919
        });
1920
        delete leafEl.getBoundingClientRect;
×
1921
    }
1922
};
1923

1924
/**
1925
 * Check if the target is inside void and in the editor.
1926
 */
1927

1928
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1929
    let slateNode: Node | null = null;
1✔
1930
    try {
1✔
1931
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1932
    } catch (error) {}
1933
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1934
};
1935

1936
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1937
    return (
2✔
1938
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1939
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1940
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1941
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1942
    );
1943
};
1944

1945
/**
1946
 * remove default insert from composition
1947
 * @param text
1948
 */
1949
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1950
    const types = ['compositionend', 'insertFromComposition'];
×
1951
    if (!types.includes(event.type)) {
×
1952
        return;
×
1953
    }
1954
    const insertText = (event as CompositionEvent).data;
×
1955
    const window = AngularEditor.getWindow(editor);
×
1956
    const domSelection = window.getSelection();
×
1957
    // ensure text node insert composition input text
1958
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1959
        const textNode = domSelection.anchorNode;
×
1960
        textNode.splitText(textNode.length - insertText.length).remove();
×
1961
    }
1962
};
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