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

worktile / slate-angular / 9bcb1bae-5e7d-4e46-86d8-e574c18d4784

04 Dec 2025 06:51AM UTC coverage: 45.005% (-0.1%) from 45.146%
9bcb1bae-5e7d-4e46-86d8-e574c18d4784

push

circleci

web-flow
fix: optimize logs, diff needs to determine whether it is consistent before and after (#308)

* fix: optimize logs

* fix: get historical altitude variables

* chore: add note

* fix: diff needs to determine whether it is consistent before and after

* chore: update note

384 of 1061 branches covered (36.19%)

Branch coverage included in aggregate %.

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

2 existing lines in 1 file now uncovered.

1053 of 2132 relevant lines covered (49.39%)

30.43 hits per line

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

27.73
/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 } 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
    VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT,
49
    VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT,
50
    SLATE_DEBUG_KEY
51
} from '../../utils/environment';
52
import Hotkeys from '../../utils/hotkeys';
53
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
54
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
55
import { SlateErrorCode } from '../../types/error';
56
import { NG_VALUE_ACCESSOR } from '@angular/forms';
57
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
58
import { ViewType } from '../../types/view';
59
import { HistoryEditor } from 'slate-history';
60
import { ELEMENT_TO_COMPONENT, isDecoratorRangeListEqual } from '../../utils';
61
import { SlatePlaceholder } from '../../types/feature';
62
import { restoreDom } from '../../utils/restore-dom';
63
import { ListRender } from '../../view/render/list-render';
64
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
65
import { BaseElementComponent } from '../../view/base';
66
import { BaseElementFlavour } from '../../view/flavour/element';
67
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
68

69
export const JUST_NOW_UPDATED_VIRTUAL_VIEW = new WeakMap<AngularEditor, boolean>();
1✔
70

71
// not correctly clipboardData on beforeinput
72
const forceOnDOMPaste = IS_SAFARI;
1✔
73

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

99
    private destroy$ = new Subject();
23✔
100

101
    isComposing = false;
23✔
102
    isDraggingInternally = false;
23✔
103
    isUpdatingSelection = false;
23✔
104
    latestElement = null as DOMElement | null;
23✔
105

106
    protected manualListeners: (() => void)[] = [];
23✔
107

108
    private initialized: boolean;
109

110
    private onTouchedCallback: () => void = () => {};
23✔
111

112
    private onChangeCallback: (_: any) => void = () => {};
23✔
113

114
    @Input() editor: AngularEditor;
115

116
    @Input() renderElement: (element: Element) => ViewType | null;
117

118
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
119

120
    @Input() renderText: (text: SlateText) => ViewType | null;
121

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

124
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
125

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

128
    @Input() isStrictDecorate: boolean = true;
23✔
129

130
    @Input() trackBy: (node: Element) => any = () => null;
206✔
131

132
    @Input() readonly = false;
23✔
133

134
    @Input() placeholder: string;
135

136
    @Input()
137
    set virtualScroll(config: SlateVirtualScrollConfig) {
138
        this.virtualConfig = config;
×
139
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
140
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
141
            const virtualView = this.refreshVirtualView();
×
142
            const diff = this.diffVirtualView(virtualView);
×
143
            if (diff) {
×
144
                this.applyVirtualView(virtualView);
×
145
                if (this.listRender.initialized) {
×
146
                    this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
147
                }
148
                this.scheduleMeasureVisibleHeights();
×
149
            }
150
        });
151
    }
152

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

171
    //#region DOM attr
172
    @Input() spellCheck = false;
23✔
173
    @Input() autoCorrect = false;
23✔
174
    @Input() autoCapitalize = false;
23✔
175

176
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
177
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
178
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
179

180
    get hasBeforeInputSupport() {
181
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
182
    }
183
    //#endregion
184

185
    viewContainerRef = inject(ViewContainerRef);
23✔
186

187
    getOutletParent = () => {
23✔
188
        return this.elementRef.nativeElement;
43✔
189
    };
190

191
    getOutletElement = () => {
23✔
192
        if (this.virtualScrollInitialized) {
23!
193
            return this.virtualCenterOutlet;
×
194
        } else {
195
            return null;
23✔
196
        }
197
    };
198

199
    listRender: ListRender;
200

201
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
202
        enabled: false,
203
        scrollTop: 0,
204
        viewportHeight: 0
205
    };
206
    private renderedChildren: Element[] = [];
23✔
207
    private virtualVisibleIndexes = new Set<number>();
23✔
208
    private measuredHeights = new Map<string, number>();
23✔
209
    private measurePending = false;
23✔
210
    private refreshVirtualViewAnimId: number;
211
    private measureVisibleHeightsAnimId: number;
212

213
    constructor(
214
        public elementRef: ElementRef,
23✔
215
        public renderer2: Renderer2,
23✔
216
        public cdr: ChangeDetectorRef,
23✔
217
        private ngZone: NgZone,
23✔
218
        private injector: Injector
23✔
219
    ) {}
220

221
    ngOnInit() {
222
        this.editor.injector = this.injector;
23✔
223
        this.editor.children = [];
23✔
224
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
225
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
226
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
227
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
228
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
229
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
230
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
231
            this.ngZone.run(() => {
13✔
232
                this.onChange();
13✔
233
            });
234
        });
235
        this.ngZone.runOutsideAngular(() => {
23✔
236
            this.initialize();
23✔
237
        });
238
        this.initializeViewContext();
23✔
239
        this.initializeContext();
23✔
240

241
        // add browser class
242
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
243
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
244
        this.initializeVirtualScrolling();
23✔
245
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
246
    }
247

248
    ngOnChanges(simpleChanges: SimpleChanges) {
249
        if (!this.initialized) {
30✔
250
            return;
23✔
251
        }
252
        const decorateChange = simpleChanges['decorate'];
7✔
253
        if (decorateChange) {
7✔
254
            this.forceRender();
2✔
255
        }
256
        const placeholderChange = simpleChanges['placeholder'];
7✔
257
        if (placeholderChange) {
7✔
258
            this.render();
1✔
259
        }
260
        const readonlyChange = simpleChanges['readonly'];
7✔
261
        if (readonlyChange) {
7!
262
            IS_READ_ONLY.set(this.editor, this.readonly);
×
263
            this.render();
×
264
            this.toSlateSelection();
×
265
        }
266
    }
267

268
    registerOnChange(fn: any) {
269
        this.onChangeCallback = fn;
23✔
270
    }
