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.

20.8 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 { IDisposable, INeedCheckDisposable, Injector, ITextRangeParam } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { BaseObject, Documents, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';
import type { IPopup } from '@univerjs/ui';
import type { Observable } from 'rxjs';
import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService } from '@univerjs/core';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService, pxToNum } from '@univerjs/engine-render';
import { ICanvasPopupService } from '@univerjs/ui';
import { animationFrameScheduler, BehaviorSubject, filter, map, throttleTime } from 'rxjs';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
import { findDocRangeNodePositions, NodePositionConvertToCursor } from './selection/convert-text-range';
import { getLineBounding } from './selection/text-range';

export function transformBound2OffsetBound(originBound: IBoundRectNoAngle, scene: Scene): IBoundRectNoAngle {
    const topLeft = transformPosition2Offset(originBound.left, originBound.top, scene);
    const bottomRight = transformPosition2Offset(originBound.right, originBound.bottom, scene);

    return {
        left: topLeft.x,
        top: topLeft.y,
        right: bottomRight.x,
        bottom: bottomRight.y,
    };
}

export function transformPosition2Offset(x: number, y: number, scene: Scene) {
    const { scaleX, scaleY } = scene.getAncestorScale();
    const viewMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
    if (!viewMain) {
        return {
            x,
            y,
        };
    }

    const { viewportScrollX: actualScrollX, viewportScrollY: actualScrollY } = viewMain;

    const offsetX = (x - actualScrollX) * scaleX;

    const offsetY = (y - actualScrollY) * scaleY;

    return {
        x: offsetX,
        y: offsetY,
    };
}

export function transformOffset2Bound(offsetX: number, offsetY: number, scene: Scene) {
    const { scaleX, scaleY } = scene.getAncestorScale();
    const viewMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
    if (!viewMain) {
        return {
            x: offsetX,
            y: offsetY,
        };
    }

    const { viewportScrollX: actualScrollX, viewportScrollY: actualScrollY } = viewMain;

    const x = offsetX / scaleX + actualScrollX;

    const y = offsetY / scaleY + actualScrollY;

    return {
        x,
        y,
    };
}

export interface IDocCanvasPopup extends Omit<IPopup, 'anchorRect$' | 'children' | 'unitId' | 'subUnitId' | 'canvasElement'> {
    /** Notify when a business-owned rect changes independently of scene transforms. */
    positionChanges$?: Observable<unknown>;
    /** Defaults to true. Passive hover affordances can track layout without holding it. */
    requiresStableLayout?: boolean;
    mask?: boolean;
    extraProps?: Record<string, unknown>;
    multipleDirection?: IPopup['direction'];
    /** Anchor at the focus end while retaining the entire selection for outside-click exclusion. */
    rangeAnchor?: 'selection-end';
}

export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRender): IBoundRectNoAngle[] | undefined => {
    const { scene, mainComponent, engine } = currentRender;
    const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();
    let positions: ReturnType<typeof findDocRangeNodePositions>;
    if (range.collapsed) {
        // Paragraph separators are valid caret anchors, including at the start of an empty paragraph.
        const caretPosition = skeleton.findNodePositionByCharIndex(
            range.startOffset,
            true,
            range.segmentId,
            range.segmentPage
        );
        if (caretPosition) {
            positions = { startPosition: caretPosition, endPosition: caretPosition };
        }
    } else {
        positions = findDocRangeNodePositions(
            skeleton,
            range.startOffset,
            range.endOffset - 1,
            range.segmentId,
            range.segmentPage
        );
    }
    const document = mainComponent as Documents;

    if (!positions) {
        return;
    }

    const documentOffsetConfig = document.getOffsetConfig();
    const { docsLeft, docsTop } = documentOffsetConfig;
    const canvasElement = engine.getCanvasElement();
    if (canvasElement == null) {
        return;
    }

    const canvasClientRect = canvasElement.getBoundingClientRect();
    const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width
    const { top, left, width } = canvasClientRect; // real width affected by scale
    const scaleAdjust = width / widthOfCanvas;

    const { scaleX, scaleY } = scene.getAncestorScale();
    const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);
    const { borderBoxPointGroup } = convertor.getRangePointData(
        positions.startPosition,
        range.collapsed ? positions.startPosition : positions.endPosition
    );
    const bounds = getLineBounding(borderBoxPointGroup);
    const res = bounds.map((bound) => transformBound2OffsetBound(bound, scene)).map((i) => ({
        left: (i.left + docsLeft * scaleX) * scaleAdjust + left,
        right: (i.right + docsLeft * scaleX) * scaleAdjust + left,
        top: (i.top + docsTop * scaleY) * scaleAdjust + top,
        bottom: (i.bottom + docsTop * scaleY) * scaleAdjust + top,
    }));

    return res;
};

