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

worktile / slate-angular / 1e7b4ad2-8a43-48cf-8f59-7798c81ae5cf

11 Feb 2026 08:40AM UTC coverage: 35.409% (-0.07%) from 35.475%
1e7b4ad2-8a43-48cf-8f59-7798c81ae5cf

push

circleci

pubuzhixing8
chore: add debug update

407 of 1362 branches covered (29.88%)

Branch coverage included in aggregate %.

2 of 10 new or added lines in 3 files covered. (20.0%)

3 existing lines in 1 file now uncovered.

1128 of 2973 relevant lines covered (37.94%)

22.63 hits per line

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

21.54
/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_VIRTUAL_SCROLL_SELECTION,
54
    ELEMENT_KEY_TO_HEIGHTS,
55
    getBusinessTop,
56
    isDebug,
57
    isDebugScrollTop,
58
    isDecoratorRangeListEqual,
59
    measureHeightByIndics,
60
    roundTo
61
} from '../../utils';
62
import { SlatePlaceholder } from '../../types/feature';
63
import { restoreDom } from '../../utils/restore-dom';
64
import { ListRender, updatePreRenderingElementWidth } from '../../view/render/list-render';
65
import { TRIPLE_CLICK, EDITOR_TO_ON_CHANGE } from 'slate-dom';
66
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
67
import { isKeyHotkey } from 'is-hotkey';
68
import {
69
    calcBusinessTop,
70
    calculateAccumulatedTopHeight,
71
    debugLog,
72
    EDITOR_TO_IS_FROM_SCROLL_TO,
73
    EDITOR_TO_ROOT_NODE_WIDTH,
74
    EDITOR_TO_VIEWPORT_HEIGHT,
75
    EDITOR_TO_VIRTUAL_SCROLL_CONFIG,
76
    getCachedHeightByElement,
77
    getViewportHeight,
78
    isDebugUpdate,
79
    VIRTUAL_BOTTOM_HEIGHT_CLASS_NAME,
80
    VIRTUAL_CENTER_OUTLET_CLASS_NAME,
81
    VIRTUAL_TOP_HEIGHT_CLASS_NAME
82
} from '../../utils/virtual-scroll';
83

84
// not correctly clipboardData on beforeinput
85
const forceOnDOMPaste = IS_SAFARI;
1✔
86

87
class RemeasureConfig {
88
    indics: number[];
89
    tryUpdateViewport: boolean;
90
}
91

