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

worktile / slate-angular / 42dd0296-afc8-4ad2-b465-5ab825fdd746

12 Jan 2026 02:18AM UTC coverage: 36.802% (+0.07%) from 36.73%
42dd0296-afc8-4ad2-b465-5ab825fdd746

push

circleci

web-flow
feat: optimize measure height timing (#332)

401 of 1286 branches covered (31.18%)

Branch coverage included in aggregate %.

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

1 existing line in 1 file now uncovered.

1102 of 2798 relevant lines covered (39.39%)

23.9 hits per line

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

23.08
/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 { debounceTime, 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 editorResizeObserver?: ResizeObserver;
218

219
    viewportRefresh$ = new Subject<void>();
23✔
220

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

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

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

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

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

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

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

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

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

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

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

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

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

414
            const hasDomSelection = domSelection.type !== 'None';
1✔
415

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

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

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

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

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

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

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

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

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

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

521
    ngAfterViewChecked() {}
522

523
    ngDoCheck() {}
524

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

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

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

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

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

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

650
    composePlaceholderDecorate(editor: Editor) {
651
        if (this.placeholderDecorate) {
64!
652
            return this.placeholderDecorate(editor) || [];
×
653
        }
654

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

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

676
    private isEnabledVirtualScroll() {
677
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
678
    }
679

680
    virtualScrollInitialized = false;
23✔
681

682
    virtualTopHeightElement: HTMLElement;
683

684
    virtualBottomHeightElement: HTMLElement;
685

686
    virtualCenterOutlet: HTMLElement;
687

688
    initializeVirtualScroll() {
689
        if (this.virtualScrollInitialized) {
23!
690
            return;
×
691
        }
692
        if (this.isEnabledVirtualScroll()) {
23!
693
            this.virtualScrollInitialized = true;
×
694
            this.virtualTopHeightElement = document.createElement('div');
×
695
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
696
            this.virtualTopHeightElement.contentEditable = 'false';
×
697
            this.virtualBottomHeightElement = document.createElement('div');
×
698
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
699
            this.virtualBottomHeightElement.contentEditable = 'false';
×
700
            this.virtualCenterOutlet = document.createElement('div');
×
701
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
702
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
703
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
704
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
705
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
706
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
707
            this.editorResizeObserver = new ResizeObserver(entries => {
×
708
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
709
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
710
                    this.keyHeightMap.clear();
×
711
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
NEW
712
                    this.viewportRefresh$.next();
×
713
                    if (isDebug) {
×
714
                        debugLog(
×
715
                            'log',
716
                            'editorResizeObserverRectWidth: ',
717
                            editorResizeObserverRectWidth,
718
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
719
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
720
                        );
721
                    }
722
                }
723
            });
724
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
NEW
725
            this.viewportRefresh$.pipe(debounceTime(1000)).subscribe(() => {
×
NEW
726
                const res = measureHeightByIndics(this.editor, this.inViewportIndics);
×
NEW
727
                if (isDebug) {
×
NEW
728
                    debugLog(
×
729
                        'log',
730
                        'viewportRefresh$ debounceTime 1000ms',
731
                        'inViewportIndics: ',
732
                        this.inViewportIndics,
733
                        'measureHeightByIndics height changed: ',
734
                        res
735
                    );
736
                }
737
            });
738
        }
739
    }
740

741
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
742
        if (!this.virtualScrollInitialized) {
×
743
            return;
×
744
        }
745
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
746
        if (bottomHeight !== undefined) {
×
747
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
748
        }
749
    }
750

751
    getActualVirtualTopHeight() {
752
        if (!this.virtualScrollInitialized) {
×
753
            return 0;
×
754
        }
755
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
756
    }
757

758
    handlePreRendering() {
759
        let preRenderingCount = 0;
×
760
        const childrenWithPreRendering = [...this.inViewportChildren];
×
761
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
762
        const firstIndex = this.inViewportIndics[0];
×
763
        for (let index = firstIndex - 1; index >= 0; index--) {
×
764
            const element = this.editor.children[index] as Element;
×
765
            if (this.editor.isVisible(element)) {
×
766
                childrenWithPreRendering.unshift(element);
×
767
                childrenWithPreRenderingIndics.unshift(index);
×
768
                preRenderingCount = 1;
×
769
                break;
×
770
            }
771
        }
772
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
773
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
774
            const element = this.editor.children[index] as Element;
×
775
            if (this.editor.isVisible(element)) {
×
776
                childrenWithPreRendering.push(element);
×
777
                childrenWithPreRenderingIndics.push(index);
×
778
                break;
×
779
            }
780
        }
781
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
782
    }
