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

worktile / slate-angular / 03a62070-3530-44c6-af12-6f826940b4bb

26 Jan 2026 07:07AM UTC coverage: 36.06%. Remained the same
03a62070-3530-44c6-af12-6f826940b4bb

push

circleci

pubuzhixing8
refactor(virtual-scroll): editable codes position

402 of 1319 branches covered (30.48%)

Branch coverage included in aggregate %.

71 of 365 new or added lines in 1 file covered. (19.45%)

1 existing line in 1 file now uncovered.

1110 of 2874 relevant lines covered (38.62%)

23.3 hits per line

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

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

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

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

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

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

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

114
    private initialized: boolean;
115

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

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

120
    @Input() editor: AngularEditor;
121

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

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

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

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

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

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

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

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

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

140
    @Input() placeholder: string;
141

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

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

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

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

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

186
    viewContainerRef = inject(ViewContainerRef);
23✔
187

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

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

200
    listRender: ListRender;
201

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

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

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

218
    virtualScrollInitialized = false;
23✔
219

220
    virtualTopHeightElement: HTMLElement;
221

222
    virtualBottomHeightElement: HTMLElement;
223

224
    virtualCenterOutlet: HTMLElement;
225

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

872
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
873
                return;
14✔
874
            }
875

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

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

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

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

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

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

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

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

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

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

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

983
    ngAfterViewChecked() {}
984

985
    ngDoCheck() {}
986

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

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

1046
    updateListRenderAndRemeasureHeights() {
NEW
1047
        const visibleStates = this.editor.getAllVisibleStates();
×
NEW
1048
        const previousInViewportChildren = [...this.inViewportChildren];
×
NEW
1049
        let virtualView = this.calculateVirtualViewport(visibleStates);
×
NEW
1050
        let diff = this.diffVirtualViewport(virtualView, 'onChange');
×
NEW
1051
        if (diff.isDifferent && diff.needRemoveOnTop) {
×
NEW
1052
            const remeasureIndics = diff.changedIndexesOfTop;
×
NEW
1053
            const changed = measureHeightByIndics(this.editor, remeasureIndics);
×
NEW
1054
            if (changed) {
×
NEW
1055
                virtualView = this.calculateVirtualViewport(visibleStates);
×
NEW
1056
                diff = this.diffVirtualViewport(virtualView, 'second');
×
1057
            }
1058
        }
NEW
1059
        this.applyVirtualView(virtualView);
×
NEW
1060
        const { preRenderingCount, childrenWithPreRendering, childrenWithPreRenderingIndics } = this.handlePreRendering(visibleStates);
×
NEW
1061
        this.listRender.update(childrenWithPreRendering, this.editor, this.context, preRenderingCount, childrenWithPreRenderingIndics);
×
NEW
1062
        const remeasureIndics = this.getChangedIndics(previousInViewportChildren);
×
NEW
1063
        if (remeasureIndics.length) {
×
NEW
1064
            this.indicsOfNeedBeMeasured$.next(remeasureIndics);
×
1065
        }
1066
    }
1067

1068
    updateContext() {
1069
        const decorations = this.generateDecorations();
17✔
1070
        if (
17✔
1071
            this.context.selection !== this.editor.selection ||
46✔
1072
            this.context.decorate !== this.decorate ||
1073
            this.context.readonly !== this.readonly ||
1074
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
1075
        ) {
1076
            this.context = {
10✔
1077
                parent: this.editor,
1078
                selection: this.editor.selection,
1079
                decorations: decorations,
1080
                decorate: this.decorate,
1081
                readonly: this.readonly
1082
            };
1083
            return true;
10✔
1084
        }
1085
        return false;
7✔
1086
    }
1087

1088
    initializeContext() {
1089
        this.context = {
49✔
1090
            parent: this.editor,
1091
            selection: this.editor.selection,
1092
            decorations: this.generateDecorations(),
1093
            decorate: this.decorate,
1094
            readonly: this.readonly
1095
        };
1096
    }
1097

