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

worktile / slate-angular / 849a8a83-b43a-41b2-a7c5-8cb13d3d08ac

06 Jan 2026 05:54AM UTC coverage: 36.646% (-0.06%) from 36.704%
849a8a83-b43a-41b2-a7c5-8cb13d3d08ac

Pull #330

circleci

Xwatson
Merge branch 'master' into xws/#WIK-19695
Pull Request #330: feat(virtual-scroll): #WIK-19695 collapsed content will not be rendered

394 of 1277 branches covered (30.85%)

Branch coverage included in aggregate %.

14 of 60 new or added lines in 3 files covered. (23.33%)

1 existing line in 1 file now uncovered.

1092 of 2778 relevant lines covered (39.31%)

24.11 hits per line

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

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

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

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

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

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

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

117
    private initialized: boolean;
118

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

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

123
    @Input() editor: AngularEditor;
124

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

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

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

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

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

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

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

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

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

143
    @Input() placeholder: string;
144

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

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

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

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

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

189
    viewContainerRef = inject(ViewContainerRef);
23✔
190

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

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

203
    listRender: ListRender;
204

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

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

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

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

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

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

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

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

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

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

388
    toNativeSelection(autoScroll = true) {
15✔
389
        try {
15✔
390
            let { selection } = this.editor;
15✔
391
            if (this.isEnabledVirtualScroll()) {
15!
392
                selection = this.calculateVirtualScrollSelection(selection);
×
393
            }
394
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
395
            const { activeElement } = root;
15✔
396
            const domSelection = (root as Document).getSelection();
15✔
397

398
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
399
                return;
14✔
400
            }
401

402
            const hasDomSelection = domSelection.type !== 'None';
1✔
403

404
            // If the DOM selection is properly unset, we're done.
405
            if (!selection && !hasDomSelection) {
1!
406
                return;
×
407
            }
408

409
            // If the DOM selection is already correct, we're done.
410
            // verify that the dom selection is in the editor
411
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
412
            let hasDomSelectionInEditor = false;
1✔
413
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
414
                hasDomSelectionInEditor = true;
1✔
415
            }
416

417
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
418
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
419
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
420
                    exactMatch: false,
421
                    suppressThrow: true
422
                });
423
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
424
                    return;
×
425
                }
426
            }
427

428
            // prevent updating native selection when active element is void element
429
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
430
                return;
×
431
            }
432

433
            // when <Editable/> is being controlled through external value
434
            // then its children might just change - DOM responds to it on its own
435
            // but Slate's value is not being updated through any operation
436
            // and thus it doesn't transform selection on its own
437
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
438
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
439
                return;
×
440
            }
441

442
            // Otherwise the DOM selection is out of sync, so update it.
443
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
444
            this.isUpdatingSelection = true;
1✔
445

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

448
            if (newDomRange) {
1!
449
                // COMPAT: Since the DOM range has no concept of backwards/forwards
450
                // we need to check and do the right thing here.
451
                if (Range.isBackward(selection)) {
1!
452
                    // eslint-disable-next-line max-len
453
                    domSelection.setBaseAndExtent(
×
454
                        newDomRange.endContainer,
455
                        newDomRange.endOffset,
456
                        newDomRange.startContainer,
457
                        newDomRange.startOffset
458
                    );
459
                } else {
460
                    // eslint-disable-next-line max-len
461
                    domSelection.setBaseAndExtent(
1✔
462
                        newDomRange.startContainer,
463
                        newDomRange.startOffset,
464
                        newDomRange.endContainer,
465
                        newDomRange.endOffset
466
                    );
467
                }
468
            } else {
469
                domSelection.removeAllRanges();
×
470
            }
471

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

503
    onChange() {
504
        this.forceRender();
13✔
505
        this.onChangeCallback(this.editor.children);
13✔
506
    }
507

508
    ngAfterViewChecked() {}
509

510
    ngDoCheck() {}
511

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