783

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

862
    private calculateVirtualViewport() {
863
        const children = (this.editor.children || []) as Element[];
×
864
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
865
            return {
×
866
                inViewportChildren: children,
867
                inViewportIndics: [],
868
                top: 0,
869
                bottom: 0,
870
                heights: []
871
            };
872
        }
873
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
874
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
875
        if (!viewportHeight) {
×
876
            return {
×
877
                inViewportChildren: [],
878
                inViewportIndics: [],
879
                top: 0,
880
                bottom: 0,
881
                heights: []
882
            };
883
        }
884
        const elementLength = children.length;
×
885
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
886
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
887
            setTimeout(() => {
×
888
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
889
                const businessTop =
890
                    Math.ceil(virtualTopBoundingTop) +
×
891
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
892
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
893
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
894
                if (isDebug) {
×
895
                    debugLog('log', 'businessTop', businessTop);
×
896
                }
897
            }, 100);
898
        }
899
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
900
        const { heights, accumulatedHeights, visibleStates } = buildHeightsAndAccumulatedHeights(this.editor);
×
901
        const totalHeight = accumulatedHeights[elementLength];
×
902
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
903
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
904
        const viewBottom = limitedScrollTop + viewportHeight;
×
905
        let accumulatedOffset = 0;
×
906
        let inViewportStartIndex = -1;
×
907
        const visible: Element[] = [];
×
908
        const inViewportIndics: number[] = [];
×
909

910
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
911
            const currentHeight = heights[i];
×
912
            const nextOffset = accumulatedOffset + currentHeight;
×
913
            if (!visibleStates[i]) {
×
914
                accumulatedOffset = nextOffset;
×
915
                continue;
×
916
            }
917
            // 可视区域有交集,加入渲染
918
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
919
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
920
                visible.push(children[i]);
×
921
                inViewportIndics.push(i);
×
922
            }
923
            accumulatedOffset = nextOffset;
×
924
        }
925

926
        const inViewportEndIndex =
927
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
928
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
929
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
930
        return {
×
931
            inViewportChildren: visible.length ? visible : children,
×
932
            inViewportIndics,
933
            top,
934
            bottom,
935
            heights,
936
            accumulatedHeights
937
        };
938
    }
939

940
    private applyVirtualView(virtualView: VirtualViewResult) {
941
        this.inViewportChildren = virtualView.inViewportChildren;
×
942
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
943
        this.inViewportIndics = virtualView.inViewportIndics;
×
944
    }
945

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

1084
    //#region event proxy
1085
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
1086
        this.manualListeners.push(
483✔
1087
            this.renderer2.listen(target, eventName, (event: Event) => {
1088
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
1089
                if (beforeInputEvent) {
5!
1090
                    this.onFallbackBeforeInput(beforeInputEvent);
×
1091
                }
1092
                listener(event);
5✔
1093
            })
1094
        );
1095
    }
1096

1097
    private toSlateSelection() {
1098
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1099
            try {
1✔
1100
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1101
                const { activeElement } = root;
1✔
1102
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1103
                const domSelection = (root as Document).getSelection();
1✔
1104

1105
                if (activeElement === el) {
1!
1106
                    this.latestElement = activeElement;
1✔
1107
                    IS_FOCUSED.set(this.editor, true);
1✔
1108
                } else {
1109
                    IS_FOCUSED.delete(this.editor);
×
1110
                }
1111

1112
                if (!domSelection) {
1!
1113
                    return Transforms.deselect(this.editor);
×
1114
                }
1115

1116
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1117
                const hasDomSelectionInEditor =
1118
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1119
                if (!hasDomSelectionInEditor) {
1!
1120
                    Transforms.deselect(this.editor);
×
1121
                    return;
×
1122
                }
1123

1124
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1125
                // for example, double-click the last cell of the table to select a non-editable DOM
1126
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1127
                if (range) {
1✔
1128
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1129
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1130
                            // force adjust DOMSelection
1131
                            this.toNativeSelection(false);
×
1132
                        }
1133
                    } else {
1134
                        Transforms.select(this.editor, range);
1✔
1135
                    }
1136
                }