1098
    initializeViewContext() {
1099
        this.viewContext = {
23✔
1100
            editor: this.editor,
1101
            renderElement: this.renderElement,
1102
            renderLeaf: this.renderLeaf,
1103
            renderText: this.renderText,
1104
            trackBy: this.trackBy,
1105
            isStrictDecorate: this.isStrictDecorate
1106
        };
1107
    }
1108

1109
    composePlaceholderDecorate(editor: Editor) {
1110
        if (this.placeholderDecorate) {
64!
NEW
1111
            return this.placeholderDecorate(editor) || [];
×
1112
        }
1113

1114
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
1115
            const start = Editor.start(editor, []);
3✔
1116
            return [
3✔
1117
                {
1118
                    placeholder: this.placeholder,
1119
                    anchor: start,
1120
                    focus: start
1121
                }
1122
            ];
1123
        } else {
1124
            return [];
61✔
1125
        }
1126
    }
1127

1128
    generateDecorations() {
1129
        const decorations = this.decorate([this.editor, []]);
66✔
1130
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
1131
        decorations.push(...placeholderDecorations);
66✔
1132
        return decorations;
66✔
1133
    }
1134

1135
    private toSlateSelection() {
1136
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
1137
            try {
1✔
1138
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
1139
                const { activeElement } = root;
1✔
1140
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
1141
                const domSelection = (root as Document).getSelection();
1✔
1142

1143
                if (activeElement === el) {
1!
1144
                    this.latestElement = activeElement;
1✔
1145
                    IS_FOCUSED.set(this.editor, true);
1✔
1146
                } else {
1147
                    IS_FOCUSED.delete(this.editor);
×
1148
                }
1149

1150
                if (!domSelection) {
1!
1151
                    return Transforms.deselect(this.editor);
×
1152
                }
1153

1154
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
1155
                const hasDomSelectionInEditor =
1156
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
1157
                if (!hasDomSelectionInEditor) {
1!
1158
                    Transforms.deselect(this.editor);
×
1159
                    return;
×
1160
                }
1161

1162
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
1163
                // for example, double-click the last cell of the table to select a non-editable DOM
1164
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
1165
                if (range) {
1✔
1166
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
1167
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
1168
                            // force adjust DOMSelection
1169
                            this.toNativeSelection(false);
×
1170
                        }
1171
                    } else {
1172
                        Transforms.select(this.editor, range);
1✔
1173
                    }
1174
                }
1175
            } catch (error) {
1176
                this.editor.onError({
×
1177
                    code: SlateErrorCode.ToSlateSelectionError,
1178
                    nativeError: error
1179
                });
1180
            }
1181
        }
1182
    }
1183

