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

worktile / slate-angular / 8fd3d244-a948-4c01-bc5b-8174089e528f

11 Dec 2025 09:45AM UTC coverage: 38.191% (-2.4%) from 40.626%
8fd3d244-a948-4c01-bc5b-8174089e528f

push

circleci

web-flow
chore: optimize debug view (#320)

386 of 1204 branches covered (32.06%)

Branch coverage included in aggregate %.

5 of 226 new or added lines in 2 files covered. (2.21%)

3 existing lines in 1 file now uncovered.

1071 of 2611 relevant lines covered (41.02%)

24.97 hits per line

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

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

71
export const JUST_NOW_UPDATED_VIRTUAL_VIEW = new WeakMap<AngularEditor, boolean>();
1✔
72

73
export const ELEMENT_KEY_TO_HEIGHTS = new WeakMap<AngularEditor, Map<string, number>>();
1✔
74

75
// not correctly clipboardData on beforeinput
76
const forceOnDOMPaste = IS_SAFARI;
1✔
77

78
const isDebug = localStorage.getItem(SLATE_DEBUG_KEY) === 'true';
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.virtualConfig = config;
×
145
        this.doVirtualScroll();
×
146
    }
147

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

166
    //#region DOM attr
167
    @Input() spellCheck = false;
23✔
168
    @Input() autoCorrect = false;
23✔
169
    @Input() autoCapitalize = false;
23✔
170

171
    @HostBinding('attr.data-slate-editor') dataSlateEditor = true;
23✔
172
    @HostBinding('attr.data-slate-node') dataSlateNode = 'value';
23✔
173
    @HostBinding('attr.data-gramm') dataGramm = false;
23✔
174

175
    get hasBeforeInputSupport() {
176
        return HAS_BEFORE_INPUT_SUPPORT;
456✔
177
    }
178
    //#endregion
179

180
    viewContainerRef = inject(ViewContainerRef);
23✔
181

182
    getOutletParent = () => {
23✔
183
        return this.elementRef.nativeElement;
43✔
184
    };
185

186
    getOutletElement = () => {
23✔
187
        if (this.virtualScrollInitialized) {
23!
188
            return this.virtualCenterOutlet;
×
189
        } else {
190
            return null;
23✔
191
        }
192
    };
193

194
    listRender: ListRender;
195

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

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

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

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

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

264
    registerOnChange(fn: any) {
265
        this.onChangeCallback = fn;
23✔
266
    }
267
    registerOnTouched(fn: any) {
268
        this.onTouchedCallback = fn;
23✔
269
    }
270

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

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

320
    toNativeSelection() {
321
        try {
15✔
322
            let { selection } = this.editor;
15✔
323
            if (this.virtualConfig?.enabled && selection) {
15!
324
                const indics = Array.from(this.virtualVisibleIndexes.values());
×
325
                if (indics.length > 0) {
×
326
                    const currentVisibleRange: Range = {
×
327
                        anchor: Editor.start(this.editor, [indics[0]]),
328
                        focus: Editor.end(this.editor, [indics[indics.length - 1]])
329
                    };
330
                    const [start, end] = Range.edges(selection);
×
331
                    const forwardSelection = { anchor: start, focus: end };
×
332
                    const intersectedSelection = Range.intersection(forwardSelection, currentVisibleRange);
×
333
                    if (!intersectedSelection || !Range.equals(intersectedSelection, forwardSelection)) {
×
334
                        selection = intersectedSelection;
×
335
                        if (isDebug) {
×
336
                            this.debugLog(
×
337
                                'log',
338
                                `selection is not in visible range, selection: ${JSON.stringify(
339
                                    selection
340
                                )}, intersectedSelection: ${JSON.stringify(intersectedSelection)}`
341
                            );
342
                        }
343
                    }
344
                }
345
            }
346
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
15✔
347
            const { activeElement } = root;
15✔
348
            const domSelection = (root as Document).getSelection();
15✔
349

350
            if ((this.isComposing && !IS_ANDROID) || !domSelection || !AngularEditor.isFocused(this.editor)) {
15!
351
                return;
14✔
352
            }
353

354
            const hasDomSelection = domSelection.type !== 'None';
1✔
355

356
            // If the DOM selection is properly unset, we're done.
357
            if (!selection && !hasDomSelection) {
1!
358
                return;
×
359
            }
360

361
            // If the DOM selection is already correct, we're done.
362
            // verify that the dom selection is in the editor
363
            const editorElement = EDITOR_TO_ELEMENT.get(this.editor)!;
1✔
364
            let hasDomSelectionInEditor = false;
1✔
365
            if (editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode)) {
1✔
366
                hasDomSelectionInEditor = true;
1✔
367
            }
368

369
            // If the DOM selection is in the editor and the editor selection is already correct, we're done.
370
            if (hasDomSelection && hasDomSelectionInEditor && selection && hasStringTarget(domSelection)) {
1✔
371
                const rangeFromDOMSelection = AngularEditor.toSlateRange(this.editor, domSelection, {
1✔
372
                    exactMatch: false,
373
                    suppressThrow: true
374
                });
375
                if (rangeFromDOMSelection && Range.equals(rangeFromDOMSelection, selection)) {
1!
376
                    return;
×
377
                }
378
            }
379

380
            // prevent updating native selection when active element is void element
381
            if (isTargetInsideVoid(this.editor, activeElement)) {
1!
382
                return;
×
383
            }
384

385
            // when <Editable/> is being controlled through external value
386
            // then its children might just change - DOM responds to it on its own
387
            // but Slate's value is not being updated through any operation
388
            // and thus it doesn't transform selection on its own
389
            if (selection && !AngularEditor.hasRange(this.editor, selection)) {
1!
390
                this.editor.selection = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: false });
×
391
                return;
×
392
            }
393

394
            // Otherwise the DOM selection is out of sync, so update it.
395
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
396
            this.isUpdatingSelection = true;
1✔
397

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

400
            if (newDomRange) {
1!
401
                // COMPAT: Since the DOM range has no concept of backwards/forwards
402
                // we need to check and do the right thing here.
403
                if (Range.isBackward(selection)) {
1!
404
                    // eslint-disable-next-line max-len
405
                    domSelection.setBaseAndExtent(
×
406
                        newDomRange.endContainer,
407
                        newDomRange.endOffset,
408
                        newDomRange.startContainer,
409
                        newDomRange.startOffset
410
                    );
411
                } else {
412
                    // eslint-disable-next-line max-len
413
                    domSelection.setBaseAndExtent(
1✔
414
                        newDomRange.startContainer,
415
                        newDomRange.startOffset,
416
                        newDomRange.endContainer,
417
                        newDomRange.endOffset
418
                    );
419
                }
420
            } else {
421
                domSelection.removeAllRanges();
×
422
            }
423

424
            setTimeout(() => {
1✔
425
                // handle scrolling in setTimeout because of
426
                // dom should not have updated immediately after listRender's updating
427
                newDomRange && this.scrollSelectionIntoView(this.editor, newDomRange);
1✔
428
                // COMPAT: In Firefox, it's not enough to create a range, you also need
429
                // to focus the contenteditable element too. (2016/11/16)
430
                if (newDomRange && IS_FIREFOX) {
1!
431
                    el.focus();
×
432
                }
433

434
                this.isUpdatingSelection = false;
1✔
435
            });
436
        } catch (error) {
437
            this.editor.onError({
×
438
                code: SlateErrorCode.ToNativeSelectionError,
439
                nativeError: error
440
            });
441
            this.isUpdatingSelection = false;
×
442
        }
443
    }
444

445
    onChange() {
446
        this.forceRender();
13✔
447
        this.onChangeCallback(this.editor.children);
13✔
448
    }
449

450
    ngAfterViewChecked() {}
451

452
    ngDoCheck() {}
453

