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

worktile / slate-angular / 3e50b982-8535-46cb-9626-cd99c2dfc5a3

03 Dec 2025 09:11AM UTC coverage: 45.785% (-1.0%) from 46.809%
3e50b982-8535-46cb-9626-cd99c2dfc5a3

Pull #304

circleci

pubuzhixing8
feat: provider getRealHeight method
Pull Request #304: feat: Support virtual scrolling

380 of 1044 branches covered (36.4%)

Branch coverage included in aggregate %.

47 of 129 new or added lines in 5 files covered. (36.43%)

210 existing lines in 1 file now uncovered.

1043 of 2064 relevant lines covered (50.53%)

31.33 hits per line

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

28.65
/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.padding-top.px') virtualTopPadding = 0;
23✔
154
    @HostBinding('style.padding-bottom.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.measuredHeights.clear();
26✔
273
            this.initializeContext();
26✔
274
            this.refreshVirtualView();
26✔
275
            const childrenForRender = this.renderedChildren;
26✔
276
            if (!this.listRender.initialized) {
26✔
277
                this.listRender.initialize(childrenForRender, this.editor, this.context);
23✔
278
            } else {
279
                this.listRender.update(childrenForRender, this.editor, this.context);
3✔
280
            }
281
            this.scheduleMeasureVisibleHeights();
26✔
282
            this.cdr.markForCheck();
26✔
283
        }
284
    }
285

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

425
    ngAfterViewChecked() {}
426

427
    ngDoCheck() {}
428

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1106
            this.isDraggingInternally = true;
×
1107

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

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

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

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

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

1132
                this.isDraggingInternally = false;
×
1133
            }
1134

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

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

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

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

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

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

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

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

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

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

1208
                    return;
×
1209
                }
1210

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

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

UNCOV
1218
                    return;
×
1219
                }
1220

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

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

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

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

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

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

1267
                    return;
×
1268
                }
1269

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

1278
                    return;
×
1279
                }
1280

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

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

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

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

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

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

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

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

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

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

1331
                        return;
×
1332
                    }
1333

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

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

1345
                        return;
×
1346
                    }
1347

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

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

1359
                        return;
×
1360
                    }
1361

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

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

1373
                        return;
×
1374
                    }
1375

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

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

1387
                        return;
×
1388
                    }
1389

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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