1184
    private onDOMBeforeInput(
1185
        event: Event & {
1186
            inputType: string;
1187
            isComposing: boolean;
1188
            data: string | null;
1189
            dataTransfer: DataTransfer | null;
1190
            getTargetRanges(): DOMStaticRange[];
1191
        }
1192
    ) {
1193
        const editor = this.editor;
×
1194
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1195
        const { activeElement } = root;
×
1196
        const { selection } = editor;
×
1197
        const { inputType: type } = event;
×
1198
        const data = event.dataTransfer || event.data || undefined;
×
1199
        if (IS_ANDROID) {
×
1200
            let targetRange: Range | null = null;
×
1201
            let [nativeTargetRange] = event.getTargetRanges();
×
1202
            if (nativeTargetRange) {
×
1203
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1204
            }
1205
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1206
            // have to manually get the selection here to ensure it's up-to-date.
1207
            const window = AngularEditor.getWindow(editor);
×
1208
            const domSelection = window.getSelection();
×
1209
            if (!targetRange && domSelection) {
×
1210
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1211
            }
1212
            targetRange = targetRange ?? editor.selection;
×
1213
            if (type === 'insertCompositionText') {
×
1214
                if (data && data.toString().includes('\n')) {
×
1215
                    restoreDom(editor, () => {
×
1216
                        Editor.insertBreak(editor);
×
1217
                    });
1218
                } else {
1219
                    if (targetRange) {
×
1220
                        if (data) {
×
1221
                            restoreDom(editor, () => {
×
1222
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1223
                            });
1224
                        } else {
1225
                            restoreDom(editor, () => {
×
1226
                                Transforms.delete(editor, { at: targetRange });
×
1227
                            });
1228
                        }
1229
                    }
1230
                }
1231
                return;
×
1232
            }
1233
            if (type === 'deleteContentBackward') {
×
1234
                // gboard can not prevent default action, so must use restoreDom,
1235
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1236
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1237
                if (!Range.isCollapsed(targetRange)) {
×
1238
                    restoreDom(editor, () => {
×
1239
                        Transforms.delete(editor, { at: targetRange });
×
1240
                    });
1241
                    return;
×
1242
                }
1243
            }
1244
            if (type === 'insertText') {
×
1245
                restoreDom(editor, () => {
×
1246
                    if (typeof data === 'string') {
×
1247
                        Editor.insertText(editor, data);
×
1248
                    }
1249
                });
1250
                return;
×
1251
            }
1252
        }
1253
        if (
×
1254
            !this.readonly &&
×
1255
            AngularEditor.hasEditableTarget(editor, event.target) &&
1256
            !isTargetInsideVoid(editor, activeElement) &&
1257
            !this.isDOMEventHandled(event, this.beforeInput)
1258
        ) {
1259
            try {
×
1260
                event.preventDefault();
×
1261

1262
                // COMPAT: If the selection is expanded, even if the command seems like
1263
                // a delete forward/backward command it should delete the selection.
1264
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1265
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1266
                    Editor.deleteFragment(editor, { direction });
×
1267
                    return;
×
1268
                }
1269

1270
                switch (type) {
×
1271
                    case 'deleteByComposition':
1272
                    case 'deleteByCut':
1273
                    case 'deleteByDrag': {
1274
                        Editor.deleteFragment(editor);
×
1275
                        break;
×
1276
                    }
1277

1278
                    case 'deleteContent':
1279
                    case 'deleteContentForward': {
1280
                        Editor.deleteForward(editor);
×
1281
                        break;
×
1282
                    }
1283

1284
                    case 'deleteContentBackward': {
1285
                        Editor.deleteBackward(editor);
×
1286
                        break;
×
1287
                    }
1288

1289
                    case 'deleteEntireSoftLine': {
1290
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1291
                        Editor.deleteForward(editor, { unit: 'line' });
×
1292
                        break;
×
1293
                    }
1294

1295
                    case 'deleteHardLineBackward': {
1296
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1297
                        break;
×
1298
                    }
1299

1300
                    case 'deleteSoftLineBackward': {
1301
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1302
                        break;
×
1303
                    }
1304

1305
                    case 'deleteHardLineForward': {
1306
                        Editor.deleteForward(editor, { unit: 'block' });
×
1307
                        break;
×
1308
                    }
1309

1310
                    case 'deleteSoftLineForward': {
1311
                        Editor.deleteForward(editor, { unit: 'line' });
×
1312
                        break;
×
1313
                    }
1314

1315
                    case 'deleteWordBackward': {
1316
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1317
                        break;
×
1318
                    }
1319

1320
                    case 'deleteWordForward': {
1321
                        Editor.deleteForward(editor, { unit: 'word' });
×
1322
                        break;
×
1323
                    }
1324

1325
                    case 'insertLineBreak':
1326
                    case 'insertParagraph': {
1327
                        Editor.insertBreak(editor);
×
1328
                        break;
×
1329
                    }
1330

1331
                    case 'insertFromComposition': {
1332
                        // COMPAT: in safari, `compositionend` event is dispatched after
1333
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1334
                        // https://www.w3.org/TR/input-events-2/
1335
                        // so the following code is the right logic
1336
                        // because DOM selection in sync will be exec before `compositionend` event
1337
                        // isComposing is true will prevent DOM selection being update correctly.
1338
                        this.isComposing = false;
×
1339
                        preventInsertFromComposition(event, this.editor);
×
1340
                    }
1341
                    case 'insertFromDrop':
1342
                    case 'insertFromPaste':
1343
                    case 'insertFromYank':
1344
                    case 'insertReplacementText':
1345
                    case 'insertText': {
1346
                        // use a weak comparison instead of 'instanceof' to allow
1347
                        // programmatic access of paste events coming from external windows
1348
                        // like cypress where cy.window does not work realibly
1349
                        if (data?.constructor.name === 'DataTransfer') {
×
1350
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1351
                        } else if (typeof data === 'string') {
×
1352
                            Editor.insertText(editor, data);
×
1353
                        }
1354
                        break;
×
1355
                    }
1356
                }
1357
            } catch (error) {
1358
                this.editor.onError({
×
1359
                    code: SlateErrorCode.OnDOMBeforeInputError,
1360
                    nativeError: error
1361
                });
1362
            }
1363
        }
