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.

fix(ui): emit command IDs from context menu buttons (#8160)

白熱607c9f6b5421
diff --git a/packages/ui/src/views/components/context-menu/ContextMenu.tsx b/packages/ui/src/views/components/context-menu/ContextMenu.tsx
index 9ba06fa4b2..97755a836c 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenu.tsx
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ContextMenuEvent, IContextMenuTriggerContext } from '../../../services/contextmenu/contextmenu.service';
-import type { IContextMenuAnchorRect } from './AnchoredContextMenu';
import { ICommandService } from '@univerjs/core';
import { useEffect, useRef, useState } from 'react';
+import type { ContextMenuEvent, IContextMenuTriggerContext } from '../../../services/contextmenu/contextmenu.service';
+import type { IContextMenuAnchorRect } from './AnchoredContextMenu';
import { IContextMenuService } from '../../../services/contextmenu/contextmenu.service';
import { ILayoutService } from '../../../services/layout/layout.service';
import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
index 9f1481ef12..209d0f1383 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
@@ -1481,7 +1481,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
if (canExecuteItem) {
const item = menuItem as IDisplayMenuItem<IMenuButtonItem>;
onOptionSelect?.({
- commandId: item.commandId,
+ commandId: item.commandId ?? item.id,
params: item.params,
value: inputValue,
id: item.id,
@@ -1501,7 +1501,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
const item = menuItem as IDisplayMenuItem<IMenuButtonItem>;
onOptionSelect?.({
- commandId: item.commandId,
+ commandId: item.commandId ?? item.id,
params: item.params,
value: inputValue,
id: item.id,
diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenu.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenu.spec.tsx
new file mode 100644
index 0000000000..6aa548330f
--- /dev/null
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenu.spec.tsx
@@ -0,0 +1,139 @@
+/**
+ * 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 { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import {
+ CommandService,
+ CommandType,
+ ConfigService,
+ ContextService,
+ DesktopLogService,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { RediContext } from '@wendellhu/redi/react-bindings';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ComponentManager } from '../../../../common/component-manager';
+import { IconManager } from '../../../../common/icon-manager';
+import enUS from '../../../../locale/en-US';
+import { ContextMenuHostService, IContextMenuHostService } from '../../../../services/contextmenu/contextmenu-host.service';
+import { ContextMenuService, IContextMenuService } from '../../../../services/contextmenu/contextmenu.service';
+import { DesktopLayoutService, ILayoutService } from '../../../../services/layout/layout.service';
+import { MenuItemType } from '../../../../services/menu/menu';
+import { IMenuManagerService, MenuManagerService } from '../../../../services/menu/menu-manager.service';
+import {
+ IUIRuntimeScopeService,
+ UIRuntimeScopeService,
+} from '../../../../services/runtime-scope/ui-runtime-scope.service';
+import { DesktopContextMenu } from '../ContextMenu';
+
+const injectors: Injector[] = [];
+
+function createInjector() {
+ const injector = new Injector([
+ [IConfigService, { useClass: ConfigService }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ [IUniverInstanceService, { useClass: UniverInstanceService }],
+ [ICommandService, { useClass: CommandService }],
+ [IMenuManagerService, { useClass: MenuManagerService }],
+ [ILayoutService, { useClass: DesktopLayoutService }],
+ [IContextMenuService, { useClass: ContextMenuService }],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
+ [IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }],
+ [LocaleService],
+ [ComponentManager],
+ [IconManager],
+ ]);
+ injectors.push(injector);
+ return injector;
+}
+
+afterEach(() => {
+ cleanup();
+ injectors.splice(0).forEach((injector) => injector.dispose());
+});
+
+describe('DesktopContextMenu', () => {
+ it.each([
+ { id: 'insert-row', commandId: undefined, scoped: false },
+ { id: 'table.insert-row', commandId: undefined, scoped: false },
+ { id: 'table.insert-row', commandId: 'table.insert-two-rows', scoped: true },
+ ])('executes $id with command override $commandId in its runtime scope', async ({ id, commandId, scoped }) => {
+ const injector = createInjector();
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: { ...enUS, test: { insert: 'Insert row' } } });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.get(ILayoutService).registerRootContainerElement(document.body);
+ const scopedInjector = scoped ? createInjector() : injector;
+ const commandService = scopedInjector.get(ICommandService);
+ const menuService = scopedInjector.get(IMenuManagerService);
+ const contextMenuService = injector.get(IContextMenuService);
+ let rows = 3;
+ let requestedCount = 1;
+ for (const command of new Set(['insert-row', id, commandId].filter((value) => value !== undefined))) {
+ commandService.registerCommand({
+ id: command,
+ type: CommandType.OPERATION,
+ handler: (_accessor, params: { count: number }) => {
+ if (command === (commandId ?? id)) {
+ rows += params.count;
+ }
+ return true;
+ },
+ });
+ }
+ menuService.appendRootMenu({
+ table: {
+ 'insert-row': {
+ menuItemFactory: () => ({
+ id,
+ commandId,
+ type: MenuItemType.BUTTON,
+ title: 'test.insert',
+ params: () => ({ count: requestedCount }),
+ }),
+ },
+ },
+ });
+ if (scoped) {
+ injector.get(IUIRuntimeScopeService).register({
+ unitId: 'embedded-slide',
+ has: (identifier) => identifier === ICommandService || identifier === IMenuManagerService,
+ get: <T,>(identifier: unknown) => scopedInjector.get(identifier as typeof ICommandService) as T,
+ });
+ }
+ render(<RediContext.Provider value={{ injector }}><DesktopContextMenu /></RediContext.Provider>);
+ act(() => contextMenuService.triggerContextMenu(
+ { clientX: 20, clientY: 20, stopPropagation() {} },
+ 'table',
+ scoped ? { unitId: 'embedded-slide' } : undefined
+ ));
+ const button = await screen.findByRole('button', { name: 'Insert row' });
+ requestedCount = 2;
+ fireEvent.click(button);
+ await waitFor(() => expect(rows).toBe(5));
+ await waitFor(() => expect(contextMenuService.visible).toBe(false));
+ });
+});
diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
index 585345848c..4880e762b9 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
@@ -418,7 +418,7 @@ describe('ContextMenuPanel', () => {
expect(TestState.selectedOptions).toEqual([{
id: 'callout',
label: 'callout',
- commandId: undefined,
+ commandId: 'callout',
params: { block: 'callout' },
value: undefined,
}]);
@@ -582,7 +582,7 @@ describe('ContextMenuPanel', () => {
expect(trigger.getAttribute('aria-expanded')).toBe('false');
});
- it('selects an option from a selector submenu with the selector command id', () => {
+ it('keeps selector button and submenu option commands separate', () => {
renderWithDependencies(
<ContextMenuPanel
menuType="format-menu"
@@ -633,6 +633,15 @@ describe('ContextMenuPanel', () => {
value: '#ff0000',
}]);
expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(0);
+
+ fireEvent.click(colorButton);
+ expect(TestState.selectedOptions[1]).toEqual({
+ id: 'text-color',
+ label: 'color',
+ commandId: 'text-color',
+ params: undefined,
+ value: undefined,
+ });
});
it('keeps a custom submenu component interactive without selecting its parent option', async () => {