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

worktile / slate-angular / d22dcadf-93f7-467b-a128-165c0f9d5a21

03 Dec 2025 03:20AM UTC coverage: 45.723% (-1.1%) from 46.809%
d22dcadf-93f7-467b-a128-165c0f9d5a21

Pull #304

circleci

pubuzhixing8
fix: editing issue
Pull Request #304: feat: Support virtual scrolling

380 of 1047 branches covered (36.29%)

Branch coverage included in aggregate %.

46 of 128 new or added lines in 3 files covered. (35.94%)

203 existing lines in 3 files now uncovered.

1042 of 2063 relevant lines covered (50.51%)

31.35 hits per line

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

28.52
/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
} 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 { isDecoratorRangeListEqual } from '../../utils';
60
import { SlatePlaceholder } from '../../types/feature';
61
import { restoreDom } from '../../utils/restore-dom';
62
import { ListRender } from '../../view/render/list-render';
63
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
64

65
// not correctly clipboardData on beforeinput
66
const forceOnDOMPaste = IS_SAFARI;
1✔
67

68
export interface SlateVirtualScrollConfig {
69
    enabled?: boolean;
70
    scrollTop: number;
71
    viewportHeight: number;
72
    blockHeight?: number;
73
    bufferCount?: number;
74
}
75

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

101
    private destroy$ = new Subject();
23✔
102

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

108
    protected manualListeners: (() => void)[] = [];
23✔
109

110
    private initialized: boolean;
111

112
    private onTouchedCallback: () => void = () => {};
23✔
113

114
    private onChangeCallback: (_: any) => void = () => {};
23✔
115

116
    @Input() editor: AngularEditor;
117

118
    @Input() renderElement: (element: Element) => ViewType | null;
119

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

122
    @Input() renderText: (text: SlateText) => ViewType | null;
123

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

126
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
127

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

130
    @Input() isStrictDecorate: boolean = true;
23✔
131

132
    @Input() trackBy: (node: Element) => any = () => null;
206✔
133

134
    @Input() readonly = false;
23✔
135

136
    @Input() placeholder: string;
137

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

151
    @HostBinding('style.padding-top.px') virtualTopPadding = 0;
23✔
152
    @HostBinding('style.padding-bottom.px') virtualBottomPadding = 0;
23✔
153

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

192
    listRender: ListRender;
193

194
    private virtualConfig: SlateVirtualScrollConfig = {
23✔
195
        enabled: false,
196
        scrollTop: 0,
197
        viewportHeight: 0
198
    };
199
    private renderedChildren: Element[] = [];
23✔
200
    private virtualVisibleIndexes = new Set<number>();
23✔
201
    private measuredHeights = new Map<string, number>();
23✔
202
    private measurePending = false;
23✔
203
    private refreshVirtualViewAnimId: number;
204
    private measureVisibleHeightsAnimId: number;
205

206
    constructor(
207
        public elementRef: ElementRef,
23✔
208
        public renderer2: Renderer2,
23✔
209
        public cdr: ChangeDetectorRef,
23✔
210
        private ngZone: NgZone,
23✔
211
        private injector: Injector
23✔
212
    ) {}
213

214
    ngOnInit() {
215
        this.editor.injector = this.injector;
23✔
216
        this.editor.children = [];
23✔
217
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
218
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
219
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
220
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
221
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
222
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
223
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
224
            this.ngZone.run(() => {
13✔
225
                this.onChange();
13✔
226
            });
227
        });
228
        this.ngZone.runOutsideAngular(() => {
23✔
229
            this.initialize();
23✔
230
        });
231
        this.initializeViewContext();
23✔
232
        this.initializeContext();
23✔
233

234
        // add browser class
235
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
236
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
237
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, () => null);
23✔
238
    }
239

240
    ngOnChanges(simpleChanges: SimpleChanges) {
241
        if (!this.initialized) {
30✔
242
            return;
23✔
243
        }
244
        const decorateChange = simpleChanges['decorate'];
7✔
245
        if (decorateChange) {
7✔
246
            this.forceRender();
2✔
247
        }
248
        const placeholderChange = simpleChanges['placeholder'];
7✔
249
        if (placeholderChange) {
7✔
250
            this.render();
1✔
251
        }
252
        const readonlyChange = simpleChanges['readonly'];
7✔
253
        if (readonlyChange) {
7!
UNCOV
254
            IS_READ_ONLY.set(this.editor, this.readonly);
×
255
            this.render();
×
256
            this.toSlateSelection();
×
257
        }
258
    }
259

260
    registerOnChange(fn: any) {
261
        this.onChangeCallback = fn;
23✔
262
    }
263
    registerOnTouched(fn: any) {
264
        this.onTouchedCallback = fn;
23✔
265
    }
266

267
    writeValue(value: Element[]) {
268
        if (value && value.length) {
49✔
269
            this.editor.children = value;
26✔
270
            this.measuredHeights.clear();
26✔
271
            this.initializeContext();
26✔
272
            this.refreshVirtualView();
26✔
273
            const childrenForRender = this.renderedChildren;
26✔
274
            if (!this.listRender.initialized) {
26✔
275
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
276
            } else {
277
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
278
            }
279
            this.scheduleMeasureVisibleHeights();
26✔
280
            this.cdr.markForCheck();
26✔
281
        }
282
    }
283

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

316
    toNativeSelection() {
317
        try {
15✔
318
            const { selection } = this.editor;
15✔
319
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
320
            const { activeElement } = root;
15✔
321
            const domSelection = (root as Document).getSelection();
15✔
322

323
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
324
                return;
14✔
325
            }
326

327
            const hasDomSelection = domSelection.type !== 'None';
1✔
328

329
            // If the DOM selection is properly unset, we're done.
330
            if (!selection && !hasDomSelection) {
1!
331
                return;
×
332
            }
333

334
            // If the DOM selection is already correct, we're done.
335
            // verify that the dom selection is in the editor
336
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
337
            let hasDomSelectionInEditor = false;
1✔
338
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
339
                hasDomSelectionInEditor = true;
1✔
340
            }