555
    render() {
556
        const changed = this.updateContext();
2✔
557
        if (changed) {
2✔
558
            if (this.isEnabledVirtualScroll()) {
2!
559
                this.updateListRenderAndRemeasureHeights();
×
560
            } else {
561
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
562
            }
563
        }
564
    }
565

566
    updateListRenderAndRemeasureHeights() {
567
        const virtualView = this.calculateVirtualViewport();
×
568
        const oldInViewportChildren = this.inViewportChildren;
×
569
        this.applyVirtualView(virtualView);
×
NEW
570
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
NEW
571
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
572
        // 新增或者修改的才需要重算,计算出这个结果
573
        const remeasureIndics = [];
×
574
        this.inViewportChildren.forEach((child, index) => {
×
575
            if (oldInViewportChildren.indexOf(child) === -1) {
×
576
                remeasureIndics.push(this.inViewportIndics[index]);
×
577
            }
578
        });
579
        if (isDebug && remeasureIndics.length > 0) {
×
580
            console.log('remeasure height by indics: ', remeasureIndics);
×
581
        }
582
        measureHeightByIndics(this.editor, remeasureIndics, true);
×
583
    }
584

585
    updateContext() {
586
        const decorations = this.generateDecorations();
17✔
587
        if (
17✔
588
            this.context.selection !== this.editor.selection ||
46✔
589
            this.context.decorate !== this.decorate ||
590
            this.context.readonly !== this.readonly ||
591
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
592
        ) {
593
            this.context = {
10✔
594
                parent: this.editor,
595
                selection: this.editor.selection,
596
                decorations: decorations,
597
                decorate: this.decorate,
598
                readonly: this.readonly
599
            };
600
            return true;
10✔
601
        }
602
        return false;
7✔
603
    }
604

605
    initializeContext() {
606
        this.context = {
49✔
607
            parent: this.editor,
608
            selection: this.editor.selection,
609
            decorations: this.generateDecorations(),
610
            decorate: this.decorate,
611
            readonly: this.readonly
612
        };
613
    }
614

615
    initializeViewContext() {
616
        this.viewContext = {
23✔
617
            editor: this.editor,
618
            renderElement: this.renderElement,
619
            renderLeaf: this.renderLeaf,
620
            renderText: this.renderText,
621
            trackBy: this.trackBy,
622
            isStrictDecorate: this.isStrictDecorate
623
        };
624
    }
625

626
    composePlaceholderDecorate(editor: Editor) {
627
        if (this.placeholderDecorate) {
64!
628
            return this.placeholderDecorate(editor) || [];
×
629
        }
630

631
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
632
            const start = Editor.start(editor, []);
3✔
633
            return [
3✔
634
                {
635
                    placeholder: this.placeholder,
636
                    anchor: start,
637
                    focus: start
638
                }
639
            ];
640
        } else {
641
            return [];
61✔
642
        }
643
    }
644

645
    generateDecorations() {
646
        const decorations = this.decorate([this.editor, []]);
66✔
647
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
648
        decorations.push(...placeholderDecorations);
66✔
649
        return decorations;
66✔
650
    }
651

652
    private isEnabledVirtualScroll() {
653
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
654
    }
655

656
    virtualScrollInitialized = false;
23✔
657

658
    virtualTopHeightElement: HTMLElement;
659

660
    virtualBottomHeightElement: HTMLElement;
661

662
    virtualCenterOutlet: HTMLElement;
663

664
    initializeVirtualScroll() {
665
        if (this.virtualScrollInitialized) {
23!
666
            return;
×
667
        }
668
        if (this.isEnabledVirtualScroll()) {
23!
669
            this.virtualScrollInitialized = true;
×
670
            this.virtualTopHeightElement = document.createElement('div');
×
671
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
672
            this.virtualTopHeightElement.contentEditable = 'false';
×
673
            this.virtualBottomHeightElement = document.createElement('div');
×
674
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
675
            this.virtualBottomHeightElement.contentEditable = 'false';
×
676
            this.virtualCenterOutlet = document.createElement('div');
×
677
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
678
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
679
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
680
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
681
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
682
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
683
            this.editorResizeObserver = new ResizeObserver(entries => {
×
684
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
685
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
686
                    this.keyHeightMap.clear();
×
687
                    const remeasureIndics = this.inViewportIndics;
×
688
                    measureHeightByIndics(this.editor, remeasureIndics, true);
×
689
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.getBoundingClientRect().width);
×
690
                    if (isDebug) {
×
691
                        debugLog(
×
692
                            'log',
693
                            'editorResizeObserverRectWidth: ',
694
                            editorResizeObserverRectWidth,
695
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
696
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
697
                        );
698
                    }
699
                }
700
            });
