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

worktile / slate-angular / 46fbbbe6-df0b-46ec-87df-0169d3944b71

03 Dec 2025 09:33AM UTC coverage: 45.768% (-1.0%) from 46.809%
46fbbbe6-df0b-46ec-87df-0169d3944b71

Pull #304

circleci

Xwatson
feat: 滚动条使用伪元素撑开
Pull Request #304: feat: Support virtual scrolling

380 of 1044 branches covered (36.4%)

Branch coverage included in aggregate %.

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

238 existing lines in 1 file now uncovered.

1042 of 2063 relevant lines covered (50.51%)

31.34 hits per line

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

28.58
/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 { ELEMENT_TO_COMPONENT, 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
import { BaseElementComponent } from '../../view/base';
65
import { BaseElementFlavour } from '../../view/flavour/element';
66

67
// not correctly clipboardData on beforeinput
68
const forceOnDOMPaste = IS_SAFARI;
1✔
69

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

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

103
    private destroy$ = new Subject();
23✔
104

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

110
    protected manualListeners: (() => void)[] = [];
23✔
111

112
    private initialized: boolean;
113

114
    private onTouchedCallback: () => void = () => {};
23✔
115

116
    private onChangeCallback: (_: any) => void = () => {};
23✔
117

118
    @Input() editor: AngularEditor;
119

120
    @Input() renderElement: (element: Element) => ViewType | null;
121

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

124
    @Input() renderText: (text: SlateText) => ViewType | null;
125

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

128
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
129

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

132
    @Input() isStrictDecorate: boolean = true;
23✔
133

134
    @Input() trackBy: (node: Element) => any = () => null;
206✔
135

136
    @Input() readonly = false;
23✔
137

138
    @Input() placeholder: string;
139

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

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

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

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

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

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

188
    viewContainerRef = inject(ViewContainerRef);
23✔
189

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

194
    listRender: ListRender;
195

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

424
    ngAfterViewChecked() {}
425

426
    ngDoCheck() {}
427

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

653
    private measureVisibleHeights() {
NEW
654
        const children = (this.editor.children || []) as Element[];
×
NEW
655
        this.virtualVisibleIndexes.forEach(index => {
×
NEW
656
            const node = children[index];
×
NEW
657
            if (!node) {
×
NEW
658
                return;
×
659
            }
NEW
660
            const key = AngularEditor.findKey(this.editor, node);
×
661
            // 跳过已测过的块
NEW
662
            if (this.measuredHeights.has(key.id)) {
×
NEW
663
                return;
×
664
            }
NEW
665
            const view = ELEMENT_TO_COMPONENT.get(node);
×
NEW
666
            if (!view) {
×
NEW
667
                return;
×
668
            }
NEW
669
            (view as BaseElementComponent | BaseElementFlavour).getRealHeight()?.then(height => {
×
670
                const actualHeight =
NEW
671
                    height +
×
672
                    parseFloat(getComputedStyle(view.nativeElement).marginTop) +
673
                    parseFloat(getComputedStyle(view.nativeElement).marginBottom);
NEW
674
                this.measuredHeights.set(key.id, actualHeight);
×
675
            });
676
        });
677
    }
678

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1105
            this.isDraggingInternally = true;
×
1106

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

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

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

1122
            Transforms.select(editor, range);
×
1123

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1207
                    return;
×
1208
                }
1209

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

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

UNCOV
1217
                    return;
×
1218
                }
1219

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

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

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

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

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

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

UNCOV
1266
                    return;
×
1267
                }
1268

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

UNCOV
1277
                    return;
×
1278
                }
1279

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

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

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

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

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

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

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

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

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

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

UNCOV
1330
                        return;
×
1331
                    }
1332

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

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

UNCOV
1344
                        return;
×
1345
                    }
1346

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

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

UNCOV
1358
                        return;
×
1359
                    }
1360

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

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

UNCOV
1372
                        return;
×
1373
                    }
1374

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

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

UNCOV
1386
                        return;
×
1387
                    }
1388

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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