454
    forceRender() {
455
        this.updateContext();
15✔
456
        const virtualView = this.refreshVirtualView();
15✔
457
        this.applyVirtualView(virtualView);
15✔
458
        const visibleIndexes = Array.from(this.virtualVisibleIndexes);
15✔
459
        this.listRender.update(this.renderedChildren, this.editor, this.context);
15✔
460
        this.remeasureHeightByIndics(visibleIndexes);
15✔
461
        // repair collaborative editing when Chinese input is interrupted by other users' cursors
462
        // when the DOMElement where the selection is located is removed
463
        // the compositionupdate and compositionend events will no longer be fired
464
        // so isComposing needs to be corrected
465
        // need exec after this.cdr.detectChanges() to render HTML
466
        // need exec before this.toNativeSelection() to correct native selection
467
        if (this.isComposing) {
15!
468
            // Composition input text be not rendered when user composition input with selection is expanded
469
            // At this time, the following matching conditions are met, assign isComposing to false, and the status is wrong
470
            // this time condition is true and isComposing is assigned false
471
            // Therefore, need to wait for the composition input text to be rendered before performing condition matching
472
            setTimeout(() => {
×
473
                const textNode = Node.get(this.editor, this.editor.selection.anchor.path);
×
474
                const textDOMNode = AngularEditor.toDOMNode(this.editor, textNode);
×
475
                let textContent = '';
×
476
                // skip decorate text
477
                textDOMNode.querySelectorAll('[editable-text]').forEach(stringDOMNode => {
×
478
                    let text = stringDOMNode.textContent;
×
479
                    const zeroChar = '\uFEFF';
×
480
                    // remove zero with char
481
                    if (text.startsWith(zeroChar)) {
×
482
                        text = text.slice(1);
×
483
                    }
484
                    if (text.endsWith(zeroChar)) {
×
485
                        text = text.slice(0, text.length - 1);
×
486
                    }
487
                    textContent += text;
×
488
                });
489
                if (Node.string(textNode).endsWith(textContent)) {
×
490
                    this.isComposing = false;
×
491
                }
492
            }, 0);
493
        }
494
        this.toNativeSelection();
15✔
495
    }
496

497
    render() {
498
        const changed = this.updateContext();
2✔
499
        if (changed) {
2✔
500
            const virtualView = this.refreshVirtualView();
2✔
501
            this.applyVirtualView(virtualView);
2✔
502
            this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
2✔
503
            this.scheduleMeasureVisibleHeights();
2✔
504
        }
505
    }
506

507
    updateContext() {
508
        const decorations = this.generateDecorations();
17✔
509
        if (
17✔
510
            this.context.selection !== this.editor.selection ||
46✔
511
            this.context.decorate !== this.decorate ||
512
            this.context.readonly !== this.readonly ||
513
            !isDecoratorRangeListEqual(this.context.decorations, decorations)
514
        ) {
515
            this.context = {
10✔
516
                parent: this.editor,
517
                selection: this.editor.selection,
518
                decorations: decorations,
519
                decorate: this.decorate,
520
                readonly: this.readonly
521
            };
522
            return true;
10✔
523
        }
524
        return false;
7✔
525
    }
526

527
    initializeContext() {
528
        this.context = {
49✔
529
            parent: this.editor,
530
            selection: this.editor.selection,
531
            decorations: this.generateDecorations(),
532
            decorate: this.decorate,
533
            readonly: this.readonly
534
        };
535
    }
536

537
    initializeViewContext() {
538
        this.viewContext = {
23✔
539
            editor: this.editor,
540
            renderElement: this.renderElement,
541
            renderLeaf: this.renderLeaf,
542
            renderText: this.renderText,
543
            trackBy: this.trackBy,
544
            isStrictDecorate: this.isStrictDecorate
545
        };
546
    }
547

548
    composePlaceholderDecorate(editor: Editor) {
549
        if (this.placeholderDecorate) {
64!
550
            return this.placeholderDecorate(editor) || [];
×
551
        }
552

553
        if (this.placeholder && editor.children.length === 1 && Array.from(Node.texts(editor)).length === 1 && Node.string(editor) === '') {
64✔
554
            const start = Editor.start(editor, []);
3✔
555
            return [
3✔
556
                {
557
                    placeholder: this.placeholder,
558
                    anchor: start,
559
                    focus: start
560
                }
561
            ];
562
        } else {
563
            return [];
61✔
564
        }
565
    }
566

567
    generateDecorations() {
568
        const decorations = this.decorate([this.editor, []]);
66✔
569
        const placeholderDecorations = this.isComposing ? [] : this.composePlaceholderDecorate(this.editor);
66✔
570
        decorations.push(...placeholderDecorations);
66✔
571
        return decorations;
66✔
572
    }
573

574
    private shouldUseVirtual() {
575
        return !!(this.virtualConfig && this.virtualConfig.enabled);
71✔
576
    }
577

578
    // the height from scroll container top to editor top height element
579
    private businessHeight: number = 0;
23✔
580

581
    virtualScrollInitialized = false;
23✔
582

583
    virtualTopHeightElement: HTMLElement;
584

585
    virtualBottomHeightElement: HTMLElement;
586

587
    virtualCenterOutlet: HTMLElement;
588

589
    initializeVirtualScrolling() {
590
        if (this.virtualScrollInitialized) {
23!
591
            return;
×
592
        }
593
        if (this.virtualConfig && this.virtualConfig.enabled) {
23!
594
            this.virtualScrollInitialized = true;
×
595
            this.virtualTopHeightElement = document.createElement('div');
×
596
            this.virtualTopHeightElement.classList.add('virtual-top-height');
×
597
            this.virtualTopHeightElement.contentEditable = 'false';
×
598
            this.virtualBottomHeightElement = document.createElement('div');
×
599
            this.virtualBottomHeightElement.classList.add('virtual-bottom-height');
×
600
            this.virtualBottomHeightElement.contentEditable = 'false';
×
601
            this.virtualCenterOutlet = document.createElement('div');
×
602
            this.virtualCenterOutlet.classList.add('virtual-center-outlet');
×
603
            this.elementRef.nativeElement.appendChild(this.virtualTopHeightElement);
×
604
            this.elementRef.nativeElement.appendChild(this.virtualCenterOutlet);
×
605
            this.elementRef.nativeElement.appendChild(this.virtualBottomHeightElement);
×
606
            this.businessHeight = this.virtualTopHeightElement.getBoundingClientRect()?.top ?? 0;
×
607

608
            let editorResizeObserverRectWidth = this.elementRef.nativeElement.getBoundingClientRect()?.width ?? 0;
×
609
            this.editorResizeObserver = new ResizeObserver(entries => {
×
610
                if (entries.length > 0 && entries[0].contentRect.width !== editorResizeObserverRectWidth) {
×
611
                    editorResizeObserverRectWidth = entries[0].contentRect.width;
×
612
                    this.remeasureHeightByIndics(Array.from(this.virtualVisibleIndexes));
×
613
                }
614
            });
615
            this.editorResizeObserver.observe(this.elementRef.nativeElement);
×
616
            if (isDebug) {
×
617
                const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
NEW
618
                VirtualScrollDebugOverlay.getInstance(doc);
×
619
            }
620
        }
621
    }
622

623
    changeVirtualHeight(topHeight: number, bottomHeight: number) {
624
        if (!this.virtualScrollInitialized) {
43✔
625
            return;
43✔
626
        }
627
        this.virtualTopHeightElement.style.height = `${topHeight}px`;
×
628
        this.virtualBottomHeightElement.style.height = `${bottomHeight}px`;
×
629
    }
630

631
    private debugLog(type: 'log' | 'warn', ...args: any[]) {
NEW
632
        const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
NEW
633
        VirtualScrollDebugOverlay.log(doc, type, ...args);
×
634
    }
635

636
    private doVirtualScroll() {
637
        this.refreshVirtualViewAnimId && cancelAnimationFrame(this.refreshVirtualViewAnimId);
×
638
        this.refreshVirtualViewAnimId = requestAnimationFrame(() => {
×
639
            let virtualView = this.refreshVirtualView();
×
640
            let diff = this.diffVirtualView(virtualView);
×
641
            if (!diff.isDiff) {
×
642
                return;
×
643
            }
644
            if (diff.isMissingTop) {
×
645
                const result = this.remeasureHeightByIndics(diff.diffTopRenderedIndexes);
×
646
                if (result) {
×
647
                    virtualView = this.refreshVirtualView();
×
648
                    diff = this.diffVirtualView(virtualView, 'second');
×
649
                    if (!diff.isDiff) {
×
650
                        return;
×
651
                    }
652
                }
653
            }
654
            this.applyVirtualView(virtualView);
×
655
            if (this.listRender.initialized) {
×
656
                this.listRender.update(virtualView.renderedChildren, this.editor, this.context);
×
657
                if (!AngularEditor.isReadOnly(this.editor) && this.editor.selection) {
×
658
                    this.toNativeSelection();
×
659
                }
660
            }
661
            this.scheduleMeasureVisibleHeights();
×
662
        });
663
    }