341

342
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
343
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
344
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
345
                    exactMatch: false,
346
                    suppressThrow: true
347
                });
348
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
349
                    return;
×
350
                }
351
            }
352

353
            // prevent updating native selection when active element is void element
354
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
355
                return;
×
356
            }
357

358
            // when <Editable/> is being controlled through external value
359
            // then its children might just change - DOM responds to it on its own
360
            // but Slate's value is not being updated through any operation
361
            // and thus it doesn't transform selection on its own
362
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
363
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
364
                return;
×
365
            }
366

367
            // Otherwise the DOM selection is out of sync, so update it.
368
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
369
            this.isUpdatingSelection = true;
1✔
370

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

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

397
            setTimeout(() => {
1✔
398
                // handle scrolling in setTimeout because of
399
                // dom should not have updated immediately after listRender's updating
400
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
401
                // COMPAT: In Firefox, it's not enough to create a range, you also need
402
                // to focus the contenteditable element too. (2016/11/16)
403
                if (newDomRange && IS_FIREFOX) {
1!
404
                    el.focus();
×
405
                }
406

407
                this.isUpdatingSelection = false;
1✔
408
            });
409
        } catch (error) {
410
            this.editor.onError({
×
411
                code: SlateErrorCode.ToNativeSelectionError,
412
                nativeError: error
413
            });
414
            this.isUpdatingSelection = false;
×
415
        }
416
    }
417

418
    onChange() {
419
        this.forceRender();
13✔
420
        this.onChangeCallback(this.editor.children);
13✔
421
    }
422

423
    ngAfterViewChecked() {}
424

425
    ngDoCheck() {}
426

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

468
    render() {
469
        const changed = this.updateContext();
2✔
470
        if (changed) {
2✔
471
            this.refreshVirtualView();
2✔
472
            this.listRender.update(this.renderedChildren, this.editor, this.context);
2✔
473
            this.scheduleMeasureVisibleHeights();
2✔
474
        }
475
    }
476

477
    updateContext() {
478
        const decorations = this.generateDecorations();
17✔
479
        if (
17✔
480
            this.context.selection !== this.editor.selection ||
46✔
481
            this.context.decorate !== this.decorate ||
482
            this.context.readonly !== this.readonly ||
483
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
484
        ) {
485
            this.context = {
10✔
486
                parent: this.editor,
487
                selection: this.editor.selection,
488
                decorations: decorations,
489
                decorate: this.decorate,
490
                readonly: this.readonly
491
            };
492
            return true;
10✔
493
        }
494
        return false;
7✔
495
    }
496

497
    initializeContext() {
498
        this.context = {
49✔
499
            parent: this.editor,
500
            selection: this.editor.selection,
501
            decorations: this.generateDecorations(),
502
            decorate: this.decorate,
503
            readonly: this.readonly
504
        };
505
    }
506

507
    initializeViewContext() {
508
        this.viewContext = {
23✔
509
            editor: this.editor,
510
            renderElement: this.renderElement,
511
            renderLeaf: this.renderLeaf,
512
            renderText: this.renderText,
513
            trackBy: this.trackBy,
514
            isStrictDecorate: this.isStrictDecorate
515
        };
516
    }
517

518
    composePlaceholderDecorate(editor: Editor) {
519
        if (this.placeholderDecorate) {
64!
520
            return this.placeholderDecorate(editor) || [];
×
521
        }
522

523
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
524
            const start = Editor.start(editor, []);
3✔
525
            return [
3✔
526
                {
527
                    placeholder: this.placeholder,
528
                    anchor: start,
529
                    focus: start
530
                }
531
            ];
532
        } else {
533
            return [];
61✔
534
        }
535
    }
536

537
    generateDecorations() {
538
        const decorations = this.decorate([this.editor, []]);
66✔
539
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
540
        decorations.push(...placeholderDecorations);
66✔
541
        return decorations;
66✔
542
    }
543

544
    private shouldUseVirtual() {
545
        return !!(this.virtualConfig && this.virtualConfig.enabled);
86✔
546
    }
547