92
@Component({
93
    selector: 'slate-editable',
94
    host: {
95
        class: 'slate-editable-container',
96
        '[attr.contenteditable]': 'readonly ? undefined : true',
97
        '[attr.role]': `readonly ? undefined : 'textbox'`,
98
        '[attr.spellCheck]': `!hasBeforeInputSupport ? false : spellCheck`,
99
        '[attr.autoCorrect]': `!hasBeforeInputSupport ? 'false' : autoCorrect`,
100
        '[attr.autoCapitalize]': `!hasBeforeInputSupport ? 'false' : autoCapitalize`
101
    },
102
    template: '',
103
    changeDetection: ChangeDetectionStrategy.OnPush,
104
    providers: [
105
        {
106
            provide: NG_VALUE_ACCESSOR,
107
            useExisting: forwardRef(() => SlateEditable),
23✔
108
            multi: true
109
        }
110
    ],
111
    imports: []
112
})
113
export class SlateEditable implements OnInit, OnChanges, OnDestroy, AfterViewChecked, DoCheck {
1✔
114
    viewContext: SlateViewContext;
115
    context: SlateChildrenContext;
116

117
    private destroy$ = new Subject();
23✔
118

119
    isComposing = false;
23✔
120
    isDraggingInternally = false;
23✔
121
    isUpdatingSelection = false;
23✔
122
    latestElement = null as DOMElement | null;
23✔
123

124
    protected manualListeners: (() => void)[] = [];
23✔
125

126
    private initialized: boolean;
127

128
    private onTouchedCallback: () => void = () => {};
23✔
129

130
    private onChangeCallback: (_: any) => void = () => {};
23✔
131

132
    @Input() editor: AngularEditor;
133

134
    @Input() renderElement: (element: Element) => ViewType | null;
135

136
    @Input() renderLeaf: (text: SlateText) => ViewType | null;
137

138
    @Input() renderText: (text: SlateText) => ViewType | null;
139

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

142
    @Input() placeholderDecorate: (editor: Editor) => SlatePlaceholder[];
143

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

146
    @Input() isStrictDecorate: boolean = true;
23✔
147

148
    @Input() trackBy: (node: Element) => any = () => null;
206✔
149

150
    @Input() readonly = false;
23✔
151

152
    @Input() placeholder: string;
153

154
    @Input()
155
    set virtualScroll(config: SlateVirtualScrollConfig) {
156
        this.virtualScrollConfig = config;
×
157
        EDITOR_TO_VIRTUAL_SCROLL_CONFIG.set(this.editor, config);
×
158
        if (isDebugScrollTop) {
×
159
            debugLog('log', 'virtualScrollConfig scrollTop:', config.scrollTop);
×
160
        }
161
        if (this.isEnabledVirtualScroll()) {
×
162
            this.tryUpdateVirtualViewport();
×
163
        }
164
    }
165

166
    //#region input event handler
167
    @Input() beforeInput: (event: Event) => void;
168
    @Input() blur: (event: Event) => void;
169
    @Input() click: (event: MouseEvent) => void;
170
    @Input() compositionEnd: (event: CompositionEvent) => void;
171
    @Input() compositionUpdate: (event: CompositionEvent) => void;
172
    @Input() compositionStart: (event: CompositionEvent) => void;
173
    @Input() copy: (event: ClipboardEvent) => void;
174
    @Input() cut: (event: ClipboardEvent) => void;
175
    @Input() dragOver: (event: DragEvent) => void;
176
    @Input() dragStart: (event: DragEvent) => void;
177
    @Input() dragEnd: (event: DragEvent) => void;
178
    @Input() drop: (event: DragEvent) => void;
179
    @Input() focus: (event: Event) => void;
180
    @Input() keydown: (event: KeyboardEvent) => void;
181
    @Input() paste: (event: ClipboardEvent) => void;
182
    //#endregion
183

184
    //#region DOM attr
185
    @Input() spellCheck = false;
23✔
186
    @Input() autoCorrect = false;
23✔
187
    @Input() autoCapitalize = false;
23✔
188

189
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
190
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
191
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
192

193
    get hasBeforeInputSupport() {
194
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
195
    }
196
    //#endregion
197

198
    viewContainerRef = inject(ViewContainerRef);
23✔
199

200
    getOutletParent = () => {
23✔
201
        return this.elementRef.nativeElement;
43✔
202
    };
203

204
    getOutletElement = () => {
23✔
205
        if (this.virtualScrollInitialized) {
23!
206
            return this.virtualCenterOutlet;
×
207
        } else {
208
            return null;
23✔
209
        }
210
    };
211

212
    listRender: ListRender;
213

214
    private virtualScrollConfig: SlateVirtualScrollConfig = {
23✔
215
        enabled: false,
216
        scrollTop: 0,
217
        scrollContainer: null
218
    };
219

220
    private inViewportChildren: Element[] = [];
23✔
221
    private inViewportIndics: number[] = [];
23✔
222
    private keyHeightMap = new Map<string, number>();
23✔
223
    private tryUpdateVirtualViewportAnimId: number;
224
    private editorResizeObserver?: ResizeObserver;
225
    private editorScrollContainerResizeObserver?: ResizeObserver;
226

227
    indicsOfNeedRemeasured$ = new Subject<RemeasureConfig>();
23✔
228

229
    virtualScrollInitialized = false;
23✔
230

231
    virtualTopHeightElement: HTMLElement;
232

233
    virtualBottomHeightElement: HTMLElement;
234

235
    virtualCenterOutlet: HTMLElement;
236

237
    constructor(
238
        public elementRef: ElementRef,
23✔
239
        public renderer2: Renderer2,
23✔
240
        public cdr: ChangeDetectorRef,
23✔
241
        private ngZone: NgZone,
23✔
242
        private injector: Injector
23✔
243
    ) {}
244

245
    ngOnInit() {
246
        this.editor.injector = this.injector;
23✔
247
        this.editor.children = [];
23✔
248
        let window = getDefaultView(this.elementRef.nativeElement);
23✔
249
        EDITOR_TO_WINDOW.set(this.editor, window);
23✔
250
        EDITOR_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
251
        NODE_TO_ELEMENT.set(this.editor, this.elementRef.nativeElement);
23✔
252
        ELEMENT_TO_NODE.set(this.elementRef.nativeElement, this.editor);
23✔
253
        IS_READ_ONLY.set(this.editor, this.readonly);
23✔
254
        ELEMENT_KEY_TO_HEIGHTS.set(this.editor, this.keyHeightMap);
23✔
255
        EDITOR_TO_ON_CHANGE.set(this.editor, () => {
23✔
256
            this.ngZone.run(() => {
13✔
257
                this.onChange();
13✔
258
            });
259
        });
260
        this.ngZone.runOutsideAngular(() => {
23✔
261
            this.initialize();
23✔
262
        });
263
        this.initializeViewContext();
23✔
264
        this.initializeContext();
23✔
265
        // add browser class
266
        let browserClass = IS_FIREFOX ? 'firefox' : IS_SAFARI ? 'safari' : '';
23!
267
        browserClass && this.elementRef.nativeElement.classList.add(browserClass);
23!
268
        this.initializeVirtualScroll();
23✔
269
        this.listRender = new ListRender(this.viewContext, this.viewContainerRef, this.getOutletParent, this.getOutletElement);
23✔
270
    }
271

272
    ngOnChanges(simpleChanges: SimpleChanges) {
273
        if (!this.initialized) {
30✔
274
            return;
23✔
275
        }
276
        const decorateChange = simpleChanges['decorate'];
7✔
277
        if (decorateChange) {
7✔
278
            this.forceRender();
2✔
279
        }
280
        const placeholderChange = simpleChanges['placeholder'];
7✔
281
        if (placeholderChange) {
7✔
282
            this.render();
1✔
283
        }
284
        const readonlyChange = simpleChanges['readonly'];
7✔
285
        if (readonlyChange) {
7!
286
            IS_READ_ONLY.set(this.editor, this.readonly);
×
287
            this.render();
×
288
            this.toSlateSelection();
×
289
        }
290
    }
291

292
    registerOnChange(fn: any) {
293
        this.onChangeCallback = fn;
23✔
294
    }
295
    registerOnTouched(fn: any) {
296
        this.onTouchedCallback = fn;
23✔
297
    }
298

299
    writeValue(value: Element[]) {
300
        if (value && value.length) {
49✔
301
            this.editor.children = value;
26✔
302
            this.initializeContext();
26✔
303
            if (this.isEnabledVirtualScroll()) {
26!
304
                const previousInViewportChildren = [...this.inViewportChildren];
×
305
                const visibleStates = this.editor.getAllVisibleStates();
×
306
                const virtualView = this.calculateVirtualViewport(visibleStates);
×
307
                this.applyVirtualView(virtualView);
×
308
                const childrenForRender = virtualView.inViewportChildren;
×
309
                if (isDebug) {
×
310
                    debugLog('log', 'writeValue calculate: ', virtualView.inViewportIndics, 'initialized: ', this.listRender.initialized);
×
311
                }
312
                if (!this.listRender.initialized) {
×
313
                    this.listRender.initialize(childrenForRender, this.editor, this.context, 0, virtualView.inViewportIndics);
×
314
                } else {
315
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
316
                        this.appendPreRenderingToViewport(visibleStates);
×
NEW
317
                    if (isDebugUpdate) {
×
NEW
318
                        debugLog('log', 'writeValue update list render');
×
319
                    }
UNCOV
320
                    this.listRender.update(
×
321
                        childrenWithPreRendering,
322
                        this.editor,
323
                        this.context,
324
                        preRenderingCount,
325
                        childrenWithPreRenderingIndics
326
                    );
327
                }
328
                const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
329
                if (remeasureIndics.length) {
×
330
                    this.indicsOfNeedRemeasured$.next({ indics: remeasureIndics, tryUpdateViewport: true });
×
331
                }
332
            } else {
333
                if (!this.listRender.initialized) {
26✔
334
                    this.listRender.initialize(this.editor.children, this.editor, this.context);
23✔
335
                } else {
336
                    this.listRender.update(this.editor.children, this.editor, this.context);
3✔
337
                }
338
            }
339
            this.cdr.markForCheck();
26✔
340
        }
341
    }
342

343
    initialize() {
344
        this.initialized = true;
23✔
345
        const window = AngularEditor.getWindow(this.editor);
23✔
346
        this.addEventListener(
23✔
347
            'selectionchange',
348
            event => {
349
                this.toSlateSelection();
2✔
350
            },
351
            window.document
352
        );
353
        if (HAS_BEFORE_INPUT_SUPPORT) {
23✔
354
            this.addEventListener('beforeinput', this.onDOMBeforeInput.bind(this));
23✔
355
        }
356
        this.addEventListener('blur', this.onDOMBlur.bind(this));
23✔
357
        this.addEventListener('click', this.onDOMClick.bind(this));
23✔
358
        this.addEventListener('compositionend', this.onDOMCompositionEnd.bind(this));
23✔
359
        this.addEventListener('compositionupdate', this.onDOMCompositionUpdate.bind(this));
23✔
360
        this.addEventListener('compositionstart', this.onDOMCompositionStart.bind(this));
23✔
361
        this.addEventListener('copy', this.onDOMCopy.bind(this));
23✔
362
        this.addEventListener('cut', this.onDOMCut.bind(this));
23✔
363
        this.addEventListener('dragover', this.onDOMDragOver.bind(this));
23✔
364
        this.addEventListener('dragstart', this.onDOMDragStart.bind(this));
23✔
365
        this.addEventListener('dragend', this.onDOMDragEnd.bind(this));
23✔
366
        this.addEventListener('drop', this.onDOMDrop.bind(this));
23✔
367
        this.addEventListener('focus', this.onDOMFocus.bind(this));
23✔
368
        this.addEventListener('keydown', this.onDOMKeydown.bind(this));
23✔
369
        this.addEventListener('paste', this.onDOMPaste.bind(this));
23✔
370
        BEFORE_INPUT_EVENTS.forEach(event => {
23✔
371
            this.addEventListener(event.name, () => {});
115✔
372
        });
373
    }
374

375
    private isEnabledVirtualScroll() {
376
        return !!(this.virtualScrollConfig && this.virtualScrollConfig.enabled);
82✔
377
    }
378

379
    initializeVirtualScroll() {
380
        if (this.virtualScrollInitialized) {
23!
381
            return;
×
382
        }
383
        if (this.isEnabledVirtualScroll()) {
23!
384
            this.virtualScrollInitialized = true;
×
385
            this.virtualTopHeightElement = document.createElement('div');
×
386
            this.virtualTopHeightElement.classList.add(VIRTUAL_TOP_HEIGHT_CLASS_NAME);
×
387
            this.virtualTopHeightElement.contentEditable = 'false';
×
388
            this.virtualBottomHeightElement = document.createElement('div');
×
389
            this.virtualBottomHeightElement.classList.add(VIRTUAL_BOTTOM_HEIGHT_CLASS_NAME);
×
390
            this.virtualBottomHeightElement.contentEditable = 'false';
×
391
            this.virtualCenterOutlet = document.createElement('div');
×
392
            this.virtualCenterOutlet.classList.add(VIRTUAL_CENTER_OUTLET_CLASS_NAME);
×
393
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
394
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
395
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
396
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect().width;
×
397
            EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, this.virtualTopHeightElement.offsetWidth);
×
398
            this.editorResizeObserver = new ResizeObserver(entries => {
×
399
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
400
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
401
                    this.keyHeightMap.clear();
×
402
                    let target = this.virtualTopHeightElement;
×
403
                    if (this.inViewportChildren[0]) {
×
404
                        const firstElement = this.inViewportChildren[0];
×
405
                        const firstDomElement = AngularEditor.toDOMNode(this.editor, firstElement);
×
406
                        target = firstDomElement;
×
407
                    }
408
                    EDITOR_TO_ROOT_NODE_WIDTH.set(this.editor, target.offsetWidth);
×
409
                    updatePreRenderingElementWidth(this.editor);
×
410
                    if (isDebug) {
×
411
                        debugLog(
×
412
                            'log',
413
                            'editorResizeObserverRectWidth: ',
414
                            editorResizeObserverRectWidth,
415
                            'EDITOR_TO_ROOT_NODE_WIDTH: ',
416
                            EDITOR_TO_ROOT_NODE_WIDTH.get(this.editor)
417
                        );
418
                    }
419
                }
420
            });
421
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
422
            if (this.virtualScrollConfig.scrollContainer) {
×
423
                this.editorScrollContainerResizeObserver = new ResizeObserver(entries => {
×
424
                    const height = this.virtualScrollConfig.scrollContainer.getBoundingClientRect().height;
×
425
                    EDITOR_TO_VIEWPORT_HEIGHT.set(this.editor, height);
×
426
                    if (isDebug) {
×
427
                        debugLog('log', 'editorScrollContainerResizeObserver calc viewport height: ', height);
×
428
                        this.virtualTopHeightElement.setAttribute('viewport-height', height.toString());
×
429
                    }
430
                });
431
                this.editorScrollContainerResizeObserver.observe(this.virtualScrollConfig.scrollContainer);
×
432
            }
433

434
            let pendingRemeasureIndics: number[] = [];
×
435
            this.indicsOfNeedRemeasured$
×
436
                .pipe(
437
                    tap((previousValue: RemeasureConfig) => {
438
                        previousValue.indics.forEach((index: number) => {
×
439
                            if (!pendingRemeasureIndics.includes(index)) {
×
440
                                pendingRemeasureIndics.push(index);
×
441
                            }
442
                        });
443
                    }),
444
                    debounceTime(500),
445
                    filter(() => pendingRemeasureIndics.length > 0)
×
446
                )
447
                .subscribe((previousValue: RemeasureConfig) => {
448
                    const changed = measureHeightByIndics(this.editor, pendingRemeasureIndics, true);
×
449
                    if (changed) {
×
450
                        if (previousValue.tryUpdateViewport) {
×
451
                            this.tryUpdateVirtualViewport();
×
452
                            if (isDebug) {
×
453
                                debugLog(
×
454
                                    'log',
455
                                    'exist pendingRemeasureIndics: ',
456
                                    pendingRemeasureIndics,
457
                                    'will try to update virtual viewport'
458
                                );
459
                            }
460
                        }
461
                    }
462
                    pendingRemeasureIndics = [];
×
463
                });
464
        }
465
    }
466

467
    getChangedIndics(previousValue: Descendant[]) {
468
        const remeasureIndics = [];
×
469
        this.inViewportChildren.forEach((child, index) => {
×
470
            if (previousValue.indexOf(child) === -1) {
×
471
                remeasureIndics.push(this.inViewportIndics[index]);
×
472
            }
473
        });
474
        return remeasureIndics;
×
475
    }
476

477
    setVirtualSpaceHeight(topHeight: number, bottomHeight?: number) {
478
        if (!this.virtualScrollInitialized) {
×
479
            return;
×
480
        }
481
        this.virtualTopHeightElement.style.height = `${roundTo(topHeight, 1)}px`;
×
482
        if (bottomHeight !== undefined) {
×
483
            this.virtualBottomHeightElement.style.height = `${roundTo(bottomHeight, 1)}px`;
×
484
        }
485
    }
486