1364
    }
1365

1366
    private onDOMBlur(event: FocusEvent) {
1367
        if (
×
1368
            this.readonly ||
×
1369
            this.isUpdatingSelection ||
1370
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1371
            this.isDOMEventHandled(event, this.blur)
1372
        ) {
1373
            return;
×
1374
        }
1375

1376
        const window = AngularEditor.getWindow(this.editor);
×
1377

1378
        // COMPAT: If the current `activeElement` is still the previous
1379
        // one, this is due to the window being blurred when the tab
1380
        // itself becomes unfocused, so we want to abort early to allow to
1381
        // editor to stay focused when the tab becomes focused again.
1382
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1383
        if (this.latestElement === root.activeElement) {
×
1384
            return;
×
1385
        }
1386

1387
        const { relatedTarget } = event;
×
1388
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1389

1390
        // COMPAT: The event should be ignored if the focus is returning
1391
        // to the editor from an embedded editable element (eg. an <input>
1392
        // element inside a void node).
1393
        if (relatedTarget === el) {
×
1394
            return;
×
1395
        }
1396

1397
        // COMPAT: The event should be ignored if the focus is moving from
1398
        // the editor to inside a void node's spacer element.
1399
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1400
            return;
×
1401
        }
1402

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

1409
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1410
                return;
×
1411
            }
1412
        }
1413

1414
        IS_FOCUSED.delete(this.editor);
×
1415
    }
1416

1417
    private onDOMClick(event: MouseEvent) {
1418
        if (
×
1419
            !this.readonly &&
×
1420
            AngularEditor.hasTarget(this.editor, event.target) &&
1421
            !this.isDOMEventHandled(event, this.click) &&
1422
            isDOMNode(event.target)
1423
        ) {
1424
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1425
            const path = AngularEditor.findPath(this.editor, node);
×
1426
            const start = Editor.start(this.editor, path);
×
1427
            const end = Editor.end(this.editor, path);
×
1428

1429
            const startVoid = Editor.void(this.editor, { at: start });
×
1430
            const endVoid = Editor.void(this.editor, { at: end });
×
1431

1432
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1433
                let blockPath = path;
×
1434
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1435
                    const block = Editor.above(this.editor, {
×
1436
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1437
                        at: path
1438
                    });
1439

1440
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1441
                }
1442

1443
                const range = Editor.range(this.editor, blockPath);
×
1444
                Transforms.select(this.editor, range);
×
1445
                return;
×
1446
            }
1447

1448
            if (
×
1449
                startVoid &&
×
1450
                endVoid &&
1451
                Path.equals(startVoid[1], endVoid[1]) &&
1452
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1453
            ) {
1454
                const range = Editor.range(this.editor, start);
×
1455
                Transforms.select(this.editor, range);
×
1456
            }
1457
        }
1458
    }
1459

1460
    private onDOMCompositionStart(event: CompositionEvent) {
1461
        const { selection } = this.editor;
1✔
1462
        if (selection) {
1!
1463
            // solve the problem of cross node Chinese input
1464
            if (Range.isExpanded(selection)) {
×
1465
                Editor.deleteFragment(this.editor);
×
1466
                this.forceRender();
×
1467
            }
1468
        }
1469
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1470
            this.isComposing = true;
1✔
1471
        }