1137
            } catch (error) {
1138
                this.editor.onError({
×
1139
                    code: SlateErrorCode.ToSlateSelectionError,
1140
                    nativeError: error
1141
                });
1142
            }
1143
        }
1144
    }
1145

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

1224
                // COMPAT: If the selection is expanded, even if the command seems like
1225
                // a delete forward/backward command it should delete the selection.
1226
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1227
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1228
                    Editor.deleteFragment(editor, { direction });
×
1229
                    return;
×
1230
                }
1231

1232
                switch (type) {
×
1233
                    case 'deleteByComposition':
1234
                    case 'deleteByCut':
1235
                    case 'deleteByDrag': {
1236
                        Editor.deleteFragment(editor);
×
1237
                        break;
×
1238
                    }
1239

1240
                    case 'deleteContent':
1241
                    case 'deleteContentForward': {
1242
                        Editor.deleteForward(editor);
×
1243
                        break;
×
1244
                    }
1245

1246
                    case 'deleteContentBackward': {
1247
                        Editor.deleteBackward(editor);
×
1248
                        break;
×
1249
                    }
1250

1251
                    case 'deleteEntireSoftLine': {
1252
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1253
                        Editor.deleteForward(editor, { unit: 'line' });
×
1254
                        break;
×
1255
                    }
1256

1257
                    case 'deleteHardLineBackward': {
1258
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1259
                        break;
×
1260
                    }
1261

1262
                    case 'deleteSoftLineBackward': {
1263
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1264
                        break;
×
1265
                    }
1266

1267
                    case 'deleteHardLineForward': {
1268
                        Editor.deleteForward(editor, { unit: 'block' });
×
1269
                        break;
×
1270
                    }
1271

1272
                    case 'deleteSoftLineForward': {
1273
                        Editor.deleteForward(editor, { unit: 'line' });
×
1274
                        break;
×
1275
                    }
1276

1277
                    case 'deleteWordBackward': {
1278
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1279
                        break;
×
1280
                    }
1281

1282
                    case 'deleteWordForward': {
1283
                        Editor.deleteForward(editor, { unit: 'word' });
×
1284
                        break;
×
1285
                    }
1286

1287
                    case 'insertLineBreak':
1288
                    case 'insertParagraph': {
1289
                        Editor.insertBreak(editor);
×
1290
                        break;
×
1291
                    }
1292

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

1328
    private onDOMBlur(event: FocusEvent) {
1329
        if (
×
1330
            this.readonly ||
×
1331
            this.isUpdatingSelection ||
1332
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1333
            this.isDOMEventHandled(event, this.blur)
1334
        ) {
1335
            return;
×
1336
        }
1337

1338
        const window = AngularEditor.getWindow(this.editor);
×
1339

1340
        // COMPAT: If the current `activeElement` is still the previous
1341
        // one, this is due to the window being blurred when the tab
1342
        // itself becomes unfocused, so we want to abort early to allow to
1343
        // editor to stay focused when the tab becomes focused again.
1344
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1345
        if (this.latestElement === root.activeElement) {
×
1346
            return;
×
1347
        }
1348

1349
        const { relatedTarget } = event;
×
1350
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1351

1352
        // COMPAT: The event should be ignored if the focus is returning
1353
        // to the editor from an embedded editable element (eg. an <input>
1354
        // element inside a void node).
1355
        if (relatedTarget === el) {
×
1356
            return;
×
1357
        }
1358

1359
        // COMPAT: The event should be ignored if the focus is moving from
1360
        // the editor to inside a void node's spacer element.
1361
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1362
            return;
×
1363
        }
1364

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

1371
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1372
                return;
×
1373
            }
1374
        }
1375

1376
        IS_FOCUSED.delete(this.editor);
×
1377
    }
1378

