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

worktile / slate-angular / 6c66ae92-3c28-4c33-8035-400a0af577fe

27 Jan 2026 02:54AM UTC coverage: 36.387% (+0.6%) from 35.787%
6c66ae92-3c28-4c33-8035-400a0af577fe

push

circleci

pubuzhixing8
fix(virtual-scroll): isFocus is always true when editor is readonly mode

414 of 1330 branches covered (31.13%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

1123 of 2894 relevant lines covered (38.8%)

23.33 hits per line

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

23.59
/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, Selection, Descendant } 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 { debounceTime, filter, Subject, tap } from 'rxjs';
42
import { IS_FIREFOX, IS_SAFARI, IS_CHROME, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID } from '../../utils/environment';
43
import Hotkeys from '../../utils/hotkeys';
44
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
45
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
46
import { SlateErrorCode } from '../../types/error';
47
import { NG_VALUE_ACCESSOR } from '@angular/forms';
48
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
49
import { ViewType } from '../../types/view';
50
import { HistoryEditor } from 'slate-history';
51
import {
52
    buildHeightsAndAccumulatedHeights,
53
    EDITOR_TO_BUSINESS_TOP,
54
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
55
    ELEMENT_KEY_TO_HEIGHTS,
56
    getBusinessTop,
57
    IS_ENABLED_VIRTUAL_SCROLL,
58
    isDebug,
59
    isDebugScrollTop,
60
    isDecoratorRangeListEqual,
61
    measureHeightByIndics
62
} from '../../utils';
63
import { SlatePlaceholder } from '../../types/feature';
64
import { restoreDom } from '../../utils/restore-dom';
65
import { ListRender, updatePreRenderingElementWidth } from '../../view/render/list-render';
66
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
67
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
68
import { isKeyHotkey } from 'is-hotkey';
69
import {
70
    calculateVirtualTopHeight,
71
    debugLog,
72
    EDITOR_TO_IS_FROM_SCROLL_TO,
73
    EDITOR_TO_ROOT_NODE_WIDTH,
74
    getCachedHeightByElement
75
} from '../../utils/virtual-scroll';
76

77
// not correctly clipboardData on beforeinput
78
const forceOnDOMPaste = IS_SAFARI;
1✔
79

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

105
    private destroy$ = new Subject();
23✔
106

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

112
    protected manualListeners: (() => void)[] = [];
23✔
113

114
    private initialized: boolean;
115

116
    private onTouchedCallback: () => void = () => {};
23✔
117

118
    private onChangeCallback: (_: any) => void = () => {};
23✔
119

120
    @Input() editor: AngularEditor;
121

122
    @Input() renderElement: (element: Element) => ViewType | null;
123

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

126
    @Input() renderText: (text: SlateText) => ViewType | null;
127

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

130
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
131

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

134
    @Input() isStrictDecorate: boolean = true;
23✔
135

136
    @Input() trackBy: (node: Element) => any = () => null;
206✔
137

138
    @Input() readonly = false;
23✔
139

140
    @Input() placeholder: string;
141

142
    @Input()
143
    set virtualScroll(config: SlateVirtualScrollConfig) {
144
        this.virtualScrollConfig = config;
×
145
        if (isDebugScrollTop) {
×
146
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
147
        }
148
        IS_ENABLED_VIRTUAL_SCROLL.set(this.editor, config.enabled);
×
149
        if (this.isEnabledVirtualScroll()) {
×
150
            this.tryUpdateVirtualViewport();
×
151
        }
152
    }
153

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

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

200
    listRender: ListRender;
201

202
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
203
        enabled: false,
204
        scrollTop: 0,
205
        viewportHeight: 0,
206
        viewportBoundingTop: 0,
207
        scrollContainer: null
208
    };
209

210
    private inViewportChildren: Element[] = [];
23✔
211
    private inViewportIndics: number[] = [];
23✔
212
    private keyHeightMap = new Map<string, number>();
23✔
213
    private tryUpdateVirtualViewportAnimId: number;
214
    private editorResizeObserver?: ResizeObserver;
215

216
    indicsOfNeedBeMeasured$ = new Subject<number[]>();
23✔
217

218
    virtualScrollInitialized = false;
23✔
219

220
    virtualTopHeightElement: HTMLElement;
221

222
    virtualBottomHeightElement: HTMLElement;
223

224
    virtualCenterOutlet: HTMLElement;
225

226
    constructor(
227
        public elementRef: ElementRef,
23✔
228
        public renderer2: Renderer2,
23✔
229
        public cdr: ChangeDetectorRef,
23✔
230
        private ngZone: NgZone,
23✔
231
        private injector: Injector
23✔
232
    ) {}
233

234
    ngOnInit() {
235
        this.editor.injector = this.injector;
23✔
236
        this.editor.children = [];
23✔
237
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
238
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
239
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
240
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
241
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
242
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
243
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
244
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
245
            this.ngZone.run(() => {
13✔
246
                this.onChange();
13✔
247
            });
248
        });
249
        this.ngZone.runOutsideAngular(() => {
23✔
250
            this.initialize();
23✔
251
        });
252
        this.initializeViewContext();
23✔
253
        this.initializeContext();
23✔
254

255
        // add browser class
256
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
257
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
258
        this.initializeVirtualScroll();
23✔
259
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
260
    }
261

262
    ngOnChanges(simpleChanges: SimpleChanges) {
263
        if (!this.initialized) {
30✔
264
            return;
23✔
265
        }
266
        const decorateChange = simpleChanges['decorate'];
7✔
267
        if (decorateChange) {
7✔
268
            this.forceRender();
2✔
269
        }
270
        const placeholderChange = simpleChanges['placeholder'];
7✔
271
        if (placeholderChange) {
7✔
272
            this.render();
1✔
273
        }
274
        const readonlyChange = simpleChanges['readonly'];
7✔
275
        if (readonlyChange) {
7!
276
            IS_READ_ONLY.set(this.editor, this.readonly);
×
277
            this.render();
×
278
            this.toSlateSelection();
×
279
        }
280
    }
281

282
    registerOnChange(fn: any) {
283
        this.onChangeCallback = fn;
23✔
284
    }
285
    registerOnTouched(fn: any) {
286
        this.onTouchedCallback = fn;
23✔
287
    }
288

289
    writeValue(value: Element[]) {
290
        if (value && value.length) {
49✔
291
            this.editor.children = value;
26✔
292
            this.initializeContext();
26✔
293
            if (this.isEnabledVirtualScroll()) {
26!
294
                const previousInViewportChildren = [...this.inViewportChildren];
×
295
                const visibleStates = this.editor.getAllVisibleStates();
×
296
                const virtualView = this.calculateVirtualViewport(visibleStates);
×
297
                this.applyVirtualView(virtualView);
×
298
                const childrenForRender = virtualView.inViewportChildren;
×
299
                if (isDebug) {
×
300
                    debugLog('log', 'writeValue calculate: ', virtualView.inViewportIndics, 'initialized: ', this.listRender.initialized);
×
301
                }
302
                if (!this.listRender.initialized) {
×
303
                    this.listRender.initialize(childrenForRender, this.editor, this.context, 0, virtualView.inViewportIndics);
×
304
                } else {
305
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
306
                        this.handlePreRendering(visibleStates);
×
307
                    this.listRender.update(
×
308
                        childrenWithPreRendering,
309
                        this.editor,
310
                        this.context,
311
                        preRenderingCount,
312
                        childrenWithPreRenderingIndics
313
                    );
314
                }
315
                const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
316
                if (remeasureIndics.length) {
×
317
                    this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
318
                }
319
            } else {
320
                if (!this.listRender.initialized) {
26✔
321
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
322
                } else {
323
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
324
                }
325
            }
326
            this.cdr.markForCheck();
26✔
327
        }
328
    }
329