1472
        this.render();
1✔
1473
    }
1474

1475
    private onDOMCompositionUpdate(event: CompositionEvent) {
1476
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1477
    }
1478

1479
    private onDOMCompositionEnd(event: CompositionEvent) {
1480
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1481
            Transforms.delete(this.editor);
×
1482
        }
1483
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1484
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1485
            // aren't correct and never fire the "insertFromComposition"
1486
            // type that we need. So instead, insert whenever a composition
1487
            // ends since it will already have been committed to the DOM.
1488
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1489
                preventInsertFromComposition(event, this.editor);
×
1490
                Editor.insertText(this.editor, event.data);
×
1491
            }
1492

1493
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1494
            // so we need avoid repeat isnertText by isComposing === true,
1495
            this.isComposing = false;
×
1496
        }
1497
        this.render();
×
1498
    }
1499

1500
    private onDOMCopy(event: ClipboardEvent) {
1501
        const window = AngularEditor.getWindow(this.editor);
×
1502
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1503
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1504
            event.preventDefault();
×
1505
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1506
        }
1507
    }
1508

1509
    private onDOMCut(event: ClipboardEvent) {
1510
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1511
            event.preventDefault();
×
1512
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1513
            const { selection } = this.editor;
×
1514

1515
            if (selection) {
×
1516
                AngularEditor.deleteCutData(this.editor);
×
1517
            }
1518
        }
1519
    }
1520

1521
    private onDOMDragOver(event: DragEvent) {
1522
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1523
            // Only when the target is void, call `preventDefault` to signal
1524
            // that drops are allowed. Editable content is droppable by
1525
            // default, and calling `preventDefault` hides the cursor.
1526
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1527

1528
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1529
                event.preventDefault();
×
1530
            }
1531
        }
1532
    }
1533

1534
    private onDOMDragStart(event: DragEvent) {
1535
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1536
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1537
            const path = AngularEditor.findPath(this.editor, node);
×
1538
            const voidMatch =
1539
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1540

1541
            // If starting a drag on a void node, make sure it is selected
1542
            // so that it shows up in the selection's fragment.
1543
            if (voidMatch) {
×
1544
                const range = Editor.range(this.editor, path);
×
1545
                Transforms.select(this.editor, range);
×
1546
            }
1547

1548
            this.isDraggingInternally = true;
×
1549

1550
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1551
        }
1552
    }
1553

1554
    private onDOMDrop(event: DragEvent) {
1555
        const editor = this.editor;
×
1556
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1557
            event.preventDefault();
×
1558
            // Keep a reference to the dragged range before updating selection
1559
            const draggedRange = editor.selection;
×
1560

1561
            // Find the range where the drop happened
1562
            const range = AngularEditor.findEventRange(editor, event);
×
1563
            const data = event.dataTransfer;
×
1564

1565
            Transforms.select(editor, range);
×
1566

1567
            if (this.isDraggingInternally) {
×
1568
                if (draggedRange) {
×
1569
                    Transforms.delete(editor, {
×
1570
                        at: draggedRange
1571
                    });
1572
                }
1573

1574
                this.isDraggingInternally = false;
×
1575
            }
1576

1577
            AngularEditor.insertData(editor, data);
×
1578

1579
            // When dragging from another source into the editor, it's possible
1580
            // that the current editor does not have focus.
1581
            if (!AngularEditor.isFocused(editor)) {
×
1582
                AngularEditor.focus(editor);
×
1583
            }
1584
        }
1585
    }
1586

1587
    private onDOMDragEnd(event: DragEvent) {
1588
        if (
×
1589
            !this.readonly &&
×
1590
            this.isDraggingInternally &&
1591
            AngularEditor.hasTarget(this.editor, event.target) &&
1592
            !this.isDOMEventHandled(event, this.dragEnd)
1593
        ) {
1594
            this.isDraggingInternally = false;
×
1595
        }
1596
    }
1597