548
    private refreshVirtualView() {
549
        const children = (this.editor.children || []) as Element[];
43!
550
        if (!children.length || !this.shouldUseVirtual()) {
43✔
551
            this.renderedChildren = children;
43✔
552
            this.virtualTopPadding = 0;
43✔
553
            this.virtualBottomPadding = 0;
43✔
554
            this.virtualVisibleIndexes.clear();
43✔
555
            return;
43✔
556
        }
NEW
557
        const scrollTop = this.virtualConfig.scrollTop ?? 0;
×
NEW
558
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
NEW
559
        if (!viewportHeight) {
×
560
            // 已经启用虚拟滚动,但可视区域高度还未获取到,先置空不渲染
NEW
561
            this.renderedChildren = [];
×
NEW
562
            this.virtualTopPadding = 0;
×
NEW
563
            this.virtualBottomPadding = 0;
×
NEW
564
            this.virtualVisibleIndexes.clear();
×
NEW
565
            return;
×
566
        }
NEW
567
        const bufferCount = this.virtualConfig.bufferCount ?? VIRTUAL_SCROLL_DEFAULT_BUFFER_COUNT;
×
NEW
568
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
NEW
569
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
NEW
570
        const total = accumulatedHeights[accumulatedHeights.length - 1] || 0;
×
571

NEW
572
        let visibleStart = 0;
×
573
        // 按真实或估算高度往后累加,找到滚动起点所在块
NEW
574
        while (visibleStart < heights.length && accumulatedHeights[visibleStart + 1] <= scrollTop) {
×
NEW
575
            visibleStart++;
×
576
        }
577

578
        // 向上预留 bufferCount 块
NEW
579
        const startIndex = Math.max(0, visibleStart - bufferCount);
×
NEW
580
        const top = accumulatedHeights[startIndex];
×
NEW
581
        const bufferBelowHeight = this.getBufferBelowHeight(viewportHeight, visibleStart, bufferCount);
×
NEW
582
        const targetHeight = accumulatedHeights[visibleStart] - top + viewportHeight + bufferBelowHeight;
×
583

NEW
584
        const visible: Element[] = [];
×
NEW
585
        const visibleIndexes: number[] = [];
×
NEW
586
        let accumulated = 0;
×
NEW
587
        let cursor = startIndex;
×
588
        // 循环累计高度超出目标高度(可视高度 + 上下 buffer)
NEW
589
        while (cursor < children.length && accumulated < targetHeight) {
×
NEW
590
            visible.push(children[cursor]);
×
NEW
591
            visibleIndexes.push(cursor);
×
NEW
592
            accumulated += this.getBlockHeight(cursor);
×
NEW
593
            cursor++;
×
594
        }
NEW
595
        const bottom = Math.max(total - top - accumulated, 0); // 下占位高度
×
NEW
596
        this.renderedChildren = visible.length ? visible : children;
×
597
        // padding 占位
NEW
598
        this.virtualTopPadding = this.renderedChildren === visible ? top : 0;
×
NEW
599
        this.virtualBottomPadding = this.renderedChildren === visible ? bottom : 0;
×
NEW
600
        this.virtualVisibleIndexes = new Set(visibleIndexes);
×
601
    }
602

603
    private getBlockHeight(index: number) {
NEW
604
        const blockHeight = this.virtualConfig.blockHeight ?? VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT;
×
NEW
605
        const node = this.editor.children[index];
×
NEW
606
        if (!node) {
×
NEW
607
            return blockHeight;
×
608
        }
NEW
609
        const key = AngularEditor.findKey(this.editor, node);
×
NEW
610
        return this.measuredHeights.get(key.id) ?? blockHeight;
×
611
    }
612

613
    private buildAccumulatedHeight(heights: number[]) {
NEW
614
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
NEW
615
        for (let i = 0; i < heights.length; i++) {
×
616
            // 存储前 i 个的累计高度
NEW
617
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
618
        }
NEW
619
        return accumulatedHeights;
×
620
    }
621

622
    private getBufferBelowHeight(viewportHeight: number, visibleStart: number, bufferCount: number) {
NEW
623
        let blockHeight = 0;
×
NEW
624
        let start = visibleStart;
×
625
        // 循环累计高度超出视图高度代表找到向下缓冲区的起始位置
NEW
626
        while (blockHeight < viewportHeight) {
×
NEW
627
            blockHeight += this.getBlockHeight(start);
×
NEW
628
            start++;
×
629
        }
NEW
630
        let bufferHeight = 0;
×
NEW
631
        for (let i = start; i < start + bufferCount; i++) {
×
NEW
632
            bufferHeight += this.getBlockHeight(i);
×
633
        }
NEW
634
        return bufferHeight;
×
635
    }
636

637
    private scheduleMeasureVisibleHeights() {
638
        if (!this.shouldUseVirtual()) {
43✔
639
            return;
43✔
640
        }
NEW
641
        if (this.measurePending) {
×
NEW
642
            return;
×
643
        }
NEW
644
        this.measurePending = true;
×
NEW
645
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
NEW
646
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
NEW
647
            this.measureVisibleHeights();
×
NEW
648
            this.measurePending = false;
×
649
        });
650
    }
651

652
    private measureVisibleHeights() {
NEW
653
        const children = (this.editor.children || []) as Element[];
×
NEW
654
        this.virtualVisibleIndexes.forEach(index => {
×
NEW
655
            const node = children[index];
×
NEW
656
            if (!node) {
×
NEW
657
                return;
×
658
            }
NEW
659
            const key = AngularEditor.findKey(this.editor, node);
×
660
            // 跳过已测过的块
NEW
661
            if (this.measuredHeights.has(key.id)) {
×
NEW
662
                return;
×
663
            }
NEW
664
            try {
×
NEW
665
                const el = AngularEditor.toDOMNode(this.editor, node);
×
NEW
666
                const rect = el.getBoundingClientRect();
×
NEW
667
                const style = getComputedStyle(el);
×
NEW
668
                const marginTop = parseFloat(style.marginTop) || 0;
×
NEW
669
                const marginBottom = parseFloat(style.marginBottom) || 0;
×
NEW
670
                const marginHeight = rect.height + marginTop + marginBottom;
×
NEW
671
                this.measuredHeights.set(key.id, marginHeight);
×
672
            } catch {
673
                // dom可能没准备好
674
            }
675
        });
676
    }
677

678
    //#region event proxy
679
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
680
        this.manualListeners.push(
483✔
681
            this.renderer2.listen(target, eventName, (event: Event) => {
682
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
683
                if (beforeInputEvent) {
5!
UNCOV
684
                    this.onFallbackBeforeInput(beforeInputEvent);
×
685
                }
686
                listener(event);
5✔
687
            })
688
        );
689
    }
690