330
    initialize() {
331
        this.initialized = true;
23✔
332
        const window = AngularEditor.getWindow(this.editor);
23✔
333
        this.addEventListener(
23✔
334
            'selectionchange',
335
            event => {
336
                this.toSlateSelection();
5✔
337
            },
338
            window.document
339
        );
340
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
341
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
342
        }
343
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
344
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
345
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
346
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
347
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
348
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
349
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
350
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
351
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
352
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
353
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
354
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
355
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
356
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
357
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
358
            this.addEventListener(event.name, () => {});
115✔
359
        });
360
    }
361

362
    private isEnabledVirtualScroll() {
363
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
89✔
364
    }
365

366
    initializeVirtualScroll() {
367
        if (this.virtualScrollInitialized) {
23!
368
            return;
×
369
        }
370
        if (this.isEnabledVirtualScroll()) {
23!
371
            this.virtualScrollInitialized = true;
×
372
            this.virtualTopHeightElement = document.createElement('div');
×
373
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
374
            this.virtualTopHeightElement.contentEditable = 'false';
×
375
            this.virtualBottomHeightElement = document.createElement('div');
×
376
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
377
            this.virtualBottomHeightElement.contentEditable = 'false';
×
378
            this.virtualCenterOutlet = document.createElement('div');
×
379
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
380
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
381
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
382
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
383
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
384
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.offsetWidth);
×
385
            this.editorResizeObserver = new ResizeObserver(entries => {
×
386
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
387
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
388
                    this.keyHeightMap.clear();
×
389
                    let target = this.virtualTopHeightElement;
×
390
                    if (this.inViewportChildren[0]) {
×
391
                        const firstElement = this.inViewportChildren[0];
×
392
                        const firstDomElement = AngularEditor.toDOMNode(this.editor, firstElement);
×
393
                        target = firstDomElement;
×
394
                    }
395
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, target.offsetWidth);
×
396
                    updatePreRenderingElementWidth(this.editor);
×
397
                    if (isDebug) {
×
398
                        debugLog(
×
399
                            'log',
400
                            'editorResizeObserverRectWidth: ',
401
                            editorResizeObserverRectWidth,
402
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
403
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
404
                        );
405
                    }
406
                }
407
            });
408
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
409

410
            let pendingRemeasureIndics: number[] = [];
×
411
            this.indicsOfNeedBeMeasured$
×
412
                .pipe(
413
                    tap((previousValue: number[]) => {
414
                        previousValue.forEach((index: number) => {
×
415
                            if (!pendingRemeasureIndics.includes(index)) {
×
416
                                pendingRemeasureIndics.push(index);
×
417
                            }
418
                        });
419
                    }),
420
                    debounceTime(500),
421
                    filter(() => pendingRemeasureIndics.length > 0)
×
422
                )
423
                .subscribe(() => {
424
                    const changed = measureHeightByIndics(this.editor, pendingRemeasureIndics, true);
×
425
                    if (changed) {
×
426
                        this.tryUpdateVirtualViewport();
×
427
                        if (isDebug) {
×
428
                            debugLog(
×
429
                                'log',
430
                                'exist pendingRemeasureIndics: ',
431
                                pendingRemeasureIndics,
432
                                'will try to update virtual viewport'
433
                            );
434
                        }
435
                    }
436
                    pendingRemeasureIndics = [];
×
437
                });
438
        }
439
    }
440

441
    getChangedIndics(previousValue: Descendant[]) {
442
        const remeasureIndics = [];
×
443
        this.inViewportChildren.forEach((child, index) => {
×
444
            if (previousValue.indexOf(child) === -1) {
×
445
                remeasureIndics.push(this.inViewportIndics[index]);
×
446
            }
447
        });
448
        return remeasureIndics;
×
449
    }
450

451
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
452
        if (!this.virtualScrollInitialized) {
×
453
            return;
×
454
        }
455
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
456
        if (bottomHeight !== undefined) {
×
457
            this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
458
        }
459
    }
460

461
    getActualVirtualTopHeight() {
462
        if (!this.virtualScrollInitialized) {
×
463
            return 0;
×
464
        }
465
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
466
    }
467

468
    handlePreRendering(visibleStates: boolean[]) {
469
        let preRenderingCount = 0;
×
470
        const childrenWithPreRendering = [...this.inViewportChildren];
×
471
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
472
        const firstIndex = this.inViewportIndics[0];
×
473
        for (let index = firstIndex - 1; index >= 0; index--) {
×
474
            const element = this.editor.children[index] as Element;
×
475
            if (visibleStates[index]) {
×
476
                childrenWithPreRendering.unshift(element);
×
477
                childrenWithPreRenderingIndics.unshift(index);
×
478
                preRenderingCount = 1;
×
479
                break;
×
480
            }
481
        }
482
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
483
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
484
            const element = this.editor.children[index] as Element;
×
485
            if (visibleStates[index]) {
×
486
                childrenWithPreRendering.push(element);
×
487
                childrenWithPreRenderingIndics.push(index);
×
488
                break;
×
489
            }
490
        }
491
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
492
    }
493