1598
    private onDOMFocus(event: Event) {
1599
        if (
2✔
1600
            !this.readonly &&
8✔
1601
            !this.isUpdatingSelection &&
1602
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1603
            !this.isDOMEventHandled(event, this.focus)
1604
        ) {
1605
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1606
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1607
            this.latestElement = root.activeElement;
2✔
1608

1609
            // COMPAT: If the editor has nested editable elements, the focus
1610
            // can go to them. In Firefox, this must be prevented because it
1611
            // results in issues with keyboard navigation. (2017/03/30)
1612
            if (IS_FIREFOX && event.target !== el) {
2!
1613
                el.focus();
×
1614
                return;
×
1615
            }
1616

1617
            IS_FOCUSED.set(this.editor, true);
2✔
1618
        }
1619
    }
1620

1621
    private onDOMKeydown(event: KeyboardEvent) {
1622
        const editor = this.editor;
×
1623
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1624
        const { activeElement } = root;
×
1625
        if (
×
1626
            !this.readonly &&
×
1627
            AngularEditor.hasEditableTarget(editor, event.target) &&
1628
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1629
            !this.isComposing &&
1630
            !this.isDOMEventHandled(event, this.keydown)
1631
        ) {
1632
            const nativeEvent = event;
×
1633
            const { selection } = editor;
×
1634

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

1638
            try {
×
1639
                // COMPAT: Since we prevent the default behavior on
1640
                // `beforeinput` events, the browser doesn't think there's ever
1641
                // any history stack to undo or redo, so we have to manage these
1642
                // hotkeys ourselves. (2019/11/06)
1643
                if (Hotkeys.isRedo(nativeEvent)) {
×
1644
                    event.preventDefault();
×
1645

1646
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1647
                        editor.redo();
×
1648
                    }
1649

1650
                    return;
×
1651
                }
1652

1653
                if (Hotkeys.isUndo(nativeEvent)) {
×
1654
                    event.preventDefault();
×
1655

1656
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1657
                        editor.undo();
×
1658
                    }
1659

1660
                    return;
×
1661
                }
1662

1663
                // COMPAT: Certain browsers don't handle the selection updates
1664
                // properly. In Chrome, the selection isn't properly extended.
1665
                // And in Firefox, the selection isn't properly collapsed.
1666
                // (2017/10/17)
1667
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1668
                    event.preventDefault();
×
1669
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1670
                    return;
×
1671
                }
1672

1673
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1674
                    event.preventDefault();
×
1675
                    Transforms.move(editor, { unit: 'line' });
×
1676
                    return;
×
1677
                }
1678

1679
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1680
                    event.preventDefault();
×
1681
                    Transforms.move(editor, {
×
1682
                        unit: 'line',
1683
                        edge: 'focus',
1684
                        reverse: true
1685
                    });
1686
                    return;
×
1687
                }
1688

1689
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1690
                    event.preventDefault();
×
1691
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1692
                    return;
×
1693
                }
1694

1695
                // COMPAT: If a void node is selected, or a zero-width text node
1696
                // adjacent to an inline is selected, we need to handle these
1697
                // hotkeys manually because browsers won't be able to skip over
1698
                // the void node with the zero-width space not being an empty
1699
                // string.
1700
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1701
                    event.preventDefault();
×
1702

1703
                    if (selection && Range.isCollapsed(selection)) {
×
1704
                        Transforms.move(editor, { reverse: !isRTL });
×
1705
                    } else {
1706
                        Transforms.collapse(editor, { edge: 'start' });
×
1707
                    }
1708

1709
                    return;
×
1710
                }
1711

1712
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1713
                    event.preventDefault();
×
1714
                    if (selection && Range.isCollapsed(selection)) {
×
1715
                        Transforms.move(editor, { reverse: isRTL });
×
1716
                    } else {
1717
                        Transforms.collapse(editor, { edge: 'end' });
×
1718
                    }
1719

1720
                    return;
×
1721
                }
1722

1723
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1724
                    event.preventDefault();
×
1725

1726
                    if (selection && Range.isExpanded(selection)) {
×
1727
                        Transforms.collapse(editor, { edge: 'focus' });
×
1728
                    }