271
    registerOnTouched(fn: any) {
272
        this.onTouchedCallback = fn;
23✔
273
    }
274

275
    writeValue(value: Element[]) {
276
        if (value && value.length) {
49✔
277
            this.editor.children = value;
26✔
278
            this.initializeContext();
26✔
279
            const virtualView = this.refreshVirtualView();
26✔
280
            this.applyVirtualView(virtualView);
26✔
281
            const childrenForRender = virtualView.renderedChildren;
26✔
282
            if (!this.listRender.initialized) {
26✔
283
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
284
            } else {
285
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
286
            }
287
            this.scheduleMeasureVisibleHeights();
26✔
288
            this.cdr.markForCheck();
26✔
289
        }
290
    }
291

292
    initialize() {
293
        this.initialized = true;
23✔
294
        const window = AngularEditor.getWindow(this.editor);
23✔
295
        this.addEventListener(
23✔
296
            'selectionchange',
297
            event => {
298
                this.toSlateSelection();
2✔
299
            },
300
            window.document
301
        );
302
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
303
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
304
        }
305
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
306
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
307
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
308
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
309
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
310
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
311
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
312
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
313
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
314
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
315
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
316
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
317
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
318
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
319
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
320
            this.addEventListener(event.name, () => {});
115✔
321
        });
322
    }
323

324
    toNativeSelection() {
325
        try {
15✔
326
            const { selection } = this.editor;
15✔
327
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
328
            const { activeElement } = root;
15✔
329
            const domSelection = (root as Document).getSelection();
15✔
330

331
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
332
                return;
14✔
333
            }
334

335
            const hasDomSelection = domSelection.type !== 'None';
1✔
336

337
            // If the DOM selection is properly unset, we're done.
338
            if (!selection && !hasDomSelection) {
1!
339
                return;
×
340
            }
341

342
            // If the DOM selection is already correct, we're done.
343
            // verify that the dom selection is in the editor
344
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
345
            let hasDomSelectionInEditor = false;
1✔
346
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
347
                hasDomSelectionInEditor = true;
1✔
348
            }
349

350
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
351
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
352
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
353
                    exactMatch: false,
354
                    suppressThrow: true
355
                });
356
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
357
                    return;
×
358
                }
359
            }
360

361
            // prevent updating native selection when active element is void element
362
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
363
                return;
×
364
            }
365

366
            // when <Editable/> is being controlled through external value
367
            // then its children might just change - DOM responds to it on its own
368
            // but Slate's value is not being updated through any operation
369
            // and thus it doesn't transform selection on its own
370
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
371
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
372
                return;
×
373
            }
374

375
            // Otherwise the DOM selection is out of sync, so update it.
376
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
377
            this.isUpdatingSelection = true;
1✔
378

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

381
            if (newDomRange) {
1!
382
                // COMPAT: Since the DOM range has no concept of backwards/forwards
383
                // we need to check and do the right thing here.
384
                if (Range.isBackward(selection)) {
1!
385
                    // eslint-disable-next-line max-len
386
                    domSelection.setBaseAndExtent(
×
387
                        newDomRange.endContainer,
388
                        newDomRange.endOffset,
389
                        newDomRange.startContainer,
390
                        newDomRange.startOffset
391
                    );
392
                } else {
393
                    // eslint-disable-next-line max-len
394
                    domSelection.setBaseAndExtent(
1✔
395
                        newDomRange.startContainer,
396
                        newDomRange.startOffset,
397
                        newDomRange.endContainer,
398
                        newDomRange.endOffset
399
                    );
400
                }
401
            } else {
402
                domSelection.removeAllRanges();
×
403
            }
404

405
            setTimeout(() => {
1✔
406
                // handle scrolling in setTimeout because of
407
                // dom should not have updated immediately after listRender's updating
408
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
409
                // COMPAT: In Firefox, it's not enough to create a range, you also need
410
                // to focus the contenteditable element too. (2016/11/16)
411
                if (newDomRange && IS_FIREFOX) {
1!
412
                    el.focus();
×
413
                }
414

415
                this.isUpdatingSelection = false;
1✔
416
            });
417
        } catch (error) {
418
            this.editor.onError({
×
419
                code: SlateErrorCode.ToNativeSelectionError,
420
                nativeError: error
421
            });
422
            this.isUpdatingSelection = false;
×
423
        }
424
    }
425

426
    onChange() {
427
        this.forceRender();
13✔
428
        this.onChangeCallback(this.editor.children);
13✔
429
    }
430

431
    ngAfterViewChecked() {}
432

433
    ngDoCheck() {}
434

435
    forceRender() {
436
        this.updateContext();
15✔
437
        const virtualView = this.refreshVirtualView();
15✔
438
        this.applyVirtualView(virtualView);
15✔
439
        this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
15✔
440
        this.scheduleMeasureVisibleHeights();
15✔
441
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
442
        // when the DOMElement where the selection is located is removed
443
        // the compositionupdate and compositionend events will no longer be fired
444
        // so isComposing needs to be corrected
445
        // need exec after this.cdr.detectChanges() to render HTML
446
        // need exec before this.toNativeSelection() to correct native selection
447
        if (this.isComposing) {
15!
448
            // Composition input text be not rendered when user composition input with selection is expanded
449
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
450
            // this time condition is true and isComposing is assigned false
451
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
452
            setTimeout(() => {
×
453
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
454
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
455
                let textContent = '';
×
456
                // skip decorate text
457
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
458
                    let text = stringDOMNode.textContent;
×
459
                    const zeroChar = '\uFEFF';
×
460
                    // remove zero with char
461
                    if (text.startsWith(zeroChar)) {
×
462
                        text = text.slice(1);
×
463
                    }
464
                    if (text.endsWith(zeroChar)) {
×
465
                        text = text.slice(0, text.length - 1);
×
466
                    }
467
                    textContent += text;
×
468
                });
469
                if (Node.string(textNode).endsWith(textContent)) {
×
470
                    this.isComposing = false;
×
471
                }
472
            }, 0);
473
        }
474
        this.toNativeSelection();
15✔
475
    }
476

477
    render() {
478
        const changed = this.updateContext();
2✔
479
        if (changed) {
2✔
480
            const virtualView = this.refreshVirtualView();
2✔
481
            this.applyVirtualView(virtualView);
2✔
482
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
483
            this.scheduleMeasureVisibleHeights();
2✔
484
        }
485
    }