691
    private toSlateSelection() {
692
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
693
            try {
1✔
694
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
695
                const { activeElement } = root;
1✔
696
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
697
                const domSelection = (root as Document).getSelection();
1✔
698

699
                if (activeElement === el) {
1!
700
                    this.latestElement = activeElement;
1✔
701
                    IS_FOCUSED.set(this.editor, true);
1✔
702
                } else {
UNCOV
703
                    IS_FOCUSED.delete(this.editor);
×
704
                }
705

706
                if (!domSelection) {
1!
UNCOV
707
                    return Transforms.deselect(this.editor);
×
708
                }
709

710
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
711
                const hasDomSelectionInEditor =
712
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
713
                if (!hasDomSelectionInEditor) {
1!
714
                    Transforms.deselect(this.editor);
×
UNCOV
715
                    return;
×
716
                }
717

718
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
719
                // for example, double-click the last cell of the table to select a non-editable DOM
720
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
721
                if (range) {
1✔
722
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
UNCOV
723
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
724
                            // force adjust DOMSelection
UNCOV
725
                            this.toNativeSelection();
×
726
                        }
727
                    } else {
728
                        Transforms.select(this.editor, range);
1✔
729
                    }
730
                }
731
            } catch (error) {
UNCOV
732
                this.editor.onError({
×
733
                    code: SlateErrorCode.ToSlateSelectionError,
734
                    nativeError: error
735
                });
736
            }
737
        }
738
    }
739

740
    private onDOMBeforeInput(
741
        event: Event & {
742
            inputType: string;
743
            isComposing: boolean;
744
            data: string | null;
745
            dataTransfer: DataTransfer | null;
746
            getTargetRanges(): DOMStaticRange[];
747
        }
748
    ) {
749
        const editor = this.editor;
×
750
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
751
        const { activeElement } = root;
×
752
        const { selection } = editor;
×
753
        const { inputType: type } = event;
×
754
        const data = event.dataTransfer || event.data || undefined;
×
755
        if (IS_ANDROID) {
×
756
            let targetRange: Range | null = null;
×
757
            let [nativeTargetRange] = event.getTargetRanges();
×
758
            if (nativeTargetRange) {
×
UNCOV
759
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
760
            }
761
            // COMPAT: SelectionChange event is fired after the action is performed, so we
762
            // have to manually get the selection here to ensure it's up-to-date.
763
            const window = AngularEditor.getWindow(editor);
×
764
            const domSelection = window.getSelection();
×
765
            if (!targetRange && domSelection) {
×
UNCOV
766
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
767
            }
768
            targetRange = targetRange ?? editor.selection;
×
769
            if (type === 'insertCompositionText') {
×
770
                if (data && data.toString().includes('\n')) {
×
771
                    restoreDom(editor, () => {
×
UNCOV
772
                        Editor.insertBreak(editor);
×
773
                    });
774
                } else {
775
                    if (targetRange) {
×
776
                        if (data) {
×
777
                            restoreDom(editor, () => {
×
UNCOV
778
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
779
                            });
780
                        } else {
781
                            restoreDom(editor, () => {
×
UNCOV
782
                                Transforms.delete(editor, { at: targetRange });
×
783
                            });
784
                        }
785
                    }
786
                }
UNCOV
787
                return;
×
788
            }
UNCOV
789
            if (type === 'deleteContentBackward') {
×
790
                // gboard can not prevent default action, so must use restoreDom,
791
                // sougou Keyboard can prevent default action(only in Chinese input mode).
792
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
793
                if (!Range.isCollapsed(targetRange)) {
×
794
                    restoreDom(editor, () => {
×
UNCOV
795
                        Transforms.delete(editor, { at: targetRange });
×
796
                    });
UNCOV
797
                    return;
×
798
                }
799
            }
800
            if (type === 'insertText') {
×
801
                restoreDom(editor, () => {
×
802
                    if (typeof data === 'string') {
×
UNCOV
803
                        Editor.insertText(editor, data);
×
804
                    }
805
                });
UNCOV
806
                return;
×
807
            }
808
        }
UNCOV
809
        if (
×
810
            !this.readonly &&
×
811
            AngularEditor.hasEditableTarget(editor, event.target) &&
812
            !isTargetInsideVoid(editor, activeElement) &&
813
            !this.isDOMEventHandled(event, this.beforeInput)
814
        ) {
815
            try {
×
UNCOV
816
                event.preventDefault();
×
817

818
                // COMPAT: If the selection is expanded, even if the command seems like
819
                // a delete forward/backward command it should delete the selection.
820
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
821
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
822
                    Editor.deleteFragment(editor, { direction });
×
UNCOV
823
                    return;
×
824
                }
825

UNCOV
826
                switch (type) {
×
827
                    case 'deleteByComposition':
828
                    case 'deleteByCut':
829
                    case 'deleteByDrag': {
830
                        Editor.deleteFragment(editor);
×
UNCOV
831
                        break;
×
832
                    }
833

834
                    case 'deleteContent':
835
                    case 'deleteContentForward': {
836
                        Editor.deleteForward(editor);
×
UNCOV
837
                        break;
×
838
                    }
839

840
                    case 'deleteContentBackward': {
841
                        Editor.deleteBackward(editor);
×
UNCOV
842
                        break;
×
843
                    }
844

845
                    case 'deleteEntireSoftLine': {
846
                        Editor.deleteBackward(editor, { unit: 'line' });
×
847
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
848
                        break;
×
849
                    }
850

851
                    case 'deleteHardLineBackward': {
852
                        Editor.deleteBackward(editor, { unit: 'block' });
×
UNCOV
853
                        break;
×
854
                    }
855

856
                    case 'deleteSoftLineBackward': {
857
                        Editor.deleteBackward(editor, { unit: 'line' });
×
UNCOV
858
                        break;
×
859
                    }
860

861
                    case 'deleteHardLineForward': {
862
                        Editor.deleteForward(editor, { unit: 'block' });
×
UNCOV
863
                        break;
×
864
                    }
865

866
                    case 'deleteSoftLineForward': {
867
                        Editor.deleteForward(editor, { unit: 'line' });
×
UNCOV
868
                        break;
×
869
                    }
870

871
                    case 'deleteWordBackward': {
872
                        Editor.deleteBackward(editor, { unit: 'word' });
×
UNCOV
873
                        break;
×
874
                    }
875

876
                    case 'deleteWordForward': {
877
                        Editor.deleteForward(editor, { unit: 'word' });
×
UNCOV
878
                        break;
×
879
                    }
880

881
                    case 'insertLineBreak':
882
                    case 'insertParagraph': {
883
                        Editor.insertBreak(editor);
×
UNCOV
884
                        break;
×
885
                    }
886

887
                    case 'insertFromComposition': {
888
                        // COMPAT: in safari, `compositionend` event is dispatched after
889
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
890
                        // https://www.w3.org/TR/input-events-2/
891
                        // so the following code is the right logic
892
                        // because DOM selection in sync will be exec before `compositionend` event
893
                        // isComposing is true will prevent DOM selection being update correctly.
894
                        this.isComposing = false;
×
UNCOV
895
                        preventInsertFromComposition(event, this.editor);
×
896
                    }
897
                    case 'insertFromDrop':
898
                    case 'insertFromPaste':
899
                    case 'insertFromYank':
900
                    case 'insertReplacementText':
901
                    case 'insertText': {
902
                        // use a weak comparison instead of 'instanceof' to allow
903
                        // programmatic access of paste events coming from external windows
904
                        // like cypress where cy.window does not work realibly
905
                        if (data?.constructor.name === 'DataTransfer') {
×
906
                            AngularEditor.insertData(editor, data as DataTransfer);
×
907
                        } else if (typeof data === 'string') {
×
UNCOV
908
                            Editor.insertText(editor, data);
×
909
                        }
UNCOV
910
                        break;
×
911
                    }
912
                }
913
            } catch (error) {
UNCOV
914
                this.editor.onError({
×
915
                    code: SlateErrorCode.OnDOMBeforeInputError,
916
                    nativeError: error
917
                });
918
            }
919
        }