494
    private tryUpdateVirtualViewport() {
495
        if (isDebug) {
×
496
            debugLog('log', 'tryUpdateVirtualViewport');
×
497
        }
498
        const isFromScrollTo = EDITOR_TO_IS_FROM_SCROLL_TO.get(this.editor);
×
499
        if (this.inViewportIndics.length > 0 && !isFromScrollTo) {
×
500
            const topHeight = this.getActualVirtualTopHeight();
×
501
            const visibleStates = this.editor.getAllVisibleStates();
×
502
            const refreshVirtualTopHeight = calculateVirtualTopHeight(this.editor, this.inViewportIndics[0], visibleStates);
×
503
            if (topHeight !== refreshVirtualTopHeight) {
×
504
                if (isDebug) {
×
505
                    debugLog(
×
506
                        'log',
507
                        'update top height since dirty state(正数减去高度,负数代表增加高度): ',
508
                        topHeight - refreshVirtualTopHeight
509
                    );
510
                }
511
                this.setVirtualSpaceHeight(refreshVirtualTopHeight);
×
512
                return;
×
513
            }
514
        }
515
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
516
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
517
            if (isDebug) {
×
518
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
519
            }
520
            const visibleStates = this.editor.getAllVisibleStates();
×
521
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
522
            let diff = this.diffVirtualViewport(virtualView);
×
523
            if (diff.isDifferent && diff.needRemoveOnTop && !isFromScrollTo) {
×
524
                const remeasureIndics = diff.changedIndexesOfTop;
×
525
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
526
                if (changed) {
×
527
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
528
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
529
                }
530
            }
531
            if (diff.isDifferent) {
×
532
                this.applyVirtualView(virtualView);
×
533
                if (this.listRender.initialized) {
×
534
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
535
                        this.handlePreRendering(visibleStates);
×
536
                    this.listRender.update(
×
537
                        childrenWithPreRendering,
538
                        this.editor,
539
                        this.context,
540
                        preRenderingCount,
541
                        childrenWithPreRenderingIndics
542
                    );
543
                    if (diff.needAddOnTop && !isFromScrollTo) {
×
544
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
545
                        if (isDebug) {
×
546
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
547
                        }
548
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
549
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
550
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
551
                        if (changed) {
×
552
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
553
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
554
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
555
                            this.setVirtualSpaceHeight(newTopHeight);
×
556
                            if (isDebug) {
×
557
                                debugLog(
×
558
                                    'log',
559
                                    `update top height since will add element in top(正数减去高度,负数代表增加高度): ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
560
                                );
561
                            }
562
                        }
563
                    }
564
                    if (this.editor.selection) {
×
565
                        this.toNativeSelection(false);
×
566
                    }
567
                }
568
            }
569
            if (isDebug) {
×
570
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
571
            }
572
        });
573
    }
574

575
    private calculateVirtualViewport(visibleStates: boolean[]) {
576
        const children = (this.editor.children || []) as Element[];
×
577
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
578
            return {
×
579
                inViewportChildren: children,
580
                inViewportIndics: [],
581
                top: 0,
582
                bottom: 0,
583
                heights: []
584
            };
585
        }
586
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
587
        let viewportHeight = this.virtualScrollConfig.viewportHeight ?? 0;
×
588
        if (!viewportHeight) {
×
589
            return {
×
590
                inViewportChildren: [],
591
                inViewportIndics: [],
592
                top: 0,
593
                bottom: 0,
594
                heights: []
595
            };
596
        }
597
        const elementLength = children.length;
×
598
        if (!EDITOR_TO_BUSINESS_TOP.has(this.editor)) {
×
599
            EDITOR_TO_BUSINESS_TOP.set(this.editor, 0);
×
600
            setTimeout(() => {
×
601
                const virtualTopBoundingTop = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
602
                const businessTop =
603
                    Math.ceil(virtualTopBoundingTop) +
×
604
                    Math.ceil(this.virtualScrollConfig.scrollTop) -
605
                    Math.floor(this.virtualScrollConfig.viewportBoundingTop);
606
                EDITOR_TO_BUSINESS_TOP.set(this.editor, businessTop);
×
607
                if (isDebug) {
×
608
                    debugLog('log', 'businessTop', businessTop);
×
609
                    this.virtualTopHeightElement.setAttribute('data-business-top', businessTop.toString());
×
610
                }
611
            }, 100);
612
        }
613
        const businessTop = getBusinessTop(this.editor);
×
614
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
615
        const totalHeight = accumulatedHeights[elementLength] + businessTop;
×
616
        let startPosition = Math.max(scrollTop - businessTop, 0);
×
617
        let endPosition = startPosition + viewportHeight;
×
618
        if (scrollTop < businessTop) {
×
619
            endPosition = startPosition + viewportHeight - (businessTop - scrollTop);
×
620
        }
621
        let accumulatedOffset = 0;
×
622
        let inViewportStartIndex = -1;
×
623
        const visible: Element[] = [];
×
624
        const inViewportIndics: number[] = [];
×
625
        for (let i = 0; i < elementLength && accumulatedOffset < endPosition; i++) {
×
626
            const currentHeight = heights[i];
×
627
            const nextOffset = accumulatedOffset + currentHeight;
×
628
            const isVisible = visibleStates[i];
×
629
            if (!isVisible) {
×
630
                accumulatedOffset = nextOffset;
×
631
                continue;
×
632
            }
633
            // 可视区域有交集,加入渲染
634
            if (nextOffset > startPosition && accumulatedOffset < endPosition) {
×
635
                if (inViewportStartIndex === -1) inViewportStartIndex = i; // 第一个相交起始位置
×
636
                visible.push(children[i]);
×
637
                inViewportIndics.push(i);
×
638
            }
639
            accumulatedOffset = nextOffset;
×
640
        }
641

642
        const inViewportEndIndex =
643
            inViewportStartIndex === -1 ? elementLength - 1 : (inViewportIndics[inViewportIndics.length - 1] ?? inViewportStartIndex);
×
644
        const top = inViewportStartIndex === -1 ? 0 : accumulatedHeights[inViewportStartIndex];
×
645
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
646
        return {
×
647
            inViewportChildren: visible.length ? visible : children,
×
648
            inViewportIndics,
649
            top,
650
            bottom,
651
            heights,
652
            accumulatedHeights
653
        };
654
    }
655

656
    private applyVirtualView(virtualView: VirtualViewResult) {
657
        this.inViewportChildren = virtualView.inViewportChildren;
×
658
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
659
        this.inViewportIndics = virtualView.inViewportIndics;
×
660
    }
661

662
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
663
        if (!this.inViewportChildren.length) {
×
664
            if (isDebug) {
×
665
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
666
            }
667
            return {
×
668
                isDifferent: true,
669
                changedIndexesOfTop: [],
670
                changedIndexesOfBottom: []
671
            };
672
        }
673
        const oldIndexesInViewport = [...this.inViewportIndics];
×
674
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
675
        const firstNewIndex = newIndexesInViewport[0];
×
676
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
677
        const firstOldIndex = oldIndexesInViewport[0];
×
678
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
679
        const isSameViewport =
680
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
681
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
682
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
683
            return {
×
684
                isDifferent: !isSameViewport,
685
                changedIndexesOfTop: [],
686
                changedIndexesOfBottom: []
687
            };
688
        }
689
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
690
            const changedIndexesOfTop = [];
×
691
            const changedIndexesOfBottom = [];
×
692
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
693
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
694
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
695
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
696
            if (needRemoveOnTop || needAddOnBottom) {
×
697
                // 向下
698
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
699
                    const element = oldIndexesInViewport[index];
×
700
                    if (!newIndexesInViewport.includes(element)) {
×
701
                        changedIndexesOfTop.push(element);
×
702
                    } else {
703
                        break;
×
704
                    }
705
                }
706
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
707
                    const element = newIndexesInViewport[index];
×
708
                    if (!oldIndexesInViewport.includes(element)) {
×
709
                        changedIndexesOfBottom.push(element);
×
710
                    } else {
711
                        break;
×
712
                    }
713
                }
714
            } else if (needAddOnTop || needRemoveOnBottom) {
×
715
                // 向上
716
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
717
                    const element = newIndexesInViewport[index];
×
718
                    if (!oldIndexesInViewport.includes(element)) {
×
719
                        changedIndexesOfTop.push(element);
×
720
                    } else {
721
                        break;
×
722
                    }
723
                }
724
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
725
                    const element = oldIndexesInViewport[index];
×
726
                    if (!newIndexesInViewport.includes(element)) {
×
727
                        changedIndexesOfBottom.push(element);
×
728
                    } else {
729
                        break;
×
730
                    }
731
                }
732
            }
733
            if (isDebug) {
×
734
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
735
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
736
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
737
                // this.editor.children[index] will be undefined when it is removed
738
                debugLog(
×
739
                    'log',
740
                    'changedIndexesOfTop:',
741
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
742
                    changedIndexesOfTop,
743
                    changedIndexesOfTop.map(
744
                        index =>
745
                            (this.editor.children[index] &&
×
746
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
747
                            0
748
                    )
749
                );
750
                debugLog(
×
751
                    'log',
752
                    'changedIndexesOfBottom:',
753
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
754
                    changedIndexesOfBottom,
755
                    changedIndexesOfBottom.map(
756
                        index =>
757
                            (this.editor.children[index] &&
×
758
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
759
                            0
760
                    )
761
                );
762
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
763
                const needBottom = virtualView.heights
×
764
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
765
                    .reduce((acc, height) => acc + height, 0);
×
766
                debugLog(
×
767
                    'log',
768
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
769
                    'newTopHeight:',
770
                    needTop,
771
                    'prevTopHeight:',
772
                    parseFloat(this.virtualTopHeightElement.style.height)
773
                );
774
                debugLog(
×
775
                    'log',
776
                    'newBottomHeight:',
777
                    needBottom,
778
                    'prevBottomHeight:',
779
                    parseFloat(this.virtualBottomHeightElement.style.height)
780
                );
781
                debugLog('warn', '=========== Dividing line ===========');
×
782
            }
783
            return {
×
784
                isDifferent: true,
785
                needRemoveOnTop,
786
                needAddOnTop,
787
                needRemoveOnBottom,
788
                needAddOnBottom,
789
                changedIndexesOfTop,
790
                changedIndexesOfBottom
791
            };
792
        }
793
        return {
×
794
            isDifferent: false,
795
            changedIndexesOfTop: [],
796
            changedIndexesOfBottom: []
797
        };
798
    }
799

800
    //#region event proxy
801
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
802
        this.manualListeners.push(
483✔
803
            this.renderer2.listen(target, eventName, (event: Event) => {
804
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
12✔
805
                if (beforeInputEvent) {
12!
806
                    this.onFallbackBeforeInput(beforeInputEvent);
×
807
                }
808
                listener(event);
12✔
809
            })
810
        );
811
    }
812

813
    calculateVirtualScrollSelection(selection: Selection) {
814
        if (selection) {
×
815
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
816
            const indics = this.inViewportIndics;
×
817
            if (indics.length > 0) {
×
818
                const currentVisibleRange: Range = {
×
819
                    anchor: Editor.start(this.editor, [indics[0]]),
820
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
821
                };
822
                const [start, end] = Range.edges(selection);
×
823
                let forwardSelection = { anchor: start, focus: end };
×
824
                if (!isBlockCardCursor) {
×
825
                    forwardSelection = { anchor: start, focus: end };
×
826
                } else {
827
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
828
                }
829
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
830
                if (intersectedSelection && isBlockCardCursor) {
×
831
                    return selection;
×
832
                }
833
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
834
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
835
                    if (isDebug) {
×
836
                        debugLog(
×
837
                            'log',
838
                            `selection is not in visible range, selection: ${JSON.stringify(
839
                                selection
840
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
841
                        );
842
                    }
843
                    return intersectedSelection;
×
844
                }
845
                return selection;
×
846
            }
847
        }
848
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
849
        return selection;
×
850
    }
851

852
    private isSelectionInvisible(selection: Selection) {
853
        const anchorIndex = selection.anchor.path[0];
6✔
854
        const focusIndex = selection.focus.path[0];
6✔
855
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
856
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
857
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
858
    }
859

860
    toNativeSelection(autoScroll = true) {
15✔
861
        try {
15✔
862
            let { selection } = this.editor;
15✔
863

864
            if (this.isEnabledVirtualScroll()) {
15!
865
                selection = this.calculateVirtualScrollSelection(selection);
×
866
            }
867

868
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
869
            const { activeElement } = root;
15✔
870
            const domSelection = (root as Document).getSelection();
15✔
871

872
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
UNCOV
873
                return;
×
874
            }
875

876
            const hasDomSelection = domSelection.type !== 'None';
15✔
877

878
            // If the DOM selection is properly unset, we're done.
879
            if (!selection && !hasDomSelection) {
15✔
880
                return;
7✔
881
            }
882

883
            // If the DOM selection is already correct, we're done.
884
            // verify that the dom selection is in the editor
885
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
8✔
886
            let hasDomSelectionInEditor = false;
8✔
887
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
8✔
888
                hasDomSelectionInEditor = true;
2✔
889
            }
890

891
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
892
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
8✔
893
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
894
                    exactMatch: false,
895
                    suppressThrow: true
896
                });
897
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
898
                    return;
×
899
                }