486

487
    updateContext() {
488
        const decorations = this.generateDecorations();
17✔
489
        if (
17✔
490
            this.context.selection !== this.editor.selection ||
46✔
491
            this.context.decorate !== this.decorate ||
492
            this.context.readonly !== this.readonly ||
493
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
494
        ) {
495
            this.context = {
10✔
496
                parent: this.editor,
497
                selection: this.editor.selection,
498
                decorations: decorations,
499
                decorate: this.decorate,
500
                readonly: this.readonly
501
            };
502
            return true;
10✔
503
        }
504
        return false;
7✔
505
    }
506

507
    initializeContext() {
508
        this.context = {
49✔
509
            parent: this.editor,
510
            selection: this.editor.selection,
511
            decorations: this.generateDecorations(),
512
            decorate: this.decorate,
513
            readonly: this.readonly
514
        };
515
    }
516

517
    initializeViewContext() {
518
        this.viewContext = {
23✔
519
            editor: this.editor,
520
            renderElement: this.renderElement,
521
            renderLeaf: this.renderLeaf,
522
            renderText: this.renderText,
523
            trackBy: this.trackBy,
524
            isStrictDecorate: this.isStrictDecorate
525
        };
526
    }
527

528
    composePlaceholderDecorate(editor: Editor) {
529
        if (this.placeholderDecorate) {
64!
530
            return this.placeholderDecorate(editor) || [];
×
531
        }
532

533
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
534
            const start = Editor.start(editor, []);
3✔
535
            return [
3✔
536
                {
537
                    placeholder: this.placeholder,
538
                    anchor: start,
539
                    focus: start
540
                }
541
            ];
542
        } else {
543
            return [];
61✔
544
        }
545
    }
546

547
    generateDecorations() {
548
        const decorations = this.decorate([this.editor, []]);
66✔
549
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
550
        decorations.push(...placeholderDecorations);
66✔
551
        return decorations;
66✔
552
    }
553

554
    private shouldUseVirtual() {
555
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
556
    }
557

558
    virtualScrollInitialized = false;
23✔
559

560
    virtualTopHeightElement: HTMLElement;
561

562
    virtualBottomHeightElement: HTMLElement;
563

564
    virtualCenterOutlet: HTMLElement;
565

566
    initializeVirtualScrolling() {
567
        if (this.virtualScrollInitialized) {
23!
568
            return;
×
569
        }
570
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
571
            this.virtualScrollInitialized = true;
×
572
            this.virtualTopHeightElement = document.createElement('div');
×
573
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
574
            this.virtualBottomHeightElement = document.createElement('div');
×
575
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
576
            this.virtualCenterOutlet = document.createElement('div');
×
577
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
578
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
579
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
580
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
581
        }
582
    }
583

584
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
585
        if (!this.virtualScrollInitialized) {
43✔
586
            return;
43✔
587
        }
588
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
589
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
590
    }
591

592
    private refreshVirtualView() {
593
        const children = (this.editor.children || []) as Element[];
43!
594
        if (!children.length || !this.shouldUseVirtual()) {
43✔
595
            return {
43✔
596
                renderedChildren: children,
597
                visibleIndexes: new Set<number>(),
598
                top: 0,
599
                bottom: 0,
600
                heights: []
601
            };
602
        }
603
        const scrollTop = this.virtualConfig.scrollTop ?? 0;
×
604
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
605
        if (!viewportHeight) {
×
606
            // 已经启用虚拟滚动,但可视区域高度还未获取到,先置空不渲染
607
            return {
×
608
                renderedChildren: [],
609
                visibleIndexes: new Set<number>(),
610
                top: 0,
611
                bottom: 0,
612
                heights: []
613
            };
614
        }
615
        const bufferCount = this.virtualConfig.bufferCount ?? VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT;
×
616
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
617
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
618

619
        let visibleStart = 0;
×
620
        // 按真实或估算高度往后累加,找到滚动起点所在块
621
        while (visibleStart < heights.length && accumulatedHeights[visibleStart + 1] <= scrollTop) {
×
622
            visibleStart++;
×
623
        }
624

625
        // 向上预留 bufferCount 块
626
        const startIndex = Math.max(0, visibleStart - bufferCount);
×
627
        const top = accumulatedHeights[startIndex];
×
628
        const bufferBelowHeight = this.getBufferBelowHeight(viewportHeight, visibleStart, bufferCount);
×
629
        const targetHeight = accumulatedHeights[visibleStart] - top + viewportHeight + bufferBelowHeight;
×
630

631
        const visible: Element[] = [];
×
632
        const visibleIndexes: number[] = [];
×
633
        let accumulated = 0;
×
634
        let cursor = startIndex;
×
635
        // 循环累计高度超出目标高度(可视高度 + 上下 buffer)
636
        while (cursor < children.length && accumulated < targetHeight) {
×
637
            visible.push(children[cursor]);
×
638
            visibleIndexes.push(cursor);
×
639
            accumulated += this.getBlockHeight(cursor);
×
640
            cursor++;
×
641
        }
642
        const bottom = heights.slice(cursor).reduce((acc, height) => acc + height, 0);
×
643
        const renderedChildren = visible.length ? visible : children;
×
644
        const visibleIndexesSet = new Set(visibleIndexes);
×
645
        return {
×
646
            renderedChildren,
647
            visibleIndexes: visibleIndexesSet,
648
            top,
649
            bottom,
650
            heights
651
        };
652
    }
653

654
    private applyVirtualView(virtualView: VirtualViewResult) {
655
        this.renderedChildren = virtualView.renderedChildren;
43✔
656
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
657
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
658
    }
659