1379
    private onDOMClick(event: MouseEvent) {
1380
        if (
×
1381
            !this.readonly &&
×
1382
            AngularEditor.hasTarget(this.editor, event.target) &&
1383
            !this.isDOMEventHandled(event, this.click) &&
1384
            isDOMNode(event.target)
1385
        ) {
1386
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1387
            const path = AngularEditor.findPath(this.editor, node);
×
1388
            const start = Editor.start(this.editor, path);
×
1389
            const end = Editor.end(this.editor, path);
×
1390

1391
            const startVoid = Editor.void(this.editor, { at: start });
×
1392
            const endVoid = Editor.void(this.editor, { at: end });
×
1393

1394
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1395
                let blockPath = path;
×
1396
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1397
                    const block = Editor.above(this.editor, {
×
1398
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1399
                        at: path
1400
                    });
1401

1402
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1403
                }
1404

1405
                const range = Editor.range(this.editor, blockPath);
×
1406
                Transforms.select(this.editor, range);
×
1407
                return;
×
1408
            }
1409

1410
            if (
×
1411
                startVoid &&
×
1412
                endVoid &&
1413
                Path.equals(startVoid[1], endVoid[1]) &&
1414
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1415
            ) {
1416
                const range = Editor.range(this.editor, start);
×
1417
                Transforms.select(this.editor, range);
×
1418
            }
1419
        }
1420
    }
1421

1422
    private onDOMCompositionStart(event: CompositionEvent) {
1423
        const { selection } = this.editor;
1✔
1424
        if (selection) {
1!
1425
            // solve the problem of cross node Chinese input
1426
            if (Range.isExpanded(selection)) {
×
1427
                Editor.deleteFragment(this.editor);
×
1428
                this.forceRender();
×
1429
            }
1430
        }
1431
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1432
            this.isComposing = true;
1✔
1433
        }
1434
        this.render();
1✔
1435
    }
1436

1437
    private onDOMCompositionUpdate(event: CompositionEvent) {
1438
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1439
    }
1440

1441
    private onDOMCompositionEnd(event: CompositionEvent) {
1442
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1443
            Transforms.delete(this.editor);
×
1444
        }
1445
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1446
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1447
            // aren't correct and never fire the "insertFromComposition"
1448
            // type that we need. So instead, insert whenever a composition
1449
            // ends since it will already have been committed to the DOM.
1450
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1451
                preventInsertFromComposition(event, this.editor);
×
1452
                Editor.insertText(this.editor, event.data);
×
1453
            }
1454

1455
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1456
            // so we need avoid repeat isnertText by isComposing === true,
1457
            this.isComposing = false;
×
1458
        }
1459
        this.render();
×
1460
    }
1461

1462
    private onDOMCopy(event: ClipboardEvent) {
1463
        const window = AngularEditor.getWindow(this.editor);
×
1464
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1465
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1466
            event.preventDefault();
×
1467
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1468
        }
1469
    }
1470

1471
    private onDOMCut(event: ClipboardEvent) {
1472
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1473
            event.preventDefault();
×
1474
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1475
            const { selection } = this.editor;
×
1476

1477
            if (selection) {
×
1478
                AngularEditor.deleteCutData(this.editor);
×
1479
            }
1480
        }
1481
    }
1482

1483
    private onDOMDragOver(event: DragEvent) {
1484
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1485
            // Only when the target is void, call `preventDefault` to signal
1486
            // that drops are allowed. Editable content is droppable by
1487
            // default, and calling `preventDefault` hides the cursor.
1488
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1489

1490
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1491
                event.preventDefault();
×
1492
            }
1493
        }
1494
    }
1495

1496
    private onDOMDragStart(event: DragEvent) {
1497
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1498
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1499
            const path = AngularEditor.findPath(this.editor, node);
×
1500
            const voidMatch =
1501
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1502

1503
            // If starting a drag on a void node, make sure it is selected
1504
            // so that it shows up in the selection's fragment.
1505
            if (voidMatch) {
×
1506
                const range = Editor.range(this.editor, path);
×
1507
                Transforms.select(this.editor, range);
×
1508
            }
1509

1510
            this.isDraggingInternally = true;
×
1511

1512
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1513
        }
1514
    }
1515

1516
    private onDOMDrop(event: DragEvent) {
1517
        const editor = this.editor;
×
1518
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1519
            event.preventDefault();
×
1520
            // Keep a reference to the dragged range before updating selection
1521
            const draggedRange = editor.selection;
×
1522

1523
            // Find the range where the drop happened
1524
            const range = AngularEditor.findEventRange(editor, event);
×
1525
            const data = event.dataTransfer;
×
1526

1527
            Transforms.select(editor, range);
×
1528

1529
            if (this.isDraggingInternally) {
×
1530
                if (draggedRange) {
×
1531
                    Transforms.delete(editor, {
×
1532
                        at: draggedRange
1533
                    });
1534
                }
1535

1536
                this.isDraggingInternally = false;
×
1537
            }
1538

1539
            AngularEditor.insertData(editor, data);
×
1540

1541
            // When dragging from another source into the editor, it's possible
1542
            // that the current editor does not have focus.
1543
            if (!AngularEditor.isFocused(editor)) {
×
1544
                AngularEditor.focus(editor);
×
1545
            }
1546
        }