664

665
    private refreshVirtualView() {
666
        const children = (this.editor.children || []) as Element[];
43!
667
        if (!children.length || !this.shouldUseVirtual()) {
43✔
668
            return {
43✔
669
                renderedChildren: children,
670
                visibleIndexes: new Set<number>(),
671
                top: 0,
672
                bottom: 0,
673
                heights: []
674
            };
675
        }
676
        const scrollTop = this.virtualConfig.scrollTop;
×
NEW
677
        if (isDebug) {
×
NEW
678
            const doc = this.elementRef?.nativeElement?.ownerDocument ?? document;
×
NEW
679
            VirtualScrollDebugOverlay.syncScrollTop(doc, Number.isFinite(scrollTop) ? (scrollTop as number) : 0);
×
680
        }
681
        const viewportHeight = this.virtualConfig.viewportHeight ?? 0;
×
682
        if (!viewportHeight) {
×
683
            return {
×
684
                renderedChildren: [],
685
                visibleIndexes: new Set<number>(),
686
                top: 0,
687
                bottom: 0,
688
                heights: []
689
            };
690
        }
691
        const elementLength = children.length;
×
692
        const adjustedScrollTop = Math.max(0, scrollTop - this.businessHeight);
×
693
        const heights = children.map((_, idx) => this.getBlockHeight(idx));
×
694
        const accumulatedHeights = this.buildAccumulatedHeight(heights);
×
695
        const totalHeight = accumulatedHeights[elementLength];
×
696
        const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
×
697
        const limitedScrollTop = Math.min(adjustedScrollTop, maxScrollTop);
×
698
        const viewBottom = limitedScrollTop + viewportHeight + this.businessHeight;
×
699
        let accumulatedOffset = 0;
×
700
        let visibleStartIndex = -1;
×
701
        const visible: Element[] = [];
×
702
        const visibleIndexes: number[] = [];
×
703

704
        for (let i = 0; i < elementLength && accumulatedOffset < viewBottom; i++) {
×
705
            const currentHeight = heights[i];
×
706
            const nextOffset = accumulatedOffset + currentHeight;
×
707
            // 可视区域有交集,加入渲染
708
            if (nextOffset > limitedScrollTop && accumulatedOffset < viewBottom) {
×
709
                if (visibleStartIndex === -1) visibleStartIndex = i; // 第一个相交起始位置
×
710
                visible.push(children[i]);
×
711
                visibleIndexes.push(i);
×
712
            }
713
            accumulatedOffset = nextOffset;
×
714
        }
715

716
        if (visibleStartIndex === -1 && elementLength) {
×
717
            visibleStartIndex = elementLength - 1;
×
718
            visible.push(children[visibleStartIndex]);
×
719
            visibleIndexes.push(visibleStartIndex);
×
720
        }
721

722
        const visibleEndIndex =
723
            visibleStartIndex === -1 ? elementLength - 1 : (visibleIndexes[visibleIndexes.length - 1] ?? visibleStartIndex);
×
724
        const top = visibleStartIndex === -1 ? 0 : accumulatedHeights[visibleStartIndex];
×
725
        const bottom = totalHeight - accumulatedHeights[visibleEndIndex + 1];
×
726

727
        return {
×
728
            renderedChildren: visible.length ? visible : children,
×
729
            visibleIndexes: new Set(visibleIndexes),
730
            top,
731
            bottom,
732
            heights
733
        };
734
    }
735

736
    private applyVirtualView(virtualView: VirtualViewResult) {
737
        this.renderedChildren = virtualView.renderedChildren;
43✔
738
        this.changeVirtualHeight(virtualView.top, virtualView.bottom);
43✔
739
        this.virtualVisibleIndexes = virtualView.visibleIndexes;
43✔
740
    }
741

742
    private diffVirtualView(virtualView: VirtualViewResult, stage: 'first' | 'second' | 'onChange' = 'first') {
×
743
        if (!this.renderedChildren.length) {
×
744
            return {
×
745
                isDiff: true,
746
                diffTopRenderedIndexes: [],
747
                diffBottomRenderedIndexes: []
748
            };
749
        }
750
        const oldVisibleIndexes = [...this.virtualVisibleIndexes];
×
751
        const newVisibleIndexes = [...virtualView.visibleIndexes];
×
752
        const firstNewIndex = newVisibleIndexes[0];
×
753
        const lastNewIndex = newVisibleIndexes[newVisibleIndexes.length - 1];
×
754
        const firstOldIndex = oldVisibleIndexes[0];
×
755
        const lastOldIndex = oldVisibleIndexes[oldVisibleIndexes.length - 1];
×
756
        if (firstNewIndex !== firstOldIndex || lastNewIndex !== lastOldIndex) {
×
757
            const diffTopRenderedIndexes = [];
×
758
            const diffBottomRenderedIndexes = [];
×
759
            const isMissingTop = firstNewIndex !== firstOldIndex && firstNewIndex > firstOldIndex;
×
760
            const isAddedTop = firstNewIndex !== firstOldIndex && firstNewIndex < firstOldIndex;
×
761
            const isMissingBottom = lastNewIndex !== lastOldIndex && lastOldIndex > lastNewIndex;
×
762
            const isAddedBottom = lastNewIndex !== lastOldIndex && lastOldIndex < lastNewIndex;
×
763
            if (isMissingTop || isAddedBottom) {
×
764
                // 向下
765
                for (let index = 0; index < oldVisibleIndexes.length; index++) {
×
766
                    const element = oldVisibleIndexes[index];
×
767
                    if (!newVisibleIndexes.includes(element)) {
×
768
                        diffTopRenderedIndexes.push(element);
×
769
                    } else {
770
                        break;
×
771
                    }
772
                }
773
                for (let index = newVisibleIndexes.length - 1; index >= 0; index--) {
×
774
                    const element = newVisibleIndexes[index];
×
775
                    if (!oldVisibleIndexes.includes(element)) {
×
776
                        diffBottomRenderedIndexes.push(element);
×
777
                    } else {
778
                        break;
×
779
                    }
780
                }
781
            } else if (isAddedTop || isMissingBottom) {
×
782
                // 向上
783
                for (let index = 0; index < newVisibleIndexes.length; index++) {
×
784
                    const element = newVisibleIndexes[index];
×
785
                    if (!oldVisibleIndexes.includes(element)) {
×
786
                        diffTopRenderedIndexes.push(element);
×
787
                    } else {
788
                        break;
×
789
                    }
790
                }
791
                for (let index = oldVisibleIndexes.length - 1; index >= 0; index--) {
×
792
                    const element = oldVisibleIndexes[index];
×
793
                    if (!newVisibleIndexes.includes(element)) {
×
794
                        diffBottomRenderedIndexes.push(element);
×
795
                    } else {
796
                        break;
×
797
                    }
798
                }
799
            }
800
            if (isDebug) {
×
801
                this.debugLog('log', `====== diffVirtualView stage: ${stage} ======`);
×
802
                this.debugLog('log', 'oldVisibleIndexes:', oldVisibleIndexes);
×
803
                this.debugLog('log', 'newVisibleIndexes:', newVisibleIndexes);
×
804
                this.debugLog(
×
805
                    'log',
806
                    'diffTopRenderedIndexes:',
807
                    isMissingTop ? '-' : isAddedTop ? '+' : '-',
×
808
                    diffTopRenderedIndexes,
809
                    diffTopRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
810
                );
811
                this.debugLog(
×
812
                    'log',
813
                    'diffBottomRenderedIndexes:',
814
                    isAddedBottom ? '+' : isMissingBottom ? '-' : '+',
×
815
                    diffBottomRenderedIndexes,
816
                    diffBottomRenderedIndexes.map(index => this.getBlockHeight(index, 0))
×
817
                );
818
                const needTop = virtualView.heights.slice(0, newVisibleIndexes[0]).reduce((acc, height) => acc + height, 0);
×
819
                const needBottom = virtualView.heights
×
820
                    .slice(newVisibleIndexes[newVisibleIndexes.length - 1] + 1)
821
                    .reduce((acc, height) => acc + height, 0);
×
822
                this.debugLog('log', 'newTopHeight:', needTop, 'prevTopHeight:', parseFloat(this.virtualTopHeightElement.style.height));
×
823
                this.debugLog(
×
824
                    'log',
825
                    'newBottomHeight:',
826
                    needBottom,
827
                    'prevBottomHeight:',
828
                    parseFloat(this.virtualBottomHeightElement.style.height)
829
                );
830
                this.debugLog('warn', '=========== Dividing line ===========');
×
831
            }
832
            return {
×
833
                isDiff: true,
834
                isMissingTop,
835
                isAddedTop,
836
                isMissingBottom,
837
                isAddedBottom,
838
                diffTopRenderedIndexes,
839
                diffBottomRenderedIndexes
840
            };
841
        }
842
        return {
×
843
            isDiff: false,
844
            diffTopRenderedIndexes: [],
845
            diffBottomRenderedIndexes: []
846
        };
847
    }