660
    private diffVirtualView(virtualView: VirtualViewResult) {
661
        if (!this.renderedChildren.length) {
×
662
            return true;
×
663
        }
664
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
665
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
NEW
666
        if (
×
667
            newVisibleIndexes[0] !== oldVisibleIndexes[0] ||
×
668
            newVisibleIndexes[newVisibleIndexes.length - 1] !== oldVisibleIndexes[oldVisibleIndexes.length - 1]
669
        ) {
670
            if (localStorage.getItem(SLATE_DEBUG_KEY) === 'true') {
×
671
                const diffTopRenderedIndexes = [];
×
672
                const diffBottomRenderedIndexes = [];
×
NEW
673
                let direction = '';
×
UNCOV
674
                if (newVisibleIndexes[0] > oldVisibleIndexes[0]) {
×
675
                    // 向下
NEW
676
                    direction = 'down';
×
677
                    for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
678
                        const element = oldVisibleIndexes[index];
×
679
                        if (!newVisibleIndexes.includes(element)) {
×
680
                            diffTopRenderedIndexes.push(element);
×
681
                        } else {
682
                            break;
×
683
                        }
684
                    }
685
                    for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
686
                        const element = newVisibleIndexes[index];
×
687
                        if (!oldVisibleIndexes.includes(element)) {
×
688
                            diffBottomRenderedIndexes.push(element);
×
689
                        } else {
690
                            break;
×
691
                        }
692
                    }
693
                } else {
694
                    // 向上
NEW
695
                    direction = 'up';
×
696
                    for (let index = 0; index < newVisibleIndexes.length; index++) {
×
697
                        const element = newVisibleIndexes[index];
×
698
                        if (!oldVisibleIndexes.includes(element)) {
×
699
                            diffTopRenderedIndexes.push(element);
×
700
                        } else {
701
                            break;
×
702
                        }
703
                    }
704
                    for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
705
                        const element = oldVisibleIndexes[index];
×
706
                        if (!newVisibleIndexes.includes(element)) {
×
707
                            diffBottomRenderedIndexes.push(element);
×
708
                        } else {
709
                            break;
×
710
                        }
711
                    }
712
                }
713
                console.log('oldVisibleIndexes:', oldVisibleIndexes);
×
714
                console.log('newVisibleIndexes:', newVisibleIndexes);
×
NEW
715
                const directionStr = direction === 'down' ? '+' : '-';
×
NEW
716
                console.log(
×
717
                    'diffTopRenderedIndexes:',
718
                    directionStr,
719
                    diffTopRenderedIndexes,
NEW
720
                    diffTopRenderedIndexes.map(index => virtualView.heights[index])
×
721
                );
NEW
722
                console.log(
×
723
                    'diffBottomRenderedIndexes:',
724
                    directionStr,
725
                    diffBottomRenderedIndexes,
NEW
726
                    diffBottomRenderedIndexes.map(index => virtualView.heights[index])
×
727
                );
728
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
729
                const needBottom = virtualView.heights
×
730
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
731
                    .reduce((acc, height) => acc + height, 0);
×
NEW
732
                console.log('newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
NEW
733
                console.log('newBottomHeight:', needBottom, 'prevBottomHeight:', parseFloat(this.virtualBottomHeightElement.style.height));
×
UNCOV
734
                console.warn('=========== Dividing line ===========');
×
735
            }
736
            return true;
×
737
        }
738
        return false;
×
739
    }
740

741
    private getBlockHeight(index: number) {
742
        const node = this.editor.children[index];
×
743
        if (!node) {
×
744
            return VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
745
        }
746
        const key = AngularEditor.findKey(this.editor, node);
×
747
        return this.measuredHeights.get(key.id) ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
748
    }
749

750
    private buildAccumulatedHeight(heights: number[]) {
751
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
752
        for (let i = 0; i < heights.length; i++) {
×
753
            // 存储前 i 个的累计高度
754
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
755
        }
756
        return accumulatedHeights;
×
757
    }
758

759
    private getBufferBelowHeight(viewportHeight: number, visibleStart: number, bufferCount: number) {
760
        let blockHeight = 0;
×
761
        let start = visibleStart;
×
762
        // 循环累计高度超出视图高度代表找到向下缓冲区的起始位置
763
        while (blockHeight < viewportHeight) {
×
764
            blockHeight += this.getBlockHeight(start);
×
765
            start++;
×
766
        }
767
        let bufferHeight = 0;
×
768
        for (let i = start; i < start + bufferCount; i++) {
×
769
            bufferHeight += this.getBlockHeight(i);
×
770
        }
771
        return bufferHeight;
×
772
    }
773

774
    private scheduleMeasureVisibleHeights() {
775
        if (!this.shouldUseVirtual()) {
43✔
776
            return;
43✔
777
        }
778
        if (this.measurePending) {
×
779
            return;
×
780
        }
781
        this.measurePending = true;
×
782
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
783
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
784
            this.measureVisibleHeights();
×
785
            this.measurePending = false;
×
786
        });
787
    }
788

789
    private measureVisibleHeights() {
790
        const children = (this.editor.children || []) as Element[];
×
791
        this.virtualVisibleIndexes.forEach(index => {
×
792
            const node = children[index];
×
793
            if (!node) {
×
794
                return;
×
795
            }
796
            const key = AngularEditor.findKey(this.editor, node);
×
797
            // 跳过已测过的块
798
            if (this.measuredHeights.has(key.id)) {
×
799
                return;
×
800
            }
801
            const view = ELEMENT_TO_COMPONENT.get(node);
×
802
            if (!view) {
×
803
                return;
×
804
            }
805
            (view as BaseElementComponent | BaseElementFlavour).getRealHeight()?.then(height => {
×
806
                this.measuredHeights.set(key.id, height);
×
807
            });
808
        });
809
    }
810

811
    //#region event proxy
812
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
813
        this.manualListeners.push(
483✔
814
            this.renderer2.listen(target, eventName, (event: Event) => {
815
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
816
                if (beforeInputEvent) {
5!
817
                    this.onFallbackBeforeInput(beforeInputEvent);
×
818
                }
819
                listener(event);
5✔
820
            })
821
        );
822
    }
823

824
    private toSlateSelection() {
825
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
826
            try {
1✔
827
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
828
                const { activeElement } = root;
1✔
829
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
830
                const domSelection = (root as Document).getSelection();
1✔
831

832
                if (activeElement === el) {
1!
833
                    this.latestElement = activeElement;
1✔
834
                    IS_FOCUSED.set(this.editor, true);
1✔
835
                } else {
836
                    IS_FOCUSED.delete(this.editor);
×
837
                }
838

839
                if (!domSelection) {
1!
840
                    return Transforms.deselect(this.editor);
×
841
                }
842

843
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
844
                const hasDomSelectionInEditor =
845
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
846
                if (!hasDomSelectionInEditor) {
1!
847
                    Transforms.deselect(this.editor);
×
848
                    return;
×
849
                }
850

851
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
852
                // for example, double-click the last cell of the table to select a non-editable DOM
853
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
854
                if (range) {
1✔
855
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
856
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
857
                            // force adjust DOMSelection
858
                            this.toNativeSelection();
×
859
                        }
860
                    } else {
861
                        Transforms.select(this.editor, range);
1✔
862
                    }
863
                }