900
            }
901

902
            // prevent updating native selection when active element is void element
903
            if (isTargetInsideVoid(this.editor, activeElement)) {
8!
904
                return;
×
905
            }
906

907
            // when <Editable/> is being controlled through external value
908
            // then its children might just change - DOM responds to it on its own
909
            // but Slate's value is not being updated through any operation
910
            // and thus it doesn't transform selection on its own
911
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
8!
912
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
913
                return;
×
914
            }
915

916
            // Otherwise the DOM selection is out of sync, so update it.
917
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
8✔
918
            this.isUpdatingSelection = true;
8✔
919

920
            const newDomRange = selection && AngularEditor.toDOMRange(this.editor, selection);
8✔
921

922
            if (newDomRange) {
8✔
923
                // COMPAT: Since the DOM range has no concept of backwards/forwards
924
                // we need to check and do the right thing here.
925
                if (Range.isBackward(selection)) {
6!
926
                    // eslint-disable-next-line max-len
927
                    domSelection.setBaseAndExtent(
×
928
                        newDomRange.endContainer,
929
                        newDomRange.endOffset,
930
                        newDomRange.startContainer,
931
                        newDomRange.startOffset
932
                    );
933
                } else {
934
                    // eslint-disable-next-line max-len
935
                    domSelection.setBaseAndExtent(
6✔
936
                        newDomRange.startContainer,
937
                        newDomRange.startOffset,
938
                        newDomRange.endContainer,
939
                        newDomRange.endOffset
940
                    );
941
                }
942
            } else {
943
                domSelection.removeAllRanges();
2✔
944
            }
945

946
            setTimeout(() => {
8✔
947
                if (
8!
948
                    this.isEnabledVirtualScroll() &&
8!
949
                    !selection &&
950
                    this.editor.selection &&
951
                    autoScroll &&
952
                    this.virtualScrollConfig.scrollContainer
953
                ) {
954
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
955
                    this.isUpdatingSelection = false;
×
956
                    return;
×
957
                } else {
958
                    // handle scrolling in setTimeout because of
959
                    // dom should not have updated immediately after listRender's updating
960
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
8✔
961
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
962
                    // to focus the contenteditable element too. (2016/11/16)
963
                    if (newDomRange && IS_FIREFOX) {
8!
964
                        el.focus();
×
965
                    }
966
                }
967
                this.isUpdatingSelection = false;
8✔
968
            });
969
        } catch (error) {
970
            this.editor.onError({
×
971
                code: SlateErrorCode.ToNativeSelectionError,
972
                nativeError: error
973
            });
974
            this.isUpdatingSelection = false;
×
975
        }
976
    }
977

978
    onChange() {
979
        this.forceRender();
13✔
980
        this.onChangeCallback(this.editor.children);
13✔
981
    }
982

983
    ngAfterViewChecked() {}
984

985
    ngDoCheck() {}
986

987
    forceRender() {
988
        this.updateContext();
15✔
989
        if (this.isEnabledVirtualScroll()) {
15!
990
            this.updateListRenderAndRemeasureHeights();
×
991
        } else {
992
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
993
        }
994
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
995
        // when the DOMElement where the selection is located is removed
996
        // the compositionupdate and compositionend events will no longer be fired
997
        // so isComposing needs to be corrected
998
        // need exec after this.cdr.detectChanges() to render HTML
999
        // need exec before this.toNativeSelection() to correct native selection
1000
        if (this.isComposing) {
15!
1001
            // Composition input text be not rendered when user composition input with selection is expanded
1002
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
1003
            // this time condition is true and isComposing is assigned false
1004
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
1005
            setTimeout(() => {
×
1006
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
1007
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
1008
                let textContent = '';
×
1009
                // skip decorate text
1010
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
1011
                    let text = stringDOMNode.textContent;
×
1012
                    const zeroChar = '\uFEFF';
×
1013
                    // remove zero with char
1014
                    if (text.startsWith(zeroChar)) {
×
1015
                        text = text.slice(1);
×
1016
                    }
1017
                    if (text.endsWith(zeroChar)) {
×
1018
                        text = text.slice(0, text.length - 1);
×
1019
                    }
1020
                    textContent += text;
×
1021
                });
1022
                if (Node.string(textNode).endsWith(textContent)) {
×
1023
                    this.isComposing = false;
×
1024
                }
1025
            }, 0);
1026
        }
1027
        if (this.editor.selection && this.isSelectionInvisible(this.editor.selection)) {
15!
1028
            Transforms.deselect(this.editor);
×
1029
            return;
×
1030
        } else {
1031
            this.toNativeSelection();
15✔
1032
        }
1033
    }
1034

1035
    render() {
1036
        const changed = this.updateContext();
2✔
1037
        if (changed) {
2✔
1038
            if (this.isEnabledVirtualScroll()) {
2!
1039
                this.updateListRenderAndRemeasureHeights();
×
1040
            } else {
1041
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
1042
            }
1043
        }
1044
    }
1045