920
    }
921

922
    private onDOMBlur(event: FocusEvent) {
UNCOV
923
        if (
×
924
            this.readonly ||
×
925
            this.isUpdatingSelection ||
926
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
927
            this.isDOMEventHandled(event, this.blur)
928
        ) {
UNCOV
929
            return;
×
930
        }
931

UNCOV
932
        const window = AngularEditor.getWindow(this.editor);
×
933

934
        // COMPAT: If the current `activeElement` is still the previous
935
        // one, this is due to the window being blurred when the tab
936
        // itself becomes unfocused, so we want to abort early to allow to
937
        // editor to stay focused when the tab becomes focused again.
938
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
939
        if (this.latestElement === root.activeElement) {
×
UNCOV
940
            return;
×
941
        }
942

943
        const { relatedTarget } = event;
×
UNCOV
944
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
945

946
        // COMPAT: The event should be ignored if the focus is returning
947
        // to the editor from an embedded editable element (eg. an <input>
948
        // element inside a void node).
949
        if (relatedTarget === el) {
×
UNCOV
950
            return;
×
951
        }
952

953
        // COMPAT: The event should be ignored if the focus is moving from
954
        // the editor to inside a void node's spacer element.
955
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
UNCOV
956
            return;
×
957
        }
958

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

965
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
UNCOV
966
                return;
×
967
            }
968
        }
969

UNCOV
970
        IS_FOCUSED.delete(this.editor);
×
971
    }
972

973
    private onDOMClick(event: MouseEvent) {
UNCOV
974
        if (
×
975
            !this.readonly &&
×
976
            AngularEditor.hasTarget(this.editor, event.target) &&
977
            !this.isDOMEventHandled(event, this.click) &&
978
            isDOMNode(event.target)
979
        ) {
980
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
981
            const path = AngularEditor.findPath(this.editor, node);
×
982
            const start = Editor.start(this.editor, path);
×
UNCOV
983
            const end = Editor.end(this.editor, path);
×
984

985
            const startVoid = Editor.void(this.editor, { at: start });
×
UNCOV
986
            const endVoid = Editor.void(this.editor, { at: end });
×
987

988
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
989
                let blockPath = path;
×
990
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
991
                    const block = Editor.above(this.editor, {
×
UNCOV
992
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
993
                        at: path
994
                    });
995

UNCOV
996
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
997
                }
998

999
                const range = Editor.range(this.editor, blockPath);
×
1000
                Transforms.select(this.editor, range);
×
UNCOV
1001
                return;
×
1002
            }
1003

UNCOV
1004
            if (
×
1005
                startVoid &&
×
1006
                endVoid &&
1007
                Path.equals(startVoid[1], endVoid[1]) &&
1008
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1009
            ) {
1010
                const range = Editor.range(this.editor, start);
×
UNCOV
1011
                Transforms.select(this.editor, range);
×
1012
            }
1013
        }
1014
    }
1015

1016
    private onDOMCompositionStart(event: CompositionEvent) {
1017
        const { selection } = this.editor;
1✔
1018
        if (selection) {
1!
1019
            // solve the problem of cross node Chinese input
1020
            if (Range.isExpanded(selection)) {
×
1021
                Editor.deleteFragment(this.editor);
×
UNCOV
1022
                this.forceRender();
×
1023
            }
1024
        }
1025
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1026
            this.isComposing = true;
1✔
1027
        }
1028
        this.render();
1✔
1029
    }
1030