864
            } catch (error) {
865
                this.editor.onError({
×
866
                    code: SlateErrorCode.ToSlateSelectionError,
867
                    nativeError: error
868
                });
869
            }
870
        }
871
    }
872

873
    private onDOMBeforeInput(
874
        event: Event & {
875
            inputType: string;
876
            isComposing: boolean;
877
            data: string | null;
878
            dataTransfer: DataTransfer | null;
879
            getTargetRanges(): DOMStaticRange[];
880
        }
881
    ) {
882
        const editor = this.editor;
×
883
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
884
        const { activeElement } = root;
×
885
        const { selection } = editor;
×
886
        const { inputType: type } = event;
×
887
        const data = event.dataTransfer || event.data || undefined;
×
888
        if (IS_ANDROID) {
×
889
            let targetRange: Range | null = null;
×
890
            let [nativeTargetRange] = event.getTargetRanges();
×
891
            if (nativeTargetRange) {
×
892
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
893
            }
894
            // COMPAT: SelectionChange event is fired after the action is performed, so we
895
            // have to manually get the selection here to ensure it's up-to-date.
896
            const window = AngularEditor.getWindow(editor);
×
897
            const domSelection = window.getSelection();
×
898
            if (!targetRange && domSelection) {
×
899
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
900
            }
901
            targetRange = targetRange ?? editor.selection;
×
902
            if (type === 'insertCompositionText') {
×
903
                if (data && data.toString().includes('\n')) {
×
904
                    restoreDom(editor, () => {
×
905
                        Editor.insertBreak(editor);
×
906
                    });
907
                } else {
908
                    if (targetRange) {
×
909
                        if (data) {
×
910
                            restoreDom(editor, () => {
×
911
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
912
                            });
913
                        } else {
914
                            restoreDom(editor, () => {
×
915
                                Transforms.delete(editor, { at: targetRange });
×
916
                            });
917
                        }
918
                    }
919
                }
920
                return;
×
921
            }
922
            if (type === 'deleteContentBackward') {
×
923
                // gboard can not prevent default action, so must use restoreDom,
924
                // sougou Keyboard can prevent default action(only in Chinese input mode).
925
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
926
                if (!Range.isCollapsed(targetRange)) {
×
927
                    restoreDom(editor, () => {
×
928
                        Transforms.delete(editor, { at: targetRange });
×
929
                    });
930
                    return;
×
931
                }
932
            }
933
            if (type === 'insertText') {
×
934
                restoreDom(editor, () => {
×
935
                    if (typeof data === 'string') {
×
936
                        Editor.insertText(editor, data);
×
937
                    }
938
                });
939
                return;
×
940
            }
941
        }
942
        if (
×
943
            !this.readonly &&
×
944
            AngularEditor.hasEditableTarget(editor, event.target) &&
945
            !isTargetInsideVoid(editor, activeElement) &&
946
            !this.isDOMEventHandled(event, this.beforeInput)
947
        ) {
948
            try {
×
949
                event.preventDefault();
×
950

951
                // COMPAT: If the selection is expanded, even if the command seems like
952
                // a delete forward/backward command it should delete the selection.
953
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
954
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
955
                    Editor.deleteFragment(editor, { direction });
×
956
                    return;
×
957
                }
958

959
                switch (type) {
×
960
                    case 'deleteByComposition':
961
                    case 'deleteByCut':
962
                    case 'deleteByDrag': {
963
                        Editor.deleteFragment(editor);
×
964
                        break;
×
965
                    }
966

967
                    case 'deleteContent':
968
                    case 'deleteContentForward': {
969
                        Editor.deleteForward(editor);
×
970
                        break;
×
971
                    }
972

973
                    case 'deleteContentBackward': {
974
                        Editor.deleteBackward(editor);
×
975
                        break;
×
976
                    }
977

978
                    case 'deleteEntireSoftLine': {
979
                        Editor.deleteBackward(editor, { unit: 'line' });
×
980
                        Editor.deleteForward(editor, { unit: 'line' });
×
981
                        break;
×
982
                    }
983

984
                    case 'deleteHardLineBackward': {
985
                        Editor.deleteBackward(editor, { unit: 'block' });
×
986
                        break;
×
987
                    }
988

989
                    case 'deleteSoftLineBackward': {
990
                        Editor.deleteBackward(editor, { unit: 'line' });
×
991
                        break;
×
992
                    }
993

994
                    case 'deleteHardLineForward': {
995
                        Editor.deleteForward(editor, { unit: 'block' });
×
996
                        break;
×
997
                    }
998

999
                    case 'deleteSoftLineForward': {
1000
                        Editor.deleteForward(editor, { unit: 'line' });
×
1001
                        break;
×
1002
                    }
1003

1004
                    case 'deleteWordBackward': {
1005
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1006
                        break;
×
1007
                    }
1008

1009
                    case 'deleteWordForward': {
1010
                        Editor.deleteForward(editor, { unit: 'word' });
×
1011
                        break;
×
1012
                    }
1013

1014
                    case 'insertLineBreak':
1015
                    case 'insertParagraph': {
1016
                        Editor.insertBreak(editor);
×
1017
                        break;
×
1018
                    }
1019

1020
                    case 'insertFromComposition': {
1021
                        // COMPAT: in safari, `compositionend` event is dispatched after
1022
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1023
                        // https://www.w3.org/TR/input-events-2/
1024
                        // so the following code is the right logic
1025
                        // because DOM selection in sync will be exec before `compositionend` event
1026
                        // isComposing is true will prevent DOM selection being update correctly.
1027
                        this.isComposing = false;
×
1028
                        preventInsertFromComposition(event, this.editor);
×
1029
                    }
1030
                    case 'insertFromDrop':
1031
                    case 'insertFromPaste':
1032
                    case 'insertFromYank':
1033
                    case 'insertReplacementText':
1034
                    case 'insertText': {
1035
                        // use a weak comparison instead of 'instanceof' to allow
1036
                        // programmatic access of paste events coming from external windows
1037
                        // like cypress where cy.window does not work realibly
1038
                        if (data?.constructor.name === 'DataTransfer') {
×
1039
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1040
                        } else if (typeof data === 'string') {
×
1041
                            Editor.insertText(editor, data);
×
1042
                        }
1043
                        break;
×
1044
                    }
1045
                }
1046
            } catch (error) {
1047
                this.editor.onError({
×
1048
                    code: SlateErrorCode.OnDOMBeforeInputError,
1049
                    nativeError: error
1050
                });
1051
            }
1052
        }