1046
    updateListRenderAndRemeasureHeights() {
1047
        const operations = this.editor.operations;
×
1048
        const firstIndex = this.inViewportIndics[0];
×
1049
        const operationsOfFirstElementMerged = operations.filter(
×
1050
            op => op.type === 'merge_node' && op.path.length === 1 && firstIndex === op.path[0] - 1
×
1051
        );
1052
        const operationsOfFirstElementSplitted = operations.filter(
×
1053
            op => op.type === 'split_node' && op.path.length === 1 && firstIndex === op.path[0]
×
1054
        );
1055
        const mutationOfFirstElementHeight = operationsOfFirstElementSplitted.length > 0 || operationsOfFirstElementMerged.length > 0;
×
1056
        const visibleStates = this.editor.getAllVisibleStates();
×
1057
        const previousInViewportChildren = [...this.inViewportChildren];
×
1058
        // the first element height will reset to default height when split or merge
1059
        // if the most top content of the first element is not in viewport, the change of height will cause the viewport to scroll
1060
        // to keep viewport stable, we need to use the current inViewportIndics temporarily
1061
        if (mutationOfFirstElementHeight) {
×
1062
            const newInViewportIndics = [];
×
1063
            const newInViewportChildren = [];
×
1064
            this.inViewportIndics.forEach(index => {
×
1065
                const element = this.editor.children[index] as Element;
×
1066
                const isVisible = visibleStates[index];
×
1067
                if (isVisible) {
×
1068
                    newInViewportIndics.push(index);
×
1069
                    newInViewportChildren.push(element);
×
1070
                }
1071
            });
1072
            this.inViewportIndics = newInViewportIndics;
×
1073
            this.inViewportChildren = newInViewportChildren;
×
1074
            if (isDebug) {
×
1075
                debugLog(
×
1076
                    'log',
1077
                    'updateListRenderAndRemeasureHeights',
1078
                    'mutationOfFirstElementHeight',
1079
                    'newInViewportIndics',
1080
                    newInViewportIndics
1081
                );
1082
            }
1083
        } else {
1084
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
1085
            let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
1086
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
1087
                const remeasureIndics = diff.changedIndexesOfTop;
×
1088
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
1089
                if (changed) {
×
1090
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
1091
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
1092
                }
1093
            }
1094
            this.applyVirtualView(virtualView);
×
1095
        }
1096
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering(visibleStates);
×
1097
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
1098
        const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
1099
        if (remeasureIndics.length) {
×
1100
            this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
1101
        }
1102
    }
1103

1104
    updateContext() {
1105
        const decorations = this.generateDecorations();
17✔
1106
        if (
17✔
1107
            this.context.selection !== this.editor.selection ||
46✔
1108
            this.context.decorate !== this.decorate ||
1109
            this.context.readonly !== this.readonly ||
1110
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
1111
        ) {
1112
            this.context = {
10✔
1113
                parent: this.editor,
1114
                selection: this.editor.selection,
1115
                decorations: decorations,
1116
                decorate: this.decorate,
1117
                readonly: this.readonly
1118
            };
1119
            return true;
10✔
1120
        }
1121
        return false;
7✔
1122
    }
1123

1124
    initializeContext() {
1125
        this.context = {
49✔
1126
            parent: this.editor,
1127
            selection: this.editor.selection,
1128
            decorations: this.generateDecorations(),
1129
            decorate: this.decorate,
1130
            readonly: this.readonly
1131
        };
1132
    }
1133

1134
    initializeViewContext() {
1135
        this.viewContext = {
23✔
1136
            editor: this.editor,
1137
            renderElement: this.renderElement,
1138
            renderLeaf: this.renderLeaf,
1139
            renderText: this.renderText,
1140
            trackBy: this.trackBy,
1141
            isStrictDecorate: this.isStrictDecorate
1142
        };
1143
    }
1144

1145
    composePlaceholderDecorate(editor: Editor) {
1146
        if (this.placeholderDecorate) {
64!
1147
            return this.placeholderDecorate(editor) || [];
×
1148
        }
1149

1150
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
1151
            const start = Editor.start(editor, []);
3✔
1152
            return [
3✔
1153
                {
1154
                    placeholder: this.placeholder,
1155
                    anchor: start,
1156
                    focus: start
1157
                }
1158
            ];
1159
        } else {
1160
            return [];
61✔
1161
        }
1162
    }
1163

1164
    generateDecorations() {
1165
        const decorations = this.decorate([this.editor, []]);
66✔
1166
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1167
        decorations.push(...placeholderDecorations);
66✔
1168
        return decorations;
66✔
1169
    }
1170

1171
    private toSlateSelection() {
1172
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
5✔
1173
            try {
4✔
1174
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
4✔
1175
                const { activeElement } = root;
4✔
1176
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
4✔
1177
                const domSelection = (root as Document).getSelection();
4✔
1178

1179
                if (activeElement === el) {
4✔
1180
                    this.latestElement = activeElement;
3✔
1181
                    IS_FOCUSED.set(this.editor, true);
3✔
1182
                } else {
1183
                    IS_FOCUSED.delete(this.editor);
1✔
1184
                }
1185

1186
                if (!domSelection) {
4!
1187
                    return Transforms.deselect(this.editor);
×
1188
                }
1189

1190
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
4✔
1191
                const hasDomSelectionInEditor =
1192
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
4✔
1193
                if (!hasDomSelectionInEditor) {
4✔
1194
                    Transforms.deselect(this.editor);
1✔
1195
                    return;
1✔
1196
                }
1197

1198
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1199
                // for example, double-click the last cell of the table to select a non-editable DOM
1200
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
3✔
1201
                if (range) {
3✔
1202
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
3!
1203
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1204
                            // force adjust DOMSelection
1205
                            this.toNativeSelection(false);
×
1206
                        }
1207
                    } else {
1208
                        Transforms.select(this.editor, range);
3✔
1209
                    }
1210
                }
1211
            } catch (error) {
1212
                this.editor.onError({
×
1213
                    code: SlateErrorCode.ToSlateSelectionError,
1214
                    nativeError: error
1215
                });
1216
            }
1217
        }
1218
    }
1219