701
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
702
        }
703
    }
704

705
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
706
        if (!this.virtualScrollInitialized) {
×
707
            return;
×
708
        }
709
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
710
        if (bottomHeight !== undefined) {
×
711
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
712
        }
713
    }
714

715
    getActualVirtualTopHeight() {
716
        if (!this.virtualScrollInitialized) {
×
717
            return 0;
×
718
        }
719
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
720
    }
721

722
    handlePreRendering() {
NEW
723
        let preRenderingCount = 0;
×
724
        const childrenWithPreRendering = [...this.inViewportChildren];
×
NEW
725
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
NEW
726
        const firstIndex = this.inViewportIndics[0];
×
NEW
727
        for (let index = firstIndex - 1; index >= 0; index--) {
×
NEW
728
            const element = this.editor.children[index] as Element;
×
NEW
729
            if (this.editor.isVisible(element)) {
×
NEW
730
                childrenWithPreRendering.unshift(element);
×
NEW
731
                childrenWithPreRenderingIndics.unshift(index);
×
NEW
732
                preRenderingCount = 1;
×
NEW
733
                break;
×
734
            }
735
        }
736
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
NEW
737
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
NEW
738
            const element = this.editor.children[index] as Element;
×
NEW
739
            if (this.editor.isVisible(element)) {
×
NEW
740
                childrenWithPreRendering.push(element);
×
NEW
741
                childrenWithPreRenderingIndics.push(index);
×
NEW
742
                break;
×
743
            }
744
        }
NEW
745
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
746
    }
747

748
    private tryUpdateVirtualViewport() {
749
        if (isDebug) {
×
750
            debugLog('log', 'tryUpdateVirtualViewport');
×
751
        }
752
        if (this.inViewportIndics.length > 0) {
×
753
            const topHeight = this.getActualVirtualTopHeight();
×
754
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0]);
×
755
            if (topHeight !== refreshVirtualTopHeight) {
×
756
                if (isDebug) {
×
757
                    debugLog(
×
758
                        'log',
759
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
760
                        topHeight - refreshVirtualTopHeight
761
                    );
762
                }
763
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
764
                return;
×
765
            }
766
        }
767
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
768
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
769
            if (isDebug) {
×
770
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
771
            }
772
            let virtualView = this.calculateVirtualViewport();
×
773
            let diff = this.diffVirtualViewport(virtualView);
×
774
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
775
                const remeasureIndics = diff.changedIndexesOfTop;
×
776
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
777
                if (changed) {
×
778
                    virtualView = this.calculateVirtualViewport();
×
779
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
780
                }
781
            }
782
            if (diff.isDifferent) {
×
783
                this.applyVirtualView(virtualView);
×
784
                if (this.listRender.initialized) {
×
NEW
785
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering();
×
NEW
786
                    this.listRender.update(
×
787
                        childrenWithPreRendering,
788
                        this.editor,
789
                        this.context,
790
                        preRenderingCount,
791
                        childrenWithPreRenderingIndics
792
                    );
793
                    if (diff.needAddOnTop) {
×
794
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
795
                        if (isDebug) {
×
796
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
797
                        }
798
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
799
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
800
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
801
                        if (changed) {
×
802
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor);
×
803
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
804
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
805
                            this.setVirtualSpaceHeight(newTopHeight);
×
806
                            if (isDebug) {
×
807
                                debugLog(
×
808
                                    'log',
809
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
810
                                );
811
                            }
812
                        }
813
                    }
814
                    if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
815
                        this.toNativeSelection(false);
×
816
                    }