1547
    }
1548

1549
    private onDOMDragEnd(event: DragEvent) {
1550
        if (
×
1551
            !this.readonly &&
×
1552
            this.isDraggingInternally &&
1553
            AngularEditor.hasTarget(this.editor, event.target) &&
1554
            !this.isDOMEventHandled(event, this.dragEnd)
1555
        ) {
1556
            this.isDraggingInternally = false;
×
1557
        }
1558
    }
1559

1560
    private onDOMFocus(event: Event) {
1561
        if (
2✔
1562
            !this.readonly &&
8✔
1563
            !this.isUpdatingSelection &&
1564
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1565
            !this.isDOMEventHandled(event, this.focus)
1566
        ) {
1567
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1568
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1569
            this.latestElement = root.activeElement;
2✔
1570

1571
            // COMPAT: If the editor has nested editable elements, the focus
1572
            // can go to them. In Firefox, this must be prevented because it
1573
            // results in issues with keyboard navigation. (2017/03/30)
1574
            if (IS_FIREFOX && event.target !== el) {
2!
1575
                el.focus();
×
1576
                return;
×
1577
            }
1578

1579
            IS_FOCUSED.set(this.editor, true);
2✔
1580
        }
1581
    }
1582

1583
    private onDOMKeydown(event: KeyboardEvent) {
1584
        const editor = this.editor;
×
1585
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1586
        const { activeElement } = root;
×
1587
        if (
×
1588
            !this.readonly &&
×
1589
            AngularEditor.hasEditableTarget(editor, event.target) &&
1590
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1591
            !this.isComposing &&
1592
            !this.isDOMEventHandled(event, this.keydown)
1593
        ) {
1594
            const nativeEvent = event;
×
1595
            const { selection } = editor;
×
1596

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

1600
            try {
×
1601
                // COMPAT: Since we prevent the default behavior on
1602
                // `beforeinput` events, the browser doesn't think there's ever
1603
                // any history stack to undo or redo, so we have to manage these
1604
                // hotkeys ourselves. (2019/11/06)
1605
                if (Hotkeys.isRedo(nativeEvent)) {
×
1606
                    event.preventDefault();
×
1607

1608
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1609
                        editor.redo();
×
1610
                    }
1611

1612
                    return;
×
1613
                }
1614

1615
                if (Hotkeys.isUndo(nativeEvent)) {
×
1616
                    event.preventDefault();
×
1617

1618
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1619
                        editor.undo();
×
1620
                    }
1621

1622
                    return;
×
1623
                }
1624

1625
                // COMPAT: Certain browsers don't handle the selection updates
1626
                // properly. In Chrome, the selection isn't properly extended.
1627
                // And in Firefox, the selection isn't properly collapsed.
1628
                // (2017/10/17)
1629
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1630
                    event.preventDefault();
×
1631
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1632
                    return;
×
1633
                }
1634

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

1641
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1642
                    event.preventDefault();
×
1643
                    Transforms.move(editor, {
×
1644
                        unit: 'line',
1645
                        edge: 'focus',
1646
                        reverse: true
1647
                    });
1648
                    return;
×
1649
                }
1650

1651
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1652
                    event.preventDefault();
×
1653
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1654
                    return;
×
1655
                }
1656

1657
                // COMPAT: If a void node is selected, or a zero-width text node
1658
                // adjacent to an inline is selected, we need to handle these
1659
                // hotkeys manually because browsers won't be able to skip over
1660
                // the void node with the zero-width space not being an empty
1661
                // string.
1662
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1663
                    event.preventDefault();
×
1664

1665
                    if (selection && Range.isCollapsed(selection)) {
×
1666
                        Transforms.move(editor, { reverse: !isRTL });
×
1667
                    } else {
1668
                        Transforms.collapse(editor, { edge: 'start' });
×
1669
                    }
1670

1671
                    return;