848

849
    private getBlockHeight(index: number, defaultHeight: number = VIRTUAL_SCROLL_DEFAULT_BLOCK_HEIGHT) {
×
850
        const node = this.editor.children[index];
×
851
        if (!node) {
×
852
            return defaultHeight;
×
853
        }
854
        const key = AngularEditor.findKey(this.editor, node);
×
855
        return this.measuredHeights.get(key.id) ?? defaultHeight;
×
856
    }
857

858
    private buildAccumulatedHeight(heights: number[]) {
859
        const accumulatedHeights = new Array(heights.length + 1).fill(0);
×
860
        for (let i = 0; i < heights.length; i++) {
×
861
            // 存储前 i 个的累计高度
862
            accumulatedHeights[i + 1] = accumulatedHeights[i] + heights[i];
×
863
        }
864
        return accumulatedHeights;
×
865
    }
866

867
    private scheduleMeasureVisibleHeights() {
868
        if (!this.shouldUseVirtual()) {
28✔
869
            return;
28✔
870
        }
871
        this.measureVisibleHeightsAnimId && cancelAnimationFrame(this.measureVisibleHeightsAnimId);
×
872
        this.measureVisibleHeightsAnimId = requestAnimationFrame(() => {
×
873
            this.measureVisibleHeights();
×
874
        });
875
    }
876

877
    private measureVisibleHeights() {
878
        const children = (this.editor.children || []) as Element[];
×
879
        this.virtualVisibleIndexes.forEach(index => {
×
880
            const node = children[index];
×
881
            if (!node) {
×
882
                return;
×
883
            }
884
            const key = AngularEditor.findKey(this.editor, node);
×
885
            // 跳过已测过的块,除非强制测量
886
            if (this.measuredHeights.has(key.id)) {
×
887
                return;
×
888
            }
889
            const view = ELEMENT_TO_COMPONENT.get(node);
×
890
            if (!view) {
×
891
                return;
×
892
            }
893
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
894
            if (ret instanceof Promise) {
×
895
                ret.then(height => {
×
896
                    this.measuredHeights.set(key.id, height);
×
897
                });
898
            } else {
899
                this.measuredHeights.set(key.id, ret);
×
900
            }
901
        });
902
    }
903