817
                }
818
            }
819
            if (isDebug) {
×
820
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
821
            }
822
        });
823
    }
824

825
    private calculateVirtualViewport() {
826
        const children = (this.editor.children || []) as Element[];
×
827
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
828
            return {
×
829
                inViewportChildren: children,
830
                inViewportIndics: [],
831
                top: 0,
832
                bottom: 0,
833
                heights: []
834
            };
835
        }
836
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
837
        const viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
838
        if (!viewportHeight) {
×
839
            return {
×
840
                inViewportChildren: [],
841
                inViewportIndics: [],
842
                top: 0,
843
                bottom: 0,
844
                heights: []
845
            };
846
        }
847
        const elementLength = children.length;
×
848
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
849
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
850
            setTimeout(() => {
×
851
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
852
                const businessTop =
853
                    Math.ceil(virtualTopBoundingTop) +
×
854
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
855
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
856
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
857
                if (isDebug) {
×
858
                    debugLog('log', 'businessTop', businessTop);
×
859
                }
860
            }, 100);
861
        }
862
        const adjustedScrollTop = Math.max(0, scrollTop - getBusinessTop(this.editor));
×
NEW
863
        const { heights, accumulatedHeights, visibles } = buildHeightsAndAccumulatedHeights(this.editor);
×
864
        const totalHeight = accumulatedHeights[elementLength];
×
865
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
866
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
867
        const viewBottom = limitedScrollTop + viewportHeight;
×
868
        let accumulatedOffset = 0;
×
869
        let inViewportStartIndex = -1;
×
870
        const visible: Element[] = [];
×
871
        const inViewportIndics: number[] = [];
×
872

873
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
874
            const currentHeight = heights[i];
×
875
            const nextOffset = accumulatedOffset + currentHeight;
×
NEW
876
            if (!visibles[i]) {
×
NEW
877
                accumulatedOffset = nextOffset;
×
NEW
878
                continue;
×
879
            }
880
            // 可视区域有交集,加入渲染
881
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
882
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
883
                visible.push(children[i]);
×
884
                inViewportIndics.push(i);
×
885
            }
886
            accumulatedOffset = nextOffset;
×
887
        }
888

889
        const inViewportEndIndex =
890
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
891
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
892
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
893
        return {
×
894
            inViewportChildren: visible.length ? visible : children,
×
895
            inViewportIndics,
896
            top,
897
            bottom,
898
            heights,
899
            accumulatedHeights
900
        };
901
    }
902

903
    private applyVirtualView(virtualView: VirtualViewResult) {
904
        this.inViewportChildren = virtualView.inViewportChildren;
×
905
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
906
        this.inViewportIndics = virtualView.inViewportIndics;
×
907
    }
908

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

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

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

1071
                if (activeElement === el) {
1!
1072
                    this.latestElement = activeElement;
1✔
1073
                    IS_FOCUSED.set(this.editor, true);
1✔
1074
                } else {
1075
                    IS_FOCUSED.delete(this.editor);
×
1076
                }
1077

1078
                if (!domSelection) {
1!
1079
                    return Transforms.deselect(this.editor);
×
1080
                }
1081

1082
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1083
                const hasDomSelectionInEditor =
1084
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1085
                if (!hasDomSelectionInEditor) {
1!
1086
                    Transforms.deselect(this.editor);
×
1087
                    return;
×
1088
                }
1089

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

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

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

