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.

8.6 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 { Workbook } from '@univerjs/core';
import type {
    IMouseEvent,
    IRenderContext,
    IRenderModule,
    Spreadsheet,
    SpreadsheetColumnHeader,
    SpreadsheetHeader,
} from '@univerjs/engine-render';
import {
    Disposable,
    IContextService,
    Inject,
    Injector,
    RANGE_TYPE,
    SheetTypes,
} from '@univerjs/core';
import { attachSelectionWithCoord, REF_SELECTIONS_ENABLED, SheetsSelectionsService } from '@univerjs/sheets';
import { ContextMenuPosition, IContextMenuService, IPlatformService } from '@univerjs/ui';
import type { ISheetEmbedRuntimeDomScope } from '../../services/sheet-embed-integration.service';
import type { ISheetHostChromeOverride } from '../../services/sheet-host-chrome-override.service';
import { SHEET_VIEW_KEY } from '../../common/keys';
import { isSheetContextMenuGesture } from '../../common/selection-input';
import { ISheetSelectionRenderService } from '../../services/selection/base-selection-render.service';
import { ISheetEmbedRuntimeFocusCoordinator } from '../../services/sheet-embed-integration.service';
import { ISheetHostChromeOverrideService } from '../../services/sheet-host-chrome-override.service';

/**
 * This controller subscribe to context menu events in sheet rendering views and invoke context menu at a correct
 * position and with correct menu type.
 */
export class SheetContextMenuRenderController extends Disposable implements IRenderModule {
    constructor(
        private readonly _context: IRenderContext<Workbook>,
        @IContextMenuService private readonly _contextMenuService: IContextMenuService,
        @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
        @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,
        @Inject(Injector) private readonly _injector: Injector,
        @IPlatformService private readonly _platformService: IPlatformService,
        @IContextService private readonly _contextService: IContextService
    ) {
        super();

        this._init();
        this._initEmbedRuntimeSessionListener();
    }

    private _getSheetType(): SheetTypes | undefined {
        return this._context.unit.getActiveSheet()?.getConfig().type;
    }

    private _init(): void {
        const spreadsheetPointerDownObserver = (this._context?.mainComponent as Spreadsheet)?.onPointerDown$;

        // Content range context menu
        const spreadsheetSubscription = spreadsheetPointerDownObserver.subscribeEvent((event) => {
            if (this._getSheetType() === SheetTypes.CHART) {
                return;
            }
            if (this._isContextMenuGesture(event)) {
                const selections = this._selectionManagerService.getCurrentSelections();
                const currentSelection = selections?.[0];
                if (!currentSelection) {
                    return;
                }
                const rangeType = currentSelection.range.rangeType;
                const skeleton = this._selectionRenderService.getSkeleton();
                const selectionRangeWithCoord = attachSelectionWithCoord(currentSelection, skeleton);
                const range = selectionRangeWithCoord.rangeWithCoord;
                const isPointerInRange = () => {
                    if (!range) {
                        return false;
                    }
                    const x = event.offsetX;
                    const y = event.offsetY;
                    switch (rangeType) {
                        case RANGE_TYPE.ROW:
                            return range.startY <= y && range.endY >= y;
                        case RANGE_TYPE.COLUMN:
                            return range.startX <= x && range.endX >= x;
                        default:
                            return range.startX <= x && range.endX >= x && range.startY <= y && range.endY >= y;
                    }
                };

                const triggerMenu = (position: string) => {
                    if (this._shouldSuppressHostContextMenu()) {
                        return;
                    }
                    this._contextMenuService.triggerContextMenu(event, position);
                };
                if (!isPointerInRange()) {
                    triggerMenu(ContextMenuPosition.MAIN_AREA);
                } else if (rangeType === RANGE_TYPE.COLUMN) {
                    triggerMenu(ContextMenuPosition.COL_HEADER);
                } else if (rangeType === RANGE_TYPE.ROW) {
                    triggerMenu(ContextMenuPosition.ROW_HEADER);
                } else {
                    triggerMenu(ContextMenuPosition.MAIN_AREA);
                }
            }
        });
        this.disposeWithMe(spreadsheetSubscription);

        // Row header context menu
        const spreadsheetColumnHeader = this._context.components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
        const spreadsheetRowHeader = this._context.components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetHeader;
        const rowHeaderSub = spreadsheetRowHeader.onPointerDown$.subscribeEvent((event) => {
            if (this._isContextMenuGesture(event)) {
                if (this._shouldSuppressHostContextMenu()) {
                    return;
                }
                this._contextMenuService.triggerContextMenu(event, ContextMenuPosition.ROW_HEADER);
            }
        });
        this.disposeWithMe(rowHeaderSub);

        // Col header context menu
        const colHeaderPointerDownObserver = spreadsheetColumnHeader.onPointerDown$;
        const colHeaderObserver = colHeaderPointerDownObserver.subscribeEvent((event) => {
            if (this._isContextMenuGesture(event)) {
                if (this._shouldSuppressHostContextMenu()) {
                    return;
                }
                this._contextMenuService.triggerContextMenu(event, ContextMenuPosition.COL_HEADER);
            }
        });
        this.disposeWithMe(colHeaderObserver);
    }

    private _isContextMenuGesture(event: IMouseEvent): boolean {
        return isSheetContextMenuGesture(
            event,
            this._platformService.isMac,
            this._contextService.getContextValue(REF_SELECTIONS_ENABLED)
        );
    }

    private _initEmbedRuntimeSessionListener(): void {
        const runtimeFocusCoordinator = this._getSheetEmbedRuntimeFocusCoordinator();
        if (!runtimeFocusCoordinator) {
            return;
        }

        this.disposeWithMe(runtimeFocusCoordinator.runtimeSessionChanged$.subscribe(() => {
            if (shouldHideSheetHostContextMenuForEmbedSession(
                this._context.unitId,
                runtimeFocusCoordinator.resolveActiveChildSessionRuntimeScope()
            )) {
                this._contextMenuService.hideContextMenu();
            }
        }));
    }

    private _shouldSuppressHostContextMenu(): boolean {
        return shouldSuppressSheetContextMenuForEmbedOverride(
            this._context.unitId,
            this._getSheetHostChromeOverrideService()?.getOverride?.()
        );
    }

    private _getSheetHostChromeOverrideService(): ISheetHostChromeOverrideService | undefined {
        return this._injector.has(ISheetHostChromeOverrideService)
            ? this._injector.get(ISheetHostChromeOverrideService)
            : undefined;
    }

    private _getSheetEmbedRuntimeFocusCoordinator(): ISheetEmbedRuntimeFocusCoordinator | undefined {
        return this._injector.has(ISheetEmbedRuntimeFocusCoordinator)
            ? this._injector.get(ISheetEmbedRuntimeFocusCoordinator)
            : undefined;
    }
}

export function shouldHideSheetHostContextMenuForEmbedSession(
    hostUnitId: string,
    activeScope: ISheetEmbedRuntimeDomScope | undefined
): boolean {
    return activeScope?.hostUnitId === hostUnitId && activeScope.sessionMode !== 'host-passive';
}

export function shouldSuppressSheetContextMenuForEmbedOverride(
    hostUnitId: string,
    override: Pick<ISheetHostChromeOverride, 'entry' | 'hostUnitId'> | null | undefined
): boolean {
    return override != null && override.hostUnitId === hostUnitId && override.entry === 'sheets-sheet-tab';
}