Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

65.0 KB
Raw Blame
/**
 * Copyright 2023-present DreamNum Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type { DocumentDataModel, Nullable } from '@univerjs/core';
import type {
    Documents,
    DocumentSkeleton,
    Engine,
    IDocSelectionInnerParam,
    IFindNodeRestrictions,
    IMouseEvent,
    INodeInfo,
    INodePosition,
    IPointerEvent,
    IRenderContext,
    IRenderModule,
    IScrollObserverParam,
    ISuccinctDocRangeParam,
    ITextRangeWithStyle,
    ITextSelectionStyle,
} from '@univerjs/engine-render';
import type { Subscription } from 'rxjs';
import {
    DataStreamTreeTokenType,
    DOC_RANGE_TYPE,
    DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
    DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
    IContextService,
    ILogService,
    Inject,
    isInternalEditorID,
    IUniverInstanceService,
    Optional,
    RANGE_DIRECTION,
    RxDisposable,
    UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import {
    CURSOR_TYPE,
    getSystemHighlightColor,
    GlyphType,
    NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
    PageLayoutType,
    ScrollTimer,
    Vector2,
} from '@univerjs/engine-render';
import { ILayoutService, KeyCode } from '@univerjs/ui';
import { BehaviorSubject, filter, fromEvent, merge, Subject, takeUntil } from 'rxjs';
import type { RectRange } from './rect-range';
import {
    DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
    IDocEmbedInteractionBoundaryService,
    IDocEmbedRuntimeFocusCoordinator,
} from '../doc-embed-integration.service';
import { getEditorRuntimeConfig } from '../editor/editor-runtime-config';
import { compareNodePositionLogic } from './convert-text-range';
import {
    getCanvasOffsetByEngine,
    getParagraphInfoByGlyph,
    getRangeListFromCharIndex,
    getRangeListFromSelection,
    getRectRangeFromCharIndex,
    getTextRangeFromCharIndex,
    serializeRectRange,
    serializeTextRange,
} from './selection-utils';
import { cursorConvertToTextRange, TextRange } from './text-range';
import { getWordBoundaryByIndex, getWordSelectionByIndex } from './word-boundary';

export interface IEditorInputConfig {
    event: Event | CompositionEvent | KeyboardEvent;
    content?: string;
    activeRange?: Nullable<ITextRangeWithStyle>;
    rangeList?: ITextRangeWithStyle[];
}

export class DocSelectionRenderService extends RxDisposable implements IRenderModule {
    private readonly _onInputBefore$ = new Subject<Nullable<IEditorInputConfig>>();
    readonly onInputBefore$ = this._onInputBefore$.asObservable();

    private readonly _onKeydown$ = new Subject<IEditorInputConfig>();
    readonly onKeydown$ = this._onKeydown$.asObservable();

    private readonly _onInput$ = new Subject<IEditorInputConfig>();
    readonly onInput$ = this._onInput$.asObservable();

    private readonly _onCompositionstart$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
    readonly onCompositionstart$ = this._onCompositionstart$.asObservable();

    private readonly _onCompositionupdate$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
    readonly onCompositionupdate$ = this._onCompositionupdate$.asObservable();

    private readonly _onCompositionend$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);
    readonly onCompositionend$ = this._onCompositionend$.asObservable();

    private readonly _onSelectionStart$ = new BehaviorSubject<Nullable<INodePosition>>(null);
    readonly onSelectionStart$ = this._onSelectionStart$.asObservable();

    readonly onChangeByEvent$ = merge(
        this._onInput$,
        this._onKeydown$.pipe(filter((e) => (e.event as KeyboardEvent).keyCode === KeyCode.BACKSPACE)),
        this._onCompositionend$
    );

    private readonly _onPaste$ = new Subject<IEditorInputConfig>();
    readonly onPaste$ = this._onPaste$.asObservable();

    private readonly _textSelectionInner$ = new BehaviorSubject<Nullable<IDocSelectionInnerParam>>(null);
    readonly textSelectionInner$ = this._textSelectionInner$.asObservable();

    private readonly _movingSelection$ = new Subject<IDocSelectionInnerParam>();
    readonly movingSelection$ = this._movingSelection$.asObservable();

    private readonly _onFocus$ = new Subject<IEditorInputConfig>();
    readonly onFocus$ = this._onFocus$.asObservable();

    private readonly _onBlur$ = new Subject<IEditorInputConfig>();
    readonly onBlur$ = this._onBlur$.asObservable();

    private readonly _onPointerDown$ = new Subject<void>();
    readonly onPointerDown$ = this._onPointerDown$.asObservable();

    protected _container!: HTMLDivElement;
    private _inputParent!: HTMLDivElement;
    private _input!: HTMLDivElement;
    private _scrollTimers: ScrollTimer[] = [];
    protected _rangeList: TextRange[] = [];
    // Use to cache range list in moving.
    protected _rangeListCache: TextRange[] = [];
    // Rect range list.
    private _rectRangeList: RectRange[] = [];
    // Use to cache rect range list in moving.
    protected _rectRangeListCache: RectRange[] = [];
    protected _anchorNodePosition: Nullable<INodePosition> = null;
    protected _focusNodePosition: Nullable<INodePosition> = null;

    private _currentSegmentId: string = '';
    private _currentSegmentPage: number = -1;
    private readonly _segmentContext$ = new BehaviorSubject({ segmentId: '', segmentPage: -1 });
    readonly segmentContext$ = this._segmentContext$.asObservable();
    private _selectionStyle: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE;
    protected _onPointerEvent = false;

    private _viewPortObserverMap = new Map<
        string,
        {
            scrollStop: Nullable<Subscription>;
            scrollBefore: Nullable<Subscription>;
        }
    >();

    private _isIMEInputApply = false;
    private _scenePointerMoveSubs: Array<Subscription> = [];
    private _scenePointerUpSubs: Array<Subscription> = [];
    // When the user switches editors, whether to clear the doc ranges.
    private _reserveRanges = false;
    private _pendingSelection: Nullable<IDocSelectionInnerParam> = null;

    get hasPendingSelection(): boolean {
        return this._getPendingSelection() != null;
    }

    get isOnPointerEvent() {
        return this._onPointerEvent;
    }

    get isFocusing() {
        return this._input === this._getOwnerDocument().activeElement;
    }

    get inputElement(): HTMLDivElement {
        return this._input;
    }

    get selectionContainer(): HTMLDivElement {
        return this._container;
    }

    get isEditing() {
        return this._textSelectionInner$.value?.isEditing === true;
    }

    get canFocusing() {
        const ownerDocument = this._getOwnerDocument();
        const activeElement = ownerDocument.activeElement;
        return !this._isInUnfocusedFrame() && !this._shouldPreserveExternalFocus() && !this._isAnotherEditorFocused() && (
            this.isFocusing ||
            activeElement === ownerDocument.body ||
            activeElement === null ||
            (activeElement instanceof HTMLElement && this._containsCurrentEmbedRuntimeElement(activeElement))
        );
    }

    cancelPointerSelection(): void {
        if (!this._onPointerEvent) {
            return;
        }

        this._scenePointerMoveSubs.forEach((subscription) => subscription.unsubscribe());
        this._scenePointerUpSubs.forEach((subscription) => subscription.unsubscribe());
        this._scenePointerMoveSubs = [];
        this._scenePointerUpSubs = [];
        this._onPointerEvent = false;
        this._anchorNodePosition = null;
        this._focusNodePosition = null;
        this._removeAllRanges();
        this._removeAllCacheRanges();
        this._disposeScrollTimers();
        this._context.scene.enableObjectsEvent();
    }

    constructor(
        protected readonly _context: IRenderContext<DocumentDataModel>,
        @ILayoutService private readonly _layoutService: ILayoutService,
        @ILogService private readonly _logService: ILogService,
        @IContextService private readonly _contextService: IContextService,
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
        @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
        @Optional(IDocEmbedInteractionBoundaryService) private readonly _embedInteractionBoundaryService?: IDocEmbedInteractionBoundaryService,
        @Optional(IDocEmbedRuntimeFocusCoordinator) private readonly _embedRuntimeFocusCoordinator?: IDocEmbedRuntimeFocusCoordinator
    ) {
        super();
        this._initDOM();
        this._registerContainer();
        this._setSystemHighlightColorToStyle();
        this._listenCurrentUnitChange();
    }

    private _listenCurrentUnitChange() {
        this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
            .pipe(takeUntil(this.dispose$))
            .subscribe((documentModel) => {
                if (documentModel == null) {
                    return;
                }

                const unitId = documentModel.getUnitId();

                if (unitId !== this._context.unitId && !this._reserveRanges) {
                    this.removeAllRanges();
                }
            });
    }

    get activeViewPort() {
        return this._context.scene.getViewports()[0];
    }

    setSegment(id: string) {
        if (this._currentSegmentId === id) {
            return;
        }
        this._currentSegmentId = id;
        this._segmentContext$.next({ segmentId: id, segmentPage: this._currentSegmentPage });
    }

    getSegment() {
        return this._currentSegmentId;
    }

    setSegmentPage(pageIndex: number) {
        if (this._currentSegmentPage === pageIndex) {
            return;
        }
        this._currentSegmentPage = pageIndex;
        this._segmentContext$.next({ segmentId: this._currentSegmentId, segmentPage: pageIndex });
    }

    getSegmentPage() {
        return this._currentSegmentPage;
    }

    setReserveRangesStatus(status: boolean) {
        this._reserveRanges = status;
    }

    refreshRanges() {
        this._rangeList.forEach((range) => range.refresh());
        this._rectRangeList.forEach((range) => range.refresh());
    }

    private _setRangeStyle(style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE) {
        this._selectionStyle = style;
    }

    replaceDocRanges(ranges: ISuccinctDocRangeParam[], isEditing = true, options?: { [key: string]: boolean }): boolean {
        // A drag owns its in-progress ranges until pointerup publishes them.
        if (this._onPointerEvent) {
            this._pendingSelection = null;
            return false;
        }
        this._syncNoteSegment(ranges[0]);
        let currentLogicalSelection: Nullable<IDocSelectionInnerParam> = null;
        if (ranges.length > 0) {
            const { unitId } = this._context;
            const selection = this._docSelectionManagerService.getSelectionInfo({ unitId, subUnitId: unitId });
            // Only a refresh of the current logical selection belongs to this
            // publication. A new pointer/programmatic selection takes over.
            if (selection != null && ranges.length === selection.textRanges.length &&
                ranges.every((range, index) => range === selection.textRanges[index])) {
                currentLogicalSelection = selection;
                const progress = this._docSkeletonManagerService.getSkeleton().getLayoutProgress();
                if (progress?.reason === 'edit' && !progress.anchorReady && !progress.complete && !progress.cancelled) {
                    this._pendingSelection = currentLogicalSelection;
                    return false;
                }
            }
        }
        this._pendingSelection = null;
        const replaced = this.addDocRanges(ranges, isEditing, options, true);
        if (!replaced) {
            this._pendingSelection = currentLogicalSelection;
        }
        return replaced;
    }

    private _syncNoteSegment(range: ISuccinctDocRangeParam | undefined): void {
        const targetSegment = range?.segmentId;
        if (targetSegment == null) {
            return;
        }
        const notes = this._context.unit.getSnapshot().notes;
        if (targetSegment !== this._currentSegmentId &&
            (notes?.[targetSegment] || notes?.[this._currentSegmentId])) {
            this.setSegment(targetSegment);
            this.setSegmentPage(range?.segmentPage ?? -1);
        }
        if (notes?.[targetSegment] && range != null) {
            const position = this._docSkeletonManagerService.getSkeleton()
                .findNodePositionByCharIndex(range.endOffset, true, targetSegment);
            if (position != null && position.page !== this._currentSegmentPage) {
                this.setSegmentPage(position.page);
            }
        }
    }

    private _getPendingSelection(): Nullable<IDocSelectionInnerParam> {
        if (this._pendingSelection == null) {
            return null;
        }
        const { unitId } = this._context;
        if (this._docSelectionManagerService.getSelectionInfo({ unitId, subUnitId: unitId }) !== this._pendingSelection) {
            this._pendingSelection = null;
        }
        return this._pendingSelection;
    }

    private _canResolveCollapsedRanges(
        ranges: ISuccinctDocRangeParam[],
        scene: IRenderContext<DocumentDataModel>['scene'],
        document: Documents,
        docSkeleton: DocumentSkeleton
    ): boolean {
        for (const range of ranges) {
            if (range.rangeType === DOC_RANGE_TYPE.RECT || range.startOffset !== range.endOffset) {
                continue;
            }

            const textRange = cursorConvertToTextRange(
                scene,
                {
                    ...range,
                    segmentId: this._currentSegmentId,
                    segmentPage: this._currentSegmentPage,
                    style: range.style ?? this._selectionStyle,
                },
                docSkeleton,
                document
            );
            if (textRange == null) {
                return false;
            }
            const resolved = textRange.startOffset != null && textRange.endOffset != null;
            textRange.dispose();
            if (!resolved) {
                return false;
            }
        }

        return true;
    }

    addDocRanges(
        ranges: ISuccinctDocRangeParam[],
        isEditing = true,
        options?: { [key: string]: boolean },
        replace = false
    ): boolean {
        const {
            _currentSegmentId: segmentId,
            _currentSegmentPage: segmentPage,
            _selectionStyle: style,
        } = this;
        const { scene, mainComponent } = this._context;
        const document = mainComponent as Documents;
        const docSkeleton = this._docSkeletonManagerService.getSkeleton();
        if (replace && !this._canResolveCollapsedRanges(ranges, scene, document, docSkeleton)) {
            return false;
        }
        if (replace) {
            this.removeAllRanges();
        }

        const generalAddRange = (
            startOffset: number,
            endOffset: number,
            rangeStyle: ITextSelectionStyle
        ) => {
            const rangeList = getRangeListFromCharIndex(
                startOffset,
                endOffset,
                scene,
                document,
                docSkeleton,
                rangeStyle,
                segmentId,
                segmentPage
            );

            if (rangeList == null) {
                return;
            }

            const { textRanges, rectRanges } = rangeList;

            for (const textRange of textRanges) {
                this._addTextRange(textRange);
            }

            this._addRectRanges(rectRanges);
        };

        for (const range of ranges) {
            const { rangeType } = range;
            let { startOffset, endOffset, startNodePosition, endNodePosition } = range;
            // Published ranges use sorted offsets. Keep their anchor and focus
            // when rebuilding a backward selection after layout or zoom changes.
            if (rangeType !== DOC_RANGE_TYPE.RECT && range.direction === RANGE_DIRECTION.BACKWARD && startOffset < endOffset) {
                [startOffset, endOffset] = [endOffset, startOffset];
                [startNodePosition, endNodePosition] = [endNodePosition, startNodePosition];
            }
            const rangeStyle = range.style ?? style;

            if (rangeType !== DOC_RANGE_TYPE.RECT && startOffset === endOffset) {
                const textRange = cursorConvertToTextRange(
                    scene,
                    {
                        ...range,
                        segmentId,
                        segmentPage,
                        style: rangeStyle,
                    },
                    docSkeleton,
                    document
                );

                if (textRange) {
                    this._addTextRange(textRange);
                }
            } else if (rangeType === DOC_RANGE_TYPE.RECT) {
                const rectRange = getRectRangeFromCharIndex(
                    startOffset,
                    endOffset,
                    scene,
                    document,
                    docSkeleton,
                    rangeStyle,
                    segmentId,
                    segmentPage
                );

                if (rectRange) {
                    this._addRectRanges([rectRange]);
                }
            } else if (rangeType === DOC_RANGE_TYPE.TEXT) {
                // TODO: Remove try catch when text range in cell support across pages.
                try {
                    let textRange: Nullable<TextRange> = null;

                    if (startNodePosition && endNodePosition) {
                        textRange = getTextRangeFromCharIndex(
                            startNodePosition.isBack ? startOffset : startOffset - 1,
                            endNodePosition.isBack ? endOffset : endOffset - 1,
                            scene,
                            document,
                            docSkeleton,
                            rangeStyle,
                            segmentId,
                            segmentPage,
                            startNodePosition.isBack,
                            endNodePosition.isBack
                        );
                    } else {
                        textRange = getTextRangeFromCharIndex(
                            startOffset,
                            endOffset,
                            scene,
                            document,
                            docSkeleton,
                            rangeStyle,
                            segmentId,
                            segmentPage
                        );
                    }

                    if (textRange) {
                        this._addTextRange(textRange);
                    }
                } catch {
                    generalAddRange(startOffset, endOffset, rangeStyle);
                }
            } else {
                generalAddRange(startOffset, endOffset, rangeStyle);
            }
        }

        this._hideCollapsedCaretsForVisibleSelection();

        this._textSelectionInner$.next({
            textRanges: this._getAllTextRanges(),
            rectRanges: this._getAllRectRanges(),
            segmentId,
            segmentPage,
            style,
            isEditing,
            options,
        });

        if (!ranges.length || options?.shouldFocus === false) {
            return true;
        }
        this._updateInputPosition({ forceFocus: options?.forceFocus });
        return true;
    }

    setCursorManually(
        evtOffsetX: number,
        evtOffsetY: number,
        isEditing = false,
        shouldFocusInput = false,
        options?: { strict?: boolean }
    ) {
        const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY, {
            strict: options?.strict ?? true,
            segmentId: this._currentSegmentId,
            segmentPage: this._currentSegmentPage,
        });

        const position = this._getNodePosition(startNode);

        if (position == null) {
            this._clearUnresolvedSelection();

            return;
        }

        if (startNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH) {
            position.isBack = true;
        }

        this._createTextRangeByAnchorPosition(position);

        this._textSelectionInner$.next({
            textRanges: this._getAllTextRanges(),
            rectRanges: this._getAllRectRanges(),
            segmentId: this._currentSegmentId,
            segmentPage: this._currentSegmentPage,
            style: this._selectionStyle,
            isEditing,
        });

        if (shouldFocusInput) {
            this._updateInputPosition({ forceFocus: true });
        }
    }

    // Sync canvas selection to dom selection.
    sync() {
        this._updateInputPosition();
    }

    setInputPosition(x: number, y: number) {
        this._positionInput(x, y);
    }

    activate(x: number, y: number, force = false) {
        this._positionInput(x, y);

        if ((force && !this._shouldPreserveExternalFocus()) || (!force && this.canFocusing)) {
            this.focus();
        }
    }

    protected _positionInput(x: number, y: number) {
        this._ensureHostContainer();
        this._container.style.position = 'fixed';
        const fixedContainer = this._container.offsetParent;
        const rect = fixedContainer?.getBoundingClientRect();
        this._container.style.left = `${x - (rect?.left ?? 0)}px`;
        this._container.style.top = `${y - (rect?.top ?? 0)}px`;
        this._container.style.zIndex = '1000';
    }

    hasFocus(): boolean {
        return this._getOwnerDocument().activeElement === this._input;
    }

    focus(): void {
        // The layout may mount after the input; keep focus inside its owning modal.
        this._ensureHostContainer();
        if (!this._input.hasAttribute('tabindex')) {
            this._input.tabIndex = -1;
        }
        this._input.focus({ preventScroll: true });
    }

    blur() {
        this._input.blur();
    }

    // FIXME: for editor cell editor we don't need to blur the input element
    deactivate() {
        this._container.style.left = '0px';
        this._container.style.top = '0px';
    }

    // Handler double click.
    __handleDblClick(evt: IPointerEvent | IMouseEvent, isEditing = false, shouldFocusInput = true) {
        const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;

        const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY, {
            strict: false,
            segmentId: this._currentSegmentId,
            segmentPage: this._currentSegmentPage,
        });
        if (startNode == null || startNode.node == null) {
            this._clearUnresolvedSelection();
            return;
        }

        const paragraphInfo = getParagraphInfoByGlyph(startNode.node);
        if (paragraphInfo == null) {
            return;
        }

        const { content, st, nodeIndex } = paragraphInfo;
        if (nodeIndex === -1) {
            return;
        }

        const isSheetEditor = this._context.unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || this._context.unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
        const wordBoundary = isSheetEditor
            ? getWordSelectionByIndex(content, nodeIndex, st, startNode.ratioX < 0.5)
            : getWordBoundaryByIndex(content, nodeIndex, st);

        if (wordBoundary != null) {
            this.removeAllRanges();

            const textRanges = [
                {
                    startOffset: wordBoundary.startOffset,
                    endOffset: wordBoundary.endOffset,
                },
            ];

            this.addDocRanges(textRanges, isEditing, {
                forceFocus: shouldFocusInput,
                shouldFocus: shouldFocusInput,
            });
        }
    }

    __handleTripleClick(evt: IPointerEvent | IMouseEvent) {
        const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;

        const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY, {
            strict: false,
            segmentId: this._currentSegmentId,
            segmentPage: this._currentSegmentPage,
        });
        if (startNode == null || startNode.node == null) {
            this._clearUnresolvedSelection();
            return;
        }

        const paragraphInfo = getParagraphInfoByGlyph(startNode.node);
        if (paragraphInfo == null) {
            return;
        }

        this.removeAllRanges();

        const { st, ed } = paragraphInfo;

        const textRanges: ISuccinctDocRangeParam[] = [
            {
                startOffset: st,
                endOffset: ed,
            },
        ];

        this.addDocRanges(textRanges, false, { forceFocus: true });
    }

    // Handle pointer down.
    __onPointDown(evt: IPointerEvent | IMouseEvent, shouldFocusInput = true) {
        const { scene, mainComponent } = this._context;
        const skeleton = this._docSkeletonManagerService.getSkeleton();

        const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;

        const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY, {
            strict: false,
            segmentId: this._currentSegmentId,
            segmentPage: this._currentSegmentPage,
        });

        const position = this._getNodePosition(startNode);

        if (position == null || startNode == null) {
            this._clearUnresolvedSelection();

            return;
        }

        if (startNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH) {
            position.isBack = true;
        }

        const docSelection = this._textSelectionInner$.value;
        if (startNode && evt.button === 2 && docSelection) {
            const nodeCharIndex = skeleton.findCharIndexByPosition(position);
            if (typeof nodeCharIndex === 'number' && docSelection.textRanges.some((textRange) => textRange.startOffset! <= nodeCharIndex && textRange.endOffset! > nodeCharIndex)) {
                return;
            }

            if (typeof nodeCharIndex === 'number' && docSelection.rectRanges.some((rectRange) => rectRange.startOffset! <= nodeCharIndex && rectRange.endOffset! >= nodeCharIndex)) {
                return;
            }
        }

        this._pendingSelection = null;
        const { segmentId, segmentPage } = startNode;

        const notes = this._context.unit.getSnapshot().notes;
        if (segmentId !== this._currentSegmentId &&
            ((segmentId && this._currentSegmentId) || notes?.[segmentId] || notes?.[this._currentSegmentId])) {
            this.setSegment(segmentId);
        }

        if (segmentId && segmentPage !== this._currentSegmentPage) {
            this.setSegmentPage(segmentPage);
        }

        this._anchorNodePosition = position;

        if (evt.shiftKey && this._getActiveRangeInstance()) {
            this._updateActiveRangePosition(position);
        } else if (evt.ctrlKey) {
            this._removeAllCollapsedTextRanges();
        } else if (!this._isEmpty()) {
            this._removeAllRanges();
        }

        scene.disableObjectsEvent();

        const disableAutoScroll = getEditorRuntimeConfig(this._context.unit)?.disableSelectionAutoScroll === true;
        const scrollTimer = disableAutoScroll ? undefined : ScrollTimer.create(scene);
        if (scrollTimer) {
            this._scrollTimers.push(scrollTimer);
            scrollTimer.startScroll(evtOffsetX, evtOffsetY);
        }

        this._onSelectionStart$.next(this._getActiveRangeInstance()?.startNodePosition);

        scene.getTransformer()?.clearSelectedObjects();

        let preMoveOffsetX = evtOffsetX;

        let preMoveOffsetY = evtOffsetY;
        this._onPointerEvent = true;
        this._scenePointerMoveSubs.push(scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
            const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
            scene.setCursor(CURSOR_TYPE.TEXT);

            if (Math.sqrt((moveOffsetX - preMoveOffsetX) ** 2 + (moveOffsetY - preMoveOffsetY) ** 2) < 3) {
                return;
            }

            this._tryMoving(moveOffsetX, moveOffsetY);

            scrollTimer?.scrolling(moveOffsetX, moveOffsetY, () => {
                this._tryMoving(moveOffsetX, moveOffsetY);
            });

            preMoveOffsetX = moveOffsetX;
            preMoveOffsetY = moveOffsetY;
        }));

        this._scenePointerUpSubs.push(scene.onPointerUp$.subscribeEvent(() => {
            [...this._scenePointerMoveSubs, ...this._scenePointerUpSubs].forEach((e) => {
                e.unsubscribe();
            });
            this._onPointerEvent = false;
            scene.enableObjectsEvent();

            // Add cursor.
            if (this._anchorNodePosition && !this._focusNodePosition) {
                if (evt.ctrlKey) {
                    // No need to add cursor when select multi text ranges by CTRL key.
                    this._disposeScrollTimers();
                    return;
                }

                const textRange = new TextRange(scene, mainComponent as Documents, skeleton, this._anchorNodePosition, undefined, this._selectionStyle, this._currentSegmentId, this._currentSegmentPage);
                this._addTextRange(textRange);
            } else if (this._anchorNodePosition && this._focusNodePosition) {
                for (const textRange of this._rangeListCache) {
                    if (evt.ctrlKey) {
                        if (textRange.collapsed) {
                            textRange.dispose();
                        } else {
                            this._addTextRange(textRange);
                        }
                    } else {
                        this._addTextRange(textRange);
                    }
                }

                this._addRectRanges(this._rectRangeListCache);

                this._rangeListCache = [];
                this._rectRangeListCache = [];
            }

            this._anchorNodePosition = null;
            this._focusNodePosition = null;

            this._emitCurrentSelection(false);

            this._disposeScrollTimers();
            if (shouldFocusInput) {
                this._updateInputPosition({ forceFocus: true });
            }
        }));
    }

    private _clearUnresolvedSelection(): void {
        // A new pointer target takes ownership even before its page is ready.
        // Clear the logical selection as well as its geometry so a later layout
        // publication or native input cannot restore the previous caret.
        this._anchorNodePosition = null;
        this._focusNodePosition = null;
        this._removeAllCacheRanges();
        this.addDocRanges([], false, { shouldFocus: false }, true);
        this.blur();
    }

    enterEditing(): boolean {
        if (!this._getActiveRangeInstance()) {
            return false;
        }

        this._setEditing(true);
        this._updateInputPosition({ forceFocus: true });
        return true;
    }

    exitEditing(): void {
        this._setEditing(false);
        this.blur();
    }

    removeAllRanges() {
        this._pendingSelection = null;
        this._removeAllRanges();
        this.deactivate();
    }

    getActiveTextRange() {
        return this._getActiveRangeInstance();
    }

    protected _setEditing(isEditing: boolean): void {
        const selection = this._textSelectionInner$.value;
        if (!selection || selection.isEditing === isEditing) {
            return;
        }

        this._textSelectionInner$.next({
            ...selection,
            isEditing,
        });
    }

    protected _emitCurrentSelection(isEditing: boolean): void {
        this._textSelectionInner$.next({
            textRanges: this._getAllTextRanges(),
            rectRanges: this._getAllRectRanges(),
            segmentId: this._currentSegmentId,
            segmentPage: this._currentSegmentPage,
            style: this._selectionStyle,
            isEditing,
        });
    }

    private _disposeScrollTimers() {
        this._scrollTimers.forEach((timer) => {
            timer?.dispose();
        });

        this._scrollTimers = [];
    }

    private _setSystemHighlightColorToStyle() {
        const { r, g, b, a } = getSystemHighlightColor();
        // Only set selection use highlight color.
        const style: ITextSelectionStyle = {
            strokeWidth: 1,
            stroke: 'rgba(0, 0, 0, 0)',
            strokeActive: 'rgba(0, 0, 0, 1)',
            fill: `rgba(${r}, ${g}, ${b}, ${a ?? 0.3})`,
        };

        this._setRangeStyle(style);
    }

    private _getAllTextRanges() {
        return this._rangeList.map(serializeTextRange);
    }

    private _getAllRectRanges() {
        return this._rectRangeList.map(serializeRectRange);
    }

    getAllTextRanges() {
        return this._getAllTextRanges();
    }

    getAllRectRanges() {
        return this._getAllRectRanges();
    }

    private _getActiveRange(): Nullable<ITextRangeWithStyle> {
        const activeRange = this._rangeList.find((range) => range.isActive());

        if (activeRange == null) {
            return null;
        }

        const { startOffset, endOffset } = activeRange;

        if (startOffset == null || endOffset == null) {
            return null;
        }

        return serializeTextRange(activeRange);
    }

    protected _getActiveRangeInstance() {
        return this._rangeList.find((range) => range.isActive());
    }

    override dispose() {
        this._pendingSelection = null;
        super.dispose();
        this._detachEvent();
        this._removeAllRanges();
        this._container.remove();
    }

    private _initDOM() {
        const { unitId } = this._context;
        const container = document.createElement('div');
        container.style.position = 'fixed';
        container.style.left = '0px';
        container.style.top = '0px';

        container.id = `univer-doc-selection-container-${unitId}`;

        const inputParent = document.createElement('div');
        const inputDom = document.createElement('div');

        inputParent.appendChild(inputDom);
        container.appendChild(inputParent);

        this._container = container;
        this._inputParent = inputParent;
        this._input = inputDom;

        this._initInput();
        this._initInputEvents();

        const host = this._layoutService.rootContainerElement;
        const hostElement = host?.isConnected ? host : document.body;
        hostElement.appendChild(container);
    }

    private _registerContainer() {
        this.disposeWithMe(
            // the content editable div should be regarded as part of the applications container
            this._layoutService.registerContainerElement(this._container)
        );
    }

    private _initInput() {
        this._inputParent.style.cssText = `
            position:absolute;
            height:1px;
            width:1px;
            overflow: hidden;
        `;

        this._input.contentEditable = 'true';

        // TODO: to be removed
        this._input.dataset.uComp = 'editor';
        this._input.id = `__editor_${this._context.unitId}`;
        this._input.style.cssText = `
            position: absolute;
            overflow: hidden;
            opacity: 1;
            background: #000;
            color: transparent;
            outline: none;
            z-index: -2;
            caret-color: transparent;
            white-space: pre-wrap;
            user-select: text;
        `;
    }

    protected _ensureHostContainer(): void {
        // Prefer the Univer root container (often inside a Portal) so focus stays within the modal subtree.
        const host = this._layoutService.rootContainerElement;
        if (host?.isConnected) {
            if (this._container.parentElement !== host) {
                host.appendChild(this._container);
            }
            return;
        }

        if (this._container.parentElement !== document.body) {
            document.body.appendChild(this._container);
        }
    }

    private _getOwnerDocument(): Document {
        return this._container?.ownerDocument ?? document;
    }

    private _getNodePosition(node: Nullable<INodeInfo>): Nullable<INodePosition> {
        if (node == null) {
            return;
        }

        const { node: glyph, ratioX, segmentPage } = node;

        const skeleton = this._docSkeletonManagerService.getSkeleton();
        const position = skeleton.findPositionByGlyph(glyph, segmentPage);

        if (position == null) {
            return;
        }

        const HALF = 0.5;
        let isBack = ratioX < HALF;

        if (glyph.glyphType === GlyphType.LIST) {
            isBack = true;
        }

        return {
            ...position,
            isBack,
        };
    }

    private _interactTextRanges(textRanges: TextRange[]) {
        const newTextRanges: TextRange[] = [];

        for (const range of this._rangeList) {
            if (textRanges.some((textRange) => textRange.isIntersection(range))) {
                range.dispose();
                continue;
            }

            newTextRanges.push(range);
        }

        this._rangeList = newTextRanges;
    }

    private _interactRectRanges(rectRanges: RectRange[]) {
        const newRanges: RectRange[] = [];

        for (const range of this._rectRangeList) {
            if (rectRanges.some((rectRange) => rectRange.isIntersection(range))) {
                range.dispose();
                continue;
            }

            newRanges.push(range);
        }

        this._rectRangeList = newRanges;
    }

    private _removeAllRanges() {
        this._removeAllTextRanges();
        this._removeAllRectRanges();
    }

    protected _removeAllCacheRanges() {
        this._rangeListCache.forEach((range) => {
            range.dispose();
        });

        this._rectRangeListCache.forEach((range) => {
            range.dispose();
        });

        this._rangeListCache = [];
        this._rectRangeListCache = [];
    }

    private _removeAllTextRanges() {
        this._rangeList.forEach((range) => {
            range.dispose();
        });

        this._rangeList = [];
    }

    private _removeAllRectRanges() {
        this._rectRangeList.forEach((range) => {
            range.dispose();
        });

        this._rectRangeList = [];
    }

    private _removeAllCollapsedTextRanges() {
        const newRanges: TextRange[] = [];

        for (const range of this._rangeList) {
            if (range.collapsed) {
                range.dispose();
                continue;
            }

            newRanges.push(range);
        }

        this._rangeList = newRanges;
    }

    private _hideCollapsedCaretsForVisibleSelection() {
        const expandedTextRanges = this._rangeList.filter((range) => !range.collapsed);
        if (expandedTextRanges.length === 0 && this._rectRangeList.length === 0) {
            return;
        }

        this._deactivateAllTextRanges();
        expandedTextRanges[expandedTextRanges.length - 1]?.activate();
    }

    private _deactivateAllTextRanges() {
        this._rangeList.forEach((range) => {
            range.deactivate();
        });
    }

    private _deactivateAllRectRanges() {
        this._rectRangeList.forEach((range) => {
            range.deactivate();
        });
    }

    private _addTextRangesToCache(textRanges: TextRange[]) {
        this._rangeListCache.push(...textRanges);
    }

    protected _addTextRange(textRange: TextRange) {
        this._deactivateAllTextRanges();
        textRange.activate();

        this._rangeList.push(textRange);
    }

    private _addRectRangesToCache(rectRanges: RectRange[]) {
        this._rectRangeListCache.push(...rectRanges);
    }

    protected _addRectRanges(rectRanges: RectRange[]) {
        if (rectRanges.length === 0) {
            return;
        }

        this._deactivateAllRectRanges();
        rectRanges[rectRanges.length - 1].activate();

        this._rectRangeList.push(...rectRanges);
    }

    private _createTextRangeByAnchorPosition(position: INodePosition) {
        this._removeAllRanges();

        const { scene, mainComponent } = this._context;
        const skeleton = this._docSkeletonManagerService.getSkeleton();

        const lastRange = new TextRange(scene, mainComponent as Documents, skeleton, position, undefined, this._selectionStyle, this._currentSegmentId, this._currentSegmentPage);

        this._addTextRange(lastRange);
    }

    private _updateActiveRangePosition(position: INodePosition) {
        const activeTextRange = this._getActiveRangeInstance();

        if (activeTextRange == null || activeTextRange.anchorNodePosition == null) {
            this._logService.error(
                '[DocSelectionRenderService] _updateActiveRangeFocusPosition: active range has no anchor'
            );

            return;
        }

        this._removeAllRanges();

        this._anchorNodePosition = activeTextRange.anchorNodePosition;
        this._focusNodePosition = position;

        const { scene, mainComponent } = this._context;
        const skeleton = this._docSkeletonManagerService.getSkeleton();

        const { _anchorNodePosition, _focusNodePosition, _selectionStyle, _currentSegmentId, _currentSegmentPage } = this;

        if (_anchorNodePosition == null || _focusNodePosition == null || mainComponent == null) {
            return;
        }

        const ranges = getRangeListFromSelection(
            _anchorNodePosition,
            _focusNodePosition,
            scene,
            mainComponent as Documents,
            skeleton,
            _selectionStyle,
            _currentSegmentId,
            _currentSegmentPage
        );

        if (ranges == null) {
            return;
        }

        const { textRanges, rectRanges } = ranges;

        this._addTextRangesToCache(textRanges);
        this._addRectRangesToCache(rectRanges);

        if (this._movingSelection$.observed) {
            this._movingSelection$.next({
                textRanges: this._rangeListCache.map(serializeTextRange),
                rectRanges: this._rectRangeListCache.map(serializeRectRange),
                segmentId: this._currentSegmentId,
                segmentPage: this._currentSegmentPage,
                style: this._selectionStyle,
                isEditing: false,
            });
        }
        this.deactivate();
    }

    private _isEmpty() {
        return this._rangeList.length === 0 && this._rectRangeList.length === 0;
    }

    private _getCanvasOffset() {
        // This is quiet ambiguous, when did the engine's canvas offset changes?
        const engine = this._context.scene?.getEngine() as Engine;
        return getCanvasOffsetByEngine(engine);
    }

    protected _updateInputPosition({ forceFocus = false, preserveFocus = false } = {}) {
        const activeRangeInstance = this._getActiveRangeInstance();
        const anchor = activeRangeInstance?.getAnchor();

        if (!anchor || (anchor && !anchor.visible) || this.activeViewPort == null) {
            if (preserveFocus || this._shouldPreserveExternalFocus() ||
                (!forceFocus && (this._isInUnfocusedFrame() || this._isAnotherEditorFocused()))) {
                return;
            }
            this.focus();
            return;
        }

        const { left, top } = anchor;

        const absoluteCoord = this.activeViewPort.getAbsoluteVector(Vector2.FromArray([left, top]));

        const { x, y } = absoluteCoord;

        let { left: canvasLeft, top: canvasTop } = this._getCanvasOffset();

        canvasLeft += x;

        canvasTop += y;

        if (preserveFocus) {
            this._positionInput(canvasLeft, canvasTop);
        } else {
            this.activate(canvasLeft, canvasTop, forceFocus);
        }
    }

    protected _tryMoving(moveOffsetX: number, moveOffsetY: number) {
        try {
            this._moving(moveOffsetX, moveOffsetY);
        } catch (error) {
            this._logService.error('[DocSelectionRenderService] Failed to update moving selection', error);
        }
    }

    private _moving(moveOffsetX: number, moveOffsetY: number) {
        const { _currentSegmentId: segmentId, _currentSegmentPage: segmentPage } = this;
        const focusNode = this._findNodeByCoord(moveOffsetX, moveOffsetY, {
            strict: true,
            segmentId,
            segmentPage,
        });

        const focusNodePosition = this._getNodePosition(focusNode);

        if (focusNodePosition == null || focusNode == null) {
            return;
        }

        const divide = focusNode?.node.parent;
        const nextGlyph = divide?.glyphGroup[divide.glyphGroup.indexOf(focusNode.node) + 1];

        // Should not select the last paragraph break.
        if (
            focusNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH &&
            nextGlyph?.streamType === DataStreamTreeTokenType.SECTION_BREAK
        ) {
            focusNodePosition.isBack = true;
        }

        if (this._shouldSnapBackwardFocusToGlyphStart(focusNode, focusNodePosition)) {
            focusNodePosition.isBack = true;
        }

        const { _anchorNodePosition, _selectionStyle } = this;
        const { scene, mainComponent } = this._context;
        const skeleton = this._docSkeletonManagerService.getSkeleton();

        if (_anchorNodePosition == null || mainComponent == null) {
            return;
        }

        const ranges = getRangeListFromSelection(
            _anchorNodePosition,
            focusNodePosition,
            scene,
            mainComponent as Documents,
            skeleton,
            _selectionStyle,
            segmentId,
            segmentPage
        );

        if (ranges == null) {
            return;
        }

        const { textRanges, rectRanges } = ranges;
        if (!this._hasVisibleSelectionRanges(textRanges, rectRanges)) {
            textRanges.forEach((range) => range.dispose());
            rectRanges.forEach((range) => range.dispose());
            return;
        }

        this._focusNodePosition = focusNodePosition;

        this._removeAllCacheRanges();

        if (this._rangeList.length > 0 && textRanges.length > 0) {
            this._interactTextRanges(textRanges);
        }

        if (this._rectRangeList.length > 0 && rectRanges.length > 0) {
            this._interactRectRanges(rectRanges);
        }

        this._addTextRangesToCache(textRanges);
        this._addRectRangesToCache(rectRanges);

        if (this._movingSelection$.observed) {
            this._movingSelection$.next({
                textRanges: this._rangeListCache.map(serializeTextRange),
                rectRanges: this._rectRangeListCache.map(serializeRectRange),
                segmentId: this._currentSegmentId,
                segmentPage: this._currentSegmentPage,
                style: this._selectionStyle,
                isEditing: false,
            });
        }
        this.deactivate();

        this._context.scene?.getEngine()?.setCapture();
    }

    private _hasVisibleSelectionRanges(textRanges: TextRange[], rectRanges: RectRange[]): boolean {
        return rectRanges.length > 0 || textRanges.some((range) => !range.collapsed);
    }

    private _shouldSnapBackwardFocusToGlyphStart(focusNode: INodeInfo, focusNodePosition: INodePosition): boolean {
        const anchorNodePosition = this._anchorNodePosition;
        if (!anchorNodePosition || !this._isBeforeNodePosition(focusNodePosition, anchorNodePosition)) {
            return false;
        }

        return this._isFirstSelectableGlyphInDivide(focusNode);
    }

    private _isBeforeNodePosition(left: INodePosition, right: INodePosition): boolean {
        if (!compareNodePositionLogic(left, right)) {
            return false;
        }

        return left.page !== right.page ||
            left.section !== right.section ||
            left.column !== right.column ||
            left.line !== right.line ||
            left.divide !== right.divide ||
            left.glyph !== right.glyph;
    }

    private _isFirstSelectableGlyphInDivide(nodeInfo: INodeInfo): boolean {
        const glyphGroup = nodeInfo.node.parent?.glyphGroup;
        if (!glyphGroup) {
            return false;
        }

        const firstSelectableGlyph = glyphGroup.find((glyph) => glyph.content && glyph.glyphType !== GlyphType.LIST);
        return firstSelectableGlyph === nodeInfo.node;
    }

    __attachScrollEvent() {
        const viewport = this.activeViewPort;
        if (!viewport) {
            return;
        }

        const { unitId } = this._context;

        if (this._viewPortObserverMap.has(unitId)) {
            return;
        }

        const scrollBefore = viewport.onScrollAfter$.subscribeEvent((param: IScrollObserverParam) => {
            const viewport = param.viewport;
            if (!viewport) {
                return;
            }

            const activeRangeInstance = this._getActiveRangeInstance();

            activeRangeInstance?.activeStatic();
        });

        const scrollStop = viewport.onScrollEnd$.subscribeEvent((param: IScrollObserverParam) => {
            const viewport = param.viewport;
            if (!viewport) {
                return;
            }

            const bounds = viewport.calcViewportInfo();

            const activeRangeInstance = this._getActiveRangeInstance();

            const anchor = activeRangeInstance?.getAnchor();

            if (!anchor || (anchor && !anchor.visible)) {
                return;
            }

            if (bounds) {
                const { left, top, right, bottom } = bounds.viewBound;

                if (anchor.left < left || anchor.left > right || anchor.top < top || anchor.top > bottom) {
                    activeRangeInstance?.deactivateStatic();
                    return;
                }
            }

            // A delayed scroll completion must not reclaim focus from a menu or another editor.
            this._updateInputPosition({ preserveFocus: true });
        });

        this._viewPortObserverMap.set(unitId, {
            scrollBefore,
            scrollStop,
        });
    }

    // FIXME: listeners here are not correctly disposed
    private _initInputEvents() {
        this.disposeWithMe(
            fromEvent(this._input, 'keydown').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                if (this._isIMEInputApply) {
                    return;
                }

                this._stopEmbedOwnedEditorShortcutPropagation(e);
                this._eventHandle(e, (config) => {
                    this._onKeydown$.next(config);
                });
            })
        );

        this.disposeWithMe(
            fromEvent(this._input, 'input').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                // A mixed text and rect selection can replace the selected document ranges.
                if ((e as InputEvent).inputType === 'historyUndo' || (e as InputEvent).inputType === 'historyRedo') {
                    return;
                }
                if (this._rectRangeList.length > 0 && this._getActiveRange() == null) {
                    e.stopPropagation();
                    return e.preventDefault();
                }

                if (this._isIMEInputApply) {
                    return;
                }

                this._eventHandle(e, (config) => {
                    this._onInputBefore$.next(config);
                    this._refreshMissingInputRange(config);
                    this._onInput$.next(config);
                });
            })
        );

        this.disposeWithMe(
            fromEvent(this._input, 'compositionstart').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                // Mixed select-all ranges have a text insertion anchor; table-only rect selections do not.
                if (this._rectRangeList.length > 0 && this._getActiveRange() == null) {
                    e.stopPropagation();
                    return e.preventDefault();
                }

                this._isIMEInputApply = true;

                this._eventHandle(e, (config) => {
                    this._onCompositionstart$.next(config);
                }, true);
            })
        );

        this.disposeWithMe(
            fromEvent(this._input, 'compositionend').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                this._isIMEInputApply = false;

                this._eventHandle(e, (config) => {
                    this._onCompositionend$.next(config);
                });
            })
        );

        this.disposeWithMe(
            fromEvent(this._input, 'compositionupdate').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                this._eventHandle(e, (config) => {
                    this._onInputBefore$.next(config);
                    this._refreshMissingInputRange(config);
                    this._onCompositionupdate$.next(config);
                }, true);
            })
        );

        this.disposeWithMe(
            fromEvent(this._input, 'paste').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                this._eventHandle(e, (config) => {
                    this._onPaste$.next(config);
                });
            })
        );

        this.disposeWithMe(
            fromEvent(this._input, 'focus').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                this._handleInputFocus(e);
            })
        );

        // this.disposeWithMe(
        //     fromEvent(this._input, 'pointerdown').subscribe((e) => {
        //         this._eventHandle(e, () => {
        //             this._onBlur$.next();
        //         });
        //     })
        // );

        this.disposeWithMe(
            fromEvent(this._input, 'blur').subscribe((e) => {
                if (this._shouldSuppressHostHiddenEditorEvent(e)) {
                    return;
                }
                this._handleInputBlur(e);
            })
        );
    }

    private _refreshMissingInputRange(config: IEditorInputConfig): void {
        // Opening a Sheet editor in before-input can establish its first caret after the event snapshot was captured.
        if (config.activeRange == null) {
            config.activeRange = this._getActiveRange();
            config.rangeList = this._getAllTextRanges();
        }
        const { unitId } = this._context;
        if (config.activeRange != null || unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY || this._context.unit.getBody()?.dataStream !== '\r\n') {
            return;
        }
        const selection = this._docSelectionManagerService.getSelectionInfo({ unitId, subUnitId: unitId });
        if (selection == null || selection.textRanges.length !== 1 || selection.rectRanges.length > 0) {
            return;
        }
        const caret = selection.textRanges[0];
        if (!caret.isActive || caret.startOffset !== 0 || caret.endOffset !== 0) {
            return;
        }
        // A cleared formula bar can receive native input before its empty caret has render geometry.
        config.activeRange = { ...caret, segmentId: selection.segmentId, segmentPage: selection.segmentPage };
        config.rangeList = [config.activeRange];
    }

    protected _handleInputFocus(event: Event): void {
        this._eventHandle(event, (config) => {
            this._onFocus$.next(config);
        });
    }

    protected _handleInputBlur(event: Event): void {
        this._setEditing(false);
        this._emitInputBlur(event);
    }

    protected _emitInputBlur(event: Event): void {
        this._eventHandle(event, (config) => {
            this._onBlur$.next(config);
        });
    }

    private _eventHandle(
        e: Event | CompositionEvent | KeyboardEvent,
        func: (config: IEditorInputConfig) => void,
        preserveInput = false
    ) {
        const content = this._input.textContent || '';

        if (!preserveInput) {
            this._input.innerHTML = '';
        }

        // Geometry remains on the previous page until the edited page is ready.
        // Continue native input from the existing logical selection only while
        // that exact selection is waiting for publication.
        const pendingSelection = this._getPendingSelection();
        const rangeList = pendingSelection?.textRanges.map((range) => ({
            segmentId: pendingSelection.segmentId,
            segmentPage: pendingSelection.segmentPage,
            style: pendingSelection.style,
            ...range,
        })) ?? this._getAllTextRanges();
        const activeRange = pendingSelection == null
            ? this._getActiveRange()
            : rangeList.find((range) => range.isActive);

        func({
            event: e,
            content,
            activeRange,
            rangeList,
        });
    }

    private _shouldSuppressHostHiddenEditorEvent(event: Event): boolean {
        const unitId = this._context.unitId;
        if (isInternalEditorID(unitId)) {
            return false;
        }

        if (this._embedRuntimeFocusCoordinator?.isChildUnitRuntimeEvent(unitId, event.target, event)) {
            return false;
        }

        if (this._embedRuntimeFocusCoordinator?.isChildUnitInActiveSession(unitId)) {
            return false;
        }

        if (event.target instanceof HTMLElement && this._containsCurrentEmbedRuntimeElement(event.target)) {
            return false;
        }

        if (this._embedRuntimeFocusCoordinator?.shouldSuppressHostInteraction(unitId, event.target, event)) {
            event.stopPropagation();
            if (event.cancelable) {
                event.preventDefault();
            }
            if (event.type === 'focus' && event.target instanceof HTMLElement) {
                event.target.blur();
            }
            return true;
        }

        return false;
    }

    private _stopEmbedOwnedEditorShortcutPropagation(event: Event): void {
        if (!(event instanceof KeyboardEvent) || !this._getCurrentEmbedOwner()) {
            return;
        }

        const key = event.key.toLowerCase();
        const isSelectAllShortcut = key === 'a' && (event.metaKey || event.ctrlKey);
        if (!isSelectAllShortcut) {
            return;
        }

        event.stopPropagation();
    }

    private _getTransformCoordForDocumentOffset(evtOffsetX: number, evtOffsetY: number) {
        const document = this._context.mainComponent as Documents;
        const { documentTransform } = document.getOffsetConfig();

        if (this.activeViewPort == null || documentTransform == null) {
            return;
        }

        const originCoord = this.activeViewPort.transformVector2SceneCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));

        if (!originCoord) {
            return;
        }

        return documentTransform.clone().invert().applyPoint(originCoord);
    }

    private _findNodeByCoord(evtOffsetX: number, evtOffsetY: number, restrictions: IFindNodeRestrictions) {
        const coord = this._getTransformCoordForDocumentOffset(evtOffsetX, evtOffsetY);

        if (coord == null) {
            return;
        }

        const document = this._context.mainComponent as Documents;
        const skeleton = this._docSkeletonManagerService.getSkeleton();

        const {
            pageLayoutType = PageLayoutType.VERTICAL,
            pageMarginLeft,
            pageMarginTop,
        } = document.getOffsetConfig();

        const nodeInfo = skeleton.findNodeByCoord(
            coord,
            pageLayoutType,
            pageMarginLeft,
            pageMarginTop,
            restrictions
        );

        return nodeInfo;
    }

    private _shouldPreserveExternalFocus(): boolean {
        const ownerDocument = this._getOwnerDocument();
        const activeElement = ownerDocument.activeElement;
        const currentEmbedOwner = this._getCurrentEmbedOwner();
        // Layout and drawing refreshes must not take focus from native controls or open menu buttons.
        if (activeElement?.closest('input, textarea, select, [data-slot="popover-content"][data-state="open"]')) {
            return true;
        }

        if (this._embedRuntimeFocusCoordinator?.isChildUnitInActiveSession(this._context.unitId)) {
            return false;
        }

        if (this._embedRuntimeFocusCoordinator?.isChildUnitRuntimeEvent(this._context.unitId, activeElement)) {
            return false;
        }

        if (activeElement instanceof HTMLElement && this._containsOwnEditorElement(activeElement)) {
            return false;
        }

        if (activeElement instanceof HTMLElement && this._containsCurrentEmbedRuntimeElement(activeElement)) {
            return false;
        }

        if (this._embedRuntimeFocusCoordinator?.shouldSuppressHostInteraction(this._context.unitId, activeElement)) {
            return true;
        }

        if (currentEmbedOwner && this._embedInteractionBoundaryService?.contains(currentEmbedOwner, activeElement)) {
            return true;
        }

        if (activeElement instanceof HTMLElement && this._containsCurrentLayoutElement(activeElement)) {
            return false;
        }

        return this._embedInteractionBoundaryService?.hasRecentInteractionFor?.(currentEmbedOwner, ownerDocument) === true;
    }

    private _isInUnfocusedFrame(): boolean {
        const ownerDocument = this._getOwnerDocument();
        const ownerWindow = ownerDocument.defaultView;
        return ownerWindow != null && ownerWindow.parent !== ownerWindow && !ownerDocument.hasFocus();
    }

    private _isAnotherEditorFocused(): boolean {
        const activeElement = this._getOwnerDocument().activeElement;
        return activeElement instanceof HTMLElement &&
            activeElement !== this._input &&
            activeElement.dataset.uComp === this._input.dataset.uComp;
    }

    private _containsCurrentEmbedRuntimeElement(element: HTMLElement): boolean {
        const currentEmbedOwner = this._getCurrentEmbedOwner();
        if (!currentEmbedOwner) {
            return false;
        }

        const activeEmbedOwner = this._getElementEmbedOwner(element);
        return activeEmbedOwner === currentEmbedOwner && this._containsCurrentLayoutElement(element);
    }

    private _getCurrentEmbedOwner(): string | undefined {
        const rootContainerElement = this._layoutService?.rootContainerElement;
        return this._getElementEmbedOwner(this._input) ??
            this._getElementEmbedOwner(this._container) ??
            this._getElementEmbedOwner(rootContainerElement instanceof HTMLElement ? rootContainerElement : undefined);
    }

    private _getElementEmbedOwner(element: HTMLElement | null | undefined): string | undefined {
        if (!element || typeof element.closest !== 'function') {
            return undefined;
        }

        return element.closest(`[${DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}]`)?.getAttribute(DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE) ?? undefined;
    }

    private _containsOwnEditorElement(element: HTMLElement): boolean {
        return this._container === element ||
            this._input === element ||
            (typeof this._container?.contains === 'function' && this._container.contains(element)) ||
            (typeof this._inputParent?.contains === 'function' && this._inputParent.contains(element));
    }

    private _containsCurrentLayoutElement(element: HTMLElement): boolean {
        const layoutService = this._layoutService as (ILayoutService & {
            checkElementInCurrentContainers?: (element: HTMLElement) => boolean;
        }) | undefined;
        if (!layoutService) {
            return this._container === element || (
                typeof this._container?.contains === 'function' && this._container.contains(element)
            );
        }
        if (layoutService.checkElementInCurrentContainers?.(element)) {
            return true;
        }

        const root = layoutService.rootContainerElement;
        return root === element ||
            root?.contains(element) === true ||
            this._container === element ||
            (typeof this._container?.contains === 'function' && this._container.contains(element));
    }

    private _detachEvent() {
        this._onInputBefore$.complete();
        this._onKeydown$.complete();
        this._onInput$.complete();
        this._onCompositionstart$.complete();
        this._onCompositionupdate$.complete();
        this._onCompositionend$.complete();
        this._onSelectionStart$.complete();
        this._textSelectionInner$.complete();
        this._movingSelection$.complete();
        this._onPaste$.complete();
        this._onFocus$.complete();
        this._onBlur$.complete();
        this._onPointerDown$.complete();
        this._segmentContext$.complete();
    }
}