1198
                switch (type) {
×
1199
                    case 'deleteByComposition':
1200
                    case 'deleteByCut':
1201
                    case 'deleteByDrag': {
1202
                        Editor.deleteFragment(editor);
×
1203
                        break;
×
1204
                    }
1205

1206
                    case 'deleteContent':
1207
                    case 'deleteContentForward': {
1208
                        Editor.deleteForward(editor);
×
1209
                        break;
×
1210
                    }
1211

1212
                    case 'deleteContentBackward': {
1213
                        Editor.deleteBackward(editor);
×
1214
                        break;
×
1215
                    }
1216

1217
                    case 'deleteEntireSoftLine': {
1218
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1219
                        Editor.deleteForward(editor, { unit: 'line' });
×
1220
                        break;
×
1221
                    }
1222

1223
                    case 'deleteHardLineBackward': {
1224
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1225
                        break;
×
1226
                    }
1227

1228
                    case 'deleteSoftLineBackward': {
1229
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1230
                        break;
×
1231
                    }
1232

1233
                    case 'deleteHardLineForward': {
1234
                        Editor.deleteForward(editor, { unit: 'block' });
×
1235
                        break;
×
1236
                    }
1237

1238
                    case 'deleteSoftLineForward': {
1239
                        Editor.deleteForward(editor, { unit: 'line' });
×
1240
                        break;
×
1241
                    }
1242

1243
                    case 'deleteWordBackward': {
1244
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1245
                        break;
×
1246
                    }
1247

1248
                    case 'deleteWordForward': {
1249
                        Editor.deleteForward(editor, { unit: 'word' });
×
1250
                        break;
×
1251
                    }
1252

1253
                    case 'insertLineBreak':
1254
                    case 'insertParagraph': {
1255
                        Editor.insertBreak(editor);
×
1256
                        break;
×
1257
                    }
1258

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

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

1304
        const window = AngularEditor.getWindow(this.editor);
×
1305

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

1315
        const { relatedTarget } = event;
×
1316
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1317

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

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

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

1337
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1338
                return;
×
1339
            }
1340
        }
1341

1342
        IS_FOCUSED.delete(this.editor);
×
1343
    }
1344

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

1357
            const startVoid = Editor.void(this.editor, { at: start });
×
1358
            const endVoid = Editor.void(this.editor, { at: end });
×
1359

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

1368
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1369
                }
1370

1371
                const range = Editor.range(this.editor, blockPath);
×
1372
                Transforms.select(this.editor, range);
×
1373
                return;
×
1374
            }
1375

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

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

1403
    private onDOMCompositionUpdate(event: CompositionEvent) {
1404
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1405
    }
1406

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

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

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

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

1443
            if (selection) {
×
1444
                AngularEditor.deleteCutData(this.editor);
×
1445
            }
1446
        }
1447
    }
1448

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

1456
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1457
                event.preventDefault();
×
1458
            }
1459
        }
1460
    }
1461

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

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

1476
            this.isDraggingInternally = true;
×
1477

1478
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1479
        }
1480
    }
1481

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

1489
            // Find the range where the drop happened
1490
            const range = AngularEditor.findEventRange(editor, event);
×
1491
            const data = event.dataTransfer;
×
1492

1493
            Transforms.select(editor, range);
×
1494

1495
            if (this.isDraggingInternally) {
×
1496
                if (draggedRange) {
×
1497
                    Transforms.delete(editor, {
×
1498
                        at: draggedRange
1499
                    });
1500
                }
1501

1502
                this.isDraggingInternally = false;
×
1503
            }
1504

1505
            AngularEditor.insertData(editor, data);
×
1506

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

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

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

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

1545
            IS_FOCUSED.set(this.editor, true);
2✔
1546
        }
1547
    }
1548

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

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

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

1574
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1575
                        editor.redo();
×
1576
                    }
1577

1578
                    return;
×
1579
                }
1580

1581
                if (Hotkeys.isUndo(nativeEvent)) {
×
1582
                    event.preventDefault();
×
1583

1584
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1585
                        editor.undo();
×
1586
                    }
1587

1588
                    return;
×
1589
                }
1590

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

1601
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1602
                    event.preventDefault();
×
1603
                    Transforms.move(editor, { unit: 'line' });
×
1604
                    return;
×
1605
                }
1606

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

1617
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1618
                    event.preventDefault();
×
1619
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1620
                    return;
×
1621
                }
1622

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