×
1672
                }
1673

1674
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1675
                    event.preventDefault();
×
1676
                    if (selection && Range.isCollapsed(selection)) {
×
1677
                        Transforms.move(editor, { reverse: isRTL });
×
1678
                    } else {
1679
                        Transforms.collapse(editor, { edge: 'end' });
×
1680
                    }
1681

1682
                    return;
×
1683
                }
1684

1685
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1686
                    event.preventDefault();
×
1687

1688
                    if (selection && Range.isExpanded(selection)) {
×
1689
                        Transforms.collapse(editor, { edge: 'focus' });
×
1690
                    }
1691

1692
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1693
                    return;
×
1694
                }
1695

1696
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1697
                    event.preventDefault();
×
1698

1699
                    if (selection && Range.isExpanded(selection)) {
×
1700
                        Transforms.collapse(editor, { edge: 'focus' });
×
1701
                    }
1702

1703
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1704
                    return;
×
1705
                }
1706

1707
                if (isKeyHotkey('mod+a', event)) {
×
1708
                    this.editor.selectAll();
×
1709
                    event.preventDefault();
×
1710
                    return;
×
1711
                }
1712

1713
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1714
                // fall back to guessing at the input intention for hotkeys.
1715
                // COMPAT: In iOS, some of these hotkeys are handled in the
1716
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1717
                    // We don't have a core behavior for these, but they change the
1718
                    // DOM if we don't prevent them, so we have to.
1719
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1720
                        event.preventDefault();
×
1721
                        return;
×
1722
                    }
1723

1724
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1725
                        event.preventDefault();
×
1726
                        Editor.insertBreak(editor);
×
1727
                        return;
×
1728
                    }
1729

1730
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1731
                        event.preventDefault();
×
1732

1733
                        if (selection && Range.isExpanded(selection)) {
×
1734
                            Editor.deleteFragment(editor, {
×
1735
                                direction: 'backward'
1736
                            });
1737
                        } else {
1738
                            Editor.deleteBackward(editor);
×
1739
                        }
1740

1741
                        return;
×
1742
                    }
1743

1744
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1745
                        event.preventDefault();
×
1746

1747
                        if (selection && Range.isExpanded(selection)) {
×
1748
                            Editor.deleteFragment(editor, {
×
1749
                                direction: 'forward'
1750
                            });
1751
                        } else {
1752
                            Editor.deleteForward(editor);
×
1753
                        }
1754

1755
                        return;
×
1756
                    }
1757

1758
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1759
                        event.preventDefault();
×
1760

1761
                        if (selection && Range.isExpanded(selection)) {
×
1762
                            Editor.deleteFragment(editor, {
×
1763
                                direction: 'backward'
1764
                            });
1765
                        } else {
1766
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1767
                        }
1768

1769
                        return;
×
1770
                    }
1771

1772
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1773
                        event.preventDefault();
×
1774

1775
                        if (selection && Range.isExpanded(selection)) {
×
1776
                            Editor.deleteFragment(editor, {
×
1777
                                direction: 'forward'
1778
                            });
1779
                        } else {
1780
                            Editor.deleteForward(editor, { unit: 'line' });
×
1781
                        }
1782

1783
                        return;
×
1784
                    }
1785

1786
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1787
                        event.preventDefault();
×
1788

1789
                        if (selection && Range.isExpanded(selection)) {
×
1790
                            Editor.deleteFragment(editor, {
×
1791
                                direction: 'backward'
1792
                            });
1793
                        } else {
1794
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1795
                        }
1796

1797
                        return;
×
1798
                    }
1799

1800
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1801
                        event.preventDefault();
×
1802

1803
                        if (selection && Range.isExpanded(selection)) {
×
1804
                            Editor.deleteFragment(editor, {
×
1805
                                direction: 'forward'
1806
                            });
1807
                        } else {
1808
                            Editor.deleteForward(editor, { unit: 'word' });
×
1809
                        }
1810

1811
                        return;
×
1812
                    }