1031
    private onDOMCompositionUpdate(event: CompositionEvent) {
UNCOV
1032
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1033
    }
1034

1035
    private onDOMCompositionEnd(event: CompositionEvent) {
1036
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1037
            Transforms.delete(this.editor);
×
1038
        }
UNCOV
1039
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1040
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1041
            // aren't correct and never fire the "insertFromComposition"
1042
            // type that we need. So instead, insert whenever a composition
1043
            // ends since it will already have been committed to the DOM.
1044
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1045
                preventInsertFromComposition(event, this.editor);
×
UNCOV
1046
                Editor.insertText(this.editor, event.data);
×
1047
            }
1048

1049
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1050
            // so we need avoid repeat isnertText by isComposing === true,
UNCOV
1051
            this.isComposing = false;
×
1052
        }
UNCOV
1053
        this.render();
×
1054
    }
1055

1056
    private onDOMCopy(event: ClipboardEvent) {
1057
        const window = AngularEditor.getWindow(this.editor);
×
1058
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1059
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1060
            event.preventDefault();
×
UNCOV
1061
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1062
        }
1063
    }
1064

1065
    private onDOMCut(event: ClipboardEvent) {
1066
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1067
            event.preventDefault();
×
1068
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
UNCOV
1069
            const { selection } = this.editor;
×
1070

1071
            if (selection) {
×
UNCOV
1072
                AngularEditor.deleteCutData(this.editor);
×
1073
            }
1074
        }
1075
    }
1076

1077
    private onDOMDragOver(event: DragEvent) {
UNCOV
1078
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1079
            // Only when the target is void, call `preventDefault` to signal
1080
            // that drops are allowed. Editable content is droppable by
1081
            // default, and calling `preventDefault` hides the cursor.
UNCOV
1082
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1083

1084
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
UNCOV
1085
                event.preventDefault();
×
1086
            }
1087
        }
1088
    }
1089

1090
    private onDOMDragStart(event: DragEvent) {
1091
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1092
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
UNCOV
1093
            const path = AngularEditor.findPath(this.editor, node);
×
1094
            const voidMatch =
UNCOV
1095
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1096

1097
            // If starting a drag on a void node, make sure it is selected
1098
            // so that it shows up in the selection's fragment.
1099
            if (voidMatch) {
×
1100
                const range = Editor.range(this.editor, path);
×
UNCOV
1101
                Transforms.select(this.editor, range);
×
1102
            }
1103

UNCOV
1104
            this.isDraggingInternally = true;
×
1105

UNCOV
1106
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1107
        }
1108
    }
1109

1110
    private onDOMDrop(event: DragEvent) {
1111
        const editor = this.editor;
×
1112
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
UNCOV
1113
            event.preventDefault();
×
1114
            // Keep a reference to the dragged range before updating selection
UNCOV
1115
            const draggedRange = editor.selection;
×
1116

1117
            // Find the range where the drop happened
1118
            const range = AngularEditor.findEventRange(editor, event);
×
UNCOV
1119
            const data = event.dataTransfer;
×
1120

UNCOV
1121
            Transforms.select(editor, range);
×
1122

1123
            if (this.isDraggingInternally) {
×
1124
                if (draggedRange) {
×
UNCOV
1125
                    Transforms.delete(editor, {
×
1126
                        at: draggedRange
1127
                    });
1128
                }
1129

UNCOV
1130
                this.isDraggingInternally = false;
×
1131
            }
1132

UNCOV
1133
            AngularEditor.insertData(editor, data);
×
1134

1135
            // When dragging from another source into the editor, it's possible
1136
            // that the current editor does not have focus.
1137
            if (!AngularEditor.isFocused(editor)) {
×
UNCOV
1138
                AngularEditor.focus(editor);
×
1139
            }
1140
        }
1141
    }
1142

1143
    private onDOMDragEnd(event: DragEvent) {
UNCOV
1144
        if (
×
1145
            !this.readonly &&
×
1146
            this.isDraggingInternally &&
1147
            AngularEditor.hasTarget(this.editor, event.target) &&
1148
            !this.isDOMEventHandled(event, this.dragEnd)
1149
        ) {
UNCOV
1150
            this.isDraggingInternally = false;
×
1151
        }
1152
    }
1153

1154
    private onDOMFocus(event: Event) {
1155
        if (
2✔
1156
            !this.readonly &&
8✔
1157
            !this.isUpdatingSelection &&
1158
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1159
            !this.isDOMEventHandled(event, this.focus)
1160
        ) {
1161
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1162
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1163
            this.latestElement = root.activeElement;
2✔
1164

1165
            // COMPAT: If the editor has nested editable elements, the focus
1166
            // can go to them. In Firefox, this must be prevented because it
1167
            // results in issues with keyboard navigation. (2017/03/30)
1168
            if (IS_FIREFOX && event.target !== el) {
2!
1169
                el.focus();
×
UNCOV
1170
                return;
×
1171
            }
1172

1173
            IS_FOCUSED.set(this.editor, true);
2✔
1174
        }
1175
    }
1176

