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.

feat(ui): add mobile context menu support and related functionalities (#6674)

白熱8569fe8cb416
diff --git a/packages/sheets-ui/src/consts/mobile-context.ts b/packages/sheets-ui/src/consts/mobile-context.ts
index 19a9b70561..e8c1f011ab 100644
--- a/packages/sheets-ui/src/consts/mobile-context.ts
+++ b/packages/sheets-ui/src/consts/mobile-context.ts
@@ -25,3 +25,9 @@ export const MOBILE_PINCH_ZOOMING = 'MOBILE_PINCH_ZOOMING';
* Used to prevent scroll/inertia/zoom operations during selection expansion.
*/
export const MOBILE_EXPANDING_SELECTION = 'MOBILE_EXPANDING_SELECTION';
+
+/**
+ * Context key indicating that the next selection-end event was triggered by a mobile long press.
+ * Used to ensure the context menu only opens for long-press gestures, not normal taps.
+ */
+export const MOBILE_TRIGGER_CONTEXT_MENU = 'MOBILE_TRIGGER_CONTEXT_MENU';
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/mobile-contextmenu.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/mobile-contextmenu.render-controller.spec.ts
new file mode 100644
index 0000000000..f9b9448d5f
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/mobile-contextmenu.render-controller.spec.ts
@@ -0,0 +1,53 @@
+/**
+ * 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 { RANGE_TYPE } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { shouldKeepCurrentSelectionForMobileContextMenu } from '../mobile/mobile-contextmenu.render-controller';
+
+describe('mobile context menu helpers', () => {
+ it('keeps current selection when long press is inside it', () => {
+ expect(shouldKeepCurrentSelectionForMobileContextMenu([
+ {
+ range: { startRow: 1, endRow: 3, startColumn: 2, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ], {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 3,
+ rangeType: RANGE_TYPE.NORMAL,
+ })).toBe(true);
+ });
+
+ it('replaces selection when long press is outside it', () => {
+ expect(shouldKeepCurrentSelectionForMobileContextMenu([
+ {
+ range: { startRow: 1, endRow: 3, startColumn: 2, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ], {
+ startRow: 5,
+ endRow: 5,
+ startColumn: 5,
+ endColumn: 5,
+ rangeType: RANGE_TYPE.NORMAL,
+ })).toBe(false);
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
index 1479685058..4511db2497 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
@@ -14,19 +14,68 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
-import type { IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { ICellWithCoord, IRange, Nullable, Workbook } from '@univerjs/core';
+import type { IPointerEvent, IRenderContext, IRenderModule, Viewport } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { Disposable, Inject, RANGE_TYPE, Tools } from '@univerjs/core';
-import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
-import { SheetsSelectionsService } from '@univerjs/sheets';
+import { Disposable, IContextService, Inject, RANGE_TYPE, Rectangle, toDisposable } from '@univerjs/core';
+import { IRenderManagerService, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import { convertPrimaryWithCoordToPrimary, convertSelectionDataToRange, SelectionMoveType, SheetsSelectionsService } from '@univerjs/sheets';
import { ContextMenuPosition, IContextMenuService, ILayoutService } from '@univerjs/ui';
+import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING } from '../../../consts/mobile-context';
import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
-import { attachSelectionWithCoord } from '../../../services/selection/util';
+import { SELECTION_MANAGER_KEY } from '../../../services/selection/selection-control';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
+const LONG_PRESS_DURATION = 500;
+const LONG_PRESS_MOVE_THRESHOLD = 10;
+const MAIN_AREA_VIEWPORT_KEYS = new Set<string>([
+ SHEET_VIEWPORT_KEY.VIEW_MAIN,
+ SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT,
+ SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,
+ SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP,
+]);
+
+const SELECTION_OBJECT_PREFIXES = [
+ SELECTION_MANAGER_KEY.Selection,
+ SELECTION_MANAGER_KEY.top,
+ SELECTION_MANAGER_KEY.bottom,
+ SELECTION_MANAGER_KEY.left,
+ SELECTION_MANAGER_KEY.right,
+ SELECTION_MANAGER_KEY.fillTopLeft,
+ SELECTION_MANAGER_KEY.fillBottomRight,
+ SELECTION_MANAGER_KEY.backgroundTop,
+ SELECTION_MANAGER_KEY.backgroundMiddleLeft,
+ SELECTION_MANAGER_KEY.backgroundMiddleRight,
+ SELECTION_MANAGER_KEY.backgroundBottom,
+];
+
+interface ITouchPosition {
+ clientX: number;
+ clientY: number;
+ offsetX: number;
+ offsetY: number;
+}
+
+interface ILongPressState {
+ longPressTimer: ReturnType<typeof setTimeout> | null;
+ activeTouch: Nullable<ITouchPosition>;
+ longPressTriggered: boolean;
+ selectionSnapshot: ISelectionWithStyle[];
+ shouldRestoreSelectionSnapshot: boolean;
+}
+
+function isSelectionObjectKey(objectKey?: string | null): boolean {
+ return !!objectKey && SELECTION_OBJECT_PREFIXES.some((prefix) => objectKey.startsWith(prefix));
+}
+
+export function shouldKeepCurrentSelectionForMobileContextMenu(currentSelections: Array<IRange | ISelectionWithStyle>, targetRange: IRange): boolean {
+ return currentSelections.some((selection) => Rectangle.contains('range' in selection ? selection.range : selection, targetRange));
+}
+
/**
- * On mobile devices, the context menu would popup when
+ * On mobile devices, the context menu pops up after a native touch long press.
+ * This bypasses the older "selection event -> menu" chain, which was unreliable
+ * when the touch target was the selection overlay itself.
*
* @ignore
*/
@@ -35,8 +84,9 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
private readonly _context: IRenderContext<Workbook>,
@ILayoutService private readonly _layoutService: ILayoutService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
+ @IContextService private readonly _contextService: IContextService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
- @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
) {
super();
@@ -45,70 +95,240 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
}
private _init(): void {
- let listenToSelectionChangeEvent = false;
- this.disposeWithMe(this._selectionManagerService.selectionMoveStart$.subscribe(() => listenToSelectionChangeEvent = true));
- this.disposeWithMe(this._selectionManagerService.selectionMoveEnd$.subscribe((selectionWithStyleList: ISelectionWithStyle[]) => {
- const skeleton = this._sheetSkeletonManagerService.getCurrentParam()!.skeleton;
- if (!skeleton || !selectionWithStyleList || listenToSelectionChangeEvent === false) {
- return;
- }
+ const contentElement = this._layoutService.getContentElement();
+ if (!contentElement) {
+ return;
+ }
- listenToSelectionChangeEvent = false;
-
- const selectionRangeWithStyle = selectionWithStyleList[0] as unknown as ISelectionWithStyle;
-
- if (!selectionRangeWithStyle.primary) return;
-
- const selectionWithCoord = attachSelectionWithCoord(selectionRangeWithStyle, skeleton);
- const rangeType = selectionRangeWithStyle.range.rangeType;
-
- const { scene } = this._context;
- const viewMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const viewportScrollX = viewMain?.viewportScrollX || 0;
- const viewportScrollY = viewMain?.viewportScrollY || 0;
-
- let clientX = 0;
- let clientY = 0;
-
- const rowHeaderWidth = skeleton.rowHeaderWidth;
-
- // TODO @lumixraku popup should positioned by transform not topleft.
- // using transform & transform-origin would be easy to position popup
- const canvasRect = this._layoutService.getContentElement().getBoundingClientRect();
- switch (rangeType) {
- case RANGE_TYPE.NORMAL:
- clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
- clientY = selectionWithCoord.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
- break;
- case RANGE_TYPE.COLUMN:
- clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
- // slightly lower than control point for easy to drag control point.
- clientY = Math.min(canvasRect.height / 2, selectionWithCoord.rangeWithCoord.endY) + 40;
- break;
- case RANGE_TYPE.ROW:
- // slightly left than control point for easy to drag control point.
- clientX = (canvasRect.width - rowHeaderWidth) / 2 + 20;
- clientY = selectionWithCoord.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
- break;
- case RANGE_TYPE.ALL:
- clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left;
- clientY = selectionWithCoord.rangeWithCoord.startY + canvasRect.top;
- break;
- default:
- clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
- clientY = selectionWithCoord.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
- break;
- }
- // in case clientXY is not in screen area.
- clientX = Tools.clamp(clientX, rowHeaderWidth, canvasRect.width);
- clientY = Tools.clamp(clientY, canvasRect.top, canvasRect.height);
-
- this._contextMenuService.triggerContextMenu({
- clientX,
- clientY,
- preventDefault: () => {},
- stopPropagation: () => {},
- } as unknown as IPointerEvent, ContextMenuPosition.MAIN_AREA);
+ const state = this._createLongPressState();
+ const handleTouchStart = (event: TouchEvent) => this._handleTouchStart(contentElement, state, event);
+ const handleTouchMove = (event: TouchEvent) => this._handleTouchMove(contentElement, state, event);
+ const handleTouchEnd = (event: TouchEvent) => this._handleTouchEnd(state, event);
+
+ contentElement.addEventListener('touchstart', handleTouchStart, { passive: true });
+ contentElement.addEventListener('touchmove', handleTouchMove, { passive: true });
+ contentElement.addEventListener('touchend', handleTouchEnd, { passive: false });
+ contentElement.addEventListener('touchcancel', handleTouchEnd, { passive: false });
+
+ this.disposeWithMe(toDisposable(() => {
+ this._clearLongPressTimer(state);
+ contentElement.removeEventListener('touchstart', handleTouchStart);
+ contentElement.removeEventListener('touchmove', handleTouchMove);
+ contentElement.removeEventListener('touchend', handleTouchEnd);
+ contentElement.removeEventListener('touchcancel', handleTouchEnd);
+ }));
+ }
+
+ private _createLongPressState(): ILongPressState {
+ return {
+ longPressTimer: null,
+ activeTouch: null,
+ longPressTriggered: false,
+ selectionSnapshot: [],
+ shouldRestoreSelectionSnapshot: false,
+ };
+ }
+
+ private _clearLongPressTimer(state: ILongPressState): void {
+ if (state.longPressTimer) {
+ clearTimeout(state.longPressTimer);
+ state.longPressTimer = null;
+ }
+ }
+
+ private _resetLongPressState(state: ILongPressState): void {
+ this._clearLongPressTimer(state);
+ state.activeTouch = null;
+ }
+
+ private _getTouchOffset(contentElement: HTMLElement, touch: Touch): ITouchPosition {
+ const rect = contentElement.getBoundingClientRect();
+ return {
+ clientX: touch.clientX,
+ clientY: touch.clientY,
+ offsetX: touch.clientX - rect.left,
+ offsetY: touch.clientY - rect.top,
+ };
+ }
+
+ private _getMainAreaViewport(offsetX: number, offsetY: number): Nullable<Viewport> {
+ const { scene } = this._context;
+ const viewport = scene.getActiveViewportByCoord(Vector2.FromArray([offsetX, offsetY]));
+
+ if (!viewport || !MAIN_AREA_VIEWPORT_KEYS.has(viewport.viewportKey)) {
+ return null;
+ }
+
+ return viewport;
+ }
+
+ private _getTargetCellByOffset(offsetX: number, offsetY: number): Nullable<ICellWithCoord> {
+ const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
+ const viewport = this._getMainAreaViewport(offsetX, offsetY);
+ const { scene } = this._context;
+
+ if (!skeleton || !viewport) {
+ return null;
+ }
+
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([offsetX, offsetY]));
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords, viewport);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ return skeleton.getCellWithCoordByOffset(relativeCoords.x - scrollXY.x, relativeCoords.y - scrollXY.y, scaleX, scaleY, scrollXY);
+ }
+
+ private _getCurrentRenderSelections(): ISelectionWithStyle[] {
+ const currentRender = this._renderManagerService.getRenderById(this._context.unitId);
+ const selectionRenderService = currentRender?.with(ISheetSelectionRenderService);
+ return selectionRenderService?.getSelectionControls().map((control) => convertSelectionDataToRange(control.getValue())) ?? [];
+ }
+
+ private _cloneSelections(selections: ISelectionWithStyle[]): ISelectionWithStyle[] {
+ return selections.map((selection) => ({
+ range: { ...selection.range },
+ primary: selection.primary ? { ...selection.primary } : selection.primary,
+ style: selection.style ? { ...selection.style } : selection.style,
}));
}
+
+ private _getSelectionSnapshot(): ISelectionWithStyle[] {
+ const renderedSelections = this._getCurrentRenderSelections();
+ if (renderedSelections.length) {
+ return this._cloneSelections(renderedSelections);
+ }
+
+ return this._cloneSelections(this._selectionManagerService.getCurrentSelections() as ISelectionWithStyle[]);
+ }
+
+ private _restoreSelectionSnapshot(selectionSnapshot: ISelectionWithStyle[]): void {
+ const worksheet = this._context.unit.getActiveSheet();
+ if (!worksheet || !selectionSnapshot.length) {
+ return;
+ }
+
+ this._selectionManagerService.setSelections(
+ this._context.unitId,
+ worksheet.getSheetId(),
+ this._cloneSelections(selectionSnapshot),
+ SelectionMoveType.MOVE_END
+ );
+ }
+
+ private _replaceSelectionWithTargetCell(targetCell: ICellWithCoord): void {
+ const worksheet = this._context.unit.getActiveSheet();
+ if (!worksheet) {
+ return;
+ }
+
+ this._selectionManagerService.setSelections(this._context.unitId, worksheet.getSheetId(), [{
+ range: {
+ startRow: targetCell.mergeInfo.startRow,
+ endRow: targetCell.mergeInfo.endRow,
+ startColumn: targetCell.mergeInfo.startColumn,
+ endColumn: targetCell.mergeInfo.endColumn,
+ rangeType: RANGE_TYPE.NORMAL,
+ unitId: this._context.unitId,
+ sheetId: worksheet.getSheetId(),
+ },
+ primary: convertPrimaryWithCoordToPrimary(targetCell),
+ style: null,
+ }], SelectionMoveType.MOVE_END);
+ }
+
+ private _openMenu(clientX: number, clientY: number): void {
+ this._contextMenuService.triggerContextMenu({
+ clientX,
+ clientY,
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ } as unknown as IPointerEvent, ContextMenuPosition.MAIN_AREA);
+ }
+
+ private _triggerLongPressMenu(state: ILongPressState): void {
+ if (!state.activeTouch || this._contextMenuService.visible) {
+ return;
+ }
+
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) || this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)) {
+ return;
+ }
+
+ const targetCell = this._getTargetCellByOffset(state.activeTouch.offsetX, state.activeTouch.offsetY);
+ if (!targetCell) {
+ return;
+ }
+
+ const pickedObject = this._context.scene.pick(Vector2.FromArray([state.activeTouch.offsetX, state.activeTouch.offsetY])) as { oKey?: string } | null;
+ const snapshotRanges = state.selectionSnapshot.map((selection) => selection.range);
+ const shouldKeepSelection = isSelectionObjectKey(pickedObject?.oKey)
+ || shouldKeepCurrentSelectionForMobileContextMenu(snapshotRanges, targetCell.mergeInfo);
+
+ state.longPressTriggered = true;
+ state.shouldRestoreSelectionSnapshot = shouldKeepSelection;
+
+ if (shouldKeepSelection) {
+ this._restoreSelectionSnapshot(state.selectionSnapshot);
+ queueMicrotask(() => this._restoreSelectionSnapshot(state.selectionSnapshot));
+ }
+
+ this._openMenu(state.activeTouch.clientX, state.activeTouch.clientY);
+
+ if (!shouldKeepSelection) {
+ queueMicrotask(() => this._replaceSelectionWithTargetCell(targetCell));
+ }
+ }
+
+ private _handleTouchStart(contentElement: HTMLElement, state: ILongPressState, event: TouchEvent): void {
+ if (event.touches.length !== 1 || this._contextMenuService.visible) {
+ this._resetLongPressState(state);
+ return;
+ }
+
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) || this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)) {
+ this._resetLongPressState(state);
+ return;
+ }
+
+ const touch = this._getTouchOffset(contentElement, event.touches[0]);
+ if (!this._getTargetCellByOffset(touch.offsetX, touch.offsetY)) {
+ this._resetLongPressState(state);
+ return;
+ }
+
+ state.longPressTriggered = false;
+ state.shouldRestoreSelectionSnapshot = false;
+ state.selectionSnapshot = this._getSelectionSnapshot();
+ state.activeTouch = touch;
+ this._clearLongPressTimer(state);
+ state.longPressTimer = setTimeout(() => this._triggerLongPressMenu(state), LONG_PRESS_DURATION);
+ }
+
+ private _handleTouchMove(contentElement: HTMLElement, state: ILongPressState, event: TouchEvent): void {
+ if (!state.activeTouch || event.touches.length !== 1) {
+ this._resetLongPressState(state);
+ return;
+ }
+
+ const touch = this._getTouchOffset(contentElement, event.touches[0]);
+ if (
+ Math.abs(touch.offsetX - state.activeTouch.offsetX) > LONG_PRESS_MOVE_THRESHOLD ||
+ Math.abs(touch.offsetY - state.activeTouch.offsetY) > LONG_PRESS_MOVE_THRESHOLD
+ ) {
+ this._resetLongPressState(state);
+ }
+ }
+
+ private _handleTouchEnd(state: ILongPressState, event: TouchEvent): void {
+ if (state.longPressTriggered) {
+ event.preventDefault();
+ if (state.shouldRestoreSelectionSnapshot) {
+ queueMicrotask(() => this._restoreSelectionSnapshot(state.selectionSnapshot));
+ }
+ }
+
+ state.longPressTriggered = false;
+ state.shouldRestoreSelectionSnapshot = false;
+ this._resetLongPressState(state);
+ }
}
diff --git a/packages/sheets-ui/src/menu/mobile-menu.ts b/packages/sheets-ui/src/menu/mobile-menu.ts
index 902769969b..f8cdcb0eb5 100644
--- a/packages/sheets-ui/src/menu/mobile-menu.ts
+++ b/packages/sheets-ui/src/menu/mobile-menu.ts
@@ -14,60 +14,4 @@
* limitations under the License.
*/
-import type { MenuSchemaType } from '@univerjs/ui';
-import { ContextMenuGroup, ContextMenuPosition } from '@univerjs/ui';
-import {
- SheetCopyCommand,
-} from '../commands/commands/clipboard.command';
-import { CopyMenuItemFactory } from './menu';
-
-export const menuSchema: MenuSchemaType = {
- [ContextMenuPosition.MAIN_AREA]: {
- [ContextMenuGroup.FORMAT]: {
- [SheetCopyCommand.name]: {
- order: 0,
- menuItemFactory: CopyMenuItemFactory,
- },
- },
- [ContextMenuGroup.DATA]: {
- order: 2,
- },
- [ContextMenuGroup.OTHERS]: {
- order: 3,
- },
- },
- [ContextMenuPosition.COL_HEADER]: {
- [ContextMenuGroup.FORMAT]: {
- [SheetCopyCommand.name]: {
- order: 0,
- menuItemFactory: CopyMenuItemFactory,
- },
- },
- [ContextMenuGroup.LAYOUT]: {
- order: 1,
- },
- [ContextMenuGroup.DATA]: {
- order: 2,
- },
- [ContextMenuGroup.OTHERS]: {
- order: 3,
- },
- },
- [ContextMenuPosition.ROW_HEADER]: {
- [ContextMenuGroup.FORMAT]: {
- [SheetCopyCommand.name]: {
- order: 0,
- menuItemFactory: CopyMenuItemFactory,
- },
- },
- [ContextMenuGroup.LAYOUT]: {
- order: 1,
- },
- [ContextMenuGroup.DATA]: {
- order: 2,
- },
- [ContextMenuGroup.OTHERS]: {
- order: 3,
- },
- },
-};
+export { menuSchema } from './schema';
diff --git a/packages/sheets-ui/src/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.ts
index 43600b245b..79464a9ae0 100644
--- a/packages/sheets-ui/src/mobile-plugin.ts
+++ b/packages/sheets-ui/src/mobile-plugin.ts
@@ -58,7 +58,7 @@ import { HeaderFreezeRenderController } from './controllers/render-controllers/f
import { HeaderMenuRenderController } from './controllers/render-controllers/header-menu.render-controller';
import { HeaderMoveRenderController } from './controllers/render-controllers/header-move.render-controller';
import { HeaderUnhideRenderController } from './controllers/render-controllers/header-unhide.render-controller';
-// import { SheetContextMenuMobileRenderController } from './controllers/render-controllers/mobile/mobile-contextmenu.render-controller';
+import { SheetContextMenuMobileRenderController } from './controllers/render-controllers/mobile/mobile-contextmenu.render-controller';
import { MobileHeaderResizeRenderController } from './controllers/render-controllers/mobile/mobile-header-resize.render-controller';
import { MobileSheetsScrollRenderController } from './controllers/render-controllers/mobile/mobile-scroll.render-controller';
import { SheetsScrollRenderController } from './controllers/render-controllers/scroll.render-controller';
@@ -265,7 +265,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
[DragRenderController],
[ForceStringRenderController],
[CellCustomRenderController],
- // [SheetContextMenuMobileRenderController],
+ [SheetContextMenuMobileRenderController],
[MobileHeaderResizeRenderController],
[MoveRangeRenderController],
diff --git a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
new file mode 100644
index 0000000000..813a3fa638
--- /dev/null
+++ b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
@@ -0,0 +1,82 @@
+/**
+ * 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 { RANGE_TYPE } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { shouldKeepCurrentSelectionOnMobileLongPress } from '../mobile-selection-render.service';
+
+describe('shouldKeepCurrentSelectionOnMobileLongPress', () => {
+ it('keeps the existing selection when long press is inside it', () => {
+ expect(shouldKeepCurrentSelectionOnMobileLongPress([
+ {
+ startRow: 1,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ ], {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 3,
+ rangeType: RANGE_TYPE.NORMAL,
+ })).toBe(true);
+ });
+
+ it('does not keep the existing selection when long press is outside it', () => {
+ expect(shouldKeepCurrentSelectionOnMobileLongPress([
+ {
+ startRow: 1,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ ], {
+ startRow: 5,
+ endRow: 5,
+ startColumn: 5,
+ endColumn: 5,
+ rangeType: RANGE_TYPE.NORMAL,
+ })).toBe(false);
+ });
+
+ it('checks all existing selections', () => {
+ expect(shouldKeepCurrentSelectionOnMobileLongPress([
+ {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ {
+ startRow: 4,
+ endRow: 6,
+ startColumn: 4,
+ endColumn: 6,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ ], {
+ startRow: 5,
+ endRow: 5,
+ startColumn: 5,
+ endColumn: 5,
+ rangeType: RANGE_TYPE.NORMAL,
+ })).toBe(true);
+ });
+});
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
index be7d3c6a2f..0b1685f566 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
@@ -35,6 +35,7 @@ import {
Inject,
Injector,
RANGE_TYPE,
+ Rectangle,
ThemeService,
toDisposable,
} from '@univerjs/core';
@@ -59,6 +60,11 @@ enum ExpandingControl {
TOP = 'top',
BOTTOM = 'bottom',
}
+
+export function shouldKeepCurrentSelectionOnMobileLongPress(currentSelections: IRange[], targetRange: IRange): boolean {
+ return currentSelections.some((selection) => Rectangle.contains(selection, targetRange));
+}
+
export class MobileSheetsSelectionRenderService extends BaseSelectionRenderService implements IRenderModule {
private readonly _workbookSelections: WorkbookSelectionModel;
private _renderDisposable: Nullable<IDisposable> = null;
@@ -208,16 +214,8 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
private _initSpreadsheetEvent(sheetObject: ISheetObjectParam): void {
const { spreadsheet } = sheetObject;
- let longPressTimer: ReturnType<typeof setTimeout>;
- const longPressDuration = 500; // Longpress duration in milliseconds
const pointerDownPos = { x: 0, y: 0 };
-
- const clearLongPressTimer = () => {
- // Clear the timer if pointer is moved or released
- clearTimeout(longPressTimer);
- };
-
- const createNewSelection = (evt: IPointerEvent | IMouseEvent, showContextMenu: boolean) => {
+ const createNewSelection = (evt: IPointerEvent | IMouseEvent) => {
// Don't create selection during pinch zoom
if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
@@ -228,27 +226,13 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
RANGE_TYPE.NORMAL,
this._getActiveViewport(evt)
);
-
- // show contextmenu when longpress and change selection area
- // do not show contextmenu when click a cell
this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
};
- spreadsheet?.onPointerMove$.subscribeEvent((evt: IPointerEvent | IMouseEvent, _state) => {
- const edge = 10;
- if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
- Math.abs(evt.offsetY - pointerDownPos.y) > edge) {
- clearLongPressTimer();
- }
- });
const spreadsheetPointerDownSub = spreadsheet?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
// Don't start long press timer during pinch zoom
if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
-
pointerDownPos.x = evt.offsetX;
pointerDownPos.y = evt.offsetY;
- longPressTimer = setTimeout(() => {
- createNewSelection(evt, true);
- }, longPressDuration);
state.stopPropagation();
});
@@ -257,13 +241,12 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
// Don't create selection during pinch zoom
if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
- clearTimeout(longPressTimer);
const edge = 10;
if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
Math.abs(evt.offsetY - pointerDownPos.y) > edge) {
return;
}
- createNewSelection(evt, false);
+ createNewSelection(evt);
state.stopPropagation();
});
diff --git a/packages/ui/src/components/menu/mobile/MobileMenu.tsx b/packages/ui/src/components/menu/mobile/MobileMenu.tsx
index 7010f98cab..000d78f924 100644
--- a/packages/ui/src/components/menu/mobile/MobileMenu.tsx
+++ b/packages/ui/src/components/menu/mobile/MobileMenu.tsx
@@ -14,97 +14,500 @@
* limitations under the License.
*/
-import type { IDisplayMenuItem, IMenuItem, IValueOption, MenuItemDefaultValueType } from '../../../services/menu/menu';
+import type { IDisplayMenuItem, IMenuButtonItem, IMenuItem, IMenuSelectorItem, IValueOption, MenuItemDefaultValueType } from '../../../services/menu/menu';
import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
import type { IBaseMenuProps } from '../desktop/Menu';
-import { clsx } from '@univerjs/design';
-import { useMemo } from 'react';
+import { LocaleService } from '@univerjs/core';
+import { borderBottomClassName, clsx } from '@univerjs/design';
+import { CheckMarkIcon, MoreIcon, MoreLeftIcon } from '@univerjs/icons';
+import { useEffect, useMemo, useState } from 'react';
+import { combineLatest, isObservable, of } from 'rxjs';
+import { scan, startWith } from 'rxjs/operators';
import { MenuItemType } from '../../../services/menu/menu';
import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
import { useDependency, useObservable } from '../../../utils/di';
import { CustomLabel } from '../../custom-label';
-/**
- * The mobile context menu wrapper.
- */
+type MobileMenuView =
+ | {
+ kind: 'schema';
+ title?: string;
+ schemas: IMenuSchema[];
+ }
+ | {
+ kind: 'options';
+ title?: string;
+ options: IValueOption[];
+ menuItem: IDisplayMenuItem<IMenuSelectorItem<MenuItemDefaultValueType, any>>;
+ menuKey: string;
+ currentValue: MenuItemDefaultValueType;
+ };
+
export function MobileMenu(props: IBaseMenuProps) {
const { menuType, onOptionSelect } = props;
const menuManagerService = useDependency(IMenuManagerService);
+ const [viewStack, setViewStack] = useState<MobileMenuView[]>([]);
+
+ const menuSchemaVersion$ = useMemo(() => {
+ return menuManagerService.menuChanged$.pipe(
+ scan((version) => version + 1, 0),
+ startWith(0)
+ );
+ }, [menuManagerService]);
+ const menuSchemaVersion = useObservable(menuSchemaVersion$, 0);
+
+ const menuSchemas = useMemo(() => {
+ if (!menuType) {
+ return [];
+ }
+
+ return menuManagerService.getMenuByPositionKey(menuType);
+ }, [menuManagerService, menuSchemaVersion, menuType]);
+
+ useEffect(() => {
+ setViewStack([]);
+ }, [menuType]);
+
+ const currentView = viewStack[viewStack.length - 1] ?? null;
if (!menuType) {
return null;
}
- // There is no submenu on mobile devices, so if there are sub menu items, we should flat them.
- const flattedMenuItems = useMemo(() => {
- const menuItems = menuManagerService.getMenuByPositionKey(menuType);
+ const openView = (view: MobileMenuView) => setViewStack((stack) => [...stack, view]);
+ const closeView = () => setViewStack((stack) => stack.slice(0, -1));
- // Flat all menu items recursively.
- function flatMenuItems(items: IMenuSchema[]): IMenuSchema[] {
- return items.reduce((acc, item) => {
- if (item.children) {
- return [...acc, ...flatMenuItems(item.children)];
- }
- return [...acc, item];
- }, [] as IMenuSchema[]);
- }
+ return (
+ <div className="univer-flex univer-max-h-[min(72vh,560px)] univer-flex-col univer-overflow-hidden">
+ {currentView && (
+ <header
+ className="
+ univer-grid univer-grid-cols-[32px_minmax(0,1fr)_32px] univer-items-center univer-gap-3
+ univer-border-0 univer-border-b univer-border-solid univer-border-gray-200 univer-bg-white
+ univer-px-4 univer-py-3
+ "
+ >
+ <button
+ type="button"
+ aria-label="Back"
+ className="
+ univer-flex univer-size-8 univer-appearance-none univer-items-center univer-justify-center
+ univer-rounded-full univer-border-0 univer-bg-transparent univer-p-0 univer-text-gray-700
+ hover:univer-bg-gray-100
+ active:univer-bg-gray-200
+ "
+ onClick={closeView}
+ >
+ <MoreLeftIcon className="univer-text-base" />
+ </button>
+ <div
+ className="
+ univer-min-w-0 univer-truncate univer-text-center univer-text-sm univer-font-semibold
+ univer-text-gray-900
+ "
+ >
+ {currentView.title}
+ </div>
+ <div className="univer-size-8" aria-hidden="true" />
+ </header>
+ )}
- return flatMenuItems(menuItems);
- }, [menuType]);
+ <div className="univer-flex-1 univer-overflow-y-auto univer-px-4 univer-pb-2 univer-pt-1">
+ {currentView?.kind !== 'options' && (
+ <div className="univer-overflow-hidden univer-rounded-2xl univer-bg-white">
+ <MobileSchemaList
+ schemas={currentView?.kind === 'schema' ? currentView.schemas : menuSchemas}
+ menuType={menuType}
+ onExecute={onOptionSelect}
+ onOpenView={openView}
+ />
+ </div>
+ )}
- return (
- <div
- className={`
- univer-box-border univer-grid univer-min-w-8 univer-max-w-52 univer-gap-1 univer-rounded
- univer-bg-gray-900 univer-px-2 univer-py-1
- `}
- style={{
- gridTemplateColumns: `repeat(${Math.min(2, flattedMenuItems.length)}, 72px)`,
- }}
- >
- {flattedMenuItems.map((item) => item.item && (
- <MobileMenuItem
- key={item.key}
- menuItem={item.item}
- onClick={(object: Partial<IValueOption>) => onOptionSelect?.({ value: '', label: item.key, ...object })}
- />
- ))}
+ {currentView?.kind === 'options' && (
+ <div className="univer-overflow-hidden univer-rounded-2xl univer-bg-white">
+ <MobileSelectionOptionsView
+ menuKey={currentView.menuKey}
+ menuItem={currentView.menuItem}
+ options={currentView.options}
+ currentValue={currentView.currentValue}
+ onExecute={onOptionSelect}
+ />
+ </div>
+ )}
+ </div>
</div>
);
}
-interface IMobileMenuItemProps {
- menuItem: IDisplayMenuItem<IMenuItem>;
- onClick: (object: Partial<IValueOption>) => void;
+function MobileSchemaList(props: {
+ schemas: IMenuSchema[];
+ menuType: string;
+ onExecute?: IBaseMenuProps['onOptionSelect'];
+ onOpenView: (view: MobileMenuView) => void;
+}) {
+ const { schemas, menuType, onExecute, onOpenView } = props;
+ const localeService = useDependency(LocaleService);
+ const hiddenGroupStates = useContextGroupHiddenStates(schemas);
+
+ const visibleSchemas = useMemo(() => {
+ return schemas.filter((schema) => {
+ if (schema.children?.length) {
+ return !hiddenGroupStates[schema.key];
+ }
+
+ return !!schema.item;
+ });
+ }, [hiddenGroupStates, schemas]);
+
+ return (
+ <>
+ {visibleSchemas.map((schema, index) => {
+ if (schema.item) {
+ return (
+ <MobileSchemaRow
+ key={schema.key}
+ schema={schema}
+ menuType={menuType}
+ onExecute={onExecute}
+ onOpenView={onOpenView}
+ bordered={index !== visibleSchemas.length - 1}
+ />
+ );
+ }
+
+ if (!schema.children?.length) {
+ return null;
+ }
+
+ return (
+ <section
+ key={schema.key}
+ className={clsx(
+ 'univer-grid',
+ index !== visibleSchemas.length - 1 && borderBottomClassName
+ )}
+ >
+ {schema.title && (
+ <div
+ className="
+ univer-px-4 univer-pb-1 univer-pt-3 univer-text-xs univer-font-medium univer-uppercase
+ univer-tracking-[0.08em] univer-text-gray-500
+ "
+ >
+ {localeService.t(schema.title)}
+ </div>
+ )}
+ {schema.children.map((childSchema, childIndex) => (
+ <MobileSchemaRow
+ key={childSchema.key}
+ schema={childSchema}
+ menuType={menuType}
+ onExecute={onExecute}
+ onOpenView={onOpenView}
+ bordered={childIndex !== schema.children!.length - 1}
+ />
+ ))}
+ </section>
+ );
+ })}
+ </>
+ );
}
-function MobileMenuItem(props: IMobileMenuItemProps) {
- const { menuItem, onClick } = props;
- const { id, type, title, label, icon } = menuItem;
+function MobileSchemaRow(props: {
+ schema: IMenuSchema;
+ menuType: string;
+ onExecute?: IBaseMenuProps['onOptionSelect'];
+ onOpenView: (view: MobileMenuView) => void;
+ bordered: boolean;
+}) {
+ const { schema, menuType, onExecute, onOpenView, bordered } = props;
+ const interaction = useMobileSchemaInteraction({ schema, menuType, onOpenView });
- if (type !== MenuItemType.BUTTON) {
- throw new Error(`[MobileMenuItem]: on mobile devices only "BUTTON" type menu items are supported. Please check "${id}".`);
+ if (!interaction || interaction.hidden) {
+ return null;
}
- const disabled = useObservable<boolean>(menuItem.disabled$, false);
- // const activated = useObservable<boolean>(menuItem.activated$, false);
- // const hidden = useObservable(menuItem.hidden$, false);
- const value = useObservable<MenuItemDefaultValueType>(menuItem.value$);
+ const { menuItem, disabled, value, currentValueText, hasSubmenu, onPress } = interaction;
return (
<button
type="button"
- className={clsx(`
- univer-w-18 univer-flex univer-flex-col univer-items-center univer-justify-center univer-border-none
- univer-bg-transparent univer-text-white
- [&>span]:univer-mt-0.5 [&>span]:univer-w-full [&>span]:univer-truncate [&>span]:univer-text-sm
- [&>svg]:univer-size-[18px] [&>svg]:univer-text-lg
- `)}
- key={id}
+ className={clsx(
+ `
+ univer-flex univer-min-h-[56px] univer-w-full univer-appearance-none univer-items-center univer-gap-3
+ univer-border-0 univer-bg-white univer-px-4 univer-py-3 univer-text-left univer-transition-colors
+ enabled:hover:univer-bg-gray-50
+ enabled:active:univer-bg-gray-100
+ disabled:univer-cursor-not-allowed disabled:univer-opacity-40
+ `,
+ bordered && borderBottomClassName
+ )}
disabled={disabled}
- onClick={() => onClick({ id })}
+ onClick={() => onPress(onExecute)}
+ >
+ <div
+ className="
+ univer-flex univer-min-w-0 univer-flex-1 univer-items-center univer-gap-3 univer-text-gray-900
+ [&>span]:univer-truncate [&>span]:univer-text-sm [&>span]:univer-font-medium
+ [&>svg]:univer-shrink-0 [&>svg]:univer-text-lg [&>svg]:univer-text-gray-700
+ "
+ >
+ <CustomLabel value={value} title={menuItem.title} label={menuItem.label} icon={menuItem.icon} />
+ </div>
+ {currentValueText && (
+ <span
+ className="
+ univer-max-w-[32%] univer-truncate univer-text-xs univer-font-medium univer-text-gray-400
+ "
+ >
+ {currentValueText}
+ </span>
+ )}
+ {hasSubmenu && <MoreIcon className="univer-shrink-0 univer-text-base univer-text-gray-400" />}
+ </button>
+ );
+}
+
+function MobileSelectionOptionsView(props: {
+ options: IValueOption[];
+ menuKey: string;
+ menuItem: IDisplayMenuItem<IMenuSelectorItem<MenuItemDefaultValueType, any>>;
+ currentValue: MenuItemDefaultValueType;
+ onExecute?: IBaseMenuProps['onOptionSelect'];
+}) {
+ const { options, menuKey, menuItem, currentValue, onExecute } = props;
+
+ return (
+ <>
+ {options.map((option, index) => (
+ <MobileSelectionOptionRow
+ key={`${menuKey}-${String(option.value ?? index)}`}
+ option={option}
+ menuKey={menuKey}
+ menuItem={menuItem}
+ currentValue={currentValue}
+ bordered={index !== options.length - 1}
+ onExecute={onExecute}
+ />
+ ))}
+ </>
+ );
+}
+
+function MobileSelectionOptionRow(props: {
+ option: IValueOption;
+ menuKey: string;
+ menuItem: IDisplayMenuItem<IMenuSelectorItem<MenuItemDefaultValueType, any>>;
+ currentValue: MenuItemDefaultValueType;
+ bordered: boolean;
+ onExecute?: IBaseMenuProps['onOptionSelect'];
+}) {
+ const { option, menuKey, menuItem, currentValue, bordered, onExecute } = props;
+ const optionValue = useObservable(option.value$);
+ const displayValue = option.value ?? optionValue;
+ const selected = displayValue === currentValue;
+
+ return (
+ <button
+ type="button"
+ className={clsx(
+ `
+ univer-relative univer-flex univer-min-h-[56px] univer-w-full univer-appearance-none
+ univer-items-center univer-gap-3 univer-border-0 univer-bg-white univer-px-4 univer-py-3
+ univer-text-left univer-transition-colors
+ enabled:hover:univer-bg-gray-50
+ enabled:active:univer-bg-gray-100
+ disabled:univer-cursor-not-allowed disabled:univer-opacity-40
+ `,
+ bordered && borderBottomClassName
+ )}
+ disabled={option.disabled}
+ onClick={() => {
+ onExecute?.({
+ ...option,
+ value: displayValue,
+ id: menuItem.id,
+ label: menuKey,
+ commandId: option.commandId,
+ });
+ }}
>
- <CustomLabel value={value} title={title} label={label} icon={icon} />
+ <div
+ className="
+ univer-flex univer-min-w-0 univer-flex-1 univer-items-center univer-gap-3 univer-text-gray-900
+ [&>span]:univer-truncate [&>span]:univer-text-sm [&>span]:univer-font-medium
+ [&>svg]:univer-shrink-0 [&>svg]:univer-text-lg [&>svg]:univer-text-gray-700
+ "
+ >
+ <CustomLabel value$={option.value$} value={displayValue} label={option.label} icon={option.icon} />
+ </div>
+ {selected && <CheckMarkIcon className="univer-shrink-0 univer-text-base univer-text-primary-600" />}
</button>
);
}
+
+function useMobileSchemaInteraction(props: {
+ schema: IMenuSchema;
+ menuType: string;
+ onOpenView: (view: MobileMenuView) => void;
+}) {
+ const { schema, menuType, onOpenView } = props;
+ const menuManagerService = useDependency(IMenuManagerService);
+ const localeService = useDependency(LocaleService);
+ const menuItem = schema.item as IDisplayMenuItem<IMenuItem> | undefined;
+ const selectorItem = menuItem as IDisplayMenuItem<IMenuSelectorItem<MenuItemDefaultValueType, any>> | undefined;
+ const disabled = useObservable<boolean>(menuItem?.disabled$, false);
+ const hidden = useObservable<boolean>(menuItem?.hidden$, false);
+ const value = useObservable<MenuItemDefaultValueType>(menuItem?.value$);
+ const selectionsFromObservable = useObservable(
+ selectorItem && isObservable(selectorItem.selections) ? selectorItem.selections : undefined
+ );
+
+ const selections = useMemo(() => {
+ if (!selectorItem || (menuItem?.type !== MenuItemType.SELECTOR && menuItem?.type !== MenuItemType.BUTTON_SELECTOR)) {
+ return [];
+ }
+
+ if (selectionsFromObservable) {
+ return selectionsFromObservable;
+ }
+
+ return Array.isArray(selectorItem.selections) ? selectorItem.selections : [];
+ }, [menuItem?.type, selectionsFromObservable, selectorItem]);
+
+ const subMenuItems = useMemo(() => {
+ if (!menuItem || menuItem.type !== MenuItemType.SUBITEMS || !menuItem.id) {
+ return [];
+ }
+
+ return menuManagerService.getMenuByPositionKey(menuItem.id);
+ }, [menuItem, menuManagerService]);
+
+ if (!menuItem) {
+ return null;
+ }
+
+ const schemaChildren = schema.children ?? [];
+ const hasSubmenu = schemaChildren.length > 0 || selections.length > 0 || subMenuItems.length > 0;
+ const currentValueText = typeof value === 'string' || typeof value === 'number' ? String(value) : '';
+
+ const onPress = (onExecute?: IBaseMenuProps['onOptionSelect']) => {
+ if (schemaChildren.length > 0) {
+ onOpenView({
+ kind: 'schema',
+ title: getMenuSchemaTitle(schema, localeService),
+ schemas: schemaChildren,
+ });
+ return;
+ }
+
+ if (selections.length > 0 && selectorItem) {
+ onOpenView({
+ kind: 'options',
+ title: getMenuSchemaTitle(schema, localeService),
+ options: selections,
+ menuItem: selectorItem,
+ menuKey: schema.key,
+ currentValue: value,
+ });
+ return;
+ }
+
+ if (subMenuItems.length > 0) {
+ onOpenView({
+ kind: 'schema',
+ title: getMenuSchemaTitle(schema, localeService),
+ schemas: subMenuItems,
+ });
+ return;
+ }
+
+ if (menuItem.type !== MenuItemType.BUTTON && menuItem.type !== MenuItemType.BUTTON_SELECTOR) {
+ return;
+ }
+
+ const buttonItem = menuItem as IDisplayMenuItem<IMenuButtonItem<MenuItemDefaultValueType>>;
+ onExecute?.({
+ commandId: buttonItem.commandId,
+ value,
+ id: buttonItem.id,
+ label: schema.key,
+ });
+ };
+
+ return {
+ menuItem,
+ disabled,
+ hidden,
+ value,
+ currentValueText,
+ hasSubmenu,
+ onPress,
+ };
+}
+
+function getMenuSchemaTitle(schema: IMenuSchema, localeService: LocaleService) {
+ const menuItem = schema.item as IDisplayMenuItem<IMenuItem> | undefined;
+
+ if (typeof menuItem?.title === 'string') {
+ return localeService.t(menuItem.title);
+ }
+
+ if (typeof menuItem?.label === 'string') {
+ return localeService.t(menuItem.label);
+ }
+
+ if (typeof schema.title === 'string') {
+ return localeService.t(schema.title);
+ }
+
+ return schema.key;
+}
+
+function useContextGroupHiddenStates(menuSchemas: IMenuSchema[]) {
+ const [hiddenStates, setHiddenStates] = useState<Record<string, boolean>>({});
+
+ useEffect(() => {
+ const subscriptions = menuSchemas.map((menuSchema) => {
+ if (!menuSchema.children?.length) {
+ return null;
+ }
+
+ const hiddenObservables = getLeafItemSchemas(menuSchema.children).map((childSchema) => childSchema.item?.hidden$ ?? of(false));
+ if (!hiddenObservables.length) {
+ return null;
+ }
+
+ return combineLatest(hiddenObservables).subscribe((hiddenValues) => {
+ const isAllHidden = hiddenValues.every((hidden) => hidden === true);
+ setHiddenStates((state) => ({
+ ...state,
+ [menuSchema.key]: isAllHidden,
+ }));
+ });
+ });
+
+ return () => {
+ subscriptions.forEach((subscription) => subscription?.unsubscribe());
+ setHiddenStates({});
+ };
+ }, [menuSchemas]);
+
+ return hiddenStates;
+}
+
+function getLeafItemSchemas(schemas: IMenuSchema[]): IMenuSchema[] {
+ return schemas.reduce((acc, schema) => {
+ if (schema.children?.length) {
+ return [...acc, ...getLeafItemSchemas(schema.children)];
+ }
+
+ if (schema.item) {
+ return [...acc, schema];
+ }
+
+ return acc;
+ }, [] as IMenuSchema[]);
+}
diff --git a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
index fd2114e173..6a30ee2163 100644
--- a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
@@ -15,12 +15,16 @@
*/
import type { IMouseEvent } from '@univerjs/engine-render';
-import { ICommandService } from '@univerjs/core';
-import { Popup } from '@univerjs/design';
-import { useEffect, useRef, useState } from 'react';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { ConfigContext } from '@univerjs/design';
+import { CloseIcon } from '@univerjs/icons';
+import { useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
import { MobileMenu } from '../../../components/menu/mobile/MobileMenu';
import { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { IContextMenuService } from '../../../services/contextmenu/contextmenu.service';
+import { ILayoutService } from '../../../services/layout/layout.service';
+import { ContextMenuPosition } from '../../../services/menu/types';
import { useDependency } from '../../../utils/di';
const MOBILE_CONTEXT_MENU_HOST_ID = 'mobile-context-menu';
@@ -28,11 +32,13 @@ const MOBILE_CONTEXT_MENU_HOST_ID = 'mobile-context-menu';
export function MobileContextMenu() {
const [visible, setVisible] = useState(false);
const [menuType, setMenuType] = useState('');
- const [offset, setOffset] = useState<[number, number]>([0, 0]);
const visibleRef = useRef(visible);
const contextMenuHostService = useDependency(IContextMenuHostService);
const contextMenuService = useDependency(IContextMenuService);
const commandService = useDependency(ICommandService);
+ const layoutService = useDependency(ILayoutService);
+ const localeService = useDependency(LocaleService);
+ const { mountContainer } = useContext(ConfigContext);
visibleRef.current = visible;
useEffect(() => {
@@ -50,22 +56,16 @@ export function MobileContextMenu() {
},
});
- document.addEventListener('pointerdown', handleClose);
- document.addEventListener('wheel', handleClose);
-
return () => {
- document.removeEventListener('pointerdown', handleClose);
- document.removeEventListener('wheel', handleClose);
disposables.dispose();
hostDisposable.dispose();
contextMenuHostService.deactivateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
};
}, [contextMenuHostService, contextMenuService]);
- function handleContextMenu(event: IMouseEvent, menuType: string) {
+ function handleContextMenu(_event: IMouseEvent, nextMenuType: string) {
contextMenuHostService.activateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
- setMenuType(menuType);
- setOffset([event.clientX, event.clientY]);
+ setMenuType(nextMenuType);
setVisible(true);
}
@@ -74,22 +74,85 @@ export function MobileContextMenu() {
contextMenuHostService.deactivateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
}
- return (
- <Popup visible={visible} offset={offset}>
- <section onPointerDown={(e) => e.stopPropagation()}>
- {/* TODO@wzhudev: maybe we should add another component for mobile devices. */}
+ const sheetTitle = useMemo(() => {
+ switch (menuType) {
+ case ContextMenuPosition.ROW_HEADER:
+ return localeService.t('row');
+ case ContextMenuPosition.COL_HEADER:
+ return localeService.t('column');
+ default:
+ return '';
+ }
+ }, [localeService, menuType]);
+
+ if (!mountContainer || !visible) {
+ return null;
+ }
+
+ return createPortal(
+ <div className="univer-fixed univer-inset-0 univer-z-[1080] univer-flex univer-items-end">
+ <button
+ type="button"
+ aria-label={localeService.t('rangeSelector.cancel')}
+ className="univer-absolute univer-inset-0 univer-bg-[rgba(15,23,42,0.32)] univer-backdrop-blur-[2px]"
+ onClick={handleClose}
+ />
+ <section
+ role="dialog"
+ aria-modal="true"
+ className="
+ univer-relative univer-z-[1] univer-mx-auto univer-flex univer-max-h-[80vh] univer-w-full
+ univer-max-w-[560px] univer-flex-col univer-overflow-hidden univer-rounded-t-[28px] univer-bg-gray-50
+ univer-shadow-[0_-16px_48px_rgba(15,23,42,0.18)]
+ "
+ style={{
+ paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 8px)',
+ }}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <div className="univer-flex univer-flex-col univer-gap-3 univer-px-4 univer-pb-3 univer-pt-3">
+ <div className="univer-mx-auto univer-h-1.5 univer-w-10 univer-rounded-full univer-bg-gray-300" />
+ <div className="univer-flex univer-items-center univer-justify-between univer-gap-3">
+ <div className="univer-min-w-0 univer-flex-1">
+ {sheetTitle && (
+ <div
+ className="univer-truncate univer-text-sm univer-font-semibold univer-text-gray-900"
+ >
+ {sheetTitle}
+ </div>
+ )}
+ </div>
+ <button
+ type="button"
+ aria-label={localeService.t('rangeSelector.cancel')}
+ className="
+ univer-flex univer-size-8 univer-shrink-0 univer-appearance-none univer-items-center
+ univer-justify-center univer-rounded-full univer-border-0 univer-bg-white univer-p-0
+ univer-leading-none univer-text-gray-600 univer-shadow-sm univer-outline-none
+ univer-ring-0 univer-transition-colors
+ hover:univer-bg-gray-100
+ active:univer-bg-gray-200
+ "
+ style={{ margin: 0 }}
+ onClick={handleClose}
+ >
+ <CloseIcon className="univer-size-4 univer-text-current" />
+ </button>
+ </div>
+ </div>
{menuType && (
- // TODO@wzhudev: change to mobile menu
<MobileMenu
menuType={menuType}
onOptionSelect={(params) => {
const { label: id, value, commandId } = params;
- commandService && commandService.executeCommand(commandId ?? id as string, { value });
- setVisible(false);
+ layoutService.focus();
+ commandService.executeCommand(commandId ?? id as string, { value });
+ handleClose();
}}
/>
)}
</section>
- </Popup>
+ </div>,
+ mountContainer
);
}