1220
    private onDOMBeforeInput(
1221
        event: Event & {
1222
            inputType: string;
1223
            isComposing: boolean;
1224
            data: string | null;
1225
            dataTransfer: DataTransfer | null;
1226
            getTargetRanges(): DOMStaticRange[];
1227
        }
1228
    ) {
1229
        const editor = this.editor;
×
1230
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1231
        const { activeElement } = root;
×
1232
        const { selection } = editor;
×
1233
        const { inputType: type } = event;
×
1234
        const data = event.dataTransfer || event.data || undefined;
×
1235
        if (IS_ANDROID) {
×
1236
            let targetRange: Range | null = null;
×
1237
            let [nativeTargetRange] = event.getTargetRanges();
×
1238
            if (nativeTargetRange) {
×
1239
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1240
            }
1241
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1242
            // have to manually get the selection here to ensure it's up-to-date.
1243
            const window = AngularEditor.getWindow(editor);
×
1244
            const domSelection = window.getSelection();
×
1245
            if (!targetRange && domSelection) {
×
1246
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1247
            }
1248
            targetRange = targetRange ?? editor.selection;
×
1249
            if (type === 'insertCompositionText') {
×
1250
                if (data && data.toString().includes('\n')) {
×
1251
                    restoreDom(editor, () => {
×
1252
                        Editor.insertBreak(editor);
×
1253
                    });
1254
                } else {
1255
                    if (targetRange) {
×
1256
                        if (data) {
×
1257
                            restoreDom(editor, () => {
×
1258
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1259
                            });
1260
                        } else {
1261
                            restoreDom(editor, () => {
×
1262
                                Transforms.delete(editor, { at: targetRange });
×
1263
                            });
1264
                        }
1265
                    }
1266
                }
1267
                return;
×
1268
            }
1269
            if (type === 'deleteContentBackward') {
×
1270
                // gboard can not prevent default action, so must use restoreDom,
1271
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1272
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1273
                if (!Range.isCollapsed(targetRange)) {
×
1274
                    restoreDom(editor, () => {
×
1275
                        Transforms.delete(editor, { at: targetRange });
×
1276
                    });
1277
                    return;
×
1278
                }
1279
            }
1280
            if (type === 'insertText') {
×
1281
                restoreDom(editor, () => {
×
1282
                    if (typeof data === 'string') {
×
1283
                        Editor.insertText(editor, data);
×
1284
                    }
1285
                });
1286
                return;
×
1287
            }
1288
        }
1289
        if (
×
1290
            !this.readonly &&
×
1291
            AngularEditor.hasEditableTarget(editor, event.target) &&
1292
            !isTargetInsideVoid(editor, activeElement) &&
1293
            !this.isDOMEventHandled(event, this.beforeInput)
1294
        ) {
1295
            try {
×
1296
                event.preventDefault();
×
1297

1298
                // COMPAT: If the selection is expanded, even if the command seems like
1299
                // a delete forward/backward command it should delete the selection.
1300
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1301
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1302
                    Editor.deleteFragment(editor, { direction });
×
1303
                    return;
×
1304
                }
1305

1306
                switch (type) {
×
1307
                    case 'deleteByComposition':
1308
                    case 'deleteByCut':
1309
                    case 'deleteByDrag': {
1310
                        Editor.deleteFragment(editor);
×
1311
                        break;
×
1312
                    }
1313

1314
                    case 'deleteContent':
1315
                    case 'deleteContentForward': {
1316
                        Editor.deleteForward(editor);
×
1317
                        break;
×
1318
                    }
1319

1320
                    case 'deleteContentBackward': {
1321
                        Editor.deleteBackward(editor);
×
1322
                        break;
×
1323
                    }
1324

1325
                    case 'deleteEntireSoftLine': {
1326
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1327
                        Editor.deleteForward(editor, { unit: 'line' });
×
1328
                        break;
×
1329
                    }
1330

1331
                    case 'deleteHardLineBackward': {
1332
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1333
                        break;
×
1334
                    }
1335

1336
                    case 'deleteSoftLineBackward': {
1337
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1338
                        break;
×
1339
                    }
1340

1341
                    case 'deleteHardLineForward': {
1342
                        Editor.deleteForward(editor, { unit: 'block' });
×
1343
                        break;
×
1344
                    }
1345

1346
                    case 'deleteSoftLineForward': {
1347
                        Editor.deleteForward(editor, { unit: 'line' });
×
1348
                        break;
×
1349
                    }
1350

1351
                    case 'deleteWordBackward': {
1352
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1353
                        break;
×
1354
                    }
1355

1356
                    case 'deleteWordForward': {
1357
                        Editor.deleteForward(editor, { unit: 'word' });
×
1358
                        break;
×
1359
                    }
1360

1361
                    case 'insertLineBreak':
1362
                    case 'insertParagraph': {
1363
                        Editor.insertBreak(editor);
×
1364
                        break;
×
1365
                    }
1366

1367
                    case 'insertFromComposition': {
1368
                        // COMPAT: in safari, `compositionend` event is dispatched after
1369
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1370
                        // https://www.w3.org/TR/input-events-2/
1371
                        // so the following code is the right logic
1372
                        // because DOM selection in sync will be exec before `compositionend` event
1373
                        // isComposing is true will prevent DOM selection being update correctly.
1374
                        this.isComposing = false;
×
1375
                        preventInsertFromComposition(event, this.editor);
×
1376
                    }
1377
                    case 'insertFromDrop':
1378
                    case 'insertFromPaste':
1379
                    case 'insertFromYank':
1380
                    case 'insertReplacementText':
1381
                    case 'insertText': {
1382
                        // use a weak comparison instead of 'instanceof' to allow
1383
                        // programmatic access of paste events coming from external windows
1384
                        // like cypress where cy.window does not work realibly
1385
                        if (data?.constructor.name === 'DataTransfer') {
×
1386
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1387
                        } else if (typeof data === 'string') {
×
1388
                            Editor.insertText(editor, data);
×
1389
                        }
1390
                        break;
×
1391
                    }
1392
                }
1393
            } catch (error) {
1394
                this.editor.onError({
×
1395
                    code: SlateErrorCode.OnDOMBeforeInputError,
1396
                    nativeError: error
1397
                });
1398
            }
1399
        }
1400
    }
1401

1402
    private onDOMBlur(event: FocusEvent) {
1403
        if (
×
1404
            this.readonly ||
×
1405
            this.isUpdatingSelection ||
1406
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1407
            this.isDOMEventHandled(event, this.blur)
1408
        ) {
1409
            return;
×
1410
        }
1411

1412
        const window = AngularEditor.getWindow(this.editor);
×
1413

1414
        // COMPAT: If the current `activeElement` is still the previous
1415
        // one, this is due to the window being blurred when the tab
1416
        // itself becomes unfocused, so we want to abort early to allow to
1417
        // editor to stay focused when the tab becomes focused again.
1418
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1419
        if (this.latestElement === root.activeElement) {
×
1420
            return;
×
1421
        }
1422

1423
        const { relatedTarget } = event;
×
1424
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1425

1426
        // COMPAT: The event should be ignored if the focus is returning
1427
        // to the editor from an embedded editable element (eg. an <input>
1428
        // element inside a void node).
1429
        if (relatedTarget === el) {
×
1430
            return;
×
1431
        }
1432

1433
        // COMPAT: The event should be ignored if the focus is moving from
1434
        // the editor to inside a void node's spacer element.
1435
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1436
            return;
×
1437
        }
1438

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

1445
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1446
                return;
×
1447
            }
1448
        }
1449

1450
        IS_FOCUSED.delete(this.editor);
×
1451
    }
1452

1453
    private onDOMClick(event: MouseEvent) {
1454
        if (
×
1455
            !this.readonly &&
×
1456
            AngularEditor.hasTarget(this.editor, event.target) &&
1457
            !this.isDOMEventHandled(event, this.click) &&
1458
            isDOMNode(event.target)
1459
        ) {
1460
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1461
            const path = AngularEditor.findPath(this.editor, node);
×
1462
            const start = Editor.start(this.editor, path);
×
1463
            const end = Editor.end(this.editor, path);
×
1464

1465
            const startVoid = Editor.void(this.editor, { at: start });
×
1466
            const endVoid = Editor.void(this.editor, { at: end });
×
1467

1468
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1469
                let blockPath = path;
×
1470
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1471
                    const block = Editor.above(this.editor, {
×
1472
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1473
                        at: path
1474
                    });
1475

1476
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1477
                }
1478

1479
                const range = Editor.range(this.editor, blockPath);
×
1480
                Transforms.select(this.editor, range);
×
1481
                return;
×
1482
            }
1483

1484
            if (
×
1485
                startVoid &&
×
1486
                endVoid &&
1487
                Path.equals(startVoid[1], endVoid[1]) &&
1488
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1489
            ) {
1490
                const range = Editor.range(this.editor, start);
×
1491
                Transforms.select(this.editor, range);
×
1492
            }
1493
        }
1494
    }
1495

1496
    private onDOMCompositionStart(event: CompositionEvent) {
1497
        const { selection } = this.editor;
1✔
1498
        if (selection) {
1!
1499
            // solve the problem of cross node Chinese input
1500
            if (Range.isExpanded(selection)) {
×
1501
                Editor.deleteFragment(this.editor);
×
1502
                this.forceRender();
×
1503
            }
1504
        }
1505
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1506
            this.isComposing = true;
1✔
1507
        }
1508
        this.render();
1✔
1509
    }
1510

1511
    private onDOMCompositionUpdate(event: CompositionEvent) {
1512
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1513
    }
1514

1515
    private onDOMCompositionEnd(event: CompositionEvent) {
1516
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1517
            Transforms.delete(this.editor);
×
1518
        }
1519
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1520
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1521
            // aren't correct and never fire the "insertFromComposition"
1522
            // type that we need. So instead, insert whenever a composition
1523
            // ends since it will already have been committed to the DOM.
1524
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1525
                preventInsertFromComposition(event, this.editor);
×
1526
                Editor.insertText(this.editor, event.data);
×
1527
            }
1528