487
    setTopHeightDebugInfo(accumulatedHeight: number, accumulatedEndIndex: number) {
488
        if (isDebug) {
×
489
            this.virtualTopHeightElement.setAttribute('accumulated-height', accumulatedHeight.toString());
×
490
            this.virtualTopHeightElement.setAttribute('accumulated-height-end-index', accumulatedEndIndex.toString());
×
491
        }
492
    }
493

494
    getActualVirtualTopHeight() {
495
        if (!this.virtualScrollInitialized) {
×
496
            return 0;
×
497
        }
498
        return parseFloat(this.virtualTopHeightElement.style.height.replace('px', ''));
×
499
    }
500

501
    appendPreRenderingToViewport(visibleStates: boolean[]) {
502
        let preRenderingCount = 0;
×
503
        const childrenWithPreRendering = [...this.inViewportChildren];
×
504
        const childrenWithPreRenderingIndics = [...this.inViewportIndics];
×
505
        const firstIndex = this.inViewportIndics[0];
×
506
        for (let index = firstIndex - 1; index >= 0; index--) {
×
507
            const element = this.editor.children[index] as Element;
×
508
            if (visibleStates[index]) {
×
509
                childrenWithPreRendering.unshift(element);
×
510
                childrenWithPreRenderingIndics.unshift(index);
×
511
                preRenderingCount = 1;
×
512
                break;
×
513
            }
514
        }
515
        const lastIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
516
        for (let index = lastIndex + 1; index < this.editor.children.length; index++) {
×
517
            const element = this.editor.children[index] as Element;
×
518
            if (visibleStates[index]) {
×
519
                childrenWithPreRendering.push(element);
×
520
                childrenWithPreRenderingIndics.push(index);
×
521
                break;
×
522
            }
523
        }
524
        return { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics };
×
525
    }
526

527
    calculateIndicsStartAndEndBySelection() {
528
        if (!this.editor.selection || Range.isCollapsed(this.editor.selection)) {
×
529
            return;
×
530
        }
531
        const isBackward = Range.isBackward(this.editor.selection);
×
532
        const anchorIndex = this.editor.selection.anchor.path[0];
×
533
        const focusIndex = this.editor.selection.focus.path[0];
×
534
        let minStartIndex = anchorIndex;
×
535
        let minEndIndex = focusIndex;
×
536
        if (isBackward) {
×
537
            minStartIndex = focusIndex;
×
538
            minEndIndex = anchorIndex;
×
539
        }
540
        if (minStartIndex < this.inViewportIndics[0]) {
×
541
            minStartIndex = this.inViewportIndics[0];
×
542
        }
543
        if (minEndIndex > this.inViewportIndics[this.inViewportIndics.length - 1]) {
×
544
            minEndIndex = this.inViewportIndics[this.inViewportIndics.length - 1];
×
545
        }
546
        return { minStartIndex, minEndIndex };
×
547
    }
548

549
    private tryUpdateVirtualViewport() {
550
        if (isDebug) {
×
551
            debugLog('log', 'tryUpdateVirtualViewport');
×
552
        }
553
        const isFromScrollTo = EDITOR_TO_IS_FROM_SCROLL_TO.get(this.editor);
×
554
        if (this.inViewportIndics.length > 0 && !isFromScrollTo) {
×
555
            const realTopHeight = this.getActualVirtualTopHeight();
×
556
            const visibleStates = this.editor.getAllVisibleStates();
×
557
            const accumulateTopHeigh = calculateAccumulatedTopHeight(this.editor, this.inViewportIndics[0], visibleStates);
×
558
            this.setTopHeightDebugInfo(accumulateTopHeigh, this.inViewportIndics[0] - 1);
×
559
            if (realTopHeight !== accumulateTopHeigh) {
×
560
                if (isDebug) {
×
561
                    debugLog('log', 'update top height since dirty state,增加高度: ', accumulateTopHeigh - realTopHeight);
×
562
                }
563
                this.setVirtualSpaceHeight(accumulateTopHeigh);
×
564
                return;
×
565
            }
566
        }
567
        this.tryUpdateVirtualViewportAnimId && cancelAnimationFrame(this.tryUpdateVirtualViewportAnimId);
×
568
        this.tryUpdateVirtualViewportAnimId = requestAnimationFrame(() => {
×
569
            if (isDebug) {
×
570
                debugLog('log', 'tryUpdateVirtualViewport Anim start');
×
571
            }
572
            const visibleStates = this.editor.getAllVisibleStates();
×
573
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
574
            let diff = this.diffVirtualViewport(virtualView);
×
575
            if (diff.isDifferent && diff.needRemoveOnTop && !isFromScrollTo) {
×
576
                const remeasureIndics = diff.changedIndexesOfTop;
×
577
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
578
                if (changed) {
×
579
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
580
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
581
                }
582
            }
583
            if (diff.isDifferent) {
×
584
                this.applyVirtualView(virtualView);
×
585
                if (this.listRender.initialized) {
×
586
                    const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
587
                        this.appendPreRenderingToViewport(visibleStates);
×
NEW
588
                    if (isDebugUpdate) {
×
NEW
589
                        debugLog('log', 'tryUpdateVirtualViewport update list render');
×
590
                    }
UNCOV
591
                    this.listRender.update(
×
592
                        childrenWithPreRendering,
593
                        this.editor,
594
                        this.context,
595
                        preRenderingCount,
596
                        childrenWithPreRenderingIndics
597
                    );
598
                    if (diff.needAddOnTop && !isFromScrollTo && diff.changedIndexesOfTop.length === 1) {
×
599
                        const remeasureAddedIndics = diff.changedIndexesOfTop;
×
600
                        if (isDebug) {
×
601
                            debugLog('log', 'needAddOnTop to remeasure heights: ', remeasureAddedIndics);
×
602
                        }
603
                        const startIndexBeforeAdd = diff.changedIndexesOfTop[diff.changedIndexesOfTop.length - 1] + 1;
×
604
                        const topHeightBeforeAdd = virtualView.accumulatedHeights[startIndexBeforeAdd];
×
605
                        const changed = measureHeightByIndics(this.editor, remeasureAddedIndics);
×
606
                        if (changed) {
×
607
                            const newHeights = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
608
                            const actualTopHeightAfterAdd = newHeights.accumulatedHeights[startIndexBeforeAdd];
×
609
                            const newTopHeight = virtualView.top - (actualTopHeightAfterAdd - topHeightBeforeAdd);
×
610
                            this.setTopHeightDebugInfo(
×
611
                                newHeights.accumulatedHeights[this.inViewportIndics[0]],
612
                                this.inViewportIndics[0] - 1
613
                            );
614
                            if (topHeightBeforeAdd !== actualTopHeightAfterAdd) {
×
615
                                this.setVirtualSpaceHeight(newTopHeight);
×
616
                                if (isDebug) {
×
617
                                    debugLog(
×
618
                                        'log',
619
                                        `update top height since will add element in top,减去高度: ${actualTopHeightAfterAdd - topHeightBeforeAdd}`
620
                                    );
621
                                }
622
                            }
623
                        }
624
                    }
625
                    if (this.editor.selection) {
×
626
                        this.toNativeSelection(false);
×
627
                    }
628
                }
629
            }
630
            if (isDebug) {
×
631
                debugLog('log', 'tryUpdateVirtualViewport Anim end');
×
632
            }
633
        });
634
    }
635

636
    private calculateVirtualViewport(visibleStates: boolean[]) {
637
        const children = (this.editor.children || []) as Element[];
×
638
        if (!children.length || !this.isEnabledVirtualScroll()) {
×
639
            return {
×
640
                inViewportChildren: children,
641
                inViewportIndics: [],
642
                top: 0,
643
                bottom: 0,
644
                heights: []
645
            };
646
        }
647
        const scrollTop = this.virtualScrollConfig.scrollTop;
×
648
        let viewportHeight = getViewportHeight(this.editor);
×
649
        const elementLength = children.length;
×
650
        let businessTop = getBusinessTop(this.editor);
×
651
        if (businessTop === 0 && this.virtualScrollConfig.scrollTop > 0) {
×
652
            businessTop = calcBusinessTop(this.editor);
×
653
        }
654
        const { heights, accumulatedHeights } = buildHeightsAndAccumulatedHeights(this.editor, visibleStates);
×
655
        const totalHeight = accumulatedHeights[elementLength] + businessTop;
×
656
        let startPosition = Math.max(scrollTop - businessTop, 0);
×
657
        let endPosition = startPosition + viewportHeight;
×
658
        if (scrollTop < businessTop) {
×
659
            endPosition = startPosition + viewportHeight - (businessTop - scrollTop);
×
660
        }
661
        let accumulatedOffset = 0;
×
662
        const inViewportChildren: Element[] = [];
×
663
        const inViewportIndics: number[] = [];
×
664
        const indicsBySelection = this.calculateIndicsStartAndEndBySelection();
×
665
        if (isDebug) {
×
666
            debugLog('log', 'indicsBySelection: ', indicsBySelection);
×
667
        }
668
        for (let i = 0; i < elementLength; i++) {
×
669
            const currentHeight = heights[i];
×
670
            const nextOffset = accumulatedOffset + currentHeight;
×
671
            const isVisible = visibleStates[i];
×
672
            if (!isVisible) {
×
673
                accumulatedOffset = nextOffset;
×
674
                continue;
×
675
            }
676
            if (
×
677
                (indicsBySelection && i > indicsBySelection.minEndIndex && accumulatedOffset >= endPosition) ||
×
678
                (!indicsBySelection && accumulatedOffset >= endPosition)
679
            ) {
680
                break;
×
681
            }
682
            if (
×
683
                (indicsBySelection && i < indicsBySelection.minStartIndex && nextOffset <= startPosition) ||
×
684
                (!indicsBySelection && nextOffset <= startPosition)
685
            ) {
686
                accumulatedOffset = nextOffset;
×
687
                continue;
×
688
            }
689
            inViewportChildren.push(children[i]);
×
690
            inViewportIndics.push(i);
×
691
            accumulatedOffset = nextOffset;
×
692
        }
693
        if (inViewportIndics.length === 0) {
×
694
            inViewportChildren.push(...children);
×
695
            inViewportIndics.push(...Array.from({ length: elementLength }, (_, i) => i));
×
696
        }
697
        const inViewportStartIndex = inViewportIndics[0];
×
698
        const inViewportEndIndex = inViewportIndics[inViewportIndics.length - 1];
×
699
        const top = accumulatedHeights[inViewportStartIndex];
×
700
        // todo: totalHeight: totalHeight 逻辑需要优化
701
        const bottom = totalHeight - accumulatedHeights[inViewportEndIndex + 1];
×
702
        return {
×
703
            inViewportChildren,
704
            inViewportIndics,
705
            top,
706
            bottom,
707
            heights,
708
            accumulatedHeights
709
        };
710
    }