export class DocCanvasPopManagerService extends Disposable {
    private readonly _popupCountByUnit = new Map<string, number>();
    private readonly _popupUnits$ = new BehaviorSubject<ReadonlySet<string>>(new Set());
    readonly popupUnits$ = this._popupUnits$.asObservable();

    constructor(
        @Inject(ICanvasPopupService) private readonly _globalPopupManagerService: ICanvasPopupService,
        @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @ICommandService private readonly _commandService: ICommandService
    ) {
        super();
    }

    override dispose(): void {
        this._popupCountByUnit.clear();
        this._popupUnits$.next(new Set());
        this._popupUnits$.complete();
        super.dispose();
    }

    private _beginPopupActivity(unitId: string): IDisposable {
        this._popupCountByUnit.set(unitId, (this._popupCountByUnit.get(unitId) ?? 0) + 1);
        this._publishPopupUnits();

        let disposed = false;
        return {
            dispose: () => {
                if (disposed) {
                    return;
                }
                disposed = true;

                const count = this._popupCountByUnit.get(unitId) ?? 0;
                if (count <= 1) {
                    this._popupCountByUnit.delete(unitId);
                } else {
                    this._popupCountByUnit.set(unitId, count - 1);
                }
                this._publishPopupUnits();
            },
        };
    }

    private _publishPopupUnits(): void {
        this._popupUnits$.next(new Set(this._popupCountByUnit.keys()));
    }

    getRangeBounds(range: ITextRangeParam, unitId: string): IBoundRectNoAngle[] | undefined {
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        return currentRender ? calcDocRangePositions(range, currentRender) : undefined;
    }

    private _shouldUpdateForCommand(commandInfo: { id: string; params?: unknown }, unitId: string): boolean {
        if (commandInfo.id !== SetDocZoomRatioOperation.id && commandInfo.id !== RichTextEditingMutation.id) {
            return false;
        }

        const params = commandInfo.params as IRichTextEditingMutationParams | undefined;
        return params?.unitId == null || params.unitId === unitId;
    }