1813
                } else {
1814
                    if (IS_CHROME || IS_SAFARI) {
×
1815
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1816
                        // an event when deleting backwards in a selected void inline node
1817
                        if (
×
1818
                            selection &&
×
1819
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1820
                            Range.isCollapsed(selection)
1821
                        ) {
1822
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1823
                            if (
×
1824
                                Element.isElement(currentNode) &&
×
1825
                                Editor.isVoid(editor, currentNode) &&
1826
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1827
                            ) {
1828
                                event.preventDefault();
×
1829
                                Editor.deleteBackward(editor, {
×
1830
                                    unit: 'block'
1831
                                });
1832
                                return;
×
1833
                            }
1834
                        }
1835
                    }
1836
                }
1837
            } catch (error) {
1838
                this.editor.onError({
×
1839
                    code: SlateErrorCode.OnDOMKeydownError,
1840
                    nativeError: error
1841
                });
1842
            }
1843
        }
1844
    }
1845

1846
    private onDOMPaste(event: ClipboardEvent) {
1847
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1848
        // fall back to React's `onPaste` here instead.
1849
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1850
        // when "paste without formatting" option is used.
1851
        // This unfortunately needs to be handled with paste events instead.
1852
        if (
×
1853
            !this.isDOMEventHandled(event, this.paste) &&
×
1854
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1855
            !this.readonly &&
1856
            AngularEditor.hasEditableTarget(this.editor, event.target)
1857
        ) {
1858
            event.preventDefault();
×
1859
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1860
        }
1861
    }
1862

1863
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1864
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1865
        // fall back to React's leaky polyfill instead just for it. It
1866
        // only works for the `insertText` input type.
1867
        if (
×
1868
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1869
            !this.readonly &&
1870
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1871
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1872
        ) {
1873
            event.nativeEvent.preventDefault();
×
1874
            try {
×
1875
                const text = event.data;
×
1876
                if (!Range.isCollapsed(this.editor.selection)) {
×
1877
                    Editor.deleteFragment(this.editor);
×
1878
                }
1879
                // just handle Non-IME input
1880
                if (!this.isComposing) {
×
1881
                    Editor.insertText(this.editor, text);
×
1882
                }
1883
            } catch (error) {
1884
                this.editor.onError({
×
1885
                    code: SlateErrorCode.ToNativeSelectionError,
1886
                    nativeError: error
1887
                });
1888
            }
1889
        }
1890
    }
1891

1892
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1893
        if (!handler) {
3✔
1894
            return false;
3✔
1895
        }
1896
        handler(event);
×
1897
        return event.defaultPrevented;
×
1898
    }
1899
    //#endregion
1900

1901
    ngOnDestroy() {
1902
        this.editorResizeObserver?.disconnect();
22✔
1903
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1904
        this.manualListeners.forEach(manualListener => {
22✔
1905
            manualListener();
462✔
1906
        });
1907
        this.destroy$.complete();
22✔
1908
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1909
    }
1910
}
1911

1912
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1913
    // This was affecting the selection of multiple blocks and dragging behavior,
1914
    // so enabled only if the selection has been collapsed.
1915
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1916
        const leafEl = domRange.startContainer.parentElement!;
×
1917

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

1923
        if (isZeroDimensionRect) {
×
1924
            const leafRect = leafEl.getBoundingClientRect();
×
1925
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1926

1927
            if (leafHasDimensions) {
×
1928
                return;
×
1929
            }
1930
        }
1931

1932
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1933
        scrollIntoView(leafEl, {
×
1934
            scrollMode: 'if-needed'
1935
        });
1936
        delete leafEl.getBoundingClientRect;
×
1937
    }
1938
};
1939

1940
/**
1941
 * Check if the target is inside void and in the editor.
1942
 */
1943

1944
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1945
    let slateNode: Node | null = null;
1✔
1946
    try {
1✔
1947
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1948
    } catch (error) {}
1949
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1950
};
1951

1952
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1953
    return (
2✔
1954
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1955
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1956
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1957
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1958
    );
1959
};
1960

1961
/**
1962
 * remove default insert from composition
1963
 * @param text
1964
 */
1965
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1966
    const types = ['compositionend', 'insertFromComposition'];
×
1967
    if (!types.includes(event.type)) {
×
1968
        return;
×
1969
    }
1970
    const insertText = (event as CompositionEvent).data;
×
1971
    const window = AngularEditor.getWindow(editor);
×
1972
    const domSelection = window.getSelection();
×
1973
    // ensure text node insert composition input text
1974
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1975
        const textNode = domSelection.anchorNode;
×
1976
        textNode.splitText(textNode.length - insertText.length).remove();
×
1977
    }
1978
};
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