711

712
    private applyVirtualView(virtualView: VirtualViewResult) {
713
        this.inViewportChildren = virtualView.inViewportChildren;
×
714
        this.setVirtualSpaceHeight(virtualView.top, virtualView.bottom);
×
715
        this.inViewportIndics = virtualView.inViewportIndics;
×
716
        this.setTopHeightDebugInfo(virtualView.top, this.inViewportIndics[0] - 1);
×
717
    }
718

719
    private diffVirtualViewport(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
720
        if (!this.inViewportChildren.length) {
×
721
            if (isDebug) {
×
722
                debugLog('log', 'diffVirtualViewport', stage, 'empty inViewportChildren', virtualView.inViewportIndics);
×
723
            }
724
            return {
×
725
                isDifferent: true,
726
                changedIndexesOfTop: [],
727
                changedIndexesOfBottom: []
728
            };
729
        }
730
        const oldIndexesInViewport = [...this.inViewportIndics];
×
731
        const newIndexesInViewport = [...virtualView.inViewportIndics];
×
732
        const firstNewIndex = newIndexesInViewport[0];
×
733
        const lastNewIndex = newIndexesInViewport[newIndexesInViewport.length - 1];
×
734
        const firstOldIndex = oldIndexesInViewport[0];
×
735
        const lastOldIndex = oldIndexesInViewport[oldIndexesInViewport.length - 1];
×
736
        const isSameViewport =
737
            oldIndexesInViewport.length === newIndexesInViewport.length &&
×
738
            oldIndexesInViewport.every((index, i) => index === newIndexesInViewport[i]);
×
739
        if (firstNewIndex === firstOldIndex && lastNewIndex === lastOldIndex) {
×
740
            return {
×
741
                isDifferent: !isSameViewport,
742
                changedIndexesOfTop: [],
743
                changedIndexesOfBottom: []
744
            };
745
        }
746
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
747
            const changedIndexesOfTop = [];
×
748
            const changedIndexesOfBottom = [];
×
749
            const needRemoveOnTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
750
            const needAddOnTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
751
            const needRemoveOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
752
            const needAddOnBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
753
            if (needRemoveOnTop || needAddOnBottom) {
×
754
                // 向下
755
                for (let index = 0; index < oldIndexesInViewport.length; index++) {
×
756
                    const element = oldIndexesInViewport[index];
×
757
                    if (!newIndexesInViewport.includes(element)) {
×
758
                        changedIndexesOfTop.push(element);
×
759
                    } else {
760
                        break;
×
761
                    }
762
                }
763
                for (let index = newIndexesInViewport.length - 1; index >= 0; index--) {
×
764
                    const element = newIndexesInViewport[index];
×
765
                    if (!oldIndexesInViewport.includes(element)) {
×
766
                        changedIndexesOfBottom.push(element);
×
767
                    } else {
768
                        break;
×
769
                    }
770
                }
771
            } else if (needAddOnTop || needRemoveOnBottom) {
×
772
                // 向上
773
                for (let index = 0; index < newIndexesInViewport.length; index++) {
×
774
                    const element = newIndexesInViewport[index];
×
775
                    if (!oldIndexesInViewport.includes(element)) {
×
776
                        changedIndexesOfTop.push(element);
×
777
                    } else {
778
                        break;
×
779
                    }
780
                }
781
                for (let index = oldIndexesInViewport.length - 1; index >= 0; index--) {
×
782
                    const element = oldIndexesInViewport[index];
×
783
                    if (!newIndexesInViewport.includes(element)) {
×
784
                        changedIndexesOfBottom.push(element);
×
785
                    } else {
786
                        break;
×
787
                    }
788
                }
789
            }
790
            if (isDebug) {
×
791
                debugLog('log', `====== diffVirtualViewport stage: ${stage} ======`);
×
792
                debugLog('log', 'oldIndexesInViewport:', oldIndexesInViewport);
×
793
                debugLog('log', 'newIndexesInViewport:', newIndexesInViewport);
×
794
                // this.editor.children[index] will be undefined when it is removed
795
                debugLog(
×
796
                    'log',
797
                    'changedIndexesOfTop:',
798
                    needRemoveOnTop ? '-' : needAddOnTop ? '+' : '-',
×
799
                    changedIndexesOfTop,
800
                    changedIndexesOfTop.map(
801
                        index =>
802
                            (this.editor.children[index] &&
×
803
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
804
                            0
805
                    )
806
                );
807
                debugLog(
×
808
                    'log',
809
                    'changedIndexesOfBottom:',
810
                    needAddOnBottom ? '+' : needRemoveOnBottom ? '-' : '+',
×
811
                    changedIndexesOfBottom,
812
                    changedIndexesOfBottom.map(
813
                        index =>
814
                            (this.editor.children[index] &&
×
815
                                getCachedHeightByElement(this.editor, this.editor.children[index] as Element)) ||
816
                            0
817
                    )
818
                );
819
                const needTop = virtualView.heights.slice(0, newIndexesInViewport[0]).reduce((acc, height) => acc + height, 0);
×
820
                const needBottom = virtualView.heights
×
821
                    .slice(newIndexesInViewport[newIndexesInViewport.length - 1] + 1)
822
                    .reduce((acc, height) => acc + height, 0);
×
823
                debugLog(
×
824
                    'log',
825
                    needTop - parseFloat(this.virtualTopHeightElement.style.height),
826
                    'newTopHeight:',
827
                    needTop,
828
                    'prevTopHeight:',
829
                    parseFloat(this.virtualTopHeightElement.style.height)
830
                );
831
                debugLog(
×
832
                    'log',
833
                    'newBottomHeight:',
834
                    needBottom,
835
                    'prevBottomHeight:',
836
                    parseFloat(this.virtualBottomHeightElement.style.height)
837
                );
838
                debugLog('warn', '=========== Dividing line ===========');
×
839
            }
840
            return {
×
841
                isDifferent: true,
842
                needRemoveOnTop,
843
                needAddOnTop,
844
                needRemoveOnBottom,
845
                needAddOnBottom,
846
                changedIndexesOfTop,
847
                changedIndexesOfBottom
848
            };
849
        }
850
        return {
×
851
            isDifferent: false,
852
            changedIndexesOfTop: [],
853
            changedIndexesOfBottom: []
854
        };
855
    }
856

857
    //#region event proxy
858
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
859
        this.manualListeners.push(
483✔
860
            this.renderer2.listen(target, eventName, (event: Event) => {
861
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
862
                if (beforeInputEvent) {
5!
863
                    this.onFallbackBeforeInput(beforeInputEvent);
×
864
                }
865
                listener(event);
5✔
866
            })
867
        );
868
    }
869