1053
    }
1054

1055
    private onDOMBlur(event: FocusEvent) {
1056
        if (
×
1057
            this.readonly ||
×
1058
            this.isUpdatingSelection ||
1059
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1060
            this.isDOMEventHandled(event, this.blur)
1061
        ) {
1062
            return;
×
1063
        }
1064

1065
        const window = AngularEditor.getWindow(this.editor);
×
1066

1067
        // COMPAT: If the current `activeElement` is still the previous
1068
        // one, this is due to the window being blurred when the tab
1069
        // itself becomes unfocused, so we want to abort early to allow to
1070
        // editor to stay focused when the tab becomes focused again.
1071
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1072
        if (this.latestElement === root.activeElement) {
×
1073
            return;
×
1074
        }
1075

1076
        const { relatedTarget } = event;
×
1077
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1078

1079
        // COMPAT: The event should be ignored if the focus is returning
1080
        // to the editor from an embedded editable element (eg. an <input>
1081
        // element inside a void node).
1082
        if (relatedTarget === el) {
×
1083
            return;
×
1084
        }
1085

1086
        // COMPAT: The event should be ignored if the focus is moving from
1087
        // the editor to inside a void node's spacer element.
1088
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1089
            return;
×
1090
        }
1091

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

1098
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1099
                return;
×
1100
            }
1101
        }
1102

1103
        IS_FOCUSED.delete(this.editor);
×
1104
    }
1105

1106
    private onDOMClick(event: MouseEvent) {
1107
        if (
×
1108
            !this.readonly &&
×
1109
            AngularEditor.hasTarget(this.editor, event.target) &&
1110
            !this.isDOMEventHandled(event, this.click) &&
1111
            isDOMNode(event.target)
1112
        ) {
1113
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1114
            const path = AngularEditor.findPath(this.editor, node);
×
1115
            const start = Editor.start(this.editor, path);
×
1116
            const end = Editor.end(this.editor, path);
×
1117

1118
            const startVoid = Editor.void(this.editor, { at: start });
×
1119
            const endVoid = Editor.void(this.editor, { at: end });
×
1120

1121
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1122
                let blockPath = path;
×
1123
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1124
                    const block = Editor.above(this.editor, {
×
1125
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1126
                        at: path
1127
                    });
1128

1129
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1130
                }
1131

1132
                const range = Editor.range(this.editor, blockPath);
×
1133
                Transforms.select(this.editor, range);
×
1134
                return;
×
1135
            }
1136

1137
            if (
×
1138
                startVoid &&
×
1139
                endVoid &&
1140
                Path.equals(startVoid[1], endVoid[1]) &&
1141
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1142
            ) {
1143
                const range = Editor.range(this.editor, start);
×
1144
                Transforms.select(this.editor, range);
×
1145
            }
1146
        }
1147
    }
1148

1149
    private onDOMCompositionStart(event: CompositionEvent) {
1150
        const { selection } = this.editor;
1✔
1151
        if (selection) {
1!
1152
            // solve the problem of cross node Chinese input
1153
            if (Range.isExpanded(selection)) {
×
1154
                Editor.deleteFragment(this.editor);
×
1155
                this.forceRender();
×
1156
            }
1157
        }
1158
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1159
            this.isComposing = true;
1✔
1160
        }
1161
        this.render();
1✔
1162
    }
1163

1164
    private onDOMCompositionUpdate(event: CompositionEvent) {
1165
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1166
    }
1167

1168
    private onDOMCompositionEnd(event: CompositionEvent) {
1169
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1170
            Transforms.delete(this.editor);
×
1171
        }
1172
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1173
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1174
            // aren't correct and never fire the "insertFromComposition"
1175
            // type that we need. So instead, insert whenever a composition
1176
            // ends since it will already have been committed to the DOM.
1177
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1178
                preventInsertFromComposition(event, this.editor);
×
1179
                Editor.insertText(this.editor, event.data);
×
1180
            }
1181

1182
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1183
            // so we need avoid repeat isnertText by isComposing === true,
1184
            this.isComposing = false;
×
1185
        }
1186
        this.render();
×
1187
    }
1188

1189
    private onDOMCopy(event: ClipboardEvent) {
1190
        const window = AngularEditor.getWindow(this.editor);
×
1191
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1192
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1193
            event.preventDefault();
×
1194
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1195
        }
1196
    }
1197

1198
    private onDOMCut(event: ClipboardEvent) {
1199
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1200
            event.preventDefault();
×
1201
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1202
            const { selection } = this.editor;
×
1203

1204
            if (selection) {
×
1205
                AngularEditor.deleteCutData(this.editor);
×
1206
            }
1207
        }
1208
    }
1209

1210
    private onDOMDragOver(event: DragEvent) {
1211
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1212
            // Only when the target is void, call `preventDefault` to signal
1213
            // that drops are allowed. Editable content is droppable by
1214
            // default, and calling `preventDefault` hides the cursor.
1215
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1216

1217
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1218
                event.preventDefault();
×
1219
            }
1220
        }
1221
    }
1222

1223
    private onDOMDragStart(event: DragEvent) {
1224
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1225
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1226
            const path = AngularEditor.findPath(this.editor, node);
×
1227
            const voidMatch =
1228
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1229

1230
            // If starting a drag on a void node, make sure it is selected
1231
            // so that it shows up in the selection's fragment.
1232
            if (voidMatch) {
×
1233
                const range = Editor.range(this.editor, path);
×
1234
                Transforms.select(this.editor, range);
×
1235
            }
1236

1237
            this.isDraggingInternally = true;
×
1238

1239
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1240
        }
1241
    }
1242

1243
    private onDOMDrop(event: DragEvent) {
1244
        const editor = this.editor;
×
1245
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1246
            event.preventDefault();
×
1247
            // Keep a reference to the dragged range before updating selection
1248
            const draggedRange = editor.selection;
×
1249

1250
            // Find the range where the drop happened
1251
            const range = AngularEditor.findEventRange(editor, event);
×
1252
            const data = event.dataTransfer;
×
1253

1254
            Transforms.select(editor, range);
×
1255

1256
            if (this.isDraggingInternally) {
×
1257
                if (draggedRange) {
×
1258
                    Transforms.delete(editor, {
×
1259
                        at: draggedRange
1260
                    });
1261
                }
1262

1263
                this.isDraggingInternally = false;
×
1264
            }
1265

1266
            AngularEditor.insertData(editor, data);
×
1267

1268
            // When dragging from another source into the editor, it's possible
1269
            // that the current editor does not have focus.
1270
            if (!AngularEditor.isFocused(editor)) {
×
1271
                AngularEditor.focus(editor);
×
1272
            }
1273
        }
