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

worktile / slate-angular / 0b0089f8-e36e-4dee-b06b-514e0506de64

03 Dec 2025 10:35AM UTC coverage: 45.797% (-0.02%) from 45.812%
0b0089f8-e36e-4dee-b06b-514e0506de64

push

circleci

pubuzhixing8
fix(virtual-scroll): move marginTop and marginBottom to getRealHeight

380 of 1042 branches covered (36.47%)

Branch coverage included in aggregate %.

0 of 5 new or added lines in 3 files covered. (0.0%)

1042 of 2063 relevant lines covered (50.51%)

31.35 hits per line

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

28.69
/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
    bufferCount?: number;
75
}
76

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

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

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

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

111
    private initialized: boolean;
112

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

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

117
    @Input() editor: AngularEditor;
118

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

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

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

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

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

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

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

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

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

137
    @Input() placeholder: string;
138

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

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

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

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

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

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

187
    viewContainerRef = inject(ViewContainerRef);
23✔
188

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

193
    listRender: ListRender;
194

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

423
    ngAfterViewChecked() {}
424

425
    ngDoCheck() {}
426

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

686
    private toSlateSelection() {
687
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
688
            try {
1✔
689
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
690
                const { activeElement } = root;
1✔
691
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
692
                const domSelection = (root as Document).getSelection();
1✔
693

694
                if (activeElement === el) {
1!
695
                    this.latestElement = activeElement;
1✔
696
                    IS_FOCUSED.set(this.editor, true);
1✔
697
                } else {
698
                    IS_FOCUSED.delete(this.editor);
×
699
                }
700

701
                if (!domSelection) {
1!
702
                    return Transforms.deselect(this.editor);
×
703
                }
704

705
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
706
                const hasDomSelectionInEditor =
707
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
708
                if (!hasDomSelectionInEditor) {
1!
709
                    Transforms.deselect(this.editor);
×
710
                    return;
×
711
                }
712

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

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

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

821
                switch (type) {
×
822
                    case 'deleteByComposition':
823
                    case 'deleteByCut':
824
                    case 'deleteByDrag': {
825
                        Editor.deleteFragment(editor);
×
826
                        break;
×
827
                    }
828

829
                    case 'deleteContent':
830
                    case 'deleteContentForward': {
831
                        Editor.deleteForward(editor);
×
832
                        break;
×
833
                    }
834

835
                    case 'deleteContentBackward': {
836
                        Editor.deleteBackward(editor);
×
837
                        break;
×
838
                    }
839

840
                    case 'deleteEntireSoftLine': {
841
                        Editor.deleteBackward(editor, { unit: 'line' });
×
842
                        Editor.deleteForward(editor, { unit: 'line' });
×
843
                        break;
×
844
                    }
845

846
                    case 'deleteHardLineBackward': {
847
                        Editor.deleteBackward(editor, { unit: 'block' });
×
848
                        break;
×
849
                    }
850

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

856
                    case 'deleteHardLineForward': {
857
                        Editor.deleteForward(editor, { unit: 'block' });
×
858
                        break;
×
859
                    }
860

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

866
                    case 'deleteWordBackward': {
867
                        Editor.deleteBackward(editor, { unit: 'word' });
×
868
                        break;
×
869
                    }
870

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

876
                    case 'insertLineBreak':
877
                    case 'insertParagraph': {
878
                        Editor.insertBreak(editor);
×
879
                        break;
×
880
                    }
881

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

917
    private onDOMBlur(event: FocusEvent) {
918
        if (
×
919
            this.readonly ||
×
920
            this.isUpdatingSelection ||
921
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
922
            this.isDOMEventHandled(event, this.blur)
923
        ) {
924
            return;
×
925
        }
926

927
        const window = AngularEditor.getWindow(this.editor);
×
928

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

938
        const { relatedTarget } = event;
×
939
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
940

941
        // COMPAT: The event should be ignored if the focus is returning
942
        // to the editor from an embedded editable element (eg. an <input>
943
        // element inside a void node).
944
        if (relatedTarget === el) {
×
945
            return;
×
946
        }
947

948
        // COMPAT: The event should be ignored if the focus is moving from
949
        // the editor to inside a void node's spacer element.
950
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
951
            return;
×
952
        }
953

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

960
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
961
                return;
×
962
            }
963
        }
964

965
        IS_FOCUSED.delete(this.editor);
×
966
    }
967

968
    private onDOMClick(event: MouseEvent) {
969
        if (
×
970
            !this.readonly &&
×
971
            AngularEditor.hasTarget(this.editor, event.target) &&
972
            !this.isDOMEventHandled(event, this.click) &&
973
            isDOMNode(event.target)
974
        ) {
975
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
976
            const path = AngularEditor.findPath(this.editor, node);
×
977
            const start = Editor.start(this.editor, path);
×
978
            const end = Editor.end(this.editor, path);
×
979

980
            const startVoid = Editor.void(this.editor, { at: start });
×
981
            const endVoid = Editor.void(this.editor, { at: end });
×
982

983
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
984
                let blockPath = path;
×
985
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
986
                    const block = Editor.above(this.editor, {
×
987
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
988
                        at: path
989
                    });
990

991
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
992
                }
993

994
                const range = Editor.range(this.editor, blockPath);
×
995
                Transforms.select(this.editor, range);
×
996
                return;
×
997
            }