1177
    private onDOMKeydown(event: KeyboardEvent) {
1178
        const editor = this.editor;
×
1179
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1180
        const { activeElement } = root;
×
UNCOV
1181
        if (
×
1182
            !this.readonly &&
×
1183
            AngularEditor.hasEditableTarget(editor, event.target) &&
1184
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1185
            !this.isComposing &&
1186
            !this.isDOMEventHandled(event, this.keydown)
1187
        ) {
1188
            const nativeEvent = event;
×
UNCOV
1189
            const { selection } = editor;
×
1190

1191
            const element = editor.children[selection !== null ? selection.focus.path[0] : 0];
×
UNCOV
1192
            const isRTL = direction(Node.string(element)) === 'rtl';
×
1193

UNCOV
1194
            try {
×
1195
                // COMPAT: Since we prevent the default behavior on
1196
                // `beforeinput` events, the browser doesn't think there's ever
1197
                // any history stack to undo or redo, so we have to manage these
1198
                // hotkeys ourselves. (2019/11/06)
1199
                if (Hotkeys.isRedo(nativeEvent)) {
×
UNCOV
1200
                    event.preventDefault();
×
1201

1202
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1203
                        editor.redo();
×
1204
                    }
1205

UNCOV
1206
                    return;
×
1207
                }
1208

1209
                if (Hotkeys.isUndo(nativeEvent)) {
×
UNCOV
1210
                    event.preventDefault();
×
1211

1212
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
UNCOV
1213
                        editor.undo();
×
1214
                    }
1215

UNCOV
1216
                    return;
×
1217
                }
1218

1219
                // COMPAT: Certain browsers don't handle the selection updates
1220
                // properly. In Chrome, the selection isn't properly extended.
1221
                // And in Firefox, the selection isn't properly collapsed.
1222
                // (2017/10/17)
1223
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1224
                    event.preventDefault();
×
1225
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
UNCOV
1226
                    return;
×
1227
                }
1228

1229
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1230
                    event.preventDefault();
×
1231
                    Transforms.move(editor, { unit: 'line' });
×
UNCOV
1232
                    return;
×
1233
                }
1234

1235
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1236
                    event.preventDefault();
×
UNCOV
1237
                    Transforms.move(editor, {
×
1238
                        unit: 'line',
1239
                        edge: 'focus',
1240
                        reverse: true
1241
                    });
UNCOV
1242
                    return;
×
1243
                }
1244

1245
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1246
                    event.preventDefault();
×
1247
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
UNCOV
1248
                    return;
×
1249
                }
1250

1251
                // COMPAT: If a void node is selected, or a zero-width text node
1252
                // adjacent to an inline is selected, we need to handle these
1253
                // hotkeys manually because browsers won't be able to skip over
1254
                // the void node with the zero-width space not being an empty
1255
                // string.
1256
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
UNCOV
1257
                    event.preventDefault();
×
1258

1259
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1260
                        Transforms.move(editor, { reverse: !isRTL });
×
1261
                    } else {
UNCOV
1262
                        Transforms.collapse(editor, { edge: 'start' });
×
1263
                    }
1264

UNCOV
1265
                    return;
×
1266
                }
1267

1268
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1269
                    event.preventDefault();
×
1270
                    if (selection && Range.isCollapsed(selection)) {
×
UNCOV
1271
                        Transforms.move(editor, { reverse: isRTL });
×
1272
                    } else {
UNCOV
1273
                        Transforms.collapse(editor, { edge: 'end' });
×
1274
                    }
1275

UNCOV
1276
                    return;
×
1277
                }
1278

1279
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
UNCOV
1280
                    event.preventDefault();
×
1281

1282
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1283
                        Transforms.collapse(editor, { edge: 'focus' });
×
1284
                    }
1285

1286
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
UNCOV
1287
                    return;
×
1288
                }
1289

1290
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
UNCOV
1291
                    event.preventDefault();
×
1292

1293
                    if (selection && Range.isExpanded(selection)) {
×
UNCOV
1294
                        Transforms.collapse(editor, { edge: 'focus' });
×
1295
                    }
1296

1297
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
UNCOV
1298
                    return;
×
1299
                }
1300

1301
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1302
                // fall back to guessing at the input intention for hotkeys.
1303
                // COMPAT: In iOS, some of these hotkeys are handled in the
UNCOV
1304
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1305
                    // We don't have a core behavior for these, but they change the
1306
                    // DOM if we don't prevent them, so we have to.
1307
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1308
                        event.preventDefault();
×
UNCOV
1309
                        return;
×
1310
                    }
1311

1312
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1313
                        event.preventDefault();
×
1314
                        Editor.insertBreak(editor);
×
UNCOV
1315
                        return;
×
1316
                    }
1317

1318
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
UNCOV
1319
                        event.preventDefault();
×
1320

1321
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1322
                            Editor.deleteFragment(editor, {
×
1323
                                direction: 'backward'
1324
                            });
1325
                        } else {
UNCOV
1326
                            Editor.deleteBackward(editor);
×
1327
                        }
1328

UNCOV
1329
                        return;
×
1330
                    }
1331

1332
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
UNCOV
1333
                        event.preventDefault();
×
1334

1335
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1336
                            Editor.deleteFragment(editor, {
×
1337
                                direction: 'forward'
1338
                            });
1339
                        } else {
UNCOV
1340
                            Editor.deleteForward(editor);
×
1341
                        }
1342

UNCOV
1343
                        return;
×
1344
                    }
1345

1346
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
UNCOV
1347
                        event.preventDefault();
×
1348

1349
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1350
                            Editor.deleteFragment(editor, {
×
1351
                                direction: 'backward'
1352
                            });
1353
                        } else {
UNCOV
1354
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1355
                        }
1356

UNCOV
1357
                        return;
×
1358
                    }
1359

1360
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
UNCOV
1361
                        event.preventDefault();
×
1362

1363
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1364
                            Editor.deleteFragment(editor, {
×
1365
                                direction: 'forward'
1366
                            });
1367
                        } else {
UNCOV
1368
                            Editor.deleteForward(editor, { unit: 'line' });
×
1369
                        }
1370

UNCOV
1371
                        return;
×
1372
                    }
1373

1374
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
UNCOV
1375
                        event.preventDefault();
×
1376

1377
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1378
                            Editor.deleteFragment(editor, {
×
1379
                                direction: 'backward'
1380
                            });