904
    private remeasureHeightByIndics(indics: number[]): boolean {
905
        const children = (this.editor.children || []) as Element[];
15!
906
        let isHeightChanged = false;
15✔
907
        indics.forEach(index => {
15✔
908
            const node = children[index];
×
909
            if (!node) {
×
910
                return;
×
911
            }
912
            const key = AngularEditor.findKey(this.editor, node);
×
913
            const view = ELEMENT_TO_COMPONENT.get(node);
×
914
            if (!view) {
×
915
                return;
×
916
            }
917
            const prevHeight = this.measuredHeights.get(key.id);
×
918
            const ret = (view as BaseElementComponent | BaseElementFlavour).getRealHeight();
×
919
            if (ret instanceof Promise) {
×
920
                ret.then(height => {
×
921
                    if (height !== prevHeight) {
×
922
                        this.measuredHeights.set(key.id, height);
×
923
                        isHeightChanged = true;
×
924
                        if (isDebug) {
×
925
                            this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${height}`);
×
926
                        }
927
                    }
928
                });
929
            } else {
930
                if (ret !== prevHeight) {
×
931
                    this.measuredHeights.set(key.id, ret);
×
932
                    isHeightChanged = true;
×
933
                    if (isDebug) {
×
934
                        this.debugLog('log', `remeasureHeightByIndics, index: ${index} prevHeight: ${prevHeight} newHeight: ${ret}`);
×
935
                    }
936
                }
937
            }
938
        });
939
        return isHeightChanged;
15✔
940
    }
941

942
    //#region event proxy
943
    private addEventListener(eventName: string, listener: EventListener, target: HTMLElement | Document = this.elementRef.nativeElement) {
460✔
944
        this.manualListeners.push(
483✔
945
            this.renderer2.listen(target, eventName, (event: Event) => {
946
                const beforeInputEvent = extractBeforeInputEvent(event.type, null, event, event.target);
5✔
947
                if (beforeInputEvent) {
5!
948
                    this.onFallbackBeforeInput(beforeInputEvent);
×
949
                }
950
                listener(event);
5✔
951
            })
952
        );
953
    }
954

955
    private toSlateSelection() {
956
        if ((!this.isComposing || IS_ANDROID) && !this.isUpdatingSelection && !this.isDraggingInternally) {
2✔
957
            try {
1✔
958
                const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
1✔
959
                const { activeElement } = root;
1✔
960
                const el = AngularEditor.toDOMNode(this.editor, this.editor);
1✔
961
                const domSelection = (root as Document).getSelection();
1✔
962

963
                if (activeElement === el) {
1!
964
                    this.latestElement = activeElement;
1✔
965
                    IS_FOCUSED.set(this.editor, true);
1✔
966
                } else {
967
                    IS_FOCUSED.delete(this.editor);
×
968
                }
969

970
                if (!domSelection) {
1!
971
                    return Transforms.deselect(this.editor);
×
972
                }
973

974
                const editorElement = EDITOR_TO_ELEMENT.get(this.editor);
1✔
975
                const hasDomSelectionInEditor =
976
                    editorElement.contains(domSelection.anchorNode) && editorElement.contains(domSelection.focusNode);
1✔
977
                if (!hasDomSelectionInEditor) {
1!
978
                    Transforms.deselect(this.editor);
×
979
                    return;
×
980
                }
981

982
                // try to get the selection directly, because some terrible case can be normalize for normalizeDOMPoint
983
                // for example, double-click the last cell of the table to select a non-editable DOM
984
                const range = AngularEditor.toSlateRange(this.editor, domSelection, { exactMatch: false, suppressThrow: true });
1✔
985
                if (range) {
1✔
986
                    if (this.editor.selection && Range.equals(range, this.editor.selection) && !hasStringTarget(domSelection)) {
1!
987
                        if (!isTargetInsideVoid(this.editor, activeElement)) {
×
988
                            // force adjust DOMSelection
989
                            this.toNativeSelection();
×
990
                        }
991
                    } else {
992
                        Transforms.select(this.editor, range);
1✔
993
                    }
994
                }
995
            } catch (error) {
996
                this.editor.onError({
×
997
                    code: SlateErrorCode.ToSlateSelectionError,
998
                    nativeError: error
999
                });
1000
            }
1001
        }
1002
    }
1003

1004
    private onDOMBeforeInput(
1005
        event: Event & {
1006
            inputType: string;
1007
            isComposing: boolean;
1008
            data: string | null;
1009
            dataTransfer: DataTransfer | null;
1010
            getTargetRanges(): DOMStaticRange[];
1011
        }
1012
    ) {
1013
        const editor = this.editor;
×
1014
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1015
        const { activeElement } = root;
×
1016
        const { selection } = editor;
×
1017
        const { inputType: type } = event;
×
1018
        const data = event.dataTransfer || event.data || undefined;
×
1019
        if (IS_ANDROID) {
×
1020
            let targetRange: Range | null = null;
×
1021
            let [nativeTargetRange] = event.getTargetRanges();
×
1022
            if (nativeTargetRange) {
×
1023
                targetRange = AngularEditor.toSlateRange(editor, nativeTargetRange, { exactMatch: false, suppressThrow: false });
×
1024
            }
1025
            // COMPAT: SelectionChange event is fired after the action is performed, so we
1026
            // have to manually get the selection here to ensure it's up-to-date.
1027
            const window = AngularEditor.getWindow(editor);
×
1028
            const domSelection = window.getSelection();
×
1029
            if (!targetRange && domSelection) {
×
1030
                targetRange = AngularEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: false });
×
1031
            }
1032
            targetRange = targetRange ?? editor.selection;
×
1033
            if (type === 'insertCompositionText') {
×
1034
                if (data && data.toString().includes('\n')) {
×
1035
                    restoreDom(editor, () => {
×
1036
                        Editor.insertBreak(editor);
×
1037
                    });
1038
                } else {
1039
                    if (targetRange) {
×
1040
                        if (data) {
×
1041
                            restoreDom(editor, () => {
×
1042
                                Transforms.insertText(editor, data.toString(), { at: targetRange });
×
1043
                            });
1044
                        } else {
1045
                            restoreDom(editor, () => {
×
1046
                                Transforms.delete(editor, { at: targetRange });
×
1047
                            });
1048
                        }
1049
                    }
1050
                }
1051
                return;
×
1052
            }
1053
            if (type === 'deleteContentBackward') {
×
1054
                // gboard can not prevent default action, so must use restoreDom,
1055
                // sougou Keyboard can prevent default action(only in Chinese input mode).
1056
                // In order to avoid weird action in Sougou Keyboard, use resotreDom only range's isCollapsed is false (recognize gboard)
1057
                if (!Range.isCollapsed(targetRange)) {
×
1058
                    restoreDom(editor, () => {
×
1059
                        Transforms.delete(editor, { at: targetRange });
×
1060
                    });
1061
                    return;
×
1062
                }
1063
            }
1064
            if (type === 'insertText') {
×
1065
                restoreDom(editor, () => {
×
1066
                    if (typeof data === 'string') {
×
1067
                        Editor.insertText(editor, data);
×
1068
                    }
1069
                });
1070
                return;
×
1071
            }
1072
        }
1073
        if (
×
1074
            !this.readonly &&
×
1075
            AngularEditor.hasEditableTarget(editor, event.target) &&
1076
            !isTargetInsideVoid(editor, activeElement) &&
1077
            !this.isDOMEventHandled(event, this.beforeInput)
1078
        ) {
1079
            try {
×
1080
                event.preventDefault();
×
1081

1082
                // COMPAT: If the selection is expanded, even if the command seems like
1083
                // a delete forward/backward command it should delete the selection.
1084
                if (selection && Range.isExpanded(selection) && type.startsWith('delete')) {
×
1085
                    const direction = type.endsWith('Backward') ? 'backward' : 'forward';
×
1086
                    Editor.deleteFragment(editor, { direction });
×
1087
                    return;
×
1088
                }
1089

1090
                switch (type) {
×
1091
                    case 'deleteByComposition':
1092
                    case 'deleteByCut':
1093
                    case 'deleteByDrag': {
1094
                        Editor.deleteFragment(editor);
×
1095
                        break;
×
1096
                    }
1097

1098
                    case 'deleteContent':
1099
                    case 'deleteContentForward': {
1100
                        Editor.deleteForward(editor);
×
1101
                        break;
×
1102
                    }
1103

1104
                    case 'deleteContentBackward': {
1105
                        Editor.deleteBackward(editor);
×
1106
                        break;
×
1107
                    }
1108

1109
                    case 'deleteEntireSoftLine': {
1110
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1111
                        Editor.deleteForward(editor, { unit: 'line' });
×
1112
                        break;
×
1113
                    }
1114

1115
                    case 'deleteHardLineBackward': {
1116
                        Editor.deleteBackward(editor, { unit: 'block' });
×
1117
                        break;
×
1118
                    }
1119

1120
                    case 'deleteSoftLineBackward': {
1121
                        Editor.deleteBackward(editor, { unit: 'line' });
×
1122
                        break;
×
1123
                    }
1124

1125
                    case 'deleteHardLineForward': {
1126
                        Editor.deleteForward(editor, { unit: 'block' });
×
1127
                        break;
×
1128
                    }
1129

1130
                    case 'deleteSoftLineForward': {
1131
                        Editor.deleteForward(editor, { unit: 'line' });
×
1132
                        break;
×
1133
                    }
1134

1135
                    case 'deleteWordBackward': {
1136
                        Editor.deleteBackward(editor, { unit: 'word' });
×
1137
                        break;
×
1138
                    }
1139

1140
                    case 'deleteWordForward': {
1141
                        Editor.deleteForward(editor, { unit: 'word' });
×
1142
                        break;
×
1143
                    }
1144

1145
                    case 'insertLineBreak':
1146
                    case 'insertParagraph': {
1147
                        Editor.insertBreak(editor);
×
1148
                        break;
×
1149
                    }
1150

1151
                    case 'insertFromComposition': {
1152
                        // COMPAT: in safari, `compositionend` event is dispatched after
1153
                        // the beforeinput event with the inputType "insertFromComposition" has been dispatched.
1154
                        // https://www.w3.org/TR/input-events-2/
1155
                        // so the following code is the right logic
1156
                        // because DOM selection in sync will be exec before `compositionend` event
1157
                        // isComposing is true will prevent DOM selection being update correctly.
1158
                        this.isComposing = false;
×
1159
                        preventInsertFromComposition(event, this.editor);
×
1160
                    }
1161
                    case 'insertFromDrop':
1162
                    case 'insertFromPaste':
1163
                    case 'insertFromYank':
1164
                    case 'insertReplacementText':
1165
                    case 'insertText': {
1166
                        // use a weak comparison instead of 'instanceof' to allow
1167
                        // programmatic access of paste events coming from external windows
1168
                        // like cypress where cy.window does not work realibly
1169
                        if (data?.constructor.name === 'DataTransfer') {
×
1170
                            AngularEditor.insertData(editor, data as DataTransfer);
×
1171
                        } else if (typeof data === 'string') {
×
1172
                            Editor.insertText(editor, data);
×
1173
                        }
1174
                        break;
×
1175
                    }
1176
                }
1177
            } catch (error) {
1178
                this.editor.onError({
×
1179
                    code: SlateErrorCode.OnDOMBeforeInputError,
1180
                    nativeError: error
1181
                });
1182
            }
1183
        }
1184
    }
1185

1186
    private onDOMBlur(event: FocusEvent) {
1187
        if (
×
1188
            this.readonly ||
×
1189
            this.isUpdatingSelection ||
1190
            !AngularEditor.hasEditableTarget(this.editor, event.target) ||
1191
            this.isDOMEventHandled(event, this.blur)
1192
        ) {
1193
            return;
×
1194
        }
1195

1196
        const window = AngularEditor.getWindow(this.editor);
×
1197

1198
        // COMPAT: If the current `activeElement` is still the previous
1199
        // one, this is due to the window being blurred when the tab
1200
        // itself becomes unfocused, so we want to abort early to allow to
1201
        // editor to stay focused when the tab becomes focused again.
1202
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1203
        if (this.latestElement === root.activeElement) {
×
1204
            return;
×
1205
        }
1206

1207
        const { relatedTarget } = event;
×
1208
        const el = AngularEditor.toDOMNode(this.editor, this.editor);
×
1209

1210
        // COMPAT: The event should be ignored if the focus is returning
1211
        // to the editor from an embedded editable element (eg. an <input>
1212
        // element inside a void node).
1213
        if (relatedTarget === el) {
×
1214
            return;
×
1215
        }
1216

1217
        // COMPAT: The event should be ignored if the focus is moving from
1218
        // the editor to inside a void node's spacer element.
1219
        if (isDOMElement(relatedTarget) && relatedTarget.hasAttribute('data-slate-spacer')) {
×
1220
            return;
×
1221
        }
1222

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

1229
            if (Element.isElement(node) && !this.editor.isVoid(node)) {
×
1230
                return;
×
1231
            }
1232
        }
1233

1234
        IS_FOCUSED.delete(this.editor);
×
1235
    }
1236

1237
    private onDOMClick(event: MouseEvent) {
1238
        if (
×
1239
            !this.readonly &&
×
1240
            AngularEditor.hasTarget(this.editor, event.target) &&
1241
            !this.isDOMEventHandled(event, this.click) &&
1242
            isDOMNode(event.target)
1243
        ) {
1244
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1245
            const path = AngularEditor.findPath(this.editor, node);
×
1246
            const start = Editor.start(this.editor, path);
×
1247
            const end = Editor.end(this.editor, path);
×
1248

1249
            const startVoid = Editor.void(this.editor, { at: start });
×
1250
            const endVoid = Editor.void(this.editor, { at: end });
×
1251

1252
            if (event.detail === TRIPLE_CLICK && path.length >= 1) {
×
1253
                let blockPath = path;
×
1254
                if (!(Element.isElement(node) && Editor.isBlock(this.editor, node))) {
×
1255
                    const block = Editor.above(this.editor, {
×
1256
                        match: n => Element.isElement(n) && Editor.isBlock(this.editor, n),
×
1257
                        at: path
1258
                    });
1259

1260
                    blockPath = block?.[1] ?? path.slice(0, 1);
×
1261
                }
1262

1263
                const range = Editor.range(this.editor, blockPath);
×
1264
                Transforms.select(this.editor, range);
×
1265
                return;
×
1266
            }
1267

1268
            if (
×
1269
                startVoid &&
×
1270
                endVoid &&
1271
                Path.equals(startVoid[1], endVoid[1]) &&
1272
                !(AngularEditor.isBlockCardLeftCursor(this.editor) || AngularEditor.isBlockCardRightCursor(this.editor))
×
1273
            ) {
1274
                const range = Editor.range(this.editor, start);
×
1275
                Transforms.select(this.editor, range);
×
1276
            }
1277
        }
1278
    }
1279

1280
    private onDOMCompositionStart(event: CompositionEvent) {
1281
        const { selection } = this.editor;
1✔
1282
        if (selection) {
1!
1283
            // solve the problem of cross node Chinese input
1284
            if (Range.isExpanded(selection)) {
×
1285
                Editor.deleteFragment(this.editor);
×
1286
                this.forceRender();
×
1287
            }
1288
        }
1289
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionStart)) {
1✔
1290
            this.isComposing = true;
1✔
1291
        }
1292
        this.render();
1✔
1293
    }
1294

1295
    private onDOMCompositionUpdate(event: CompositionEvent) {
1296
        this.isDOMEventHandled(event, this.compositionUpdate);
×
1297
    }
1298

1299
    private onDOMCompositionEnd(event: CompositionEvent) {
1300
        if (!event.data && !Range.isCollapsed(this.editor.selection)) {
×
1301
            Transforms.delete(this.editor);
×
1302
        }
1303
        if (AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.compositionEnd)) {
×
1304
            // COMPAT: In Chrome/Firefox, `beforeinput` events for compositions
1305
            // aren't correct and never fire the "insertFromComposition"
1306
            // type that we need. So instead, insert whenever a composition
1307
            // ends since it will already have been committed to the DOM.
1308
            if (this.isComposing === true && !IS_SAFARI && !IS_ANDROID && event.data) {
×
1309
                preventInsertFromComposition(event, this.editor);
×
1310
                Editor.insertText(this.editor, event.data);
×
1311
            }
1312

1313
            // COMPAT: In Firefox 87.0 CompositionEnd fire twice
1314
            // so we need avoid repeat isnertText by isComposing === true,
1315
            this.isComposing = false;
×
1316
        }
1317
        this.render();
×
1318
    }
1319

1320
    private onDOMCopy(event: ClipboardEvent) {
1321
        const window = AngularEditor.getWindow(this.editor);
×
1322
        const isOutsideSlate = !hasStringTarget(window.getSelection()) && isTargetInsideVoid(this.editor, event.target);
×
1323
        if (!isOutsideSlate && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.copy)) {
×
1324
            event.preventDefault();
×
1325
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'copy');
×
1326
        }
1327
    }
1328

1329
    private onDOMCut(event: ClipboardEvent) {
1330
        if (!this.readonly && AngularEditor.hasEditableTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.cut)) {
×
1331
            event.preventDefault();
×
1332
            AngularEditor.setFragmentData(this.editor, event.clipboardData, 'cut');
×
1333
            const { selection } = this.editor;
×
1334

1335
            if (selection) {
×
1336
                AngularEditor.deleteCutData(this.editor);
×
1337
            }
1338
        }
1339
    }
1340

1341
    private onDOMDragOver(event: DragEvent) {
1342
        if (AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragOver)) {
×
1343
            // Only when the target is void, call `preventDefault` to signal
1344
            // that drops are allowed. Editable content is droppable by
1345
            // default, and calling `preventDefault` hides the cursor.
1346
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1347

1348
            if (Element.isElement(node) && Editor.isVoid(this.editor, node)) {
×
1349
                event.preventDefault();
×
1350
            }
1351
        }
1352
    }
1353

1354
    private onDOMDragStart(event: DragEvent) {
1355
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.dragStart)) {
×
1356
            const node = AngularEditor.toSlateNode(this.editor, event.target);
×
1357
            const path = AngularEditor.findPath(this.editor, node);
×
1358
            const voidMatch =
1359
                Element.isElement(node) && (Editor.isVoid(this.editor, node) || Editor.void(this.editor, { at: path, voids: true }));
×
1360

1361
            // If starting a drag on a void node, make sure it is selected
1362
            // so that it shows up in the selection's fragment.
1363
            if (voidMatch) {
×
1364
                const range = Editor.range(this.editor, path);
×
1365
                Transforms.select(this.editor, range);
×
1366
            }
1367

1368
            this.isDraggingInternally = true;
×
1369

1370
            AngularEditor.setFragmentData(this.editor, event.dataTransfer, 'drag');
×
1371
        }
1372
    }
1373

1374
    private onDOMDrop(event: DragEvent) {
1375
        const editor = this.editor;
×
1376
        if (!this.readonly && AngularEditor.hasTarget(this.editor, event.target) && !this.isDOMEventHandled(event, this.drop)) {
×
1377
            event.preventDefault();
×
1378
            // Keep a reference to the dragged range before updating selection
1379
            const draggedRange = editor.selection;
×
1380

1381
            // Find the range where the drop happened
1382
            const range = AngularEditor.findEventRange(editor, event);
×
1383
            const data = event.dataTransfer;
×
1384

1385
            Transforms.select(editor, range);
×
1386

1387
            if (this.isDraggingInternally) {
×
1388
                if (draggedRange) {
×
1389
                    Transforms.delete(editor, {
×
1390
                        at: draggedRange
1391
                    });
1392
                }
1393

1394
                this.isDraggingInternally = false;
×
1395
            }
1396

1397
            AngularEditor.insertData(editor, data);
×
1398

1399
            // When dragging from another source into the editor, it's possible
1400
            // that the current editor does not have focus.
1401
            if (!AngularEditor.isFocused(editor)) {
×
1402
                AngularEditor.focus(editor);
×
1403
            }
1404
        }
1405
    }
1406

1407
    private onDOMDragEnd(event: DragEvent) {
1408
        if (
×
1409
            !this.readonly &&
×
1410
            this.isDraggingInternally &&
1411
            AngularEditor.hasTarget(this.editor, event.target) &&
1412
            !this.isDOMEventHandled(event, this.dragEnd)
1413
        ) {
1414
            this.isDraggingInternally = false;
×
1415
        }
1416
    }
1417

1418
    private onDOMFocus(event: Event) {
1419
        if (
2✔
1420
            !this.readonly &&
8✔
1421
            !this.isUpdatingSelection &&
1422
            AngularEditor.hasEditableTarget(this.editor, event.target) &&
1423
            !this.isDOMEventHandled(event, this.focus)
1424
        ) {
1425
            const el = AngularEditor.toDOMNode(this.editor, this.editor);
2✔
1426
            const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
2✔
1427
            this.latestElement = root.activeElement;
2✔
1428

1429
            // COMPAT: If the editor has nested editable elements, the focus
1430
            // can go to them. In Firefox, this must be prevented because it
1431
            // results in issues with keyboard navigation. (2017/03/30)
1432
            if (IS_FIREFOX && event.target !== el) {
2!
1433
                el.focus();
×
1434
                return;
×
1435
            }
1436

1437
            IS_FOCUSED.set(this.editor, true);
2✔
1438
        }
1439
    }
1440

1441
    private onDOMKeydown(event: KeyboardEvent) {
1442
        const editor = this.editor;
×
1443
        const root = AngularEditor.findDocumentOrShadowRoot(this.editor);
×
1444
        const { activeElement } = root;
×
1445
        if (
×
1446
            !this.readonly &&
×
1447
            AngularEditor.hasEditableTarget(editor, event.target) &&
1448
            !isTargetInsideVoid(editor, activeElement) && // stop fire keydown handle when focus void node
1449
            !this.isComposing &&
1450
            !this.isDOMEventHandled(event, this.keydown)
1451
        ) {
1452
            const nativeEvent = event;
×
1453
            const { selection } = editor;
×
1454

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

1458
            try {
×
1459
                // COMPAT: Since we prevent the default behavior on
1460
                // `beforeinput` events, the browser doesn't think there's ever
1461
                // any history stack to undo or redo, so we have to manage these
1462
                // hotkeys ourselves. (2019/11/06)
1463
                if (Hotkeys.isRedo(nativeEvent)) {
×
1464
                    event.preventDefault();
×
1465

1466
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1467
                        editor.redo();
×
1468
                    }
1469

1470
                    return;
×
1471
                }
1472

1473
                if (Hotkeys.isUndo(nativeEvent)) {
×
1474
                    event.preventDefault();
×
1475

1476
                    if (HistoryEditor.isHistoryEditor(editor)) {
×
1477
                        editor.undo();
×
1478
                    }
1479

1480
                    return;
×
1481
                }
1482

1483
                // COMPAT: Certain browsers don't handle the selection updates
1484
                // properly. In Chrome, the selection isn't properly extended.
1485
                // And in Firefox, the selection isn't properly collapsed.
1486
                // (2017/10/17)
1487
                if (Hotkeys.isMoveLineBackward(nativeEvent)) {
×
1488
                    event.preventDefault();
×
1489
                    Transforms.move(editor, { unit: 'line', reverse: true });
×
1490
                    return;
×
1491
                }
1492

1493
                if (Hotkeys.isMoveLineForward(nativeEvent)) {
×
1494
                    event.preventDefault();
×
1495
                    Transforms.move(editor, { unit: 'line' });
×
1496
                    return;
×
1497
                }
1498

1499
                if (Hotkeys.isExtendLineBackward(nativeEvent)) {
×
1500
                    event.preventDefault();
×
1501
                    Transforms.move(editor, {
×
1502
                        unit: 'line',
1503
                        edge: 'focus',
1504
                        reverse: true
1505
                    });
1506
                    return;
×
1507
                }
1508

1509
                if (Hotkeys.isExtendLineForward(nativeEvent)) {
×
1510
                    event.preventDefault();
×
1511
                    Transforms.move(editor, { unit: 'line', edge: 'focus' });
×
1512
                    return;
×
1513
                }
1514

1515
                // COMPAT: If a void node is selected, or a zero-width text node
1516
                // adjacent to an inline is selected, we need to handle these
1517
                // hotkeys manually because browsers won't be able to skip over
1518
                // the void node with the zero-width space not being an empty
1519
                // string.
1520
                if (Hotkeys.isMoveBackward(nativeEvent)) {
×
1521
                    event.preventDefault();
×
1522

1523
                    if (selection && Range.isCollapsed(selection)) {
×
1524
                        Transforms.move(editor, { reverse: !isRTL });
×
1525
                    } else {
1526
                        Transforms.collapse(editor, { edge: 'start' });
×
1527
                    }
1528

1529
                    return;
×
1530
                }
1531

1532
                if (Hotkeys.isMoveForward(nativeEvent)) {
×
1533
                    event.preventDefault();
×
1534
                    if (selection && Range.isCollapsed(selection)) {
×
1535
                        Transforms.move(editor, { reverse: isRTL });
×
1536
                    } else {
1537
                        Transforms.collapse(editor, { edge: 'end' });
×
1538
                    }
1539

1540
                    return;
×
1541
                }
1542

1543
                if (Hotkeys.isMoveWordBackward(nativeEvent)) {
×
1544
                    event.preventDefault();
×
1545

1546
                    if (selection && Range.isExpanded(selection)) {
×
1547
                        Transforms.collapse(editor, { edge: 'focus' });
×
1548
                    }
1549

1550
                    Transforms.move(editor, { unit: 'word', reverse: !isRTL });
×
1551
                    return;
×
1552
                }
1553

1554
                if (Hotkeys.isMoveWordForward(nativeEvent)) {
×
1555
                    event.preventDefault();
×
1556

1557
                    if (selection && Range.isExpanded(selection)) {
×
1558
                        Transforms.collapse(editor, { edge: 'focus' });
×
1559
                    }
1560

1561
                    Transforms.move(editor, { unit: 'word', reverse: isRTL });
×
1562
                    return;
×
1563
                }
1564

1565
                if (isKeyHotkey('mod+a', event)) {
×
1566
                    this.editor.selectAll();
×
1567
                    event.preventDefault();
×
1568
                    return;
×
1569
                }
1570

1571
                // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1572
                // fall back to guessing at the input intention for hotkeys.
1573
                // COMPAT: In iOS, some of these hotkeys are handled in the
1574
                if (!HAS_BEFORE_INPUT_SUPPORT) {
×
1575
                    // We don't have a core behavior for these, but they change the
1576
                    // DOM if we don't prevent them, so we have to.
1577
                    if (Hotkeys.isBold(nativeEvent) || Hotkeys.isItalic(nativeEvent) || Hotkeys.isTransposeCharacter(nativeEvent)) {
×
1578
                        event.preventDefault();
×
1579
                        return;
×
1580
                    }
1581

1582
                    if (Hotkeys.isSplitBlock(nativeEvent)) {
×
1583
                        event.preventDefault();
×
1584
                        Editor.insertBreak(editor);
×
1585
                        return;
×
1586
                    }
1587

1588
                    if (Hotkeys.isDeleteBackward(nativeEvent)) {
×
1589
                        event.preventDefault();
×
1590

1591
                        if (selection && Range.isExpanded(selection)) {
×
1592
                            Editor.deleteFragment(editor, {
×
1593
                                direction: 'backward'
1594
                            });
1595
                        } else {
1596
                            Editor.deleteBackward(editor);
×
1597
                        }
1598

1599
                        return;
×
1600
                    }
1601

1602
                    if (Hotkeys.isDeleteForward(nativeEvent)) {
×
1603
                        event.preventDefault();
×
1604

1605
                        if (selection && Range.isExpanded(selection)) {
×
1606
                            Editor.deleteFragment(editor, {
×
1607
                                direction: 'forward'
1608
                            });
1609
                        } else {
1610
                            Editor.deleteForward(editor);
×
1611
                        }
1612

1613
                        return;
×
1614
                    }
1615

1616
                    if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
×
1617
                        event.preventDefault();
×
1618

1619
                        if (selection && Range.isExpanded(selection)) {
×
1620
                            Editor.deleteFragment(editor, {
×
1621
                                direction: 'backward'
1622
                            });
1623
                        } else {
1624
                            Editor.deleteBackward(editor, { unit: 'line' });
×
1625
                        }
1626

1627
                        return;
×
1628
                    }
1629

1630
                    if (Hotkeys.isDeleteLineForward(nativeEvent)) {
×
1631
                        event.preventDefault();
×
1632

1633
                        if (selection && Range.isExpanded(selection)) {
×
1634
                            Editor.deleteFragment(editor, {
×
1635
                                direction: 'forward'
1636
                            });
1637
                        } else {
1638
                            Editor.deleteForward(editor, { unit: 'line' });
×
1639
                        }
1640

1641
                        return;
×
1642
                    }
1643

1644
                    if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
×
1645
                        event.preventDefault();
×
1646

1647
                        if (selection && Range.isExpanded(selection)) {
×
1648
                            Editor.deleteFragment(editor, {
×
1649
                                direction: 'backward'
1650
                            });
1651
                        } else {
1652
                            Editor.deleteBackward(editor, { unit: 'word' });
×
1653
                        }
1654

1655
                        return;
×
1656
                    }
1657

1658
                    if (Hotkeys.isDeleteWordForward(nativeEvent)) {
×
1659
                        event.preventDefault();
×
1660

1661
                        if (selection && Range.isExpanded(selection)) {
×
1662
                            Editor.deleteFragment(editor, {
×
1663
                                direction: 'forward'
1664
                            });
1665
                        } else {
1666
                            Editor.deleteForward(editor, { unit: 'word' });
×
1667
                        }
1668

1669
                        return;
×
1670
                    }
1671
                } else {
1672
                    if (IS_CHROME || IS_SAFARI) {
×
1673
                        // COMPAT: Chrome and Safari support `beforeinput` event but do not fire
1674
                        // an event when deleting backwards in a selected void inline node
1675
                        if (
×
1676
                            selection &&
×
1677
                            (Hotkeys.isDeleteBackward(nativeEvent) || Hotkeys.isDeleteForward(nativeEvent)) &&
1678
                            Range.isCollapsed(selection)
1679
                        ) {
1680
                            const currentNode = Node.parent(editor, selection.anchor.path);
×
1681
                            if (
×
1682
                                Element.isElement(currentNode) &&
×
1683
                                Editor.isVoid(editor, currentNode) &&
1684
                                (Editor.isInline(editor, currentNode) || Editor.isBlock(editor, currentNode))
1685
                            ) {
1686
                                event.preventDefault();
×
1687
                                Editor.deleteBackward(editor, {
×
1688
                                    unit: 'block'
1689
                                });
1690
                                return;
×
1691
                            }
1692
                        }
1693
                    }
1694
                }
1695
            } catch (error) {
1696
                this.editor.onError({
×
1697
                    code: SlateErrorCode.OnDOMKeydownError,
1698
                    nativeError: error
1699
                });
1700
            }
1701
        }
1702
    }
1703

1704
    private onDOMPaste(event: ClipboardEvent) {
1705
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1706
        // fall back to React's `onPaste` here instead.
1707
        // COMPAT: Firefox, Chrome and Safari are not emitting `beforeinput` events
1708
        // when "paste without formatting" option is used.
1709
        // This unfortunately needs to be handled with paste events instead.
1710
        if (
×
1711
            !this.isDOMEventHandled(event, this.paste) &&
×
1712
            (!HAS_BEFORE_INPUT_SUPPORT || isPlainTextOnlyPaste(event) || forceOnDOMPaste) &&
1713
            !this.readonly &&
1714
            AngularEditor.hasEditableTarget(this.editor, event.target)
1715
        ) {
1716
            event.preventDefault();
×
1717
            AngularEditor.insertData(this.editor, event.clipboardData);
×
1718
        }
1719
    }
1720

1721
    private onFallbackBeforeInput(event: BeforeInputEvent) {
1722
        // COMPAT: Certain browsers don't support the `beforeinput` event, so we
1723
        // fall back to React's leaky polyfill instead just for it. It
1724
        // only works for the `insertText` input type.
1725
        if (
×
1726
            !HAS_BEFORE_INPUT_SUPPORT &&
×
1727
            !this.readonly &&
1728
            !this.isDOMEventHandled(event.nativeEvent, this.beforeInput) &&
1729
            AngularEditor.hasEditableTarget(this.editor, event.nativeEvent.target)
1730
        ) {
1731
            event.nativeEvent.preventDefault();
×
1732
            try {
×
1733
                const text = event.data;
×
1734
                if (!Range.isCollapsed(this.editor.selection)) {
×
1735
                    Editor.deleteFragment(this.editor);
×
1736
                }
1737
                // just handle Non-IME input
1738
                if (!this.isComposing) {
×
1739
                    Editor.insertText(this.editor, text);
×
1740
                }
1741
            } catch (error) {
1742
                this.editor.onError({
×
1743
                    code: SlateErrorCode.ToNativeSelectionError,
1744
                    nativeError: error
1745
                });
1746
            }
1747
        }
1748
    }
1749

1750
    private isDOMEventHandled(event: Event, handler?: (event: Event) => void) {
1751
        if (!handler) {
3✔
1752
            return false;
3✔
1753
        }
1754
        handler(event);
×
1755
        return event.defaultPrevented;
×
1756
    }
1757
    //#endregion
1758

1759
    ngOnDestroy() {
1760
        this.editorResizeObserver?.disconnect();
23✔
1761
        NODE_TO_ELEMENT.delete(this.editor);
23✔
1762
        this.manualListeners.forEach(manualListener => {
23✔
1763
            manualListener();
483✔
1764
        });
1765
        this.destroy$.complete();
23✔
1766
        EDITOR_TO_ON_CHANGE.delete(this.editor);
23✔
1767
    }
1768
}
1769

1770
export const defaultScrollSelectionIntoView = (editor: AngularEditor, domRange: DOMRange) => {
1✔
1771
    // This was affecting the selection of multiple blocks and dragging behavior,
1772
    // so enabled only if the selection has been collapsed.
1773
    if (domRange.getBoundingClientRect && (!editor.selection || (editor.selection && Range.isCollapsed(editor.selection)))) {
×
1774
        const leafEl = domRange.startContainer.parentElement!;
×
1775

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

1781
        if (isZeroDimensionRect) {
×
1782
            const leafRect = leafEl.getBoundingClientRect();
×
1783
            const leafHasDimensions = leafRect.width > 0 || leafRect.height > 0;
×
1784

1785
            if (leafHasDimensions) {
×
1786
                return;
×
1787
            }
1788
        }
1789

1790
        leafEl.getBoundingClientRect = domRange.getBoundingClientRect.bind(domRange);
×
1791
        scrollIntoView(leafEl, {
×
1792
            scrollMode: 'if-needed'
1793
        });
1794
        delete leafEl.getBoundingClientRect;
×
1795
    }
1796
};
1797

1798
/**
1799
 * Check if the target is inside void and in the editor.
1800
 */
1801

1802
const isTargetInsideVoid = (editor: AngularEditor, target: EventTarget | null): boolean => {
1✔
1803
    let slateNode: Node | null = null;
1✔
1804
    try {
1✔
1805
        slateNode = AngularEditor.hasTarget(editor, target) && AngularEditor.toSlateNode(editor, target);
1✔
1806
    } catch (error) {}
1807
    return slateNode && Element.isElement(slateNode) && Editor.isVoid(editor, slateNode);
1!
1808
};
1809

1810
const hasStringTarget = (domSelection: DOMSelection) => {
1✔
1811
    return (
2✔
1812
        (domSelection.anchorNode.parentElement.hasAttribute('data-slate-string') ||
4!
1813
            domSelection.anchorNode.parentElement.hasAttribute('data-slate-zero-width')) &&
1814
        (domSelection.focusNode.parentElement.hasAttribute('data-slate-string') ||
1815
            domSelection.focusNode.parentElement.hasAttribute('data-slate-zero-width'))
1816
    );
1817
};
1818

1819
/**
1820
 * remove default insert from composition
1821
 * @param text
1822
 */
1823
const preventInsertFromComposition = (event: Event, editor: AngularEditor) => {
1✔
1824
    const types = ['compositionend', 'insertFromComposition'];
×
1825
    if (!types.includes(event.type)) {
×
1826
        return;
×
1827
    }
1828
    const insertText = (event as CompositionEvent).data;
×
1829
    const window = AngularEditor.getWindow(editor);
×
1830
    const domSelection = window.getSelection();
×
1831
    // ensure text node insert composition input text
1832
    if (insertText && domSelection.anchorNode instanceof Text && domSelection.anchorNode.textContent.endsWith(insertText)) {
×
1833
        const textNode = domSelection.anchorNode;
×
1834
        textNode.splitText(textNode.length - insertText.length).remove();
×
1835
    }
1836
};
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