998

999
            if (
×
1000
                startVoid &&
×
1001
                endVoid &&
1002
                Path.equals(startVoid[1], endVoid[1]) &&
1003
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1004
            ) {
1005
                const range = Editor.range(this.editor, start);
×
1006
                Transforms.select(this.editor, range);
×
1007
            }
1008
        }
1009
    }
1010

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

1026
    private onDOMCompositionUpdate(event: CompositionEvent) {
1027
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1028
    }
1029

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

1044
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1045
            // so we need avoid repeat isnertText by isComposing === true,
1046
            this.isComposing = false;
×
1047
        }
1048
        this.render();
×
1049
    }
1050

1051
    private onDOMCopy(event: ClipboardEvent) {
1052
        const window = AngularEditor.getWindow(this.editor);
×
1053
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1054
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1055
            event.preventDefault();
×
1056
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1057
        }
1058
    }
1059

1060
    private onDOMCut(event: ClipboardEvent) {
1061
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1062
            event.preventDefault();
×
1063
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1064
            const { selection } = this.editor;
×
1065

1066
            if (selection) {
×
1067
                AngularEditor.deleteCutData(this.editor);
×
1068
            }
1069
        }
1070
    }
1071

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

1079
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1080
                event.preventDefault();
×
1081
            }
1082
        }
1083
    }
1084

1085
    private onDOMDragStart(event: DragEvent) {
1086
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1087
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1088
            const path = AngularEditor.findPath(this.editor, node);
×
1089
            const voidMatch =
1090
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1091

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

1099
            this.isDraggingInternally = true;
×
1100

1101
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1102
        }
1103
    }
1104

1105
    private onDOMDrop(event: DragEvent) {
1106
        const editor = this.editor;
×
1107
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1108
            event.preventDefault();
×
1109
            // Keep a reference to the dragged range before updating selection
1110
            const draggedRange = editor.selection;
×
1111

1112
            // Find the range where the drop happened
1113
            const range = AngularEditor.findEventRange(editor, event);
×
1114
            const data = event.dataTransfer;
×
1115

1116
            Transforms.select(editor, range);
×
1117

1118
            if (this.isDraggingInternally) {
×
1119
                if (draggedRange) {
×
1120
                    Transforms.delete(editor, {
×
1121
                        at: draggedRange
1122
                    });
1123
                }
1124

1125
                this.isDraggingInternally = false;
×
1126
            }
1127

1128
            AngularEditor.insertData(editor, data);
×
1129

1130
            // When dragging from another source into the editor, it's possible
1131
            // that the current editor does not have focus.
1132
            if (!AngularEditor.isFocused(editor)) {
×
1133
                AngularEditor.focus(editor);
×
1134
            }
1135
        }
1136
    }
1137

1138
    private onDOMDragEnd(event: DragEvent) {
1139
        if (
×
1140
            !this.readonly &&
×
1141
            this.isDraggingInternally &&
1142
            AngularEditor.hasTarget(this.editor, event.target) &&
1143
            !this.isDOMEventHandled(event, this.dragEnd)
1144
        ) {
1145
            this.isDraggingInternally = false;
×
1146
        }
1147
    }
1148

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

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

1168
            IS_FOCUSED.set(this.editor, true);
2✔
1169
        }
1170
    }
1171

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

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

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

1197
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1198
                        editor.redo();
×
1199
                    }
1200

1201
                    return;
×
1202
                }
1203

1204
                if (Hotkeys.isUndo(nativeEvent)) {
×
1205
                    event.preventDefault();
×
1206

1207
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1208
                        editor.undo();
×
1209
                    }
1210

1211
                    return;
×
1212
                }
1213

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

1224
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1225
                    event.preventDefault();
×
1226
                    Transforms.move(editor, { unit: 'line' });
×
1227
                    return;
×
1228
                }
1229

1230
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1231
                    event.preventDefault();
×
1232
                    Transforms.move(editor, {
×
1233
                        unit: 'line',
1234
                        edge: 'focus',
1235
                        reverse: true
1236
                    });
1237
                    return;
×
1238
                }
1239

1240
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1241
                    event.preventDefault();
×
1242
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1243
                    return;
×
1244
                }
1245

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

1254
                    if (selection && Range.isCollapsed(selection)) {
×
1255
                        Transforms.move(editor, { reverse: !isRTL });
×
1256
                    } else {
1257
                        Transforms.collapse(editor, { edge: 'start' });
×
1258
                    }
1259

1260
                    return;
×
1261
                }
1262

1263
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1264
                    event.preventDefault();
×
1265
                    if (selection && Range.isCollapsed(selection)) {
×
1266
                        Transforms.move(editor, { reverse: isRTL });
×
1267
                    } else {
1268
                        Transforms.collapse(editor, { edge: 'end' });
×
1269
                    }