1529
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1530
            // so we need avoid repeat isnertText by isComposing === true,
1531
            this.isComposing = false;
×
1532
        }
1533
        this.render();
×
1534
    }
1535

1536
    private onDOMCopy(event: ClipboardEvent) {
1537
        const window = AngularEditor.getWindow(this.editor);
×
1538
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1539
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1540
            event.preventDefault();
×
1541
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1542
        }
1543
    }
1544

1545
    private onDOMCut(event: ClipboardEvent) {
1546
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1547
            event.preventDefault();
×
1548
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1549
            const { selection } = this.editor;
×
1550

1551
            if (selection) {
×
1552
                AngularEditor.deleteCutData(this.editor);
×
1553
            }
1554
        }
1555
    }
1556

1557
    private onDOMDragOver(event: DragEvent) {
1558
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1559
            // Only when the target is void, call `preventDefault` to signal
1560
            // that drops are allowed. Editable content is droppable by
1561
            // default, and calling `preventDefault` hides the cursor.
1562
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1563

1564
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1565
                event.preventDefault();
×
1566
            }
1567
        }
1568
    }
1569

1570
    private onDOMDragStart(event: DragEvent) {
1571
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1572
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1573
            const path = AngularEditor.findPath(this.editor, node);
×
1574
            const voidMatch =
1575
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1576

1577
            // If starting a drag on a void node, make sure it is selected
1578
            // so that it shows up in the selection's fragment.
1579
            if (voidMatch) {
×
1580
                const range = Editor.range(this.editor, path);
×
1581
                Transforms.select(this.editor, range);
×
1582
            }
1583

1584
            this.isDraggingInternally = true;
×
1585

1586
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1587
        }
1588
    }
1589

1590
    private onDOMDrop(event: DragEvent) {
1591
        const editor = this.editor;
×
1592
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1593
            event.preventDefault();
×
1594
            // Keep a reference to the dragged range before updating selection
1595
            const draggedRange = editor.selection;
×
1596

1597
            // Find the range where the drop happened
1598
            const range = AngularEditor.findEventRange(editor, event);
×
1599
            const data = event.dataTransfer;
×
1600

1601
            Transforms.select(editor, range);
×
1602

1603
            if (this.isDraggingInternally) {
×
1604
                if (draggedRange) {
×
1605
                    Transforms.delete(editor, {
×
1606
                        at: draggedRange
1607
                    });
1608
                }
1609

1610
                this.isDraggingInternally = false;
×
1611
            }
1612

1613
            AngularEditor.insertData(editor, data);
×
1614

1615
            // When dragging from another source into the editor, it's possible
1616
            // that the current editor does not have focus.
1617
            if (!AngularEditor.isFocused(editor)) {
×
1618
                AngularEditor.focus(editor);
×
1619
            }
1620
        }
1621
    }
1622

1623
    private onDOMDragEnd(event: DragEvent) {
1624
        if (
×
1625
            !this.readonly &&
×
1626
            this.isDraggingInternally &&
1627
            AngularEditor.hasTarget(this.editor, event.target) &&
1628
            !this.isDOMEventHandled(event, this.dragEnd)
1629
        ) {
1630
            this.isDraggingInternally = false;
×
1631
        }
1632
    }
1633

1634
    private onDOMFocus(event: Event) {
1635
        if (
6✔
1636
            !this.readonly &&
16✔
1637
            !this.isUpdatingSelection &&
1638
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1639
            !this.isDOMEventHandled(event, this.focus)
1640
        ) {
1641
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1642
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1643
            this.latestElement = root.activeElement;
2✔
1644

1645
            // COMPAT: If the editor has nested editable elements, the focus
1646
            // can go to them. In Firefox, this must be prevented because it
1647
            // results in issues with keyboard navigation. (2017/03/30)
1648
            if (IS_FIREFOX && event.target !== el) {
2!
1649
                el.focus();
×
1650
                return;
×
1651
            }
1652

1653
            IS_FOCUSED.set(this.editor, true);
2✔
1654
        }
1655
    }
1656

1657
    private onDOMKeydown(event: KeyboardEvent) {
1658
        const editor = this.editor;
×
1659
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1660
        const { activeElement } = root;
×
1661
        if (
×
1662
            !this.readonly &&
×
1663
            AngularEditor.hasEditableTarget(editor, event.target) &&
1664
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1665
            !this.isComposing &&
1666
            !this.isDOMEventHandled(event, this.keydown)
1667
        ) {
1668
            const nativeEvent = event;
×
1669
            const { selection } = editor;
×
1670

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

1674
            try {
×
1675
                // COMPAT: Since we prevent the default behavior on
1676
                // `beforeinput` events, the browser doesn't think there's ever
1677
                // any history stack to undo or redo, so we have to manage these
1678
                // hotkeys ourselves. (2019/11/06)
1679
                if (Hotkeys.isRedo(nativeEvent)) {
×
1680
                    event.preventDefault();
×
1681

1682
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1683
                        editor.redo();
×
1684
                    }
1685

1686
                    return;
×
1687
                }
1688

1689
                if (Hotkeys.isUndo(nativeEvent)) {
×
1690
                    event.preventDefault();
×
1691

1692
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1693
                        editor.undo();
×
1694
                    }
1695

1696
                    return;
×
1697
                }
1698

1699
                // COMPAT: Certain browsers don't handle the selection updates
1700
                // properly. In Chrome, the selection isn't properly extended.
1701
                // And in Firefox, the selection isn't properly collapsed.
1702
                // (2017/10/17)
1703
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1704
                    event.preventDefault();
×
1705
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1706
                    return;
×
1707
                }
1708

1709
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1710
                    event.preventDefault();
×
1711
                    Transforms.move(editor, { unit: 'line' });
×
1712
                    return;
×
1713
                }
1714

1715
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1716
                    event.preventDefault();
×
1717
                    Transforms.move(editor, {
×
1718
                        unit: 'line',
1719
                        edge: 'focus',
1720
                        reverse: true
1721
                    });
1722
                    return;
×
1723
                }
1724

1725
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1726
                    event.preventDefault();
×
1727
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1728
                    return;
×
1729
                }
1730

1731
                // COMPAT: If a void node is selected, or a zero-width text node
1732
                // adjacent to an inline is selected, we need to handle these
1733
                // hotkeys manually because browsers won't be able to skip over
1734
                // the void node with the zero-width space not being an empty
1735
                // string.
1736
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1737
                    event.preventDefault();
×
1738

1739
                    if (selection && Range.isCollapsed(selection)) {
×
1740
                        Transforms.move(editor, { reverse: !isRTL });
×
1741
                    } else {
1742
                        Transforms.collapse(editor, { edge: 'start' });
×
1743
                    }
1744

1745
                    return;
×
1746
                }
1747

1748
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1749
                    event.preventDefault();
×
1750
                    if (selection && Range.isCollapsed(selection)) {
×
1751
                        Transforms.move(editor, { reverse: isRTL });
×
1752
                    } else {
1753
                        Transforms.collapse(editor, { edge: 'end' });
×
1754
                    }
1755

1756
                    return;
×
1757
                }
1758

1759
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1760
                    event.preventDefault();
×
1761

1762
                    if (selection && Range.isExpanded(selection)) {
×
1763
                        Transforms.collapse(editor, { edge: 'focus' });
×
1764
                    }
1765

1766
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1767
                    return;
×
1768
                }
1769

1770
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1771
                    event.preventDefault();
×
1772

1773
                    if (selection && Range.isExpanded(selection)) {
×
1774
                        Transforms.collapse(editor, { edge: 'focus' });
×
1775
                    }
1776

1777
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1778
                    return;
×
1779
                }
1780

1781
                if (isKeyHotkey('mod+a', event)) {
×
1782
                    this.editor.selectAll();
×
1783
                    event.preventDefault();
×
1784
                    return;
×
1785
                }
1786

1787
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1788
                // fall back to guessing at the input intention for hotkeys.