1274
    }
1275

1276
    private onDOMDragEnd(event: DragEvent) {
1277
        if (
×
1278
            !this.readonly &&
×
1279
            this.isDraggingInternally &&
1280
            AngularEditor.hasTarget(this.editor, event.target) &&
1281
            !this.isDOMEventHandled(event, this.dragEnd)
1282
        ) {
1283
            this.isDraggingInternally = false;
×
1284
        }
1285
    }
1286

1287
    private onDOMFocus(event: Event) {
1288
        if (
2✔
1289
            !this.readonly &&
8✔
1290
            !this.isUpdatingSelection &&
1291
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1292
            !this.isDOMEventHandled(event, this.focus)
1293
        ) {
1294
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1295
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1296
            this.latestElement = root.activeElement;
2✔
1297

1298
            // COMPAT: If the editor has nested editable elements, the focus
1299
            // can go to them. In Firefox, this must be prevented because it
1300
            // results in issues with keyboard navigation. (2017/03/30)
1301
            if (IS_FIREFOX && event.target !== el) {
2!
1302
                el.focus();
×
1303
                return;
×
1304
            }
1305

1306
            IS_FOCUSED.set(this.editor, true);
2✔
1307
        }
1308
    }
1309

1310
    private onDOMKeydown(event: KeyboardEvent) {
1311
        const editor = this.editor;
×
1312
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1313
        const { activeElement } = root;
×
1314
        if (
×
1315
            !this.readonly &&
×
1316
            AngularEditor.hasEditableTarget(editor, event.target) &&
1317
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1318
            !this.isComposing &&
1319
            !this.isDOMEventHandled(event, this.keydown)
1320
        ) {
1321
            const nativeEvent = event;
×
1322
            const { selection } = editor;
×
1323

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

1327
            try {
×
1328
                // COMPAT: Since we prevent the default behavior on
1329
                // `beforeinput` events, the browser doesn't think there's ever
1330
                // any history stack to undo or redo, so we have to manage these
1331
                // hotkeys ourselves. (2019/11/06)
1332
                if (Hotkeys.isRedo(nativeEvent)) {
×
1333
                    event.preventDefault();
×
1334

1335
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1336
                        editor.redo();
×
1337
                    }
1338

1339
                    return;
×
1340
                }
1341

1342
                if (Hotkeys.isUndo(nativeEvent)) {
×
1343
                    event.preventDefault();
×
1344

1345
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1346
                        editor.undo();
×
1347
                    }
1348

1349
                    return;
×
1350
                }
1351

1352
                // COMPAT: Certain browsers don't handle the selection updates
1353
                // properly. In Chrome, the selection isn't properly extended.
1354
                // And in Firefox, the selection isn't properly collapsed.
1355
                // (2017/10/17)
1356
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1357
                    event.preventDefault();
×
1358
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1359
                    return;
×
1360
                }
1361

1362
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1363
                    event.preventDefault();
×
1364
                    Transforms.move(editor, { unit: 'line' });
×
1365
                    return;
×
1366
                }
1367

1368
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1369
                    event.preventDefault();
×
1370
                    Transforms.move(editor, {
×
1371
                        unit: 'line',
1372
                        edge: 'focus',
1373
                        reverse: true
1374
                    });
1375
                    return;
×
1376
                }
1377

1378
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1379
                    event.preventDefault();
×
1380
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1381
                    return;
×
1382
                }
1383

1384
                // COMPAT: If a void node is selected, or a zero-width text node
1385
                // adjacent to an inline is selected, we need to handle these
1386
                // hotkeys manually because browsers won't be able to skip over
1387
                // the void node with the zero-width space not being an empty
1388
                // string.
1389
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1390
                    event.preventDefault();
×
1391

1392
                    if (selection && Range.isCollapsed(selection)) {
×
1393
                        Transforms.move(editor, { reverse: !isRTL });
×
1394
                    } else {
1395
                        Transforms.collapse(editor, { edge: 'start' });
×
1396
                    }
1397

1398
                    return;
×
1399
                }
1400

1401
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1402
                    event.preventDefault();
×
1403
                    if (selection && Range.isCollapsed(selection)) {
×
1404
                        Transforms.move(editor, { reverse: isRTL });
×
1405
                    } else {
1406
                        Transforms.collapse(editor, { edge: 'end' });
×
1407
                    }
1408

1409
                    return;
×
1410
                }
1411

1412
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1413
                    event.preventDefault();
×
1414

1415
                    if (selection && Range.isExpanded(selection)) {
×
1416
                        Transforms.collapse(editor, { edge: 'focus' });
×
1417
                    }
1418

1419
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1420
                    return;
×
1421
                }
1422

1423
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1424
                    event.preventDefault();
×
1425

1426
                    if (selection && Range.isExpanded(selection)) {
×
1427
                        Transforms.collapse(editor, { edge: 'focus' });
×
1428
                    }
1429

1430
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1431
                    return;
×
1432
                }
1433

1434
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1435
                // fall back to guessing at the input intention for hotkeys.
1436
                // COMPAT: In iOS, some of these hotkeys are handled in the
1437
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1438
                    // We don't have a core behavior for these, but they change the
1439
                    // DOM if we don't prevent them, so we have to.
1440
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1441
                        event.preventDefault();
×
1442
                        return;
×
1443
                    }
1444

1445
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1446
                        event.preventDefault();
×
1447
                        Editor.insertBreak(editor);
×
1448
                        return;
×
1449
                    }
1450

1451
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1452
                        event.preventDefault();
×
1453

1454
                        if (selection && Range.isExpanded(selection)) {
×
1455
                            Editor.deleteFragment(editor, {
×
1456
                                direction: 'backward'
1457
                            });
1458
                        } else {
1459
                            Editor.deleteBackward(editor);
×
1460
                        }
1461

1462
                        return;
×
1463
                    }
1464

1465
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1466
                        event.preventDefault();
×
1467