    private _createRectPositionObserver(rect: IBoundRectNoAngle | (() => IBoundRectNoAngle), currentRender: IRender) {
        const calc = () => {
            const { scene, engine } = currentRender;
            const bound: IBoundRectNoAngle = typeof rect === 'function' ? rect() : rect;
            const canvasElement = engine.getCanvasElement();
            if (canvasElement == null) {
                return;
            }

            const canvasClientRect = canvasElement.getBoundingClientRect();
            const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width

            const offsetBound = transformBound2OffsetBound(bound, scene);
            const { top: topOffset, left: leftOffset, width: domWidth } = canvasClientRect;
            const scaleAdjust = domWidth / widthOfCanvas;

            const position = {
                left: (offsetBound.left * scaleAdjust) + leftOffset,
                right: (offsetBound.right * scaleAdjust) + leftOffset,
                top: (offsetBound.top * scaleAdjust) + topOffset,
                bottom: (offsetBound.bottom * scaleAdjust) + topOffset,
            };
            return position;
        };

        const position = calc();
        if (position == null) {
            throw new Error(`Current render canvas not found, unitId: ${currentRender.unitId}`);
        }

        const position$ = new BehaviorSubject<IBoundRectNoAngle>(position);
        const disposable = new DisposableCollection();
        const updatePosition = () => {
            try {
                const newPosition = calc();
                const previous = position$.value;
                if (newPosition && (newPosition.left !== previous.left || newPosition.right !== previous.right ||
                    newPosition.top !== previous.top || newPosition.bottom !== previous.bottom)) {
                    position$.next(newPosition);
                }
            } catch {
                // The popup may outlive an embedded render while its host switches tabs.
                // Keep the last anchor until the popup is disposed.
            }
        };

        disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
            if (this._shouldUpdateForCommand(commandInfo, currentRender.unitId)) {
                updatePosition();
            }
        }));

        const viewMain = currentRender.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
        if (viewMain) {
            disposable.add(viewMain.onScrollAfter$.subscribeEvent(() => {
                updatePosition();
            }));
        }

        disposable.add(currentRender.scene.onTransformChange$.subscribeEvent(() => {
            updatePosition();
        }));

        return {
            position,
            position$,
            disposable,
            updatePosition,
        };
    }

    private _createObjectPositionObserver(
        targetObject: BaseObject,
        currentRender: IRender
    ) {
        const getBound = () => {
            const { left, top, width, height } = targetObject;
            const bound: IBoundRectNoAngle = {
                left,
                right: left + width,
                top,
                bottom: top + height,
            };
            return bound;
        };

        const observer = this._createRectPositionObserver(getBound, currentRender);
        observer.disposable.add(targetObject.onTransformChange$.subscribeEvent(observer.updatePosition));
        return observer;
    }

    private _createRangePositionObserver(range: ITextRangeParam, currentRender: IRender) {
        const positions = calcDocRangePositions(range, currentRender) ?? [];
        const positions$ = new BehaviorSubject(positions);
        const disposable = new DisposableCollection();
        const updatePositions = () => {
            try {
                positions$.next(calcDocRangePositions(range, currentRender) ?? []);
            } catch {
                // The popup may outlive an embedded render while its host switches tabs.
                // Keep the last anchor until the popup is disposed.
            }
        };

        const layoutSubscription = currentRender.with(DocSkeletonManagerService).getSkeleton().dirty$?.subscribe(updatePositions);
        if (layoutSubscription) {
            disposable.add(layoutSubscription);
        }
        disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
            if (this._shouldUpdateForCommand(commandInfo, currentRender.unitId)) {
                updatePositions();
            }
        }));

        const viewMain = currentRender.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
        if (viewMain) {
            disposable.add(viewMain.onScrollAfter$.subscribeEvent(() => {
                updatePositions();
            }));
        }

        disposable.add(currentRender.scene.onTransformChange$.subscribeEvent(() => {
            updatePositions();
        }));
        if (currentRender.mainComponent) {
            disposable.add(currentRender.mainComponent.onTransformChange$.subscribeEvent(updatePositions));
        }

        return {
            positions,
            positions$,
            disposable,
        };
    }

    attachPopupToRect(rect: IBoundRectNoAngle | (() => IBoundRectNoAngle), popup: IDocCanvasPopup, unitId: string): INeedCheckDisposable {
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        if (!currentRender) {
            throw new Error(`Current render not found, unitId: ${unitId}`);
        }
        const popupInjector = this._resolveEmbeddedPopupInjector(unitId, currentRender);
        const popupManagerService = this._resolvePopupManagerService(popupInjector);

        const { position, position$, disposable, updatePosition } = this._createRectPositionObserver(rect, currentRender);
        if (popup.positionChanges$) {
            disposable.add(popup.positionChanges$.subscribe(updatePosition));
        }
        const id = popupManagerService.addPopup({
            ...popup,
            unitId,
            subUnitId: 'default',
            connectorInjector: popupInjector,
            anchorRect: position,
            anchorRect$: position$.pipe(throttleTime(0, animationFrameScheduler, { leading: true, trailing: true })),
            canvasElement: currentRender.engine.getCanvasElement(),
        });
        const popupActivity = popup.requiresStableLayout === false ? null : this._beginPopupActivity(unitId);

        return {
            dispose: () => {
                popupManagerService.removePopup(id);
                position$.complete();
                disposable.dispose();
                popupActivity?.dispose();
            },
            canDispose: () => popupManagerService.activePopupId !== id,
        };
    }

    // #region attach to object
    /**
     * attach a popup to canvas object
     * @param targetObject target canvas object
     * @param popup popup item
     * @returns disposable
     */
    attachPopupToObject(targetObject: BaseObject, popup: IDocCanvasPopup, unitId: string): INeedCheckDisposable {
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        if (!currentRender) {
            throw new Error(`Current render not found, unitId: ${unitId}`);
        }
        const popupInjector = this._resolveEmbeddedPopupInjector(unitId, currentRender);
        const popupManagerService = this._resolvePopupManagerService(popupInjector);

        const { position, position$, disposable } = this._createObjectPositionObserver(targetObject, currentRender);
        const id = popupManagerService.addPopup({
            ...popup,
            unitId,
            subUnitId: 'default',
            connectorInjector: popupInjector,
            anchorRect: position,
            anchorRect$: position$.pipe(throttleTime(0, animationFrameScheduler, { leading: true, trailing: true })),
            canvasElement: currentRender.engine.getCanvasElement(),
        });
        const popupActivity = popup.requiresStableLayout === false ? null : this._beginPopupActivity(unitId);

        return {
            dispose: () => {
                popupManagerService.removePopup(id);
                position$.complete();
                disposable.dispose();
                popupActivity?.dispose();
            },
            canDispose: () => popupManagerService.activePopupId !== id,
        };
    }

    // #endregion
    // #region attach to range
    /**
     * attach a popup to doc range
     * @param range doc range
     * @param popup popup item
     * @param unitId unit id
     * @returns disposable
     */
    attachPopupToRange(range: ITextRangeParam, popup: IDocCanvasPopup, unitId: string): INeedCheckDisposable {
        const doc = this._univerInstanceService.getUnit(unitId);
        if (!doc) {
            throw new Error(`Document not found, unitId: ${unitId}`);
        }
        const { direction = 'top', multipleDirection } = popup;
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        if (!currentRender) {
            throw new Error(`Current render not found, unitId: ${unitId}`);
        }
        const popupInjector = this._resolveEmbeddedPopupInjector(unitId, currentRender);
        const popupManagerService = this._resolvePopupManagerService(popupInjector);

        const { positions$: bounds$, disposable } = this._createRangePositionObserver(range, currentRender);
        const getAnchor = (bounds: IBoundRectNoAngle[]) => {
            if (popup.rangeAnchor === 'selection-end') {
                const backward = range.direction === 'backward';
                const bound = backward ? bounds[0] : bounds[bounds.length - 1];
                const x = backward ? bound.left : bound.right;
                return { ...bound, left: x, right: x };
            }
            return direction.includes('top') ? bounds[0] : bounds[bounds.length - 1];
        };
        // Coalesce Docs layout notifications before the shared popup's frame throttle.
        const popupBounds$ = bounds$.pipe(throttleTime(0, animationFrameScheduler, { leading: true, trailing: true }));
        const position$ = popupBounds$.pipe(filter((bounds) => bounds.length > 0), map(getAnchor));
        let id: string | undefined;
        let popupActivity: IDisposable | null = null;
        const removePopup = () => {
            if (id != null) {
                popupManagerService.removePopup(id);
                id = undefined;
            }
            popupActivity?.dispose();
            popupActivity = null;
        };

        disposable.add(bounds$.subscribe((bounds) => {
            if (bounds.length === 0) {
                removePopup();
                return;
            }
            if (id != null) {
                return;
            }
            id = popupManagerService.addPopup({
                ...popup,
                unitId,
                subUnitId: 'default',
                connectorInjector: popupInjector,
                anchorRect: getAnchor(bounds),
                anchorRect$: position$,
                excludeRects: bounds,
                excludeRects$: popupBounds$,
                direction: (['top', 'bottom', 'horizontal'].some((i) => direction.includes(i)))
                    ? bounds.length > 1
                        ? multipleDirection ?? direction
                        : direction
                    : direction,
                canvasElement: currentRender.engine.getCanvasElement(),
            });
            popupActivity = popup.requiresStableLayout === false ? null : this._beginPopupActivity(unitId);
        }));

        return {
            dispose: () => {
                removePopup();
                bounds$.complete();
                disposable.dispose();
            },
            canDispose: () => id == null || popupManagerService.activePopupId !== id,
        };
    }
    // #endregion

    private _resolveEmbeddedPopupInjector(unitId: string, currentRender: IRender): Injector | undefined {
        const isEmbeddedRender = currentRender.isMainScene === false ||
            this._univerInstanceService.getUnitCreateOptions(unitId)?.embeddedRender === true;
        return isEmbeddedRender
            ? currentRender.getInjector?.()
            : undefined;
    }

    private _resolvePopupManagerService(popupInjector: Injector | undefined): ICanvasPopupService {
        return popupInjector?.has(ICanvasPopupService)
            ? popupInjector.get(ICanvasPopupService)
            : this._globalPopupManagerService;
    }
}