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

worktile / slate-angular / f1984220-d35a-4dbe-bde8-8f986a7e029e

31 Mar 2026 03:08AM UTC coverage: 35.45% (-0.05%) from 35.497%
f1984220-d35a-4dbe-bde8-8f986a7e029e

push

circleci

pubuzhixing8
build: bump angular 21 (#334)

* build: bump angular 21

* build: bump angular version to 21.1.2

* chore: pre enter next

---------

Co-authored-by: pubuzhixing8 <pubuzhixing@gmail.com>

407 of 1361 branches covered (29.9%)

Branch coverage included in aggregate %.

6 of 6 new or added lines in 2 files covered. (100.0%)

1 existing line in 1 file now uncovered.

1128 of 2969 relevant lines covered (37.99%)

22.64 hits per line

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

21.44
/packages/src/components/editable/editable.component.ts
1
import {
2
    AfterViewChecked,
3
    ChangeDetectionStrategy,
4
    ChangeDetectorRef,
5
    Component,
6
    DoCheck,
7
    ElementRef,
8
    forwardRef,
9
    HostBinding,
10
    inject,
11
    Injector,
12
    Input,
13
    NgZone,
14
    OnChanges,
15
    OnDestroy,
16
    OnInit,
17
    Renderer2,
18
    SimpleChanges,
19
    ViewContainerRef
20
} from '@angular/core';
21
import { NG_VALUE_ACCESSOR } from '@angular/forms';
22
import { direction } from 'direction';
23
import { isKeyHotkey } from 'is-hotkey';
24
import { debounceTime, filter, Subject, tap } from 'rxjs';
25
import scrollIntoView from 'scroll-into-view-if-needed';
26
import { Descendant, Editor, Element, Node, NodeEntry, Path, Range, Selection, Text as SlateText, Transforms } from 'slate';
27
import {
28
    DOMElement,
29
    DOMRange,
30
    DOMSelection,
31
    DOMStaticRange,
32
    EDITOR_TO_ELEMENT,
33
    EDITOR_TO_ON_CHANGE,
34
    EDITOR_TO_WINDOW,
35
    ELEMENT_TO_NODE,
36
    getDefaultView,
37
    IS_FOCUSED,
38
    IS_READ_ONLY,
39
    isDOMElement,
40
    isDOMNode,
41
    isPlainTextOnlyPaste,
42
    NODE_TO_ELEMENT,
43
    TRIPLE_CLICK
44
} from 'slate-dom';
45
import { HistoryEditor } from 'slate-history';
46
import { BeforeInputEvent, extractBeforeInputEvent } from '../../custom-event/BeforeInputEventPlugin';
47
import { BEFORE_INPUT_EVENTS } from '../../custom-event/before-input-polyfill';
48
import { AngularEditor } from '../../plugins/angular-editor';
49
import { SlateVirtualScrollConfig, VirtualViewResult } from '../../types';
50
import { SlateErrorCode } from '../../types/error';
51
import { SlatePlaceholder } from '../../types/feature';
52
import { ViewType } from '../../types/view';
53
import {
54
    buildHeightsAndAccumulatedHeights,
55
    EDITOR_TO_VIRTUAL_SCROLL_SELECTION,
56
    ELEMENT_KEY_TO_HEIGHTS,
57
    getBusinessTop,
58
    isDebug,
59
    isDebugScrollTop,
60
    isDecoratorRangeListEqual,
61
    measureHeightByIndics,
62
    roundTo
63
} from '../../utils';
64
import { HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID, IS_CHROME, IS_FIREFOX, IS_SAFARI } from '../../utils/environment';
65
import Hotkeys from '../../utils/hotkeys';
66
import { restoreDom } from '../../utils/restore-dom';
67
import {
68
    calcBusinessTop,
69
    calculateAccumulatedTopHeight,
70
    debugLog,
71
    EDITOR_TO_IS_FROM_SCROLL_TO,
72
    EDITOR_TO_ROOT_NODE_WIDTH,
73
    EDITOR_TO_VIEWPORT_HEIGHT,
74
    EDITOR_TO_VIRTUAL_SCROLL_CONFIG,
75
    getCachedHeightByElement,
76
    getViewportHeight,
77
    isDebugUpdate,
78
    VIRTUAL_BOTTOM_HEIGHT_CLASS_NAME,
79
    VIRTUAL_CENTER_OUTLET_CLASS_NAME,
80
    VIRTUAL_TOP_HEIGHT_CLASS_NAME
81
} from '../../utils/virtual-scroll';
82
import { SlateChildrenContext, SlateViewContext } from '../../view/context';
83
import { ListRender, updatePreRenderingElementWidth } from '../../view/render/list-render';
84

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

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

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

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

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

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

127
    private initialized: boolean;
128

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

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

133
    @Input() editor: AngularEditor;
134

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

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

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

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

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

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

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

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

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

153
    @Input() placeholder: string;
154

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

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

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

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

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

199
    viewContainerRef = inject(ViewContainerRef);
23✔
200

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

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

213
    listRender: ListRender;
214

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

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

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

230
    virtualScrollInitialized = false;
23✔
231

232
    virtualTopHeightElement: HTMLElement;
233

234
    virtualBottomHeightElement: HTMLElement;
235

236
    virtualCenterOutlet: HTMLElement;
237

238
    elementRef = inject(ElementRef);
23✔
239
    renderer2 = inject(Renderer2);
23✔
240
    cdr = inject(ChangeDetectorRef);
23✔
241
    ngZone = inject(NgZone);
23✔
242
    injector = inject(Injector);
23✔
243

244
    constructor() {}
245

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

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

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

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

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

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

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

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

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

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

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

495
    getActualVirtualTopHeight() {
496
        if (!this.virtualScrollInitialized) {
×
497
            return 0;
×
498
        }
499
        const rect = this.virtualTopHeightElement.getBoundingClientRect();
×
500
        return roundTo(rect.height, 1);
×
501
    }
502

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

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

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

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

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

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

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

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

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

920
    toNativeSelection(autoScroll = true) {
15✔
921
        try {
15✔
922
            let { selection } = this.editor;
15✔
923

924
            if (this.isEnabledVirtualScroll()) {
15!
925
                selection = this.calculateVirtualScrollSelection(selection);
×
926
            }
927

928
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
929
            const { activeElement } = root;
15✔
930
            const domSelection = (root as Document).getSelection();
15✔
931

932
            if ((this.isComposing && !IS_ANDROID) || !domSelection) {
15!
933
                return;
×
934
            }
935

936
            const hasDomSelection = domSelection.type !== 'None';
15✔
937

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

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

951
            if (!hasDomSelectionInEditor && !AngularEditor.isFocused(this.editor)) {
15✔
952
                return;
14✔
953
            }
954

955
            if (AngularEditor.isReadOnly(this.editor) && (!selection || Range.isCollapsed(selection))) {
1!
956
                return;
×
957
            }
958

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

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

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

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

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

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

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

1046
    onChange() {
1047
        this.forceRender();
13✔
1048
        this.onChangeCallback(this.editor.children);
13✔
1049
    }
1050

1051
    ngAfterViewChecked() {}
1052

1053
    ngDoCheck() {}
1054

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

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

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

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

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

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

1220
    composePlaceholderDecorate(editor: Editor) {
1221
        if (this.placeholderDecorate) {
64!
1222
            return this.placeholderDecorate(editor) || [];
×
1223
        }
1224

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

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

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

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

1261
                if (!domSelection) {
1!
1262
                    return Transforms.deselect(this.editor);
×
1263
                }
1264

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

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

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

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

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

1389
                    case 'deleteContent':
1390
                    case 'deleteContentForward': {
1391
                        Editor.deleteForward(editor);
×
1392
                        break;
×
1393
                    }
1394

1395
                    case 'deleteContentBackward': {
1396
                        Editor.deleteBackward(editor);
×
1397
                        break;
×
1398
                    }
1399

1400
                    case 'deleteEntireSoftLine': {
1401
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1402
                        Editor.deleteForward(editor, { unit: 'line' });
×
1403
                        break;
×
1404
                    }
1405

1406
                    case 'deleteHardLineBackward': {
1407
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1408
                        break;
×
1409
                    }
1410

1411
                    case 'deleteSoftLineBackward': {
1412
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1413
                        break;
×
1414
                    }
1415

1416
                    case 'deleteHardLineForward': {
1417
                        Editor.deleteForward(editor, { unit: 'block' });
×
1418
                        break;
×
1419
                    }
1420

1421
                    case 'deleteSoftLineForward': {
1422
                        Editor.deleteForward(editor, { unit: 'line' });
×
1423
                        break;
×
1424
                    }
1425

1426
                    case 'deleteWordBackward': {
1427
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1428
                        break;
×
1429
                    }
1430

1431
                    case 'deleteWordForward': {
1432
                        Editor.deleteForward(editor, { unit: 'word' });
×
1433
                        break;
×
1434
                    }
1435

1436
                    case 'insertLineBreak':
1437
                    case 'insertParagraph': {
1438
                        Editor.insertBreak(editor);
×
1439
                        break;
×
1440
                    }
1441

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

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

1487
        const window = AngularEditor.getWindow(this.editor);
×
1488

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

1498
        const { relatedTarget } = event;
×
1499
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1500

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

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

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

1520
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1521
                return;
×
1522
            }
1523
        }
1524

1525
        IS_FOCUSED.delete(this.editor);
×
1526
    }
1527

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

1540
            const startVoid = Editor.void(this.editor, { at: start });
×
1541
            const endVoid = Editor.void(this.editor, { at: end });
×
1542

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

1551
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1552
                }