1468
                        if (selection && Range.isExpanded(selection)) {
×
1469
                            Editor.deleteFragment(editor, {
×
1470
                                direction: 'forward'
1471
                            });
1472
                        } else {
1473
                            Editor.deleteForward(editor);
×
1474
                        }
1475

1476
                        return;
×
1477
                    }
1478

1479
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1480
                        event.preventDefault();
×
1481

1482
                        if (selection && Range.isExpanded(selection)) {
×
1483
                            Editor.deleteFragment(editor, {
×
1484
                                direction: 'backward'
1485
                            });
1486
                        } else {
1487
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1488
                        }
1489

1490
                        return;
×
1491
                    }
1492

1493
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1494
                        event.preventDefault();
×
1495

1496
                        if (selection && Range.isExpanded(selection)) {
×
1497
                            Editor.deleteFragment(editor, {
×
1498
                                direction: 'forward'
1499
                            });
1500
                        } else {
1501
                            Editor.deleteForward(editor, { unit: 'line' });
×
1502
                        }
1503

1504
                        return;
×
1505
                    }
1506

1507
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1508
                        event.preventDefault();
×
1509

1510
                        if (selection && Range.isExpanded(selection)) {
×
1511
                            Editor.deleteFragment(editor, {
×
1512
                                direction: 'backward'
1513
                            });
1514
                        } else {
1515
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1516
                        }
1517

1518
                        return;
×
1519
                    }
1520

1521
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1522
                        event.preventDefault();
×
1523

1524
                        if (selection && Range.isExpanded(selection)) {
×
1525
                            Editor.deleteFragment(editor, {
×
1526
                                direction: 'forward'
1527
                            });
1528
                        } else {
1529
                            Editor.deleteForward(editor, { unit: 'word' });
×
1530
                        }
1531

1532
                        return;
×
1533
                    }
1534
                } else {
1535
                    if (IS_CHROME || IS_SAFARI) {
×
1536
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1537
                        // an event when deleting backwards in a selected void inline node
1538
                        if (
×
1539
                            selection &&
×
1540
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1541
                            Range.isCollapsed(selection)
1542
                        ) {
1543
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1544
                            if (
×
1545
                                Element.isElement(currentNode) &&
×
1546
                                Editor.isVoid(editor, currentNode) &&
1547
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1548
                            ) {
1549
                                event.preventDefault();
×
1550
                                Editor.deleteBackward(editor, {
×
1551
                                    unit: 'block'
1552
                                });
1553
                                return;
×
1554
                            }
1555
                        }
1556
                    }
1557
                }
1558
            } catch (error) {
1559
                this.editor.onError({
×
1560
                    code: SlateErrorCode.OnDOMKeydownError,
1561
                    nativeError: error
1562
                });
1563
            }
1564
        }
1565
    }
1566

1567
    private onDOMPaste(event: ClipboardEvent) {
1568
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1569
        // fall back to React's `onPaste` here instead.
1570
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1571
        // when "paste without formatting" option is used.
1572
        // This unfortunately needs to be handled with paste events instead.
1573
        if (
×
1574
            !this.isDOMEventHandled(event, this.paste) &&
×
1575
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1576
            !this.readonly &&
1577
            AngularEditor.hasEditableTarget(this.editor, event.target)
1578
        ) {
1579
            event.preventDefault();
×
1580
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1581
        }
1582
    }
1583

1584
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1585
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1586
        // fall back to React's leaky polyfill instead just for it. It
1587
        // only works for the `insertText` input type.
1588
        if (
×
1589
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1590
            !this.readonly &&
1591
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1592
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1593
        ) {
1594
            event.nativeEvent.preventDefault();
×
1595
            try {
×
1596
                const text = event.data;
×
1597
                if (!Range.isCollapsed(this.editor.selection)) {
×
1598
                    Editor.deleteFragment(this.editor);
×
1599
                }
1600
                // just handle Non-IME input
1601
                if (!this.isComposing) {
×
1602
                    Editor.insertText(this.editor, text);
×
1603
                }
1604
            } catch (error) {
1605
                this.editor.onError({
×
1606
                    code: SlateErrorCode.ToNativeSelectionError,
1607
                    nativeError: error
1608
                });
1609
            }
1610
        }
1611
    }
1612

1613
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1614
        if (!handler) {
3✔
1615
            return false;
3✔
1616
        }
1617
        handler(event);
×
1618
        return event.defaultPrevented;
×
1619
    }
1620
    //#endregion
1621

1622
    ngOnDestroy() {
1623
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1624
        this.manualListeners.forEach(manualListener => {
23✔
1625
            manualListener();
483✔
1626
        });
1627
        this.destroy$.complete();
23✔
1628
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1629
    }
1630
}
1631

1632
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1633
    // This was affecting the selection of multiple blocks and dragging behavior,
1634
    // so enabled only if the selection has been collapsed.
1635
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1636
        const leafEl = domRange.startContainer.parentElement!;
×
1637

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

1643
        if (isZeroDimensionRect) {
×
1644
            const leafRect = leafEl.getBoundingClientRect();
×
1645
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1646

1647
            if (leafHasDimensions) {
×
1648
                return;
×
1649
            }
1650
        }
1651

1652
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1653
        scrollIntoView(leafEl, {
×
1654
            scrollMode: 'if-needed'
1655
        });
1656
        delete leafEl.getBoundingClientRect;
×
1657
    }
1658
};
1659

1660
/**
1661
 * Check if the target is inside void and in the editor.
1662
 */
1663

1664
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1665
    let slateNode: Node | null = null;
1✔
1666
    try {
1✔
1667
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1668
    } catch (error) {}
1669
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1670
};
1671

1672
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1673
    return (
2✔
1674
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1675
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1676
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1677
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1678
    );
1679
};
1680

1681
/**
1682
 * remove default insert from composition
1683
 * @param text
1684
 */
1685
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1686
    const types = ['compositionend', 'insertFromComposition'];
×
1687
    if (!types.includes(event.type)) {
×
1688
        return;
×
1689
    }
1690
    const insertText = (event as CompositionEvent).data;
×
1691
    const window = AngularEditor.getWindow(editor);
×
1692
    const domSelection = window.getSelection();
×
1693
    // ensure text node insert composition input text
1694
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1695
        const textNode = domSelection.anchorNode;
×
1696
        textNode.splitText(textNode.length - insertText.length).remove();
×
1697
    }
1698
};
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