1631
                    if (selection && Range.isCollapsed(selection)) {
×
1632
                        Transforms.move(editor, { reverse: !isRTL });
×
1633
                    } else {
1634
                        Transforms.collapse(editor, { edge: 'start' });
×
1635
                    }
1636

1637
                    return;
×
1638
                }
1639

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

1648
                    return;
×
1649
                }
1650

1651
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1652
                    event.preventDefault();
×
1653

1654
                    if (selection && Range.isExpanded(selection)) {
×
1655
                        Transforms.collapse(editor, { edge: 'focus' });
×
1656
                    }
1657

1658
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1659
                    return;
×
1660
                }
1661

1662
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1663
                    event.preventDefault();
×
1664

1665
                    if (selection && Range.isExpanded(selection)) {
×
1666
                        Transforms.collapse(editor, { edge: 'focus' });
×
1667
                    }
1668

1669
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1670
                    return;
×
1671
                }
1672

1673
                if (isKeyHotkey('mod+a', event)) {
×
1674
                    this.editor.selectAll();
×
1675
                    event.preventDefault();
×
1676
                    return;
×
1677
                }
1678

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

1690
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1691
                        event.preventDefault();
×
1692
                        Editor.insertBreak(editor);
×
1693
                        return;
×
1694
                    }
1695

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

1699
                        if (selection && Range.isExpanded(selection)) {
×
1700
                            Editor.deleteFragment(editor, {
×
1701
                                direction: 'backward'
1702
                            });
1703
                        } else {
1704
                            Editor.deleteBackward(editor);
×
1705
                        }
1706

1707
                        return;
×
1708
                    }
1709

1710
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1711
                        event.preventDefault();
×
1712

1713
                        if (selection && Range.isExpanded(selection)) {
×
1714
                            Editor.deleteFragment(editor, {
×
1715
                                direction: 'forward'
1716
                            });
1717
                        } else {
1718
                            Editor.deleteForward(editor);
×
1719
                        }
1720

1721
                        return;
×
1722
                    }
1723

1724
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1725
                        event.preventDefault();
×
1726

1727
                        if (selection && Range.isExpanded(selection)) {
×
1728
                            Editor.deleteFragment(editor, {
×
1729
                                direction: 'backward'
1730
                            });
1731
                        } else {
1732
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1733
                        }
1734

1735
                        return;
×
1736
                    }
1737

1738
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1739
                        event.preventDefault();
×
1740

1741
                        if (selection && Range.isExpanded(selection)) {
×
1742
                            Editor.deleteFragment(editor, {
×
1743
                                direction: 'forward'
1744
                            });
1745
                        } else {
1746
                            Editor.deleteForward(editor, { unit: 'line' });
×
1747
                        }
1748

1749
                        return;
×
1750
                    }
1751

1752
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1753
                        event.preventDefault();
×
1754

1755
                        if (selection && Range.isExpanded(selection)) {
×
1756
                            Editor.deleteFragment(editor, {
×
1757
                                direction: 'backward'
1758
                            });
1759
                        } else {
1760
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1761
                        }
1762

1763
                        return;
×
1764
                    }
1765

1766
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1767
                        event.preventDefault();
×
1768

1769
                        if (selection && Range.isExpanded(selection)) {
×
1770
                            Editor.deleteFragment(editor, {
×
1771
                                direction: 'forward'
1772
                            });
1773
                        } else {
1774
                            Editor.deleteForward(editor, { unit: 'word' });
×
1775
                        }
1776

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

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

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

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

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

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

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

1889
        if (isZeroDimensionRect) {
×
1890
            const leafRect = leafEl.getBoundingClientRect();
×
1891
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1892

1893
            if (leafHasDimensions) {
×
1894
                return;
×
1895
            }
1896
        }
1897

1898
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1899
        scrollIntoView(leafEl, {
×
1900
            scrollMode: 'if-needed'
1901
        });
1902
        delete leafEl.getBoundingClientRect;
×
1903
    }
1904
};
1905

1906
/**
1907
 * Check if the target is inside void and in the editor.
1908
 */
1909

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

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

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