1789
                // COMPAT: In iOS, some of these hotkeys are handled in the
1790
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1791
                    // We don't have a core behavior for these, but they change the
1792
                    // DOM if we don't prevent them, so we have to.
1793
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1794
                        event.preventDefault();
×
1795
                        return;
×
1796
                    }
1797

1798
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1799
                        event.preventDefault();
×
1800
                        Editor.insertBreak(editor);
×
1801
                        return;
×
1802
                    }
1803

1804
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1805
                        event.preventDefault();
×
1806

1807
                        if (selection && Range.isExpanded(selection)) {
×
1808
                            Editor.deleteFragment(editor, {
×
1809
                                direction: 'backward'
1810
                            });
1811
                        } else {
1812
                            Editor.deleteBackward(editor);
×
1813
                        }
1814

1815
                        return;
×
1816
                    }
1817

1818
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1819
                        event.preventDefault();
×
1820

1821
                        if (selection && Range.isExpanded(selection)) {
×
1822
                            Editor.deleteFragment(editor, {
×
1823
                                direction: 'forward'
1824
                            });
1825
                        } else {
1826
                            Editor.deleteForward(editor);
×
1827
                        }
1828

1829
                        return;
×
1830
                    }
1831

1832
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1833
                        event.preventDefault();
×
1834

1835
                        if (selection && Range.isExpanded(selection)) {
×
1836
                            Editor.deleteFragment(editor, {
×
1837
                                direction: 'backward'
1838
                            });
1839
                        } else {
1840
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1841
                        }
1842

1843
                        return;
×
1844
                    }
1845

1846
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1847
                        event.preventDefault();
×
1848

1849
                        if (selection && Range.isExpanded(selection)) {
×
1850
                            Editor.deleteFragment(editor, {
×
1851
                                direction: 'forward'
1852
                            });
1853
                        } else {
1854
                            Editor.deleteForward(editor, { unit: 'line' });
×
1855
                        }
1856

1857
                        return;
×
1858
                    }
1859

1860
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1861
                        event.preventDefault();
×
1862

1863
                        if (selection && Range.isExpanded(selection)) {
×
1864
                            Editor.deleteFragment(editor, {
×
1865
                                direction: 'backward'
1866
                            });
1867
                        } else {
1868
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1869
                        }
1870

1871
                        return;
×
1872
                    }
1873

1874
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1875
                        event.preventDefault();
×
1876

1877
                        if (selection && Range.isExpanded(selection)) {
×
1878
                            Editor.deleteFragment(editor, {
×
1879
                                direction: 'forward'
1880
                            });
1881
                        } else {
1882
                            Editor.deleteForward(editor, { unit: 'word' });
×
1883
                        }
1884

1885
                        return;
×
1886
                    }
1887
                } else {
1888
                    if (IS_CHROME || IS_SAFARI) {
×
1889
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1890
                        // an event when deleting backwards in a selected void inline node
1891
                        if (
×
1892
                            selection &&
×
1893
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1894
                            Range.isCollapsed(selection)
1895
                        ) {
1896
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1897
                            if (
×
1898
                                Element.isElement(currentNode) &&
×
1899
                                Editor.isVoid(editor, currentNode) &&
1900
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1901
                            ) {
1902
                                event.preventDefault();
×
1903
                                Editor.deleteBackward(editor, {
×
1904
                                    unit: 'block'
1905
                                });
1906
                                return;
×
1907
                            }
1908
                        }
1909
                    }
1910
                }
1911
            } catch (error) {
1912
                this.editor.onError({
×
1913
                    code: SlateErrorCode.OnDOMKeydownError,
1914
                    nativeError: error
1915
                });
1916
            }
1917
        }
1918
    }
1919

1920
    private onDOMPaste(event: ClipboardEvent) {
1921
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1922
        // fall back to React's `onPaste` here instead.
1923
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1924
        // when "paste without formatting" option is used.
1925
        // This unfortunately needs to be handled with paste events instead.
1926
        if (
×
1927
            !this.isDOMEventHandled(event, this.paste) &&
×
1928
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1929
            !this.readonly &&
1930
            AngularEditor.hasEditableTarget(this.editor, event.target)
1931
        ) {
1932
            event.preventDefault();
×
1933
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1934
        }
1935
    }
1936

1937
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1938
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1939
        // fall back to React's leaky polyfill instead just for it. It
1940
        // only works for the `insertText` input type.
1941
        if (
×
1942
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1943
            !this.readonly &&
1944
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1945
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1946
        ) {
1947
            event.nativeEvent.preventDefault();
×
1948
            try {
×
1949
                const text = event.data;
×
1950
                if (!Range.isCollapsed(this.editor.selection)) {
×
1951
                    Editor.deleteFragment(this.editor);
×
1952
                }
1953
                // just handle Non-IME input
1954
                if (!this.isComposing) {
×
1955
                    Editor.insertText(this.editor, text);
×
1956
                }
1957
            } catch (error) {
1958
                this.editor.onError({
×
1959
                    code: SlateErrorCode.ToNativeSelectionError,
1960
                    nativeError: error
1961
                });
1962
            }
1963
        }
1964
    }
1965

1966
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1967
        if (!handler) {
3✔
1968
            return false;
3✔
1969
        }
1970
        handler(event);
×
1971
        return event.defaultPrevented;
×
1972
    }
1973
    //#endregion
1974

1975
    ngOnDestroy() {
1976
        this.editorResizeObserver?.disconnect();
22✔
1977
        NODE_TO_ELEMENT.delete(this.editor);
22✔
1978
        this.manualListeners.forEach(manualListener => {
22✔
1979
            manualListener();
462✔
1980
        });
1981
        this.destroy$.complete();
22✔
1982
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
1983
    }
1984
}
1985

1986
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1987
    // This was affecting the selection of multiple blocks and dragging behavior,
1988
    // so enabled only if the selection has been collapsed.
1989
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
3✔
1990
        const leafEl = domRange.startContainer.parentElement!;
3✔
1991

1992
        // COMPAT: In Chrome, domRange.getBoundingClientRect() can return zero dimensions for valid ranges (e.g. line breaks).
1993
        // When this happens, do not scroll like most editors do.
1994
        const domRect = domRange.getBoundingClientRect();
3✔
1995
        const isZeroDimensionRect = domRect.width === 0 && domRect.height === 0 && domRect.x === 0 && domRect.y === 0;
3!
1996

1997
        if (isZeroDimensionRect) {
3!
1998
            const leafRect = leafEl.getBoundingClientRect();
×
1999
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2000

2001
            if (leafHasDimensions) {
×
2002
                return;
×
2003
            }
2004
        }
2005

2006
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
3✔
2007
        scrollIntoView(leafEl, {
3✔
2008
            scrollMode: 'if-needed'
2009
        });
2010
        delete leafEl.getBoundingClientRect;
3✔
2011
    }
2012
};
2013

2014
/**
2015
 * Check if the target is inside void and in the editor.
2016
 */
2017

2018
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
2019
    let slateNode: Node | null = null;
8✔
2020
    try {
8✔
2021
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
8✔
2022
    } catch (error) {}
2023
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
8!
2024
};
2025

2026
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
2027
    return (
5✔
2028
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
12✔
2029
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
2030
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
2031
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
2032
    );
2033
};
2034

2035
/**
2036
 * remove default insert from composition
2037
 * @param text
2038
 */
2039
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2040
    const types = ['compositionend', 'insertFromComposition'];
×
2041
    if (!types.includes(event.type)) {
×
2042
        return;
×
2043
    }
2044
    const insertText = (event as CompositionEvent).data;
×
2045
    const window = AngularEditor.getWindow(editor);
×
2046
    const domSelection = window.getSelection();
×
2047
    // ensure text node insert composition input text
2048
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2049
        const textNode = domSelection.anchorNode;
×
2050
        textNode.splitText(textNode.length - insertText.length).remove();
×
2051
    }
2052
};
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