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.

21.1 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, IPosition, Nullable } from '@univerjs/core';
import type { DocumentSkeleton, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';
import {
    Disposable,
    DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
    HorizontalAlign,
    IConfigService,
    IUniverInstanceService,
    Optional,
    UniverInstanceType,
    VerticalAlign,
    WrapStrategy,
} from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { DOCS_COMPONENT_MAIN_LAYER_INDEX, VIEWPORT_KEY } from '@univerjs/docs-ui';
import {
    convertTextRotation,
    fixLineWidthByScale,
    getCurrentTypeOfRenderer,
    IRenderManagerService,
    Rect,
    ScrollBar,
} from '@univerjs/engine-render';
import { ILayoutService } from '@univerjs/ui';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { IEditorBridgeService } from '../editor-bridge.service';
import { ISheetEmbedFloatingGeometryService } from '../sheet-embed-integration.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
import { ICellEditorManagerService } from './cell-editor-manager.service';

const EDITOR_INPUT_SELF_EXTEND_GAP = 5;

const EDITOR_BORDER_SIZE = 2;

interface ICanvasOffset {
    left: number;
    top: number;
}

export class SheetCellEditorResizeService extends Disposable {
    private _editorWidth = 0;

    private _editorHeight = 0;

    private _initialEditorSize: Nullable<{ width: number; height: number }> = null;

    private _cellSize: Nullable<{ width: number; height: number }> = null;

    constructor(
        @ILayoutService private readonly _layoutService: ILayoutService,
        @ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
        @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
        @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @IConfigService private readonly _configService: IConfigService,
        @Optional(ISheetEmbedFloatingGeometryService) private readonly _embedFloatingGeometryService?: ISheetEmbedFloatingGeometryService
    ) {
        super();

        this.disposeWithMe(this._editorBridgeService.visible$.subscribe(({ visible }) => {
            if (!visible) {
                this._editorWidth = 0;
                this._editorHeight = 0;
                this._initialEditorSize = null;
                this._cellSize = null;
            }
        }));
    }

    private get _currentRenderer() {
        return getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET, this._univerInstanceService, this._renderManagerService);
    }

    private get _editingUnitId() {
        return this._editorBridgeService.getEditCellState()?.unitId ?? '';
    }

    private get _editingRenderer() {
        return this._renderManagerService.getRenderUnitById(this._editingUnitId);
    }

    private get _renderer() {
        return this._editingRenderer ?? this._currentRenderer;
    }

    private get _sheetSkeletonManagerService() {
        return this._renderer?.with(SheetSkeletonManagerService);
    }

    private get engine() {
        return this._renderer?.engine;
    }

    fitTextSize(callback?: () => void) {
        const param = this._editorBridgeService.getEditCellState();
        if (!param) return;
        const { position, documentLayoutObject, canvasOffset, scaleX, scaleY } = param;

        const { startX, startY, endX, endY } = position;
        const cellWidth = endX - startX;
        const cellHeight = endY - startY;
        const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);

        if (documentDataModel == null) {
            return;
        }

        const documentSkeleton = this._getEditorSkeleton();
        if (!documentSkeleton) return;
        this._syncCellSize(cellWidth / scaleX, cellHeight / scaleY);
        // Cell editors are embedded docs with unspecified compatibility mode. Reset before
        // measuring so stale page width from a previous resize does not leak into this editor.
        documentSkeleton.resetInitialWidth();

        const info = this._predictingSize(
            position,
            canvasOffset,
            documentSkeleton,
            documentLayoutObject,
            scaleX,
            scaleY
        );
        if (!info || info.actualWidth <= 0) return;
        let { actualWidth, actualHeight } = info;
        const { verticalAlign, horizontalAlign, paddingData, fill } = documentLayoutObject;
        actualWidth = actualWidth + (paddingData.l ?? 0) * scaleX + (paddingData.r ?? 0) * scaleX;
        actualHeight = actualHeight + (paddingData.t ?? 0) * scaleY + (paddingData.b ?? 0) * scaleY;
        const contentWidth = cellWidth < actualWidth ? Math.ceil(actualWidth) : cellWidth;
        const contentHeight = cellHeight < actualHeight ? Math.ceil(actualHeight) : cellHeight;
        const editorWidth = Math.max(contentWidth, Math.min(this._editorWidth * scaleX, info.maxSize.width));
        const editorHeight = Math.max(contentHeight, Math.min(this._editorHeight * scaleY, info.maxSize.height));

        // Set the top margin under vertical alignment.
        let offsetTop = 0;

        if (verticalAlign === VerticalAlign.MIDDLE) {
            offsetTop = (editorHeight - actualHeight) / 2 / scaleY;
        } else if (verticalAlign === VerticalAlign.TOP) {
            offsetTop = paddingData.t || 0;
        } else {
            // VerticalAlign.UNSPECIFIED follow the same rule as HorizontalAlign.BOTTOM.
            offsetTop = (editorHeight - actualHeight) / scaleY;
        }

        let offsetLeft = 0;
        if (horizontalAlign === HorizontalAlign.RIGHT) {
            offsetLeft = (editorWidth - actualWidth) / scaleX;
        } else if (horizontalAlign !== HorizontalAlign.CENTER) {
            offsetLeft = paddingData.l || 0;
        }
        offsetTop = Math.max(offsetTop, paddingData.t || 0);
        offsetLeft = Math.max(offsetLeft, paddingData.l || 0);
        documentDataModel.updateDocumentDataMargin({
            t: offsetTop,
            l: offsetLeft,
        });

        documentSkeleton.calculate();
        this._editAreaProcessing(
            { width: editorWidth, height: editorHeight, contentWidth },
            position,
            canvasOffset,
            fill,
            scaleX,
            scaleY,
            horizontalAlign,
            callback
        );
    }

    private _syncCellSize(width: number, height: number) {
        if (this._cellSize && (
            Math.abs(this._cellSize.width - width) > 1e-6 ||
            Math.abs(this._cellSize.height - height) > 1e-6
        )) {
            // Refit resized cells while still covering the original worksheet text until the edit is submitted.
            this._editorWidth = this._initialEditorSize?.width ?? 0;
            this._editorHeight = this._initialEditorSize?.height ?? 0;
        }
        this._cellSize = { width, height };
    }

    /**
     * Mainly used to pre-calculate the width of the editor,
     * to determine whether it needs to be automatically widened.
     */
    private _predictingSize(
        actualRangeWithCoord: IPosition,
        canvasOffset: ICanvasOffset,
        documentSkeleton: DocumentSkeleton,
        documentLayoutObject: IDocumentLayoutObject,
        scaleX: number = 1,
        scaleY: number = 1
    ) {
        // startX and startY are the width and height after scaling.
        const { startX, endX } = actualRangeWithCoord;

        const { textRotation, wrapStrategy, paddingData } = documentLayoutObject;

        const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);

        const { vertexAngle: angle } = convertTextRotation(textRotation);
        const maxSize = this._getEditorMaxSize(actualRangeWithCoord, canvasOffset, documentLayoutObject.horizontalAlign);
        if (!maxSize) return;

        // Measure content without alignment margins left over from the previous editor size.
        documentDataModel?.updateDocumentDataMargin({ l: paddingData.l, t: paddingData.t });
        if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
            documentDataModel?.updateDocumentDataPageSize((endX - startX) / scaleX);
            documentSkeleton.calculate();
            const { actualWidth, actualHeight } = documentSkeleton.getActualSize();
            // The skeleton obtains the original volume, which needs to be multiplied by the magnification factor.
            return {
                actualWidth: actualWidth * scaleX,
                actualHeight: actualHeight * scaleY,
                maxSize,
            };
        }

        documentDataModel?.updateDocumentDataPageSize(maxSize.width / scaleX);
        documentSkeleton.calculate();

        const size = documentSkeleton.getActualSize();
        let editorWidth = Math.max(endX - startX, Math.min(this._editorWidth * scaleX, maxSize.width));

        if (editorWidth < size.actualWidth * scaleX + EDITOR_INPUT_SELF_EXTEND_GAP * scaleX) {
            editorWidth = size.actualWidth * scaleX + EDITOR_INPUT_SELF_EXTEND_GAP * scaleX;
        }

        // Scaling is handled by the renderer, so the skeleton only accepts the original width and height, which need to be divided by the magnification factor.
        documentDataModel?.updateDocumentDataPageSize(editorWidth / scaleX);

        /**
         * Do not rely on cell layout logic, depend on the document's internal alignment logic.
         */
        documentDataModel?.updateDocumentRenderConfig({
            horizontalAlign: HorizontalAlign.UNSPECIFIED,
            cellValueType: undefined,
        });

        return {
            actualWidth: size.actualWidth * scaleX,
            actualHeight: size.actualHeight * scaleY,
            maxSize,
        };
    }

    private _getEditorMaxSize(position: IPosition, canvasOffset: ICanvasOffset, horizontalAlign: HorizontalAlign) {
        const editorObject = this._getEditorObject();
        if (editorObject == null) {
            return;
        }
        function pxToNum(size: string | undefined): number {
            return Number.parseFloat(size?.replace('px', '') ?? '');
        }

        const engine = this.engine;
        if (!engine) return;
        const canvasElement = engine.getCanvasElement();
        const canvasClientRect = canvasElement.getBoundingClientRect();

        // We should take the scale into account when canvas is scaled by CSS.
        const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width
        const heightOfCanvas = pxToNum(canvasElement.style.height); // declared height
        const { width, height } = canvasClientRect; // real width affected by scale
        const contentElement = this._getEditorContentElement();
        const contentBoundingRect = contentElement.getBoundingClientRect();
        const contentScaleX = resolveElementScale(contentBoundingRect.width, contentElement.offsetWidth);
        const contentScaleY = resolveElementScale(contentBoundingRect.height, contentElement.offsetHeight, contentScaleX);
        const scaleAdjustX = width / widthOfCanvas / contentScaleX;
        const scaleAdjustY = Number.isFinite(heightOfCanvas) && heightOfCanvas > 0
            ? height / heightOfCanvas / contentScaleY
            : scaleAdjustX;
        const { startX, startY, endX } = position;
        const enginWidth = engine.width;

        const maxHeight = height / contentScaleY - startY - EDITOR_BORDER_SIZE * 2;

        const cellWidth = endX - startX;
        let maxWidth = width / contentScaleX - startX;
        if (horizontalAlign === HorizontalAlign.CENTER) {
            const rightGap = enginWidth - endX;
            const leftGap = startX;
            maxWidth = cellWidth + Math.min(leftGap, rightGap) * 2;
        } else if (horizontalAlign === HorizontalAlign.RIGHT) {
            maxWidth = endX;
        }
        maxWidth = maxWidth - EDITOR_BORDER_SIZE * 2;
        maxWidth = Math.max(maxWidth, cellWidth);

        return {
            height: maxHeight,
            width: maxWidth,
            contentScaleX,
            contentScaleY,
            scaleAdjustX,
            scaleAdjustY,
        };
    }

    /**
     * Mainly used to calculate the volume of scenes and objects,
     * determine whether a scrollbar appears,
     * and calculate the editor's boundaries relative to the browser.
     */
    private _editAreaProcessing(
        size: { width: number; height: number; contentWidth: number },
        actualRangeWithCoord: IPosition,
        canvasOffset: ICanvasOffset,
        fill: Nullable<string>,
        scaleX: number = 1,
        scaleY: number = 1,
        horizontalAlign: HorizontalAlign,
        callback?: () => void
    ) {
        const editorObject = this._getEditorObject();
        if (editorObject == null) {
            return;
        }

        const engine = this.engine;
        if (!engine) return;
        const canvasElement = engine.getCanvasElement();

        // We should take the scale into account when canvas is scaled by CSS.
        let { startX, startY } = actualRangeWithCoord;

        const { document: documentComponent, scene: editorScene, engine: docEngine } = editorObject;
        const info = this._getEditorMaxSize(actualRangeWithCoord, canvasOffset, horizontalAlign)!;
        const { height: clientHeight, width: clientWidth, contentScaleX, contentScaleY, scaleAdjustX, scaleAdjustY } = info;
        const { physicHeight, scrollBarWidth } = this._fitEditorViewport(editorScene, size.height, clientHeight);
        const editorWidth = Math.min(Math.max(size.width, size.contentWidth + scrollBarWidth), clientWidth);
        const editorHeight = size.height;

        // Keep the visible extent for this edit only; skeleton measurements must still discard stale layout width.
        this._editorWidth = Math.max(this._editorWidth, editorWidth / scaleX);
        this._editorHeight = Math.max(this._editorHeight, physicHeight / scaleY);
        if (!this._initialEditorSize && this._editorBridgeService.isVisible().visible) {
            this._initialEditorSize = { width: editorWidth / scaleX, height: physicHeight / scaleY };
        }

        this._addBackground(editorScene, editorWidth / scaleX, editorHeight / scaleY, fill);

        const { scaleX: precisionScaleX, scaleY: precisionScaleY } = editorScene.getPrecisionScale();

        editorScene.transformByState({
            width: editorWidth * scaleAdjustX / scaleX,
            height: editorHeight * scaleAdjustY / scaleY,
            scaleX: scaleX * scaleAdjustX,
            scaleY: scaleY * scaleAdjustY,
        });

        documentComponent.resize(editorWidth * scaleAdjustX / scaleX, editorHeight * scaleAdjustY / scaleY);

        // Defer canvas resizing until formula selections have updated the render scene.
        setTimeout(() => {
            docEngine.resizeBySize(
                fixLineWidthByScale(editorWidth, precisionScaleX),
                fixLineWidthByScale(physicHeight, precisionScaleY)
            );

            callback?.();
        }, 0);

        const contentBoundingRect = this._getEditorContentElement().getBoundingClientRect();
        const canvasBoundingRect = canvasElement.getBoundingClientRect();
        startX = startX * scaleAdjustX + (canvasBoundingRect.left - contentBoundingRect.left) / contentScaleX;
        startY = startY * scaleAdjustY + (canvasBoundingRect.top - contentBoundingRect.top) / contentScaleY;

        const cellWidth = actualRangeWithCoord.endX - actualRangeWithCoord.startX;
        if (horizontalAlign === HorizontalAlign.RIGHT) {
            startX += (cellWidth - editorWidth) * scaleAdjustX;
        } else if (horizontalAlign === HorizontalAlign.CENTER) {
            startX += (cellWidth - editorWidth * scaleAdjustX) / 2;
        }

        // Update cell editor container position and size.
        this._cellEditorManagerService.setState({
            startX,
            startY,
            endX: editorWidth * scaleAdjustX + startX,
            endY: physicHeight * scaleAdjustY + startY,
            show: true,
        });
    }

    private _fitEditorViewport(editorScene: Scene, editorHeight: number, clientHeight: number) {
        const viewportMain = editorScene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
        let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;

        if (editorHeight > clientHeight) {
            if (scrollBar == null) {
                viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false, barSize: 8 });
            } else {
                viewportMain?.resetCanvasSizeAndUpdateScroll();
            }
            viewportMain?.scrollToViewportPos({ viewportScrollY: editorHeight - clientHeight });
        } else {
            scrollBar = null;
            viewportMain?.getScrollBar()?.dispose();
        }

        return {
            physicHeight: Math.min(editorHeight, clientHeight),
            scrollBarWidth: scrollBar?.barSize ?? 0,
        };
    }

    private _getEditorContentElement(): HTMLElement {
        return this._embedFloatingGeometryService
            ?.getRegistrationByChildUnitId(this._editingUnitId)
            ?.contentRoot ?? this._layoutService.getContentElement();
    }

    /**
     * Since the document does not support cell background color, an additional rect needs to be added.
     */
    private _addBackground(scene: Scene, editorWidth: number, editorHeight: number, fill?: Nullable<string>) {
        const fillRectKey = '_backgroundRectHelperColor_';
        const rect = scene.getObject(fillRectKey) as Rect;

        if (rect == null && fill == null) {
            return;
        }

        if (rect == null) {
            scene.addObjects(
                [
                    new Rect(fillRectKey, {
                        width: editorWidth,
                        height: editorHeight,
                        fill,
                        evented: false,
                    }),
                ],
                DOCS_COMPONENT_MAIN_LAYER_INDEX
            );
        } else if (fill == null) {
            rect.dispose();
        } else {
            rect.setProps({
                fill,
            });

            rect.transformByState({
                width: editorWidth,
                height: editorHeight,
            });
        }
    }

    resizeCellEditor(callback?: () => void) {
        const state = this._cellEditorManagerService.getState();

        if (!state) return;
        if (!this._editorBridgeService.isVisible().visible) return;
        this._editorBridgeService.refreshEditCellPosition(true);
        const editCellState = this._editorBridgeService.getEditCellState();
        if (!editCellState) return;

        const skeleton = this._sheetSkeletonManagerService?.getSkeletonParam(editCellState.sheetId)?.skeleton;
        if (!skeleton) return;
        const { row, column, scaleX, scaleY, position, canvasOffset, documentLayoutObject } = editCellState;
        const { horizontalAlign } = documentLayoutObject;
        const maxSize = this._getEditorMaxSize(position, canvasOffset, horizontalAlign);
        if (!maxSize) return;
        const { height: clientHeight, width: clientWidth, scaleAdjustX, scaleAdjustY } = maxSize;

        const cell = skeleton.getCellWithCoordByIndex(row, column);
        const height = Math.min((cell.mergeInfo.endY - cell.mergeInfo.startY) * scaleY, clientHeight) * scaleAdjustY;
        const width = Math.min((cell.mergeInfo.endX - cell.mergeInfo.startX) * scaleX, clientWidth) * scaleAdjustX;
        const currentHeight = state.endY! - state.startY!;
        const currentWidth = state.endX! - state.startX!;

        if (currentHeight !== height || currentWidth !== width) {
            this._editorBridgeService.refreshEditCellPosition(true);

            const docSkeleton = this._getEditorSkeleton();
            if (!docSkeleton) {
                return;
            }
            this.fitTextSize(callback);
        }
    }

    private _getEditorObject() {
        return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
    }

    private _getEditorSkeleton() {
        return this._renderManagerService.getRenderUnitById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.with(DocSkeletonManagerService).getSkeleton();
    }
}

function resolveElementScale(renderedSize: number, layoutSize: number, fallback = 1): number {
    if (!Number.isFinite(renderedSize) || !Number.isFinite(layoutSize) || renderedSize <= 0 || layoutSize <= 0) {
        return fallback;
    }

    return renderedSize / layoutSize;
}