1553

1554
                const range = Editor.range(this.editor, blockPath);
×
1555
                Transforms.select(this.editor, range);
×
1556
                return;
×
1557
            }
1558

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

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

1590
    private onDOMCompositionUpdate(event: CompositionEvent) {
1591
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1592
    }
1593

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

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

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

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

1634
            if (selection) {
×
1635
                AngularEditor.deleteCutData(this.editor);
×
1636
            }
1637
        }
1638
    }
1639

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

1647
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1648
                event.preventDefault();
×
1649
            }
1650
        }
1651
    }
1652

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

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

1667
            this.isDraggingInternally = true;
×
1668

1669
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1670
        }
1671
    }
1672

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

1680
            // Find the range where the drop happened
1681
            const range = AngularEditor.findEventRange(editor, event);
×
1682
            const data = event.dataTransfer;
×
1683

1684
            Transforms.select(editor, range);
×
1685

1686
            if (this.isDraggingInternally) {
×
1687
                if (draggedRange) {
×
1688
                    Transforms.delete(editor, {
×
1689
                        at: draggedRange
1690
                    });
1691
                }
1692

1693
                this.isDraggingInternally = false;
×
1694
            }
1695

1696
            AngularEditor.insertData(editor, data);
×
1697

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

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

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

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

1736
            IS_FOCUSED.set(this.editor, true);
