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.

11.4 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 { ICellRenderContext, ThemeService } from '@univerjs/core';
import type { BaseObject, IRectProps, Scene, SpreadsheetSkeleton, Vector2 } from '@univerjs/engine-render';
import type { ISelectionStyle, ISelectionWithCoord } from '@univerjs/sheets';
import { RANGE_TYPE } from '@univerjs/core';
import { Rect, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
import { SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';
import { SELECTION_MANAGER_KEY, SelectionControl } from './selection-control';

class MobileSelectionHandle extends Rect {
    constructor(key: string, props: IRectProps, private readonly _isCellWidgetHit: (coord: Vector2) => boolean) {
        super(key, props);
    }

    override isHit(coord: Vector2): boolean {
        if (!super.isHit(coord)) {
            return false;
        }

        const local = this.getInverseCoord(coord);
        const onVisibleHandle = Math.abs(local.x - this.width / 2) <= (this.visualWidth ?? this.width) / 2 &&
            Math.abs(local.y - this.height / 2) <= (this.visualHeight ?? this.height) / 2;

        // Keep the handle draggable while letting cell widgets receive taps through its invisible padding.
        return onVisibleHandle || !this._isCellWidgetHit(coord);
    }
}

export class MobileSelectionControl extends SelectionControl {
    private _skeleton: SpreadsheetSkeleton | undefined;

    /**
     * topLeft controlPointer, it is not visible, just transparent, for handling event.
     */
    private _expandControlTopLeft: Rect | null;
    /**
     * bottomRight controlPointer, it is not visible, just transparent, for handling event.
     */
    private _expandControlBottomRight: Rect | null;

    protected _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;

    constructor(
        protected override _scene: Scene,
        protected override _zIndex: number,
        protected override readonly _themeService: ThemeService,
        options: {
            highlightHeader?: boolean;
            rowHeaderWidth: number;
            columnHeaderHeight: number;
            rowHeaderOffsetX?: number;
            columnHeaderOffsetY?: number;
            rangeType?: RANGE_TYPE;
        }
    ) {
        super(_scene, _zIndex, _themeService, { ...options, enableAutoFill: false });
        this._rangeType = options?.rangeType || RANGE_TYPE.NORMAL;
        this.initControlPoints();
    }

    initControlPoints(): void {
        const defaultStyle = this.currentStyle;
        const expandCornerSize = defaultStyle.expandCornerSize || 0;
        const expandCornerInnerSize = (defaultStyle.expandCornerSize || 0) / 4;
        const controlStrokeWidth = defaultStyle.autofillStrokeWidth || 0;
        const stroke = defaultStyle.stroke!;
        const controlStroke = defaultStyle.autofillStroke!;
        const zIndex = this.zIndex;
        // @transformControlPoint takes care of left & top
        this._expandControlTopLeft = new MobileSelectionHandle(SELECTION_MANAGER_KEY.expandTopLeft + zIndex, {
            zIndex: zIndex + 2,
            width: expandCornerSize,
            height: expandCornerSize,
            radius: expandCornerSize / 2,
            visualWidth: expandCornerInnerSize,
            visualHeight: expandCornerInnerSize,
            strokeWidth: controlStrokeWidth,
        }, (coord) => this._isCellWidgetHit(coord));

        this._expandControlBottomRight = new MobileSelectionHandle(SELECTION_MANAGER_KEY.expandBottomRight + zIndex, {
            zIndex: zIndex + 2,
            width: expandCornerSize,
            height: expandCornerSize,
            radius: expandCornerSize / 2,
            visualHeight: expandCornerInnerSize,
            visualWidth: expandCornerInnerSize,
            strokeWidth: controlStrokeWidth,
        }, (coord) => this._isCellWidgetHit(coord));

        const controlProps: IRectProps = {
            fill: stroke,
            stroke: controlStroke,
            strokeScaleEnabled: false,
        };
        this._expandControlTopLeft!.setProps({ ...controlProps });
        this._expandControlBottomRight!.setProps({ ...controlProps });

        // put into scene
        const objs = [
            this._expandControlTopLeft,
            this._expandControlBottomRight,
        ] as BaseObject[];

        // do not use this.model.rangeType, model has not been initialized yet
        switch (this._rangeType) {
            case RANGE_TYPE.ROW:
                this.rowHeaderGroup.addObjects(...objs);
                break;
            case RANGE_TYPE.COLUMN:
                this.columnHeaderGroup.addObjects(...objs);
                break;
            case RANGE_TYPE.NORMAL:
                this.selectionShapeGroup.addObjects(...objs);
        }

        const scene = this.getScene();
        scene.addObjects(objs, SHEET_COMPONENT_SELECTION_LAYER_INDEX);
    }

    get expandControlTopLeft(): Rect<IRectProps> | null {
        return this._expandControlTopLeft;
    }

    set expandControlTopLeft(value: Rect) {
        this._expandControlTopLeft = value;
    }

    get expandControlBottomRight(): Rect<IRectProps> | null {
        return this._expandControlBottomRight;
    }

    set expandControlBottomRight(value: Rect) {
        this._expandControlBottomRight = value;
    }

    get rangeType(): RANGE_TYPE {
        return this._rangeType;
    }

    set rangeType(value: RANGE_TYPE) {
        this._rangeType = value;
    }

    override updateRangeBySelectionWithCoord(selection: ISelectionWithCoord, skeleton?: SpreadsheetSkeleton, animate = false): void {
        if (skeleton) {
            this._skeleton = skeleton;
        }
        super.updateRangeBySelectionWithCoord(selection, skeleton, animate);
    }

    private _isCellWidgetHit(coord: Vector2): boolean {
        const skeleton = this._skeleton;
        if (!skeleton) {
            return false;
        }

        const { worksheet } = skeleton;
        const cell = skeleton.getCellWithCoordByOffset(coord.x, coord.y, 1, 1, { x: 0, y: 0 });
        const row = cell.isMerged ? cell.mergeInfo.startRow : cell.actualRow;
        const col = cell.isMerged ? cell.mergeInfo.startColumn : cell.actualColumn;
        const data = worksheet.getCell(row, col);
        if (!data?.customRender?.length) {
            return false;
        }

        const info: ICellRenderContext = {
            data,
            style: worksheet.getComposedCellStyleByCellData(row, col, data),
            primaryWithCoord: skeleton.getCellWithCoordByIndex(row, col),
            unitId: worksheet.getUnitId(),
            subUnitId: worksheet.getSheetId(),
            row,
            col,
            worksheet,
        };

        return data.customRender.some((render) => render.onPointerDown && render.isHit?.(coord, info));
    }

    override dispose(): void {
        this._expandControlBottomRight?.dispose();
        this._expandControlTopLeft?.dispose();
        super.dispose();
    }

    protected override _updateLayoutOfSelectionControl(style: ISelectionStyle): void {
        super._updateLayoutOfSelectionControl(style);

        // const rangeType = this.rangeType;
        // startX startY shares same coordinate with viewport.(include row & colheader)

        const defaultStyle = this.currentStyle;
        const selectionStyle = style ?? defaultStyle;

        const {
            widgets = defaultStyle.widgets!,
        } = selectionStyle;
        this.currentStyle = selectionStyle;

        // this condition is derived from selection-shape, I do not understand.
        if (!super._hasWidgets(widgets)) {
            const { viewportScrollX, viewportScrollY } = this.getViewportMainScrollInfo();
            const { endX, endY } = this.selectionModel;
            this.transformControlPoint(viewportScrollX, viewportScrollY, endX, endY);

            this.expandControlTopLeft!.show();
            this.expandControlBottomRight!.show();
        } else {
            this.expandControlTopLeft?.hide();
            this.expandControlBottomRight?.hide();
        }
    }

    getViewportMainScrollInfo() {
        const viewMain = this.getScene().getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
        return {
            viewportScrollX: viewMain?.viewportScrollX || 0,
            viewportScrollY: viewMain?.viewportScrollY || 0,
            width: viewMain?.width || 0,
            height: viewMain?.height || 0,
        };
    }

    /**
     * Mainly for row & col selection control point position. update control point position by when scrolling.
     * @param viewportScrollX viewportScrollX
     * @param viewportScrollY
     * @param sheetContentWidth
     * @param sheetContentHeight max sheet content height, for very short sheet, control pointer shoud not out of sheet
     */

    transformControlPoint(viewportScrollX: number = 0, viewportScrollY: number = 0, sheetContentWidth: number = 0, sheetContentHeight: number = 0): void {
        const style = this.currentStyle!;
        const rangeType = this.selectionModel.rangeType;
        const expandCornerSize = style.expandCornerSize!;
        const { startX, startY, endX, endY } = this.selectionModel;

        const viewportSizeInfo = this.getViewportMainScrollInfo();
        const viewportW = viewportSizeInfo.width;
        const viewportH = viewportSizeInfo.height;

        switch (rangeType) {
            case RANGE_TYPE.NORMAL:
                this.expandControlTopLeft!.transformByState({
                    left: -expandCornerSize / 2,
                    top: -expandCornerSize / 2,
                });
                this.expandControlBottomRight!.transformByState({
                    left: endX - startX - expandCornerSize / 2,
                    top: endY - startY - expandCornerSize / 2,
                });
                break;

            case RANGE_TYPE.ROW: {
                const left = Math.min(viewportW / 2 + viewportScrollX, sheetContentWidth);
                const controlLeft = -expandCornerSize / 2 + left;
                this.expandControlTopLeft!.transformByState({
                    left: controlLeft,
                    top: -expandCornerSize / 2,
                });
                this.expandControlBottomRight!.transformByState({
                    left: controlLeft,
                    top: -expandCornerSize / 2 + endY - startY,
                });
            }
                break;
            case RANGE_TYPE.COLUMN:
                {
                    const top = Math.min(+viewportH / 2 + viewportScrollY, sheetContentHeight);
                    const controlTop = -expandCornerSize / 2 + top;

                    this.expandControlTopLeft!.transformByState({
                        left: -expandCornerSize / 2,
                        top: controlTop,
                    });
                    this.expandControlBottomRight!.transformByState({
                        left: -expandCornerSize / 2 + endX - startX,
                        top: controlTop,
                    });
                }
                break;
            default:
                console.error('unknown range type');
        }
    }
}