1729

1730
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1731
                    return;
×
1732
                }
1733

1734
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1735
                    event.preventDefault();
×
1736

1737
                    if (selection && Range.isExpanded(selection)) {
×
1738
                        Transforms.collapse(editor, { edge: 'focus' });
×
1739
                    }
1740

1741
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1742
                    return;
×
1743
                }
1744

1745
                if (isKeyHotkey('mod+a', event)) {
×
1746
                    this.editor.selectAll();
×
1747
                    event.preventDefault();
×
1748
                    return;
×
1749
                }
1750

1751
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1752
                // fall back to guessing at the input intention for hotkeys.
1753
                // COMPAT: In iOS, some of these hotkeys are handled in the
1754
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1755
                    // We don't have a core behavior for these, but they change the
1756
                    // DOM if we don't prevent them, so we have to.
1757
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1758
                        event.preventDefault();
×
1759
                        return;
×
1760
                    }
1761

1762
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1763
                        event.preventDefault();
×
1764
                        Editor.insertBreak(editor);
×
1765
                        return;
×
1766
                    }
1767

1768
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1769
                        event.preventDefault();
×
1770

1771
                        if (selection && Range.isExpanded(selection)) {
×
1772
                            Editor.deleteFragment(editor, {
×
1773
                                direction: 'backward'
1774
                            });
1775
                        } else {
1776
                            Editor.deleteBackward(editor);
×
1777
                        }
1778

1779
                        return;
×
1780
                    }
1781

1782
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1783
                        event.preventDefault();
×
1784

1785
                        if (selection && Range.isExpanded(selection)) {
×
1786
                            Editor.deleteFragment(editor, {
×
1787
                                direction: 'forward'
1788
                            });
1789
                        } else {
1790
                            Editor.deleteForward(editor);
×
1791
                        }
1792

1793
                        return;
×
1794
                    }
1795

1796
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1797
                        event.preventDefault();
×
1798

1799
                        if (selection && Range.isExpanded(selection)) {
×
1800
                            Editor.deleteFragment(editor, {
×
1801
                                direction: 'backward'
1802
                            });
1803
                        } else {
1804
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1805
                        }
1806

1807
                        return;
×
1808
                    }
1809

1810
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1811
                        event.preventDefault();
×
1812

1813
                        if (selection && Range.isExpanded(selection)) {
×
1814
                            Editor.deleteFragment(editor, {
×
1815
                                direction: 'forward'
1816
                            });
1817
                        } else {
1818
                            Editor.deleteForward(editor, { unit: 'line' });
×
1819
                        }
1820

1821
                        return;
×
1822
                    }
1823

1824
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1825
                        event.preventDefault();
×
1826

1827
                        if (selection && Range.isExpanded(selection)) {
×
1828
                            Editor.deleteFragment(editor, {
×
1829
                                direction: 'backward'
1830
                            });
1831
                        } else {
1832
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1833
                        }
1834

1835
                        return;
×
1836
                    }
1837

1838
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1839
                        event.preventDefault();
×
1840

1841
                        if (selection && Range.isExpanded(selection)) {
×
1842
                            Editor.deleteFragment(editor, {
×
1843
                                direction: 'forward'
1844
                            });
1845
                        } else {
1846
                            Editor.deleteForward(editor, { unit: 'word' });
×
1847
                        }
1848

1849
                        return;
×
1850
                    }
1851
                } else {
1852
                    if (IS_CHROME || IS_SAFARI) {
×
1853
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1854
                        // an event when deleting backwards in a selected void inline node
1855
                        if (
×
1856
                            selection &&
×
1857
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1858
                            Range.isCollapsed(selection)
1859
                        ) {
1860
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1861
                            if (
×
1862
                                Element.isElement(currentNode) &&
×
1863
                                Editor.isVoid(editor, currentNode) &&
1864
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1865
                            ) {
1866
                                event.preventDefault();
×
1867
                                Editor.deleteBackward(editor, {
×
1868
                                    unit: 'block'
1869
                                });
1870
                                return;
×
1871
                            }
1872
                        }
1873
                    }
1874
                }