2✔
1737
        }
1738
    }
1739

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

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

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

1765
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1766
                        editor.redo();
×
1767
                    }
1768

1769
                    return;
×
1770
                }
1771

1772
                if (Hotkeys.isUndo(nativeEvent)) {
×
1773
                    event.preventDefault();
×
1774

1775
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1776
                        editor.undo();
×
1777
                    }
1778

1779
                    return;
×
1780
                }
1781

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

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

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

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

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

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

1828
                    return;
×
1829
                }
1830

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

1839
                    return;
×
1840
                }
1841

1842
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1843
                    event.preventDefault();
×
1844

1845
                    if (selection && Range.isExpanded(selection)) {
×
1846
                        Transforms.collapse(editor, { edge: 'focus' });
×
1847
                    }
1848

1849
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1850
                    return;
×
1851
                }
1852

1853
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1854
                    event.preventDefault();
×
1855

1856
                    if (selection && Range.isExpanded(selection)) {
×
1857
                        Transforms.collapse(editor, { edge: 'focus' });
×
1858
                    }
1859

1860
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1861
                    return;
×
1862
                }
1863

1864
                if (isKeyHotkey('mod+a', event)) {
×
1865
                    this.editor.selectAll();
×
1866
                    event.preventDefault();
×
1867
                    return;
×
1868
                }
1869

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

1881
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1882
                        event.preventDefault();
×
1883
                        Editor.insertBreak(editor);
×
1884
                        return;
×
1885
                    }
1886

1887
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1888
                        event.preventDefault();
×
1889

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

1898
                        return;
×
1899
                    }
1900

1901
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1902
                        event.preventDefault();
×
1903

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

1912
                        return;
×
1913
                    }
1914

1915
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1916
                        event.preventDefault();
×
1917

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

1926
                        return;
×
1927
                    }
1928

1929
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1930
                        event.preventDefault();
×
1931

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

1940
                        return;
×
1941
                    }
1942

1943
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1944
                        event.preventDefault();
×
1945

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

1954
                        return;
×
1955
                    }
1956

1957
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1958
                        event.preventDefault();
×
1959

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

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

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

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

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

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

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

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

2081
        if (isZeroDimensionRect) {
×
2082
            const leafRect = leafEl.getBoundingClientRect();
×
2083
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
2084

2085
            if (leafHasDimensions) {
×
2086
                return;
×
2087
            }
2088
        }
2089

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

2098
/**
2099
 * Check if the target is inside void and in the editor.
2100
 */
2101

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

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

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

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