870
    calculateVirtualScrollSelection(selection: Selection) {
871
        if (selection) {
×
872
            const isBlockCardCursor = AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor);
×
873
            const indics = this.inViewportIndics;
×
874
            if (indics.length > 0) {
×
875
                const currentVisibleRange: Range = {
×
876
                    anchor: Editor.start(this.editor, [indics[0]]),
877
                    focus: Editor.end(this.editor, [indics[indics.length - 1]])
878
                };
879
                const [start, end] = Range.edges(selection);
×
880
                let forwardSelection = { anchor: start, focus: end };
×
881
                if (!isBlockCardCursor) {
×
882
                    forwardSelection = { anchor: start, focus: end };
×
883
                } else {
884
                    forwardSelection = { anchor: { path: start.path, offset: 0 }, focus: { path: end.path, offset: 0 } };
×
885
                }
886
                const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
887
                if (intersectedSelection && isBlockCardCursor) {
×
888
                    return selection;
×
889
                }
890
                EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, intersectedSelection);
×
891
                if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
892
                    if (isDebug) {
×
893
                        debugLog(
×
894
                            'log',
895
                            `selection is not in visible range, selection: ${JSON.stringify(
896
                                selection
897
                            )}, currentVisibleRange: ${JSON.stringify(currentVisibleRange)}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
898
                        );
899
                    }
900
                    return intersectedSelection;
×
901
                }
902
                return selection;
×
903
            }
904
        }
905
        EDITOR_TO_VIRTUAL_SCROLL_SELECTION.set(this.editor, null);
×
906
        return selection;
×
907
    }
908

909
    private isSelectionInvisible(selection: Selection) {
910
        const anchorIndex = selection.anchor.path[0];
6✔
911
        const focusIndex = selection.focus.path[0];
6✔
912
        const anchorElement = this.editor.children[anchorIndex] as Element | undefined;
6✔
913
        const focusElement = this.editor.children[focusIndex] as Element | undefined;
6✔
914
        return !anchorElement || !focusElement || !this.editor.isVisible(anchorElement) || !this.editor.isVisible(focusElement);
6✔
915
    }
916

917
    toNativeSelection(autoScroll = true) {
15✔
918
        try {
15✔
919
            let { selection } = this.editor;
15✔
920

921
            if (this.isEnabledVirtualScroll()) {
15!
922
                selection = this.calculateVirtualScrollSelection(selection);
×
923
            }
924

925
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
926
            const { activeElement } = root;
15✔
927
            const domSelection = (root as Document).getSelection();
15✔
928

929
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
930
                return;
×
931
            }
932

933
            const hasDomSelection = domSelection.type !== 'None';
15✔
934

935
            // If the DOM selection is properly unset, we're done.
936
            if (!selection && !hasDomSelection) {
15!
UNCOV
937
                return;
×
938
            }
939

940
            // If the DOM selection is already correct, we're done.
941
            // verify that the dom selection is in the editor
942
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
15✔
943
            let hasDomSelectionInEditor = false;
15✔
944
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
15✔
945
                hasDomSelectionInEditor = true;
1✔
946
            }
947

948
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
15✔
949
                return;
14✔
950
            }
951

952
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
953
                return;
×
954
            }
955

956
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
957
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
958
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
959
                    exactMatch: false,
960
                    suppressThrow: true
961
                });
962
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
963
                    return;
×
964
                }
965
            }
966

967
            // prevent updating native selection when active element is void element
968
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
969
                return;
×
970
            }
971

972
            // when <Editable/> is being controlled through external value
973
            // then its children might just change - DOM responds to it on its own
974
            // but Slate's value is not being updated through any operation
975
            // and thus it doesn't transform selection on its own
976
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
977
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
978
                return;
×
979
            }
980

981
            // Otherwise the DOM selection is out of sync, so update it.
982
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
983
            this.isUpdatingSelection = true;
1✔
984

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

987
            if (newDomRange) {
1!
988
                // COMPAT: Since the DOM range has no concept of backwards/forwards
989
                // we need to check and do the right thing here.
990
                if (Range.isBackward(selection)) {
1!
991
                    // eslint-disable-next-line max-len
992
                    domSelection.setBaseAndExtent(
×
993
                        newDomRange.endContainer,
994
                        newDomRange.endOffset,
995
                        newDomRange.startContainer,
996
                        newDomRange.startOffset
997
                    );
998
                } else {
999
                    // eslint-disable-next-line max-len
1000
                    domSelection.setBaseAndExtent(
1✔
1001
                        newDomRange.startContainer,
1002
                        newDomRange.startOffset,
1003
                        newDomRange.endContainer,
1004
                        newDomRange.endOffset
1005
                    );
1006
                }
1007
            } else {
1008
                domSelection.removeAllRanges();
×
1009
            }
1010

1011
            setTimeout(() => {
1✔
1012
                if (
1!
1013
                    this.isEnabledVirtualScroll() &&
1!
1014
                    !selection &&
1015
                    this.editor.selection &&
1016
                    autoScroll &&
1017
                    this.virtualScrollConfig.scrollContainer
1018
                ) {
1019
                    this.virtualScrollConfig.scrollContainer.scrollTop = this.virtualScrollConfig.scrollContainer.scrollTop + 100;
×
1020
                    this.isUpdatingSelection = false;
×
1021
                    return;
×
1022
                } else {
1023
                    // handle scrolling in setTimeout because of
1024
                    // dom should not have updated immediately after listRender's updating
1025
                    newDomRange && autoScroll && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
1026
                    // COMPAT: In Firefox, it's not enough to create a range, you also need
1027
                    // to focus the contenteditable element too. (2016/11/16)
1028
                    if (newDomRange && IS_FIREFOX) {
1!
1029
                        el.focus();
×
1030
                    }
1031
                }
1032
                this.isUpdatingSelection = false;
1✔
1033
            });
1034
        } catch (error) {
1035
            this.editor.onError({
×
1036
                code: SlateErrorCode.ToNativeSelectionError,
1037
                nativeError: error
1038
            });
1039
            this.isUpdatingSelection = false;
×
1040
        }
1041
    }
1042

1043
    onChange() {
1044
        this.forceRender();
13✔
1045
        this.onChangeCallback(this.editor.children);
13✔
1046
    }
1047

1048
    ngAfterViewChecked() {}
1049

1050
    ngDoCheck() {}
1051

1052
    forceRender() {
1053
        this.updateContext();
15✔
1054
        if (this.isEnabledVirtualScroll()) {
15!
NEW
1055
            this.updateListRenderAndRemeasureHeights('forceRender');
×
1056
        } else {
1057
            this.listRender.update(this.editor.children, this.editor, this.context);
15✔
1058
        }
1059
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
1060
        // when the DOMElement where the selection is located is removed
1061
        // the compositionupdate and compositionend events will no longer be fired
1062
        // so isComposing needs to be corrected
1063
        // need exec after this.cdr.detectChanges() to render HTML
1064
        // need exec before this.toNativeSelection() to correct native selection
1065
        if (this.isComposing) {
15!
1066
            // Composition input text be not rendered when user composition input with selection is expanded
1067
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
1068
            // this time condition is true and isComposing is assigned false
1069
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
1070
            setTimeout(() => {
×
1071
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
1072
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
1073
                let textContent = '';
×
1074
                // skip decorate text
1075
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
1076
                    let text = stringDOMNode.textContent;
×
1077
                    const zeroChar = '\uFEFF';
×
1078
                    // remove zero with char
1079
                    if (text.startsWith(zeroChar)) {
×
1080
                        text = text.slice(1);
×
1081
                    }
1082
                    if (text.endsWith(zeroChar)) {
×
1083
                        text = text.slice(0, text.length - 1);
×
1084
                    }
1085
                    textContent += text;
×
1086
                });
1087
                if (Node.string(textNode).endsWith(textContent)) {
×
1088
                    this.isComposing = false;
×
1089
                }
1090
            }, 0);
1091
        }
1092
        if (this.editor.selection && this.isSelectionInvisible(this.editor.selection)) {
15!
1093
            Transforms.deselect(this.editor);
×
1094
            return;
×
1095
        } else {
1096
            this.toNativeSelection();
15✔
1097
        }
1098
    }
1099

1100
    render() {
1101
        const changed = this.updateContext();
2✔
1102
        if (changed) {
2✔
1103
            if (this.isEnabledVirtualScroll()) {
2!
NEW
1104
                this.updateListRenderAndRemeasureHeights('render');
×
1105
            } else {
1106
                this.listRender.update(this.editor.children, this.editor, this.context);
2✔
1107
            }
1108
        }
1109
    }
1110

1111
    updateListRenderAndRemeasureHeights(origin: 'render' | 'forceRender') {
1112
        const operations = this.editor.operations;
×
1113
        const firstIndex = this.inViewportIndics[0];
×
1114
        const operationsOfFirstElementMerged = operations.filter(
×
1115
            op => op.type === 'merge_node' && op.path.length === 1 && firstIndex === op.path[0] - 1
×
1116
        );
1117
        const operationsOfFirstElementSplitted = operations.filter(
×
1118
            op => op.type === 'split_node' && op.path.length === 1 && firstIndex === op.path[0]
×
1119
        );
1120
        const mutationOfFirstElementHeight = operationsOfFirstElementSplitted.length > 0 || operationsOfFirstElementMerged.length > 0;
×
1121
        const visibleStates = this.editor.getAllVisibleStates();
×
1122
        const previousInViewportChildren = [...this.inViewportChildren];
×
1123
        // the first element height will reset to default height when split or merge
1124
        // if the most top content of the first element is not in viewport, the change of height will cause the viewport to scroll
1125
        // to keep viewport stable, we need to use the current inViewportIndics temporarily
1126
        if (mutationOfFirstElementHeight) {
×
1127
            const newInViewportIndics = [];
×
1128
            const newInViewportChildren = [];
×
1129
            this.inViewportIndics.forEach(index => {
×
1130
                const element = this.editor.children[index] as Element;
×
1131
                const isVisible = visibleStates[index];
×
1132
                if (isVisible) {
×
1133
                    newInViewportIndics.push(index);
×
1134
                    newInViewportChildren.push(element);
×
1135
                }
1136
            });
1137
            if (operationsOfFirstElementSplitted.length > 0) {
×
1138
                const lastIndex = newInViewportIndics[newInViewportIndics.length - 1];
×
1139
                for (let i = lastIndex + 1; i < this.editor.children.length; i++) {
×
1140
                    const element = this.editor.children[i] as Element;
×
1141
                    const isVisible = visibleStates[i];
×
1142
                    if (isVisible) {
×
1143
                        newInViewportIndics.push(i);
×
1144
                        newInViewportChildren.push(element);
×
1145
                        break;
×
1146
                    }
1147
                }
1148
            }
1149
            this.inViewportIndics = newInViewportIndics;
×
1150
            this.inViewportChildren = newInViewportChildren;
×
1151
        } else {
1152
            let virtualView = this.calculateVirtualViewport(visibleStates);
×
1153
            let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
1154
            if (diff.isDifferent && diff.needRemoveOnTop) {
×
1155
                const remeasureIndics = diff.changedIndexesOfTop;
×
1156
                const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
1157
                if (changed) {
×
1158
                    virtualView = this.calculateVirtualViewport(visibleStates);
×
1159
                    diff = this.diffVirtualViewport(virtualView, 'second');
×
1160
                }
1161
            }
1162
            this.applyVirtualView(virtualView);
×
1163
        }
1164
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } =
1165
            this.appendPreRenderingToViewport(visibleStates);
×
NEW
1166
        if (isDebugUpdate) {
×
NEW
1167
            debugLog('log', 'updateListRenderAndRemeasureHeights update list render', 'origin', origin);
×
1168
        }
1169
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
1170
        const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
1171
        if (remeasureIndics.length) {
×
1172
            this.indicsOfNeedRemeasured$.next({ indics: remeasureIndics, tryUpdateViewport: true });
×
1173
        }
1174
    }
1175

1176
    updateContext() {
1177
        const decorations = this.generateDecorations();
17✔
1178
        if (
17✔
1179
            this.context.selection !== this.editor.selection ||
46✔
1180
            this.context.decorate !== this.decorate ||
1181
            this.context.readonly !== this.readonly ||
1182
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
1183
        ) {
1184
            this.context = {
10✔
1185
                parent: this.editor,
1186
                selection: this.editor.selection,
1187
                decorations: decorations,
1188
                decorate: this.decorate,
1189
                readonly: this.readonly
1190
            };
1191
            return true;
10✔
1192
        }
1193
        return false;
7✔
1194
    }
1195

1196
    initializeContext() {
1197
        this.context = {
49✔
1198
            parent: this.editor,
1199
            selection: this.editor.selection,
1200
            decorations: this.generateDecorations(),
1201
            decorate: this.decorate,
1202
            readonly: this.readonly
1203
        };
1204
    }
1205

1206
    initializeViewContext() {
1207
        this.viewContext = {
23✔
1208
            editor: this.editor,
1209
            renderElement: this.renderElement,
1210
            renderLeaf: this.renderLeaf,
1211
            renderText: this.renderText,
1212
            trackBy: this.trackBy,
1213
            isStrictDecorate: this.isStrictDecorate
1214
        };
1215
    }
1216

1217
    composePlaceholderDecorate(editor: Editor) {
1218
        if (this.placeholderDecorate) {
64!
1219
            return this.placeholderDecorate(editor) || [];
×
1220
        }
1221

1222
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
1223
            const start = Editor.start(editor, []);
3✔
1224
            return [
3✔
1225
                {
1226
                    placeholder: this.placeholder,
1227
                    anchor: start,
1228
                    focus: start
1229
                }
1230
            ];
1231
        } else {
1232
            return [];
61✔
1233
        }
1234
    }
1235

1236
    generateDecorations() {
1237
        const decorations = this.decorate([this.editor, []]);
66✔
1238
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1239
        decorations.push(...placeholderDecorations);
66✔
1240
        return decorations;
66✔
1241
    }
1242

1243
    private toSlateSelection() {
1244
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1245
            try {
1✔
1246
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1247
                const { activeElement } = root;
1✔
1248
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1249
                const domSelection = (root as Document).getSelection();
1✔
1250

1251
                if (activeElement === el) {
1!
1252
                    this.latestElement = activeElement;
1✔
1253
                    IS_FOCUSED.set(this.editor, true);
1✔
1254
                } else {
1255
                    IS_FOCUSED.delete(this.editor);
×
1256
                }
1257

1258
                if (!domSelection) {
1!
1259
                    return Transforms.deselect(this.editor);
×
1260
                }
1261

1262
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1263
                const hasDomSelectionInEditor =
1264
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1265
                if (!hasDomSelectionInEditor) {
1!
1266
                    Transforms.deselect(this.editor);
×
1267
                    return;
×
1268
                }
1269

1270
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1271
                // for example, double-click the last cell of the table to select a non-editable DOM
1272
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1273
                if (range) {
1✔
1274
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1275
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1276
                            // force adjust DOMSelection
1277
                            this.toNativeSelection(false);
×
1278
                        }
1279
                    } else {
1280
                        Transforms.select(this.editor, range);
1✔
1281
                    }
1282
                }
1283
            } catch (error) {
1284
                this.editor.onError({
×
1285
                    code: SlateErrorCode.ToSlateSelectionError,
1286
                    nativeError: error
1287
                });
1288
            }
1289
        }
1290
    }
1291

1292
    private onDOMBeforeInput(
1293
        event: Event & {
1294
            inputType: string;
1295
            isComposing: boolean;
1296
            data: string | null;
1297
            dataTransfer: DataTransfer | null;
1298
            getTargetRanges(): DOMStaticRange[];
1299
        }
1300
    ) {
1301
        const editor = this.editor;
×
1302
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1303
        const { activeElement } = root;
×
1304
        const { selection } = editor;
×
1305
        const { inputType: type } = event;
×
1306
        const data = event.dataTransfer || event.data || undefined;
×
1307
        if (IS_ANDROID) {
×
1308
            let targetRange: Range | null = null;
×
1309
            let [nativeTargetRange] = event.getTargetRanges();
×
1310
            if (nativeTargetRange) {
×
1311
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1312
            }
1313
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1314
            // have to manually get the selection here to ensure it's up-to-date.
1315
            const window = AngularEditor.getWindow(editor);
×
1316
            const domSelection = window.getSelection();
×
1317
            if (!targetRange && domSelection) {
×
1318
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1319
            }
1320
            targetRange = targetRange ?? editor.selection;
×
1321
            if (type === 'insertCompositionText') {
×
1322
                if (data && data.toString().includes('\n')) {
×
1323
                    restoreDom(editor, () => {
×
1324
                        Editor.insertBreak(editor);
×
1325
                    });
1326
                } else {
1327
                    if (targetRange) {
×
1328
                        if (data) {
×
1329
                            restoreDom(editor, () => {
×
1330
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1331
                            });
1332
                        } else {
1333
                            restoreDom(editor, () => {
×
1334
                                Transforms.delete(editor, { at: targetRange });
×
1335
                            });
1336
                        }
1337
                    }
1338
                }
1339
                return;
×
1340
            }
1341
            if (type === 'deleteContentBackward') {
×
1342
                // gboard can not prevent default action, so must use restoreDom,
1343
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1344
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1345
                if (!Range.isCollapsed(targetRange)) {
×
1346
                    restoreDom(editor, () => {
×
1347
                        Transforms.delete(editor, { at: targetRange });
×
1348
                    });
1349
                    return;
×
1350
                }
1351
            }
1352
            if (type === 'insertText') {
×
1353
                restoreDom(editor, () => {
×
1354
                    if (typeof data === 'string') {
×
1355
                        Editor.insertText(editor, data);
×
1356
                    }
1357
                });
1358
                return;
×
1359
            }
1360
        }
1361
        if (
×
1362
            !this.readonly &&
×
1363
            AngularEditor.hasEditableTarget(editor, event.target) &&
1364
            !isTargetInsideVoid(editor, activeElement) &&
1365
            !this.isDOMEventHandled(event, this.beforeInput)
1366
        ) {
1367
            try {
×
1368
                event.preventDefault();
×
1369

1370
                // COMPAT: If the selection is expanded, even if the command seems like
1371
                // a delete forward/backward command it should delete the selection.
1372
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1373
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1374
                    Editor.deleteFragment(editor, { direction });
×
1375
                    return;
×
1376
                }
1377

1378
                switch (type) {
×
1379
                    case 'deleteByComposition':
1380
                    case 'deleteByCut':
1381
                    case 'deleteByDrag': {
1382
                        Editor.deleteFragment(editor);
×
1383
                        break;
×
1384
                    }
1385

1386
                    case 'deleteContent':
1387
                    case 'deleteContentForward': {
1388
                        Editor.deleteForward(editor);
×
1389
                        break;
×
1390
                    }
1391

1392
                    case 'deleteContentBackward': {
1393
                        Editor.deleteBackward(editor);
×
1394
                        break;
×
1395
                    }
1396

1397
                    case 'deleteEntireSoftLine': {
1398
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1399
                        Editor.deleteForward(editor, { unit: 'line' });
×
1400
                        break;
×
1401
                    }
1402

1403
                    case 'deleteHardLineBackward': {
1404
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1405
                        break;
×
1406
                    }
1407

1408
                    case 'deleteSoftLineBackward': {
1409
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1410
                        break;
×
1411
                    }
1412

1413
                    case 'deleteHardLineForward': {
1414
                        Editor.deleteForward(editor, { unit: 'block' });
×
1415
                        break;
×
1416
                    }
1417

1418
                    case 'deleteSoftLineForward': {
1419
                        Editor.deleteForward(editor, { unit: 'line' });
×
1420
                        break;
×
1421
                    }
1422

1423
                    case 'deleteWordBackward': {
1424
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1425
                        break;
×
1426
                    }
1427

1428
                    case 'deleteWordForward': {
1429
                        Editor.deleteForward(editor, { unit: 'word' });
×
1430
                        break;
×
1431
                    }
1432

1433
                    case 'insertLineBreak':
1434
                    case 'insertParagraph': {
1435
                        Editor.insertBreak(editor);
×
1436
                        break;
×
1437
                    }
1438

1439
                    case 'insertFromComposition': {
1440
                        // COMPAT: in safari, `compositionend` event is dispatched after
1441
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1442
                        // https://www.w3.org/TR/input-events-2/
1443
                        // so the following code is the right logic
1444
                        // because DOM selection in sync will be exec before `compositionend` event
1445
                        // isComposing is true will prevent DOM selection being update correctly.
1446
                        this.isComposing = false;
×
1447
                        preventInsertFromComposition(event, this.editor);
×
1448
                    }
1449
                    case 'insertFromDrop':
1450
                    case 'insertFromPaste':
1451
                    case 'insertFromYank':
1452
                    case 'insertReplacementText':
1453
                    case 'insertText': {
1454
                        // use a weak comparison instead of 'instanceof' to allow
1455
                        // programmatic access of paste events coming from external windows
1456
                        // like cypress where cy.window does not work realibly
1457
                        if (data?.constructor.name === 'DataTransfer') {
×
1458
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1459
                        } else if (typeof data === 'string') {
×
1460
                            Editor.insertText(editor, data);
×
1461
                        }
1462
                        break;
×
1463
                    }
1464
                }
1465
            } catch (error) {
1466
                this.editor.onError({
×
1467
                    code: SlateErrorCode.OnDOMBeforeInputError,
1468
                    nativeError: error
1469
                });
1470
            }
1471
        }
1472
    }
1473

1474
    private onDOMBlur(event: FocusEvent) {
1475
        if (
×
1476
            this.readonly ||
×
1477
            this.isUpdatingSelection ||
1478
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1479
            this.isDOMEventHandled(event, this.blur)
1480
        ) {
1481
            return;
×
1482
        }
1483

1484
        const window = AngularEditor.getWindow(this.editor);
×
1485

1486
        // COMPAT: If the current `activeElement` is still the previous
1487
        // one, this is due to the window being blurred when the tab
1488
        // itself becomes unfocused, so we want to abort early to allow to
1489
        // editor to stay focused when the tab becomes focused again.
1490
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1491
        if (this.latestElement === root.activeElement) {
×
1492
            return;
×
1493
        }
1494

1495
        const { relatedTarget } = event;
×
1496
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1497

1498
        // COMPAT: The event should be ignored if the focus is returning
1499
        // to the editor from an embedded editable element (eg. an <input>
1500
        // element inside a void node).
1501
        if (relatedTarget === el) {
×
1502
            return;
×
1503
        }
1504

1505
        // COMPAT: The event should be ignored if the focus is moving from
1506
        // the editor to inside a void node's spacer element.
1507
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1508
            return;
×
1509
        }
1510

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

1517
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1518
                return;
×
1519
            }
1520
        }
1521

1522
        IS_FOCUSED.delete(this.editor);
×
1523
    }
1524

1525
    private onDOMClick(event: MouseEvent) {
1526
        if (
×
1527
            !this.readonly &&
×
1528
            AngularEditor.hasTarget(this.editor, event.target) &&
1529
            !this.isDOMEventHandled(event, this.click) &&
1530
            isDOMNode(event.target)
1531
        ) {
1532
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1533
            const path = AngularEditor.findPath(this.editor, node);
×
1534
            const start = Editor.start(this.editor, path);
×
1535
            const end = Editor.end(this.editor, path);
×
1536

1537
            const startVoid = Editor.void(this.editor, { at: start });
×
1538
            const endVoid = Editor.void(this.editor, { at: end });
×
1539

1540
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1541
                let blockPath = path;
×
1542
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1543
                    const block = Editor.above(this.editor, {
×
1544
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1545
                        at: path
1546
                    });
1547

1548
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1549
                }
1550

1551
                const range = Editor.range(this.editor, blockPath);
×
1552
                Transforms.select(this.editor, range);
×
1553
                return;
×
1554
            }
1555

1556
            if (
×
1557
                startVoid &&
×
1558
                endVoid &&
1559
                Path.equals(startVoid[1], endVoid[1]) &&
1560
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1561
            ) {
1562
                const range = Editor.range(this.editor, start);
×
1563
                Transforms.select(this.editor, range);
×
1564
            }
1565
        }
1566
    }
1567

1568
    private onDOMCompositionStart(event: CompositionEvent) {
1569
        const { selection } = this.editor;
1✔
1570
        if (selection) {
1!
1571
            // solve the problem of cross node Chinese input
1572
            if (Range.isExpanded(selection)) {
×
1573
                Editor.deleteFragment(this.editor);
×
1574
                this.forceRender();
×
1575
            }
1576
        }
1577
        if (
1✔
1578
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
3✔
1579
            !isSelectionInsideVoid(this.editor) &&
1580
            !this.isDOMEventHandled(event, this.compositionStart)
1581
        ) {
1582
            this.isComposing = true;
1✔
1583
        }
1584
        this.render();
1✔
1585
    }
1586

1587
    private onDOMCompositionUpdate(event: CompositionEvent) {
1588
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1589
    }
1590

1591
    private onDOMCompositionEnd(event: CompositionEvent) {
1592
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1593
            Transforms.delete(this.editor);
×
1594
        }
1595
        if (
×
1596
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
×
1597
            !isSelectionInsideVoid(this.editor) &&
1598
            !this.isDOMEventHandled(event, this.compositionEnd)
1599
        ) {
1600
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1601
            // aren't correct and never fire the "insertFromComposition"
1602
            // type that we need. So instead, insert whenever a composition
1603
            // ends since it will already have been committed to the DOM.
1604
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1605
                preventInsertFromComposition(event, this.editor);
×
1606
                Editor.insertText(this.editor, event.data);
×
1607
            }
1608

1609
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1610
            // so we need avoid repeat insertText by isComposing === true,
1611
            this.isComposing = false;
×
1612
        }
1613
        this.render();
×
1614
    }
1615

1616
    private onDOMCopy(event: ClipboardEvent) {
1617
        const window = AngularEditor.getWindow(this.editor);
×
1618
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1619
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1620
            event.preventDefault();
×
1621
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1622
        }
1623
    }
1624

1625
    private onDOMCut(event: ClipboardEvent) {
1626
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1627
            event.preventDefault();
×
1628
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1629
            const { selection } = this.editor;
×
1630

1631
            if (selection) {
×
1632
                AngularEditor.deleteCutData(this.editor);
×
1633
            }
1634
        }
1635
    }
1636

1637
    private onDOMDragOver(event: DragEvent) {
1638
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1639
            // Only when the target is void, call `preventDefault` to signal
1640
            // that drops are allowed. Editable content is droppable by
1641
            // default, and calling `preventDefault` hides the cursor.
1642
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1643

1644
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1645
                event.preventDefault();
×
1646
            }
1647
        }
1648
    }
1649

1650
    private onDOMDragStart(event: DragEvent) {
1651
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1652
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1653
            const path = AngularEditor.findPath(this.editor, node);
×
1654
            const voidMatch =
1655
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1656

1657
            // If starting a drag on a void node, make sure it is selected
1658
            // so that it shows up in the selection's fragment.
1659
            if (voidMatch) {
×
1660
                const range = Editor.range(this.editor, path);
×
1661
                Transforms.select(this.editor, range);
×
1662
            }
1663

1664
            this.isDraggingInternally = true;
×
1665

1666
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1667
        }
1668
    }
1669

1670
    private onDOMDrop(event: DragEvent) {
1671
        const editor = this.editor;
×
1672
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1673
            event.preventDefault();
×
1674
            // Keep a reference to the dragged range before updating selection
1675
            const draggedRange = editor.selection;
×
1676

1677
            // Find the range where the drop happened
1678
            const range = AngularEditor.findEventRange(editor, event);
×
1679
            const data = event.dataTransfer;
×
1680

1681
            Transforms.select(editor, range);
×
1682

1683
            if (this.isDraggingInternally) {
×
1684
                if (draggedRange) {
×
1685
                    Transforms.delete(editor, {
×
1686
                        at: draggedRange
1687
                    });
1688
                }
1689

1690
                this.isDraggingInternally = false;
×
1691
            }
1692

1693
            AngularEditor.insertData(editor, data);
×
1694

1695
            // When dragging from another source into the editor, it's possible
1696
            // that the current editor does not have focus.
1697
            if (!AngularEditor.isFocused(editor)) {
×
1698
                AngularEditor.focus(editor);
×
1699
            }
1700
        }
1701
    }
1702

1703
    private onDOMDragEnd(event: DragEvent) {
1704
        if (
×
1705
            !this.readonly &&
×
1706
            this.isDraggingInternally &&
1707
            AngularEditor.hasTarget(this.editor, event.target) &&
1708
            !this.isDOMEventHandled(event, this.dragEnd)
1709
        ) {
1710
            this.isDraggingInternally = false;
×
1711
        }
1712
    }
1713

1714
    private onDOMFocus(event: Event) {
1715
        if (
2✔
1716
            !this.readonly &&
8✔
1717
            !this.isUpdatingSelection &&
1718
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1719
            !this.isDOMEventHandled(event, this.focus)
1720
        ) {
1721
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1722
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1723
            this.latestElement = root.activeElement;
2✔
1724

1725
            // COMPAT: If the editor has nested editable elements, the focus
1726
            // can go to them. In Firefox, this must be prevented because it
1727
            // results in issues with keyboard navigation. (2017/03/30)
1728
            if (IS_FIREFOX && event.target !== el) {
2!
1729
                el.focus();
×
1730
                return;
×
1731
            }
1732

1733
            IS_FOCUSED.set(this.editor, true);
2✔
1734
        }
1735
    }
1736

1737
    private onDOMKeydown(event: KeyboardEvent) {
1738
        const editor = this.editor;
×
1739
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1740
        const { activeElement } = root;
×
1741
        if (
×
1742
            !this.readonly &&
×
1743
            AngularEditor.hasEditableTarget(editor, event.target) &&
1744
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1745
            !this.isComposing &&
1746
            !this.isDOMEventHandled(event, this.keydown)
1747
        ) {
1748
            const nativeEvent = event;
×
1749
            const { selection } = editor;
×
1750

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

1754
            try {
×
1755
                // COMPAT: Since we prevent the default behavior on
1756
                // `beforeinput` events, the browser doesn't think there's ever
1757
                // any history stack to undo or redo, so we have to manage these
1758
                // hotkeys ourselves. (2019/11/06)
1759
                if (Hotkeys.isRedo(nativeEvent)) {
×
1760
                    event.preventDefault();
×
1761

1762
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1763
                        editor.redo();
×
1764
                    }
1765

1766
                    return;
×
1767
                }
1768

1769
                if (Hotkeys.isUndo(nativeEvent)) {
×
1770
                    event.preventDefault();
×
1771

1772
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1773
                        editor.undo();
×
1774
                    }
1775

1776
                    return;
×
1777
                }
1778

1779
                // COMPAT: Certain browsers don't handle the selection updates
1780
                // properly. In Chrome, the selection isn't properly extended.
1781
                // And in Firefox, the selection isn't properly collapsed.
1782
                // (2017/10/17)
1783
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1784
                    event.preventDefault();
×
1785
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1786
                    return;
×
1787
                }
1788

1789
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1790
                    event.preventDefault();
×
1791
                    Transforms.move(editor, { unit: 'line' });
×
1792
                    return;
×
1793
                }
1794

1795
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1796
                    event.preventDefault();
×
1797
                    Transforms.move(editor, {
×
1798
                        unit: 'line',
1799
                        edge: 'focus',
1800
                        reverse: true
1801
                    });
1802
                    return;
×
1803
                }
1804

1805
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1806
                    event.preventDefault();
×
1807
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1808
                    return;
×
1809
                }
1810

1811
                // COMPAT: If a void node is selected, or a zero-width text node
1812
                // adjacent to an inline is selected, we need to handle these
1813
                // hotkeys manually because browsers won't be able to skip over
1814
                // the void node with the zero-width space not being an empty
1815
                // string.
1816
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1817
                    event.preventDefault();
×
1818

1819
                    if (selection && Range.isCollapsed(selection)) {
×
1820
                        Transforms.move(editor, { reverse: !isRTL });
×
1821
                    } else {
1822
                        Transforms.collapse(editor, { edge: 'start' });
×
1823
                    }
1824

1825
                    return;
×
1826
                }
1827

1828
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1829
                    event.preventDefault();
×
1830
                    if (selection && Range.isCollapsed(selection)) {
×
1831
                        Transforms.move(editor, { reverse: isRTL });
×
1832
                    } else {
1833
                        Transforms.collapse(editor, { edge: 'end' });
×
1834
                    }
1835

1836
                    return;
×
1837
                }
1838

1839
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1840
                    event.preventDefault();
×
1841

1842
                    if (selection && Range.isExpanded(selection)) {
×
1843
                        Transforms.collapse(editor, { edge: 'focus' });
×
1844
                    }
1845

1846
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1847
                    return;
×
1848
                }
1849

1850
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1851
                    event.preventDefault();
×
1852

1853
                    if (selection && Range.isExpanded(selection)) {
×
1854
                        Transforms.collapse(editor, { edge: 'focus' });
×
1855
                    }
1856

1857
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1858
                    return;
×
1859
                }
1860

1861
                if (isKeyHotkey('mod+a', event)) {
×
1862
                    this.editor.selectAll();
×
1863
                    event.preventDefault();
×
1864
                    return;
×
1865
                }
1866

1867
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1868
                // fall back to guessing at the input intention for hotkeys.
1869
                // COMPAT: In iOS, some of these hotkeys are handled in the
1870
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1871
                    // We don't have a core behavior for these, but they change the
1872
                    // DOM if we don't prevent them, so we have to.
1873
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1874
                        event.preventDefault();
×
1875
                        return;
×
1876
                    }
1877

1878
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1879
                        event.preventDefault();
×
1880
                        Editor.insertBreak(editor);
×
1881
                        return;
×
1882
                    }
1883

1884
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1885
                        event.preventDefault();
×
1886

1887
                        if (selection && Range.isExpanded(selection)) {
×
1888
                            Editor.deleteFragment(editor, {
×
1889
                                direction: 'backward'
1890
                            });
1891
                        } else {
1892
                            Editor.deleteBackward(editor);
×
1893
                        }
1894

1895
                        return;
×
1896
                    }
1897

1898
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1899
                        event.preventDefault();
×
1900

1901
                        if (selection && Range.isExpanded(selection)) {
×
1902
                            Editor.deleteFragment(editor, {
×
1903
                                direction: 'forward'
1904
                            });
1905
                        } else {
1906
                            Editor.deleteForward(editor);
×
1907
                        }
1908

1909
                        return;
×
1910
                    }
1911

1912
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1913
                        event.preventDefault();
×
1914

1915
                        if (selection && Range.isExpanded(selection)) {
×
1916
                            Editor.deleteFragment(editor, {
×
1917
                                direction: 'backward'
1918
                            });
1919
                        } else {
1920
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1921
                        }
1922

1923
                        return;
×
1924
                    }
1925

1926
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1927
                        event.preventDefault();
×
1928

1929
                        if (selection && Range.isExpanded(selection)) {
×
1930
                            Editor.deleteFragment(editor, {
×
1931
                                direction: 'forward'
1932
                            });
1933
                        } else {
1934
                            Editor.deleteForward(editor, { unit: 'line' });
×
1935
                        }
1936

1937
                        return;
×
1938
                    }
1939

1940
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1941
                        event.preventDefault();
×
1942

1943
                        if (selection && Range.isExpanded(selection)) {
×
1944
                            Editor.deleteFragment(editor, {
×
1945
                                direction: 'backward'
1946
                            });
1947
                        } else {
1948
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1949
                        }
1950

1951
                        return;
×
1952
                    }
1953

1954
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1955
                        event.preventDefault();
×
1956

1957
                        if (selection && Range.isExpanded(selection)) {
×
1958
                            Editor.deleteFragment(editor, {
×
1959
                                direction: 'forward'
1960
                            });
1961
                        } else {
1962
                            Editor.deleteForward(editor, { unit: 'word' });
×
1963
                        }
1964

1965
                        return;
×
1966
                    }
1967
                } else {
1968
                    if (IS_CHROME || IS_SAFARI) {
×
1969
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1970
                        // an event when deleting backwards in a selected void inline node
1971
                        if (
×
1972
                            selection &&
×
1973
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1974
                            Range.isCollapsed(selection)
1975
                        ) {
1976
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1977
                            if (
×
1978
                                Element.isElement(currentNode) &&
×
1979
                                Editor.isVoid(editor, currentNode) &&
1980
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1981
                            ) {
1982
                                event.preventDefault();
×
1983
                                Editor.deleteBackward(editor, {
×
1984
                                    unit: 'block'
1985
                                });
1986
                                return;
×
1987
                            }
1988
                        }
1989
                    }
1990
                }
1991
            } catch (error) {
1992
                this.editor.onError({
×
1993
                    code: SlateErrorCode.OnDOMKeydownError,
1994
                    nativeError: error
1995
                });
1996
            }
1997
        }
1998
    }
1999

2000
    private onDOMPaste(event: ClipboardEvent) {
2001
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
2002
        // fall back to React's `onPaste` here instead.
2003
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
2004
        // when "paste without formatting" option is used.
2005
        // This unfortunately needs to be handled with paste events instead.
2006
        if (
×
2007
            !this.isDOMEventHandled(event, this.paste) &&
×
2008
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
2009
            !this.readonly &&
2010
            AngularEditor.hasEditableTarget(this.editor, event.target)
2011
        ) {
2012
            event.preventDefault();
×
2013
            AngularEditor.insertData(this.editor, event.clipboardData);
×
2014
        }
2015
    }
2016

2017
    private onFallbackBeforeInput(event: BeforeInputEvent) {
2018
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
2019
        // fall back to React's leaky polyfill instead just for it. It
2020
        // only works for the `insertText` input type.
2021
        if (
×
2022
            !HAS_BEFORE_INPUT_SUPPORT &&
×
2023
            !this.readonly &&
2024
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
2025
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
2026
        ) {
2027
            event.nativeEvent.preventDefault();
×
2028
            try {
×
2029
                const text = event.data;
×
2030
                if (!Range.isCollapsed(this.editor.selection)) {
×
2031
                    Editor.deleteFragment(this.editor);
×
2032
                }
2033
                // just handle Non-IME input
2034
                if (!this.isComposing) {
×
2035
                    Editor.insertText(this.editor, text);
×
2036
                }
2037
            } catch (error) {
2038
                this.editor.onError({
×
2039
                    code: SlateErrorCode.ToNativeSelectionError,
2040
                    nativeError: error
2041
                });
2042
            }
2043
        }
2044
    }
2045

2046
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
2047
        if (!handler) {
3✔
2048
            return false;
3✔
2049
        }
2050
        handler(event);
×
2051
        return event.defaultPrevented;
×
2052
    }
2053
    //#endregion
2054

2055
    ngOnDestroy() {
2056
        this.editorResizeObserver?.disconnect();
22✔
2057
        this.editorScrollContainerResizeObserver?.disconnect();
22✔
2058
        NODE_TO_ELEMENT.delete(this.editor);
22✔
2059
        this.manualListeners.forEach(manualListener => {
22✔
2060
            manualListener();
462✔
2061
        });
2062
        this.destroy$.complete();
22✔
2063
        EDITOR_TO_ON_CHANGE.delete(this.editor);
22✔
2064
    }
2065
}
2066

2067
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
2068
    // This was affecting the selection of multiple blocks and dragging behavior,
2069
    // so enabled only if the selection has been collapsed.
2070
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
2071
        const leafEl = domRange.startContainer.parentElement!;
×
2072

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

2078
        if (isZeroDimensionRect) {
×
2079
            const leafRect = leafEl.getBoundingClientRect();
×
2080
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2081

2082
            if (leafHasDimensions) {
×
2083
                return;
×
2084
            }
2085
        }
2086

2087
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
2088
        scrollIntoView(leafEl, {
×
2089
            scrollMode: 'if-needed'
2090
        });
2091
        delete leafEl.getBoundingClientRect;
×
2092
    }
2093
};
2094

2095
/**
2096
 * Check if the target is inside void and in the editor.
2097
 */
2098

2099
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
2100
    let slateNode: Node | null = null;
1✔
2101
    try {
1✔
2102
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
2103
    } catch (error) {}
2104
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
2105
};
2106

2107
export const isSelectionInsideVoid = (editor: AngularEditor) => {
1✔
2108
    const selection = editor.selection;
1✔
2109
    if (selection && Range.isCollapsed(selection)) {
1!
2110
        const currentNode = Node.parent(editor, selection.anchor.path);
×
2111
        return Element.isElement(currentNode) && Editor.isVoid(editor, currentNode);
×
2112
    }
2113
    return false;
1✔
2114
};
2115

2116
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
2117
    return (
2✔
2118
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
2119
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
2120
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
2121
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
2122
    );
2123
};
2124

2125
/**
2126
 * remove default insert from composition
2127
 * @param text
2128
 */
2129
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2130
    const types = ['compositionend', 'insertFromComposition'];
×
2131
    if (!types.includes(event.type)) {
×
2132
        return;
×
2133
    }
2134
    const insertText = (event as CompositionEvent).data;
×
2135
    const window = AngularEditor.getWindow(editor);
×
2136
    const domSelection = window.getSelection();
×
2137
    // ensure text node insert composition input text
2138
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2139
        const textNode = domSelection.anchorNode;
×
2140
        textNode.splitText(textNode.length - insertText.length).remove();
×
2141
    }
2142
};
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