1875
            } catch (error) {
1876
                this.editor.onError({
×
1877
                    code: SlateErrorCode.OnDOMKeydownError,
1878
                    nativeError: error
1879
                });
1880
            }
1881
        }
1882
    }
1883

1884
    private onDOMPaste(event: ClipboardEvent) {
1885
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1886
        // fall back to React's `onPaste` here instead.
1887
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1888
        // when "paste without formatting" option is used.
1889
        // This unfortunately needs to be handled with paste events instead.
1890
        if (
×
1891
            !this.isDOMEventHandled(event, this.paste) &&
×
1892
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1893
            !this.readonly &&
1894
            AngularEditor.hasEditableTarget(this.editor, event.target)
1895
        ) {
1896
            event.preventDefault();
×
1897
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1898
        }
1899
    }
1900

1901
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1902
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1903
        // fall back to React's leaky polyfill instead just for it. It
1904
        // only works for the `insertText` input type.
1905
        if (
×
1906
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1907
            !this.readonly &&
1908
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1909
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1910
        ) {
1911
            event.nativeEvent.preventDefault();
×
1912
            try {
×
1913
                const text = event.data;
×
1914
                if (!Range.isCollapsed(this.editor.selection)) {
×
1915
                    Editor.deleteFragment(this.editor);
×
1916
                }
1917
                // just handle Non-IME input
1918
                if (!this.isComposing) {
×
1919
                    Editor.insertText(this.editor, text);
×
1920
                }
1921
            } catch (error) {
1922
                this.editor.onError({
×
1923
                    code: SlateErrorCode.ToNativeSelectionError,
1924
                    nativeError: error
1925
                });
1926
            }
1927
        }
1928
    }
1929

1930
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1931
        if (!handler) {
3✔
1932
            return false;
3✔
1933
        }
1934
        handler(event);
×
1935
        return event.defaultPrevented;
×
1936
    }
1937
    //#endregion
1938

1939
    ngOnDestroy() {
1940
        this.editorResizeObserver?.disconnect();
23✔
1941
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1942
        this.manualListeners.forEach(manualListener => {
23✔
1943
            manualListener();
483✔
1944
        });
1945
        this.destroy$.complete();
23✔
1946
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1947
    }
1948
}
1949

1950
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1951
    // This was affecting the selection of multiple blocks and dragging behavior,
1952
    // so enabled only if the selection has been collapsed.
1953
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1954
        const leafEl = domRange.startContainer.parentElement!;
×
1955

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

1961
        if (isZeroDimensionRect) {
×
1962
            const leafRect = leafEl.getBoundingClientRect();
×
1963
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1964

1965
            if (leafHasDimensions) {
×
1966
                return;
×
1967
            }
1968
        }
1969

1970
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1971
        scrollIntoView(leafEl, {
×
1972
            scrollMode: 'if-needed'
1973
        });
1974
        delete leafEl.getBoundingClientRect;
×
1975
    }
1976
};
1977

1978
/**
1979
 * Check if the target is inside void and in the editor.
1980
 */
1981

1982
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1983
    let slateNode: Node | null = null;
1✔
1984
    try {
1✔
1985
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1986
    } catch (error) {}
1987
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1988
};
1989

1990
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1991
    return (
2✔
1992
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1993
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1994
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1995
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1996
    );
1997
};
1998

1999
/**
2000
 * remove default insert from composition
2001
 * @param text
2002
 */
2003
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
2004
    const types = ['compositionend', 'insertFromComposition'];
×
2005
    if (!types.includes(event.type)) {
×
2006
        return;
×
2007
    }
2008
    const insertText = (event as CompositionEvent).data;
×
2009
    const window = AngularEditor.getWindow(editor);
×
2010
    const domSelection = window.getSelection();
×
2011
    // ensure text node insert composition input text
2012
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
2013
        const textNode = domSelection.anchorNode;
×
2014
        textNode.splitText(textNode.length - insertText.length).remove();
×
2015
    }
2016
};
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