1381
                        } else {
UNCOV
1382
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1383
                        }
1384

UNCOV
1385
                        return;
×
1386
                    }
1387

1388
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
UNCOV
1389
                        event.preventDefault();
×
1390

1391
                        if (selection && Range.isExpanded(selection)) {
×
UNCOV
1392
                            Editor.deleteFragment(editor, {
×
1393
                                direction: 'forward'
1394
                            });
1395
                        } else {
UNCOV
1396
                            Editor.deleteForward(editor, { unit: 'word' });
×
1397
                        }
1398

UNCOV
1399
                        return;
×
1400
                    }
1401
                } else {
UNCOV
1402
                    if (IS_CHROME || IS_SAFARI) {
×
1403
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1404
                        // an event when deleting backwards in a selected void inline node
UNCOV
1405
                        if (
×
1406
                            selection &&
×
1407
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1408
                            Range.isCollapsed(selection)
1409
                        ) {
1410
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
UNCOV
1411
                            if (
×
1412
                                Element.isElement(currentNode) &&
×
1413
                                Editor.isVoid(editor, currentNode) &&
1414
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1415
                            ) {
1416
                                event.preventDefault();
×
UNCOV
1417
                                Editor.deleteBackward(editor, {
×
1418
                                    unit: 'block'
1419
                                });
UNCOV
1420
                                return;
×
1421
                            }
1422
                        }
1423
                    }
1424
                }
1425
            } catch (error) {
UNCOV
1426
                this.editor.onError({
×
1427
                    code: SlateErrorCode.OnDOMKeydownError,
1428
                    nativeError: error
1429
                });
1430
            }
1431
        }
1432
    }
1433

1434
    private onDOMPaste(event: ClipboardEvent) {
1435
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1436
        // fall back to React's `onPaste` here instead.
1437
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1438
        // when "paste without formatting" option is used.
1439
        // This unfortunately needs to be handled with paste events instead.
UNCOV
1440
        if (
×
1441
            !this.isDOMEventHandled(event, this.paste) &&
×
1442
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1443
            !this.readonly &&
1444
            AngularEditor.hasEditableTarget(this.editor, event.target)
1445
        ) {
1446
            event.preventDefault();
×
UNCOV
1447
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1448
        }
1449
    }
1450

1451
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1452
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1453
        // fall back to React's leaky polyfill instead just for it. It
1454
        // only works for the `insertText` input type.
UNCOV
1455
        if (
×
1456
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1457
            !this.readonly &&
1458
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1459
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1460
        ) {
1461
            event.nativeEvent.preventDefault();
×
1462
            try {
×
1463
                const text = event.data;
×
1464
                if (!Range.isCollapsed(this.editor.selection)) {
×
UNCOV
1465
                    Editor.deleteFragment(this.editor);
×
1466
                }
1467
                // just handle Non-IME input
1468
                if (!this.isComposing) {
×
UNCOV
1469
                    Editor.insertText(this.editor, text);
×
1470
                }
1471
            } catch (error) {
UNCOV
1472
                this.editor.onError({
×
1473
                    code: SlateErrorCode.ToNativeSelectionError,
1474
                    nativeError: error
1475
                });
1476
            }
1477
        }
1478
    }
1479

1480
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1481
        if (!handler) {
3✔
1482
            return false;
3✔
1483
        }
1484
        handler(event);
×
UNCOV
1485
        return event.defaultPrevented;
×
1486
    }
1487
    //#endregion
1488

1489
    ngOnDestroy() {
1490
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1491
        this.manualListeners.forEach(manualListener => {
22✔
1492
            manualListener();
462✔
1493
        });
1494
        this.destroy$.complete();
22✔
1495
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1496
    }
1497
}
1498

1499
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1500
    // This was affecting the selection of multiple blocks and dragging behavior,
1501
    // so enabled only if the selection has been collapsed.
1502
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
UNCOV
1503
        const leafEl = domRange.startContainer.parentElement!;
×
1504

1505
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1506
        // When this happens, do not scroll like most editors do.
1507
        const domRect = domRange.getBoundingClientRect();
×
UNCOV
1508
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
×
1509

1510
        if (isZeroDimensionRect) {
×
1511
            const leafRect = leafEl.getBoundingClientRect();
×
UNCOV
1512
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1513

1514
            if (leafHasDimensions) {
×
UNCOV
1515
                return;
×
1516
            }
1517
        }
1518

1519
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
UNCOV
1520
        scrollIntoView(leafEl, {
×
1521
            scrollMode: 'if-needed'
1522
        });
UNCOV
1523
        delete leafEl.getBoundingClientRect;
×
1524
    }
1525
};
1526

1527
/**
1528
 * Check if the target is inside void and in the editor.
1529
 */
1530

1531
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1532
    let slateNode: Node | null = null;
1✔
1533
    try {
1✔
1534
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1535
    } catch (error) {}
1536
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1537
};
1538

1539
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1540
    return (
2✔
1541
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1542
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1543
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1544
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1545
    );
1546
};
1547

1548
/**
1549
 * remove default insert from composition
1550
 * @param text
1551
 */
1552
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1553
    const types = ['compositionend', 'insertFromComposition'];
×
1554
    if (!types.includes(event.type)) {
×
UNCOV
1555
        return;
×
1556
    }
1557
    const insertText = (event as CompositionEvent).data;
×
1558
    const window = AngularEditor.getWindow(editor);
×
UNCOV
1559
    const domSelection = window.getSelection();
×
1560
    // ensure text node insert composition input text
1561
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1562
        const textNode = domSelection.anchorNode;
×
UNCOV
1563
        textNode.splitText(textNode.length - insertText.length).remove();
×
1564
    }
1565
};
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