1270

1271
                    return;
×
1272
                }
1273

1274
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1275
                    event.preventDefault();
×
1276

1277
                    if (selection && Range.isExpanded(selection)) {
×
1278
                        Transforms.collapse(editor, { edge: 'focus' });
×
1279
                    }
1280

1281
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1282
                    return;
×
1283
                }
1284

1285
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1286
                    event.preventDefault();
×
1287

1288
                    if (selection && Range.isExpanded(selection)) {
×
1289
                        Transforms.collapse(editor, { edge: 'focus' });
×
1290
                    }
1291

1292
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1293
                    return;
×
1294
                }
1295

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

1307
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1308
                        event.preventDefault();
×
1309
                        Editor.insertBreak(editor);
×
1310
                        return;
×
1311
                    }
1312

1313
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1314
                        event.preventDefault();
×
1315

1316
                        if (selection && Range.isExpanded(selection)) {
×
1317
                            Editor.deleteFragment(editor, {
×
1318
                                direction: 'backward'
1319
                            });
1320
                        } else {
1321
                            Editor.deleteBackward(editor);
×
1322
                        }
1323

1324
                        return;
×
1325
                    }
1326

1327
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1328
                        event.preventDefault();
×
1329

1330
                        if (selection && Range.isExpanded(selection)) {
×
1331
                            Editor.deleteFragment(editor, {
×
1332
                                direction: 'forward'
1333
                            });
1334
                        } else {
1335
                            Editor.deleteForward(editor);
×
1336
                        }
1337

1338
                        return;
×
1339
                    }
1340

1341
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1342
                        event.preventDefault();
×
1343

1344
                        if (selection && Range.isExpanded(selection)) {
×
1345
                            Editor.deleteFragment(editor, {
×
1346
                                direction: 'backward'
1347
                            });
1348
                        } else {
1349
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1350
                        }
1351

1352
                        return;
×
1353
                    }
1354

1355
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1356
                        event.preventDefault();
×
1357

1358
                        if (selection && Range.isExpanded(selection)) {
×
1359
                            Editor.deleteFragment(editor, {
×
1360
                                direction: 'forward'
1361
                            });
1362
                        } else {
1363
                            Editor.deleteForward(editor, { unit: 'line' });
×
1364
                        }
1365

1366
                        return;
×
1367
                    }
1368

1369
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1370
                        event.preventDefault();
×
1371

1372
                        if (selection && Range.isExpanded(selection)) {
×
1373
                            Editor.deleteFragment(editor, {
×
1374
                                direction: 'backward'
1375
                            });
1376
                        } else {
1377
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1378
                        }
1379

1380
                        return;
×
1381
                    }
1382

1383
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1384
                        event.preventDefault();
×
1385

1386
                        if (selection && Range.isExpanded(selection)) {
×
1387
                            Editor.deleteFragment(editor, {
×
1388
                                direction: 'forward'
1389
                            });
1390
                        } else {
1391
                            Editor.deleteForward(editor, { unit: 'word' });
×
1392
                        }
1393

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

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

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

1475
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1476
        if (!handler) {
3✔
1477
            return false;
3✔
1478
        }
1479
        handler(event);
×
1480
        return event.defaultPrevented;
×
1481
    }
1482
    //#endregion
1483

1484
    ngOnDestroy() {
1485
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1486
        this.manualListeners.forEach(manualListener => {
23✔
1487
            manualListener();
483✔
1488
        });
1489
        this.destroy$.complete();
23✔
1490
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1491
    }
1492
}
1493

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

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

1505
        if (isZeroDimensionRect) {
×
1506
            const leafRect = leafEl.getBoundingClientRect();
×
1507
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1508

1509
            if (leafHasDimensions) {
×
1510
                return;
×
1511
            }
1512
        }
1513

1514
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1515
        scrollIntoView(leafEl, {
×
1516
            scrollMode: 'if-needed'
1517
        });
1518
        delete leafEl.getBoundingClientRect;
×
1519
    }
1520
};
1521

1522
/**
1523
 * Check if the target is inside void and in the editor.
1524
 */
1525

1526
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1527
    let slateNode: Node | null = null;
1✔
1528
    try {
1✔
1529
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1530
    } catch (error) {}
1531
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1532
};
1533

1534
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1535
    return (
2✔
1536
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1537
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1538
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1539
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1540
    );
1541
};
1542

1543
/**
1544
 * remove default insert from composition
1545
 * @param text
1546
 */
1547
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1548
    const types = ['compositionend', 'insertFromComposition'];
×
1549
    if (!types.includes(event.type)) {
×
1550
        return;
×
1551
    }
1552
    const insertText = (event as CompositionEvent).data;
×
1553
    const window = AngularEditor.getWindow(editor);
×
1554
    const domSelection = window.getSelection();
×
1555
    // ensure text node insert composition input text
1556
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1557
        const textNode = domSelection.anchorNode;
×
1558
        textNode.splitText(textNode.length - insertText.length).remove();
×
1559
    }
1560
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc