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): correct ribbon menu dismissal and RTL separators (#8179)

白熱575628df19e9
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts
index b76e0281b6..f8441a56e6 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts
@@ -49,10 +49,12 @@ import {
setDocsTableRenderViewportProvider,
} from '@univerjs/engine-render';
import {
+ ContextMenuHostService,
DesktopDialogService,
DesktopGalleryService,
DesktopMessageService,
DesktopNotificationService,
+ IContextMenuHostService,
IDialogService,
IGalleryService,
IMessageService,
@@ -128,6 +130,7 @@ async function createRepeatedImageTestBed(unitId: string) {
} }]);
injector.add([IUIPartsService, { useClass: UIPartsService }]);
injector.add([IGalleryService, { useClass: DesktopGalleryService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([IMessageService, { useClass: DesktopMessageService }]);
injector.add([INotificationService, { useClass: DesktopNotificationService }]);
diff --git a/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
index af25d02a6b..9e3d2b77af 100644
--- a/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
@@ -29,7 +29,16 @@ import {
} from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { CanvasPopupService, DesktopDialogService, ICanvasPopupService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';
+import {
+ CanvasPopupService,
+ ContextMenuHostService,
+ DesktopDialogService,
+ ICanvasPopupService,
+ IContextMenuHostService,
+ IDialogService,
+ IUIPartsService,
+ UIPartsService,
+} from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
import { DocHyperLinkSelectionController } from '../doc-hyper-link-selection.controller';
@@ -62,6 +71,7 @@ describe.each([1, 3])('DocHyperLinkSelectionController with a %i-character link'
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
index c6b2775e59..9f573a0f7e 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
@@ -33,7 +33,14 @@ import {
} from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { DesktopDialogService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';
+import {
+ ContextMenuHostService,
+ DesktopDialogService,
+ IContextMenuHostService,
+ IDialogService,
+ IUIPartsService,
+ UIPartsService,
+} from '@univerjs/ui';
import { NEVER } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';
@@ -65,6 +72,7 @@ describe('DocHyperLinkRenderController', () => {
} as unknown as DocCanvasPopManagerService }]);
injector.add([DocHyperLinkPopupService]);
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([DocHyperLinkRenderController, { useFactory: () => injector.createInstance(DocHyperLinkRenderController, context) }]);
diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
index 992b49c701..2035a80c53 100644
--- a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
@@ -30,8 +30,10 @@ import { Documents, FontCache, IRenderManagerService, UniverRenderEnginePlugin }
import { UnitAction } from '@univerjs/protocol';
import {
CanvasPopupService,
+ ContextMenuHostService,
DesktopDialogService,
ICanvasPopupService,
+ IContextMenuHostService,
IDialogService,
IUIPartsService,
UIPartsService,
@@ -63,6 +65,7 @@ function createService(documentFlavor = DocumentFlavor.TRADITIONAL) {
univer.registerPlugin(UniverRenderEnginePlugin);
const injector = univer.__getInjector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
injector.add([DocCanvasPopManagerService]);
diff --git a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
index 1c12414c77..6f457d9c39 100644
--- a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
+++ b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
@@ -33,7 +33,7 @@ import {
ThreadCommentModel,
} from '@univerjs/thread-comment';
import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
-import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';
+import { ContextMenuHostService, DesktopSidebarService, IContextMenuHostService, ISidebarService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AddDocCommentComment } from '../add-doc-comment.command';
import '@univerjs/docs-thread-comment/facade';
@@ -101,6 +101,7 @@ describe('AddDocCommentComment', () => {
injector.add([IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }]);
injector.add([ThreadCommentModel]);
injector.add([ThreadCommentFacadeService]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([ThreadCommentPanelService]);
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
index 46c0518639..d3e33fe077 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
@@ -16,7 +16,6 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { RenderUnit } from '@univerjs/engine-render';
-import type { HeaderFooterContentCover } from '../../views/header-footer/content-cover';
import {
BooleanNumber,
DocumentFlavor,
@@ -48,8 +47,16 @@ import {
RenderManagerService,
Vector2,
} from '@univerjs/engine-render';
-import { DesktopLayoutService, DesktopSidebarService, ILayoutService, ISidebarService } from '@univerjs/ui';
+import {
+ ContextMenuHostService,
+ DesktopLayoutService,
+ DesktopSidebarService,
+ IContextMenuHostService,
+ ILayoutService,
+ ISidebarService,
+} from '@univerjs/ui';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { HeaderFooterContentCover } from '../../views/header-footer/content-cover';
import { CloseHeaderFooterCommand } from '../../commands/commands/doc-header-footer.command';
import { SidebarDocHeaderFooterPanelOperation } from '../../commands/operations/doc-header-footer-panel.operation';
import enUS from '../../locale/en-US';
@@ -72,6 +79,7 @@ function createTestBed(documentFlavor = DocumentFlavor.TRADITIONAL, overrides: P
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([IEditorService, { useClass: EditorService }]);
injector.add([DocLayoutExecutorService]);
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts
index 438574d991..db55a702fc 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts
@@ -19,7 +19,7 @@ import type { RenderUnit } from '@univerjs/engine-render';
import { DocumentFlavor, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { CanvasColorService, DocBackground, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';
+import { ContextMenuHostService, DesktopSidebarService, IContextMenuHostService, ISidebarService } from '@univerjs/ui';
import { describe, expect, it, vi } from 'vitest';
import { DOCS_VIEW_KEY } from '../../../basics/docs-view-key';
import { DocPageLayoutService } from '../../../services/doc-page-layout.service';
@@ -53,6 +53,7 @@ describe('DocResizeRenderController', () => {
const injector = univer.__getInjector();
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
@@ -112,6 +113,7 @@ describe('DocResizeRenderController', () => {
const injector = univer.__getInjector();
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
diff --git a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx
index 95675b1148..89dc199957 100644
--- a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx
+++ b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx
@@ -25,11 +25,14 @@ import {
ILogService,
Injector,
LocaleService,
+ LocaleType,
toDisposable,
} from '@univerjs/core';
import {
ComponentManager,
+ ContextMenuHostService,
IconManager,
+ IContextMenuHostService,
ILayoutService,
IMenuManagerService,
IShortcutService,
@@ -46,6 +49,7 @@ import {
SetInlineFormatBoldCommand,
SetInlineFormatTextBackgroundColorCommand,
} from '../../../commands/commands/inline-format.command';
+import enUS from '../../../locale/en-US';
import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../../menu/menu';
import { DocLayoutInteractionService } from '../../../services/doc-layout-interaction.service';
import { FloatToolbar, resolveFloatToolbarMenus } from '../FloatToolbar';
@@ -84,12 +88,6 @@ class TestMenuManagerService {
}
}
-class TestLocaleService {
- t(key: string): string {
- return key;
- }
-}
-
class TestLayoutService {
readonly rootContainerElement = document.body;
private _focused = false;
@@ -172,12 +170,17 @@ function createToolbarTestBed() {
injector.add([IMenuManagerService, { useClass: TestMenuManagerService as never }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
- injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([LocaleService]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
injector.add([IShortcutService, { useClass: TestShortcutService as never }]);
injector.add([ILogService, { useClass: TestLogService as never }]);
injector.add([ComponentManager]);
injector.add([IconManager]);
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
return {
injector,
diff --git a/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsx b/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsx
index 5402d09a57..62669017b8 100644
--- a/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsx
+++ b/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsx
@@ -28,7 +28,15 @@ import {
} from '@univerjs/core';
import { SetDocumentPermissionCommand, UniverDocsPlugin } from '@univerjs/docs';
import { UnitAction, UnitObject } from '@univerjs/protocol';
-import { DesktopDialogService, IDialogService, IUIPartsService, RediProvider, UIPartsService } from '@univerjs/ui';
+import {
+ ContextMenuHostService,
+ DesktopDialogService,
+ IContextMenuHostService,
+ IDialogService,
+ IUIPartsService,
+ RediProvider,
+ UIPartsService,
+} from '@univerjs/ui';
import uiEnUS from '@univerjs/ui/locale/en-US';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
@@ -83,6 +91,7 @@ function setup(supportedTypes: UnitObject[] = []) {
const injector = univer.__getInjector();
injector.get(IPermissionService).addPermissionPoint({ id: `${UnitObject.Document}.${UnitAction.Edit}_doc`, type: UnitObject.Document, subType: UnitAction.Edit, value: true, status: PermissionStatus.DONE });
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
return { injector, dialogs: injector.get(IDialogService) };
}
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
index 94dd2ee973..2327320dd9 100644
--- a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
+++ b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
@@ -21,7 +21,19 @@ import type { Root } from 'react-dom/client';
import { ArrangeTypeEnum, CommandType, DrawingTypeEnum, ICommandService, LocaleType, Univer } from '@univerjs/core';
import { ConfigProvider } from '@univerjs/design';
import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';
-import { ComponentManager, IconManager, IDialogService, IMenuManagerService, IUIPartsService, MenuManagerService, MobileDialogService, RediContext, UIPartsService } from '@univerjs/ui';
+import {
+ ComponentManager,
+ ContextMenuHostService,
+ IconManager,
+ IContextMenuHostService,
+ IDialogService,
+ IMenuManagerService,
+ IUIPartsService,
+ MenuManagerService,
+ MobileDialogService,
+ RediContext,
+ UIPartsService,
+} from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -122,6 +134,7 @@ describe('drawing panel actions', () => {
injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
injector.add([DrawingImageClipService]);
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: MobileDialogService }]);
injector.get(IconManager).register({ DrawingEditIcon: () => <span /> });
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx
index f87bff5d4f..8fd3742e00 100644
--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx
@@ -79,7 +79,9 @@ import {
import { IMarkSelectionService } from '@univerjs/sheets-ui';
import {
ComponentManager,
+ ContextMenuHostService,
DesktopSidebarService,
+ IContextMenuHostService,
IDialogService,
ILayoutService,
IPlatformService,
@@ -419,6 +421,7 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {
[SheetsDataValidationValidatorService],
[SheetDataValidationModel],
[IMarkSelectionService, { useClass: TestMarkSelectionService as never }],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ISidebarService, { useClass: DesktopSidebarService }],
[DataValidationPanelService],
] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx
index 47ab54e21c..ccd6698964 100644
--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx
@@ -79,7 +79,9 @@ import {
import { IMarkSelectionService } from '@univerjs/sheets-ui';
import {
ComponentManager,
+ ContextMenuHostService,
DesktopSidebarService,
+ IContextMenuHostService,
ILayoutService,
IPlatformService,
IShortcutService,
@@ -384,6 +386,7 @@ function createItemTestBed(rule: ISheetDataValidationRule = createCheckboxRule()
[SheetsDataValidationValidatorService],
[SheetDataValidationModel],
[IMarkSelectionService, { useClass: TestMarkSelectionService as never }],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ISidebarService, { useClass: DesktopSidebarService }],
[DataValidationPanelService],
] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.spec.ts b/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.spec.ts
index d7bf73b5d8..a406c9ee1e 100644
--- a/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.spec.ts
+++ b/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.spec.ts
@@ -20,7 +20,13 @@ import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-re
import { SheetsSelectionsService } from '@univerjs/sheets';
import { SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';
import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { ComponentManager, DesktopSidebarService, ISidebarService } from '@univerjs/ui';
+import {
+ ComponentManager,
+ ContextMenuHostService,
+ DesktopSidebarService,
+ IContextMenuHostService,
+ ISidebarService,
+} from '@univerjs/ui';
import { beforeEach, describe, expect, it } from 'vitest';
import { createTestBed } from '../../../controllers/__tests__/test.util';
import { SheetNumfmtUIController } from '../../../controllers/ui.controller';
@@ -56,6 +62,7 @@ describe('number format panel operation', () => {
[IRenderManagerService, { useClass: RenderManagerService }],
[SheetSkeletonManagerService],
[ComponentManager],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ISidebarService, { useClass: DesktopSidebarService }],
[SheetsNumfmtCellContentController],
[SheetNumfmtUIController],
diff --git a/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts
index ae13f2fbe1..c8ec7639ce 100644
--- a/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts
+++ b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts
@@ -38,7 +38,14 @@ import {
SheetTableService,
TableManager,
} from '@univerjs/sheets-table';
-import { DesktopDialogService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';
+import {
+ ContextMenuHostService,
+ DesktopDialogService,
+ IContextMenuHostService,
+ IDialogService,
+ IUIPartsService,
+ UIPartsService,
+} from '@univerjs/ui';
import { afterEach, describe, expect, it } from 'vitest';
import { openRangeSelector, OpenTableSelectorOperation } from '../open-table-selector.operation';
@@ -103,6 +110,7 @@ function createTestBed(createWorkbook = true): ITestBed {
[SheetTableService],
[IDefinedNamesService, { useClass: DefinedNamesService }],
[IUIPartsService, { useClass: UIPartsService }],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[IDialogService, { useClass: DesktopDialogService }],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts
index 4bf985ee76..2c5aee2367 100644
--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts
+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-controls-render.controller.spec.ts
@@ -56,8 +56,10 @@ import {
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
import {
+ ContextMenuHostService,
DesktopDialogService,
DesktopSidebarService,
+ IContextMenuHostService,
IDialogService,
ISidebarService,
IUIPartsService,
@@ -113,6 +115,7 @@ function createTestBed(hasSkeleton = true, controllerType = SheetTableControlsRe
injector.add([SheetCanvasPopManagerService, { useValue: { attachPopupByPosition } as unknown as SheetCanvasPopManagerService }]);
injector.add([ISheetSelectionRenderService, { useValue: { resetSelectionsByModelData: vi.fn() } as unknown as ISheetSelectionRenderService }]);
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
const unit = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
diff --git a/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.ts b/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.ts
index 21040a0bcd..05c3c9a40f 100644
--- a/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.ts
+++ b/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.ts
@@ -39,7 +39,7 @@ import {
ThreadCommentModel,
} from '@univerjs/thread-comment';
import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
-import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';
+import { ContextMenuHostService, DesktopSidebarService, IContextMenuHostService, ISidebarService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SheetsThreadCommentPopupService } from '../../../services/sheets-thread-comment-popup.service';
import { SHEETS_THREAD_COMMENT_PANEL } from '../../../types/const';
@@ -127,6 +127,7 @@ describe('sheet thread comment operations', () => {
injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);
injector.add([SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService as never }]);
injector.add([SheetsThreadCommentPopupService]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([ThreadCommentPanelService]);
diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
index dc114e824f..e8c63f68ee 100644
--- a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
@@ -47,8 +47,10 @@ import {
} from '@univerjs/sheets';
import {
ComponentManager,
+ ContextMenuHostService,
DesktopLayoutService,
DesktopSidebarService,
+ IContextMenuHostService,
ILayoutService,
ISidebarService,
IUIPartsService,
@@ -297,6 +299,7 @@ function createFormulaBarTestBed(cellStyle?: IStyleData, realEditorServices = fa
injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);
injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
} else {
injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
diff --git a/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.spec.ts b/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.spec.ts
index 805e030357..ccb3bfb5ee 100644
--- a/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.spec.ts
+++ b/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.spec.ts
@@ -15,7 +15,7 @@
*/
import { ICommandService, Univer } from '@univerjs/core';
-import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';
+import { ContextMenuHostService, DesktopSidebarService, IContextMenuHostService, ISidebarService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ThreadCommentPanelService } from '../../../services/thread-comment-panel.service';
import { SetActiveCommentOperation } from '../comment.operations';
@@ -28,6 +28,7 @@ describe('SetActiveCommentOperation', () => {
beforeEach(() => {
univer = new Univer();
const injector = univer.__getInjector();
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([ThreadCommentPanelService]);
diff --git a/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts b/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts
index ee76b0b539..635f52f2ab 100644
--- a/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts
+++ b/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts
@@ -16,7 +16,7 @@
import type { IWorkbookData } from '@univerjs/core';
import { LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
-import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';
+import { ContextMenuHostService, DesktopSidebarService, IContextMenuHostService, ISidebarService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ThreadCommentPanelService } from '../thread-comment-panel.service';
@@ -44,6 +44,7 @@ describe('ThreadCommentPanelService', () => {
beforeEach(() => {
univer = new Univer();
const injector = univer.__getInjector();
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([ThreadCommentPanelService]);
diff --git a/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.ts b/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.ts
index 01c8ffad52..16e2eb7ac5 100644
--- a/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.ts
+++ b/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.ts
@@ -16,6 +16,10 @@
import { Injector } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import {
+ ContextMenuHostService,
+ IContextMenuHostService,
+} from '../../../services/contextmenu/contextmenu-host.service';
import { ShortcutPanelService } from '../../../services/shortcut/shortcut-panel.service';
import { DesktopSidebarService } from '../../../services/sidebar/desktop-sidebar.service';
import { ISidebarService } from '../../../services/sidebar/sidebar.service';
@@ -27,6 +31,7 @@ describe('ToggleShortcutPanelOperation', () => {
beforeEach(() => {
injector = new Injector([
[ShortcutPanelService],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ISidebarService, { useClass: DesktopSidebarService }],
]);
});
diff --git a/packages/ui/src/facade/__tests__/f-univer.spec.ts b/packages/ui/src/facade/__tests__/f-univer.spec.ts
index 598a518314..8597cb7aba 100644
--- a/packages/ui/src/facade/__tests__/f-univer.spec.ts
+++ b/packages/ui/src/facade/__tests__/f-univer.spec.ts
@@ -32,6 +32,7 @@ import type { IMenuSchema } from '../../services/menu/menu-manager.service';
import { ComponentManager } from '../../common/component-manager';
import { UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import { CopyCommand, PasteCommand } from '../../services/clipboard/clipboard.command';
+import { ContextMenuHostService, IContextMenuHostService } from '../../services/contextmenu/contextmenu-host.service';
import { DesktopDialogService } from '../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../services/dialog/dialog.service';
import { FontCategory, FontService, IFontService } from '../../services/font.service';
@@ -89,6 +90,7 @@ describe('ui facade', () => {
const injector = univer.__getInjector();
injector.add([ComponentManager]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([IFontService, { useClass: FontService }]);
injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.ts
index f789d6b33a..b744791937 100644
--- a/packages/ui/src/mobile-plugin.ts
+++ b/packages/ui/src/mobile-plugin.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { IUniverUIConfig } from './config/config';
import {
DependentOn,
generateRandomId,
@@ -31,6 +30,7 @@ import {
touchDependencies,
} from '@univerjs/core';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import type { IUniverUIConfig } from './config/config';
import pkg from '../package.json';
import { ComponentManager } from './common/component-manager';
import { IconManager } from './common/icon-manager';
diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.ts
index c78144e813..025e0695c8 100644
--- a/packages/ui/src/plugin.ts
+++ b/packages/ui/src/plugin.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { IUniverUIConfig } from './config/config';
import {
DependentOn,
generateRandomId,
@@ -31,6 +30,7 @@ import {
touchDependencies,
} from '@univerjs/core';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import type { IUniverUIConfig } from './config/config';
import pkg from '../package.json';
import { ComponentManager } from './common/component-manager';
import { IconManager } from './common/icon-manager';
diff --git a/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.ts b/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.ts
index 221404ac44..c4a18523bd 100644
--- a/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.ts
+++ b/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.ts
@@ -15,19 +15,22 @@
*/
import { Injector } from '@univerjs/core';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { ContextMenuHostService, IContextMenuHostService } from '../contextmenu-host.service';
-describe('ContextMenuHostService', () => {
- let service: IContextMenuHostService;
+const injectors: Injector[] = [];
- beforeEach(() => {
- const injector = new Injector();
- injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
- service = injector.get(IContextMenuHostService);
- });
+function createService() {
+ const injector = new Injector([[IContextMenuHostService, { useClass: ContextMenuHostService }]]);
+ injectors.push(injector);
+ return injector.get(IContextMenuHostService);
+}
+
+afterEach(() => injectors.splice(0).forEach((injector) => injector.dispose()));
+describe('ContextMenuHostService', () => {
it('hides the previously active menu when another menu becomes active', () => {
+ const service = createService();
const hideMainMenu = vi.fn();
const hideFooterMenu = vi.fn();
service.registerMenu('main', hideMainMenu);
@@ -42,6 +45,7 @@ describe('ContextMenuHostService', () => {
});
it('clears active menu state when a registered menu is disposed', () => {
+ const service = createService();
const disposable = service.registerMenu('main', vi.fn());
service.activateMenu('main');
@@ -51,6 +55,7 @@ describe('ContextMenuHostService', () => {
});
it('publishes active menu changes', () => {
+ const service = createService();
const activeMenuIds: Array<string | null> = [];
service.registerMenu('main', vi.fn());
const subscription = service.activeMenuId$.subscribe((menuId) => activeMenuIds.push(menuId));
@@ -61,4 +66,40 @@ describe('ContextMenuHostService', () => {
expect(activeMenuIds).toEqual([null, 'main', null]);
subscription.unsubscribe();
});
+
+ it('closes registered menus and blocks reopening until all host suspension owners release', () => {
+ const host = createService();
+ const other = createService();
+ const closeContextMenu = vi.fn();
+ const closeDropdown = vi.fn();
+ host.registerMenu('context', closeContextMenu);
+ host.registerMenu(Symbol('dropdown'), closeDropdown);
+ host.activateMenu('context');
+
+ const history = host.suspend();
+ const preview = host.suspend();
+ expect(closeContextMenu).toHaveBeenCalledWith(false);
+ expect(closeDropdown).toHaveBeenCalledWith(false);
+ other.activateMenu('other');
+ expect(other.activeMenuId).toBe('other');
+
+ history.dispose();
+ history.dispose();
+ host.activateMenu('context');
+ expect(host.activeMenuId).toBeNull();
+ preview.dispose();
+ host.activateMenu('context');
+ expect(host.activeMenuId).toBe('context');
+ });
+
+ it('releases a suspension if a registered menu fails to close', () => {
+ const host = createService();
+ const registration = host.registerMenu('custom', () => {
+ throw new Error('Cannot close');
+ });
+ expect(() => host.suspend()).toThrow('Cannot close');
+ registration.dispose();
+ host.activateMenu('context');
+ expect(host.activeMenuId).toBe('context');
+ });
});
diff --git a/packages/ui/src/services/contextmenu/contextmenu-host.service.ts b/packages/ui/src/services/contextmenu/contextmenu-host.service.ts
index 461c81d3e7..dfb68b0273 100644
--- a/packages/ui/src/services/contextmenu/contextmenu-host.service.ts
+++ b/packages/ui/src/services/contextmenu/contextmenu-host.service.ts
@@ -22,24 +22,42 @@ import { BehaviorSubject } from 'rxjs';
export interface IContextMenuHostService {
readonly activeMenuId: string | null;
readonly activeMenuId$: Observable<string | null>;
- registerMenu(menuId: string, hide: () => void): IDisposable;
+ /** Changes when pending menu interactions and focus restoration must be discarded. */
+ readonly revision: number;
+ readonly suspended: boolean;
+ registerMenu(menuId: string | symbol, hide: (restoreFocus: boolean) => void): IDisposable;
activateMenu(menuId: string): void;
deactivateMenu(menuId: string): void;
hideActiveMenu(exceptMenuId?: string): void;
+ /** Close registered menus without returning focus to their triggers. */
+ closeAll(): void;
+ /** Close host menus and prevent reopening until every replacing view releases its lease. */
+ suspend(): IDisposable;
}
export const IContextMenuHostService = createIdentifier<IContextMenuHostService>('ui.contextmenu.host.service');
export class ContextMenuHostService extends Disposable implements IContextMenuHostService {
- private readonly _menuMap = new Map<string, () => void>();
+ private readonly _menuMap = new Map<string | symbol, (restoreFocus: boolean) => void>();
private readonly _activeMenuId$ = new BehaviorSubject<string | null>(null);
+ private readonly _suspensions = new Set<symbol>();
+ private _revision = 0;
readonly activeMenuId$ = this._activeMenuId$.asObservable();
get activeMenuId(): string | null {
return this._activeMenuId$.value;
}
- registerMenu(menuId: string, hide: () => void): IDisposable {
+ get revision(): number {
+ return this._revision;
+ }
+
+ get suspended(): boolean {
+ return this._disposed || this._suspensions.size > 0;
+ }
+
+ registerMenu(menuId: string | symbol, hide: (restoreFocus: boolean) => void): IDisposable {
+ this.ensureNotDisposed();
this._menuMap.set(menuId, hide);
return toDisposable(() => {
@@ -51,6 +69,7 @@ export class ContextMenuHostService extends Disposable implements IContextMenuHo
}
activateMenu(menuId: string): void {
+ if (this.suspended) return;
this.hideActiveMenu(menuId);
this._activeMenuId$.next(menuId);
}
@@ -69,11 +88,37 @@ export class ContextMenuHostService extends Disposable implements IContextMenuHo
const hide = this._menuMap.get(activeMenuId);
this._activeMenuId$.next(null);
- hide?.();
+ hide?.(true);
+ }
+
+ closeAll(): void {
+ ++this._revision;
+ this._activeMenuId$.next(null);
+ Array.from(this._menuMap.values()).forEach((hide) => hide(false));
+ }
+
+ suspend(): IDisposable {
+ this.ensureNotDisposed();
+ const token = Symbol('menu-suspension');
+ this._suspensions.add(token);
+ try {
+ this.closeAll();
+ } catch (error) {
+ this._suspensions.delete(token);
+ throw error;
+ }
+ return toDisposable(() => this._suspensions.delete(token));
}
override dispose(): void {
- this._activeMenuId$.complete();
+ if (this._disposed) return;
super.dispose();
+ try {
+ this.closeAll();
+ } finally {
+ this._menuMap.clear();
+ this._suspensions.clear();
+ this._activeMenuId$.complete();
+ }
}
}
diff --git a/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.spec.ts b/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.spec.ts
index 3db4bd500c..b0bc87eb76 100644
--- a/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.spec.ts
+++ b/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.spec.ts
@@ -14,23 +14,33 @@
* limitations under the License.
*/
-import type { IDialogPartMethodOptions } from '../../../views/components/dialog-part/interface';
import { Injector } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IDialogPartMethodOptions } from '../../../views/components/dialog-part/interface';
+import { ContextMenuHostService, IContextMenuHostService } from '../../contextmenu/contextmenu-host.service';
import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';
import { DesktopDialogService } from '../desktop-dialog.service';
import { IDialogService } from '../dialog.service';
-function createService(): IDialogService {
+const injectors: Injector[] = [];
+
+function createInjector(): Injector {
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
- return injector.get(IDialogService);
+ injectors.push(injector);
+ return injector;
}
describe('DesktopDialogService', () => {
+ afterEach(() => {
+ injectors.splice(0).forEach((injector) => injector.dispose());
+ });
+
it('tracks opened dialogs and closes only the requested dialog', () => {
- const service = createService();
+ const injector = createInjector();
+ const service = injector.get(IDialogService);
const snapshots: IDialogPartMethodOptions[][] = [];
const sub = service.getDialogs$().subscribe((options) => snapshots.push(options));
@@ -43,7 +53,8 @@ describe('DesktopDialogService', () => {
});
it('keeps excepted dialogs open when closing all', () => {
- const service = createService();
+ const injector = createInjector();
+ const service = injector.get(IDialogService);
const snapshots: IDialogPartMethodOptions[][] = [];
const sub = service.getDialogs$().subscribe((options) => snapshots.push(options));
@@ -55,10 +66,33 @@ describe('DesktopDialogService', () => {
sub.unsubscribe();
});
+ it('dismisses menus before opening or reopening a dialog, but preserves them during updates and closing', () => {
+ const injector = createInjector();
+ const service = injector.get(IDialogService);
+ const menuHost = injector.get(IContextMenuHostService);
+ const hide = vi.fn();
+ menuHost.registerMenu('format', hide);
+ const activeMenus: Array<string | null> = [];
+ service.getDialogs$().subscribe(() => activeMenus.push(menuHost.activeMenuId));
+
+ menuHost.activateMenu('format');
+ service.open({ id: 'format-dialog' });
+ expect(hide).toHaveBeenCalledExactlyOnceWith(false);
+ expect(activeMenus).toEqual([null]);
+
+ menuHost.activateMenu('format');
+ service.open({ id: 'format-dialog', width: 500 });
+ service.close('format-dialog');
+ expect(hide).toHaveBeenCalledTimes(1);
+ expect(menuHost.activeMenuId).toBe('format');
+
+ service.open({ id: 'format-dialog' });
+ expect(hide).toHaveBeenCalledTimes(2);
+ expect(activeMenus.at(-1)).toBeNull();
+ });
+
it('registers the global dialog UI part when constructed', () => {
- const injector = new Injector();
- injector.add([IUIPartsService, { useClass: UIPartsService }]);
- injector.add([IDialogService, { useClass: DesktopDialogService }]);
+ const injector = createInjector();
injector.get(IDialogService);
expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);
diff --git a/packages/ui/src/services/dialog/desktop-dialog.service.ts b/packages/ui/src/services/dialog/desktop-dialog.service.ts
index 524fdac9b8..7b8a083c14 100644
--- a/packages/ui/src/services/dialog/desktop-dialog.service.ts
+++ b/packages/ui/src/services/dialog/desktop-dialog.service.ts
@@ -15,12 +15,13 @@
*/
import type { IDisposable } from '@univerjs/core';
-import type { IDialogPartMethodOptions } from '../../views/components/dialog-part/interface';
-import type { IDialogService } from './dialog.service';
import { Disposable, Inject, Injector, toDisposable } from '@univerjs/core';
import { Subject } from 'rxjs';
+import type { IDialogPartMethodOptions } from '../../views/components/dialog-part/interface';
+import type { IDialogService } from './dialog.service';
import { connectInjector } from '../../utils/di';
import { DialogPart } from '../../views/components/dialog-part/DialogPart';
+import { IContextMenuHostService } from '../contextmenu/contextmenu-host.service';
import { BuiltInUIPart, IUIPartsService } from '../parts/parts.service';
export class DesktopDialogService extends Disposable implements IDialogService {
@@ -29,7 +30,8 @@ export class DesktopDialogService extends Disposable implements IDialogService {
constructor(
@Inject(Injector) protected readonly _injector: Injector,
- @IUIPartsService protected readonly _uiPartsService: IUIPartsService
+ @IUIPartsService protected readonly _uiPartsService: IUIPartsService,
+ @IContextMenuHostService private readonly _menuHostService: IContextMenuHostService
) {
super();
@@ -44,7 +46,12 @@ export class DesktopDialogService extends Disposable implements IDialogService {
}
open(option: IDialogPartMethodOptions): IDisposable {
- if (this._dialogOptions.find((item) => item.id === option.id)) {
+ const existingDialog = this._dialogOptions.find((item) => item.id === option.id);
+ if (!existingDialog?.open) {
+ this._menuHostService.closeAll();
+ }
+
+ if (existingDialog) {
this._dialogOptions = this._dialogOptions.map((item) => ({
...(item.id === option.id ? option : item),
open: item.id === option.id ? true : item.open,
diff --git a/packages/ui/src/services/dialog/mobile-dialog.service.ts b/packages/ui/src/services/dialog/mobile-dialog.service.ts
index 46e2f06055..a4db20d4ab 100644
--- a/packages/ui/src/services/dialog/mobile-dialog.service.ts
+++ b/packages/ui/src/services/dialog/mobile-dialog.service.ts
@@ -17,15 +17,17 @@
import { Inject, Injector } from '@univerjs/core';
import { connectInjector } from '../../utils/di';
import { MobileDialogPart } from '../../views/components/dialog-part/MobileDialogPart';
+import { IContextMenuHostService } from '../contextmenu/contextmenu-host.service';
import { BuiltInUIPart, IUIPartsService } from '../parts/parts.service';
import { DesktopDialogService } from './desktop-dialog.service';
export class MobileDialogService extends DesktopDialogService {
constructor(
@Inject(Injector) injector: Injector,
- @IUIPartsService uiPartsService: IUIPartsService
+ @IUIPartsService uiPartsService: IUIPartsService,
+ @IContextMenuHostService menuHostService: IContextMenuHostService
) {
- super(injector, uiPartsService);
+ super(injector, uiPartsService, menuHostService);
}
override close(id: string): void {
diff --git a/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.spec.ts b/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.spec.ts
index cfa401db37..7c90015d93 100644
--- a/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.spec.ts
+++ b/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.spec.ts
@@ -16,17 +16,23 @@
import { Injector } from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ContextMenuHostService, IContextMenuHostService } from '../../contextmenu/contextmenu-host.service';
import { DesktopSidebarService } from '../desktop-sidebar.service';
import { ISidebarService } from '../sidebar.service';
-function createService(): ISidebarService {
+const injectors: Injector[] = [];
+
+function createInjector(): Injector {
const injector = new Injector();
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
- return injector.get(ISidebarService);
+ injectors.push(injector);
+ return injector;
}
describe('DesktopSidebarService', () => {
afterEach(() => {
+ injectors.splice(0).forEach((injector) => injector.dispose());
vi.unstubAllGlobals();
});
@@ -36,7 +42,8 @@ describe('DesktopSidebarService', () => {
return 1;
});
vi.stubGlobal('cancelAnimationFrame', vi.fn());
- const service = createService();
+ const injector = createInjector();
+ const service = injector.get(ISidebarService);
const snapshots: unknown[] = [];
const opened: string[] = [];
const closed: string[] = [];
@@ -52,13 +59,36 @@ describe('DesktopSidebarService', () => {
sub.unsubscribe();
});
+ it('dismisses menus before publishing an opened panel, but preserves them when the panel closes', () => {
+ vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1));
+ vi.stubGlobal('cancelAnimationFrame', vi.fn());
+ const injector = createInjector();
+ const service = injector.get(ISidebarService);
+ const menuHost = injector.get(IContextMenuHostService);
+ const hide = vi.fn();
+ menuHost.registerMenu('format', hide);
+ const activeMenus: Array<string | null> = [];
+ service.sidebarOptions$.subscribe(() => activeMenus.push(menuHost.activeMenuId));
+
+ menuHost.activateMenu('format');
+ service.open({ id: 'format-panel' });
+ expect(hide).toHaveBeenCalledExactlyOnceWith(false);
+ expect(activeMenus).toEqual([null]);
+
+ menuHost.activateMenu('format');
+ service.close();
+ expect(hide).toHaveBeenCalledTimes(1);
+ expect(menuHost.activeMenuId).toBe('format');
+ });
+
it('ignores close requests for a different sidebar id', () => {
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
callback(1);
return 1;
});
vi.stubGlobal('cancelAnimationFrame', vi.fn());
- const service = createService();
+ const injector = createInjector();
+ const service = injector.get(ISidebarService);
service.open({ id: 'inspector' });
service.close('other');
diff --git a/packages/ui/src/services/sidebar/desktop-sidebar.service.ts b/packages/ui/src/services/sidebar/desktop-sidebar.service.ts
index b67fc50d0a..4f42cfd79e 100644
--- a/packages/ui/src/services/sidebar/desktop-sidebar.service.ts
+++ b/packages/ui/src/services/sidebar/desktop-sidebar.service.ts
@@ -15,10 +15,11 @@
*/
import type { IDisposable } from '@univerjs/core';
-import type { ISidebarMethodOptions } from '../../views/components/sidebar/Sidebar';
-import type { ISidebarService } from './sidebar.service';
import { Disposable, toDisposable } from '@univerjs/core';
import { Subject } from 'rxjs';
+import type { ISidebarMethodOptions } from '../../views/components/sidebar/Sidebar';
+import type { ISidebarService } from './sidebar.service';
+import { IContextMenuHostService } from '../contextmenu/contextmenu-host.service';
export class DesktopSidebarService extends Disposable implements ISidebarService {
private _sidebarOptions: ISidebarMethodOptions = {};
@@ -30,6 +31,10 @@ export class DesktopSidebarService extends Disposable implements ISidebarService
private _openAnimationFrameId: number | null = null;
private _width?: number;
+ constructor(@IContextMenuHostService private readonly _menuHostService: IContextMenuHostService) {
+ super();
+ }
+
get visible(): boolean {
return this._sidebarOptions.visible || false;
}
@@ -61,6 +66,7 @@ export class DesktopSidebarService extends Disposable implements ISidebarService
}
open(params: ISidebarMethodOptions): IDisposable {
+ this._menuHostService.closeAll();
this._sidebarOptions = {
...params,
id: params.id,
diff --git a/packages/ui/src/utils/use-menu-host.ts b/packages/ui/src/utils/use-menu-host.ts
new file mode 100644
index 0000000000..ae1787963a
--- /dev/null
+++ b/packages/ui/src/utils/use-menu-host.ts
@@ -0,0 +1,35 @@
+/**
+ * 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 { useEffect, useRef } from 'react';
+import { IContextMenuHostService } from '../services/contextmenu/contextmenu-host.service';
+import { useDependency } from './di';
+
+export function useMenuHost(onClose: () => void): IContextMenuHostService {
+ const service = useDependency(IContextMenuHostService);
+ const callbackRef = useRef(onClose);
+ callbackRef.current = onClose;
+
+ useEffect(() => {
+ const registration = service.registerMenu(Symbol('menu'), () => callbackRef.current());
+ if (service.suspended) {
+ callbackRef.current();
+ }
+ return () => registration.dispose();
+ }, [service]);
+
+ return service;
+}
diff --git a/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx b/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx
index 8a1bd8c905..fceff41d7d 100644
--- a/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx
@@ -14,11 +14,11 @@
* limitations under the License.
*/
+import { Popup } from '@univerjs/design';
+import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import type { ILayoutService } from '../../../services/layout/layout.service';
import type { IValueOption } from '../../../services/menu/menu';
import type { IMenuManagerService } from '../../../services/menu/menu-manager.service';
-import { Popup } from '@univerjs/design';
-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { useDependency } from '../../../utils/di';
import { CONTEXT_MENU_SUBMENU_PORTAL_ATTR, ContextMenuPanel } from './ContextMenuPanel';
@@ -76,8 +76,9 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
menuTypeRef.current = menuType;
useEffect(() => {
- const disposable = contextMenuHostService.registerMenu(hostId, () => {
- onRequestCloseRef.current();
+ const disposable = contextMenuHostService.registerMenu(hostId, (restoreFocus) => {
+ if (!restoreFocus) focusReturnTargetRef.current = null;
+ if (visibleRef.current) onRequestCloseRef.current();
});
return () => {
@@ -88,6 +89,11 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
useLayoutEffect(() => {
if (visible) {
+ if (contextMenuHostService.suspended) {
+ focusReturnTargetRef.current = null;
+ onRequestCloseRef.current();
+ return;
+ }
const ownerDocument = contentRef.current?.ownerDocument ?? document;
const activeElement = ownerDocument.activeElement;
const isFocusInMenu = activeElement !== null
@@ -183,7 +189,7 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
return (
<Popup
- visible={visible && !!anchorRect}
+ visible={visible && !!anchorRect && !contextMenuHostService.suspended}
offset={offset}
overflowVisible
placementY={anchorVertical === 'top' ? 'above' : 'below'}
diff --git a/packages/ui/src/views/components/context-menu/ContextMenu.tsx b/packages/ui/src/views/components/context-menu/ContextMenu.tsx
index 97755a836c..88761ce011 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenu.tsx
@@ -18,6 +18,7 @@ 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 { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { IContextMenuService } from '../../../services/contextmenu/contextmenu.service';
import { ILayoutService } from '../../../services/layout/layout.service';
import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
@@ -29,6 +30,8 @@ const DESKTOP_CONTEXT_MENU_HOST_ID = 'desktop-context-menu';
export function DesktopContextMenu() {
const [visible, setVisible] = useState(false);
+ const pendingOpenRef = useRef<number | null>(null);
+ const menuHost = useDependency(IContextMenuHostService);
const [menuType, setMenuType] = useState('');
const [anchorRect, setAnchorRect] = useState<IContextMenuAnchorRect | null>(null);
const [menuContext, setMenuContext] = useState<IContextMenuTriggerContext | undefined>();
@@ -53,13 +56,18 @@ export function DesktopContextMenu() {
return () => {
disposables.dispose();
+ if (pendingOpenRef.current !== null) cancelAnimationFrame(pendingOpenRef.current);
};
}, [contextMenuService]);
/** A function to open context menu with given position and menu type. */
function handleContextMenu(event: ContextMenuEvent, menuType: string, context?: IContextMenuTriggerContext) {
- setVisible(false);
- requestAnimationFrame(() => {
+ handleClose();
+ if (menuHost.suspended) return;
+ const revision = menuHost.revision;
+ pendingOpenRef.current = requestAnimationFrame(() => {
+ pendingOpenRef.current = null;
+ if (menuHost.suspended || revision !== menuHost.revision) return;
setMenuType(menuType);
setMenuContext(context);
setAnchorRect({
@@ -72,6 +80,10 @@ export function DesktopContextMenu() {
}
function handleClose() {
+ if (pendingOpenRef.current !== null) {
+ cancelAnimationFrame(pendingOpenRef.current);
+ pendingOpenRef.current = null;
+ }
setVisible(false);
}
@@ -101,11 +113,12 @@ export function DesktopContextMenu() {
const rawParams = typeof params.params === 'function' ? params.params() : params.params;
const commandParams = typeof rawParams === 'undefined' ? { value } : rawParams;
+ const revision = menuHost.revision;
if (activeCommandService) {
activeCommandService.executeCommand(commandId ?? id as string, commandParams);
}
- activeLayoutService.focus();
+ if (revision === menuHost.revision && !menuHost.suspended) activeLayoutService.focus();
handleClose();
}}
diff --git a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
index b2c469addd..c9d84e2177 100644
--- a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
@@ -15,12 +15,12 @@
*/
import type { ComponentProps } from 'react';
-import type { LocaleKey } from '../../../locale/types';
-import type { ContextMenuEvent, IContextMenuTriggerContext } from '../../../services/contextmenu/contextmenu.service';
import { ICommandService, LocaleService } from '@univerjs/core';
import { ConfigContext } from '@univerjs/design';
import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
+import type { LocaleKey } from '../../../locale/types';
+import type { ContextMenuEvent, IContextMenuTriggerContext } from '../../../services/contextmenu/contextmenu.service';
import { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { IContextMenuService } from '../../../services/contextmenu/contextmenu.service';
import { ILayoutService } from '../../../services/layout/layout.service';
@@ -78,6 +78,7 @@ export function MobileContextMenu() {
nextMenuType: string,
context?: IContextMenuTriggerContext
) => {
+ if (contextMenuHostService.suspended) return;
contextMenuHostService.activateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
setMenuType(nextMenuType);
setMenuContext(context);
diff --git a/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx
index f77a05fd14..2ba8b685dc 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx
@@ -14,95 +14,90 @@
* limitations under the License.
*/
-import type { PropsWithChildren } from 'react';
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { useState } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { PropsWithChildren, ReactElement } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import {
+ ConfigService,
+ ContextService,
+ DesktopLogService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
+import { RediContext } from '@wendellhu/redi/react-bindings';
+import { BehaviorSubject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { ICustomComponentProps } from '../../../../services/menu/menu';
+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 { DesktopLayoutService, ILayoutService } from '../../../../services/layout/layout.service';
+import { MenuItemType } from '../../../../services/menu/menu';
+import { IMenuManagerService, MenuManagerService } from '../../../../services/menu/menu-manager.service';
import { AnchoredContextMenu } from '../AnchoredContextMenu';
-const hostService = {
- activateMenu: vi.fn(),
- deactivateMenu: vi.fn(),
- registerMenu: vi.fn(() => ({ dispose: vi.fn() })),
-};
-const panelProps = vi.fn();
+const injectors: Injector[] = [];
-vi.mock('@univerjs/design', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@univerjs/design')>();
+function MenuInput({ value, onChange }: ICustomComponentProps<string>) {
+ return <input aria-label="Menu value" value={value} onChange={(event) => onChange(event.target.value)} />;
+}
- return {
- ...actual,
- Popup: ({ children }: PropsWithChildren) => <>{children}</>,
- };
-});
-
-vi.mock('../../../../utils/di', () => ({
- useDependency: () => hostService,
-}));
-
-vi.mock('../ContextMenuPanel', () => ({
- CONTEXT_MENU_SUBMENU_PORTAL_ATTR: 'data-u-context-menu-submenu',
- ContextMenuPanel: (props: {
- autoFocus?: boolean;
- onCancel?: () => void;
- onOptionSelect?: (option: { label: string; value: string }) => void;
- }) => {
- const [value, setValue] = useState('2');
- panelProps(props);
+function renderWithDependencies(element: ReactElement, options?: Parameters<typeof render>[1]) {
+ const injector = new Injector([
+ [IConfigService, { useClass: ConfigService }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ [IUniverInstanceService, { useClass: UniverInstanceService }],
+ [IMenuManagerService, { useClass: MenuManagerService }],
+ [ILayoutService, { useClass: DesktopLayoutService }],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
+ [LocaleService],
+ [ComponentManager],
+ [IconManager],
+ ]);
+ injectors.push(injector);
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.get(ComponentManager).register('menu-input', MenuInput);
+ injector.get(IMenuManagerService).appendRootMenu({ drawing: {
+ 'test.command.menu-value': { menuItemFactory: () => ({
+ id: 'test.command.menu-value',
+ type: MenuItemType.BUTTON,
+ title: 'Context menu item',
+ label: 'menu-input',
+ value$: new BehaviorSubject('2'),
+ }) },
+ } });
+ const mountContainer = options?.container?.ownerDocument.body ?? document.body;
+ injector.get(ILayoutService).registerRootContainerElement(mountContainer);
+ const contextValue = { injector };
+ function Wrapper({ children }: PropsWithChildren) {
return (
- <div
- tabIndex={-1}
- onKeyDown={(event) => {
- if (event.key === 'Escape') {
- event.stopPropagation();
- props.onCancel?.();
- }
- }}
- >
- <button
- type="button"
- aria-label="Context menu item"
- onClick={() => props.onOptionSelect?.({ label: 'test.command.menu-value', value })}
- >
- <input
- aria-label="Menu value"
- value={value}
- onChange={(event) => setValue(event.target.value)}
- />
- </button>
- </div>
+ <RediContext.Provider value={contextValue}>
+ <ConfigProvider mountContainer={mountContainer}>{children}</ConfigProvider>
+ </RediContext.Provider>
);
- },
-}));
+ }
+ return { ...render(element, { ...options, baseElement: mountContainer, wrapper: Wrapper }), injector };
+}
describe('AnchoredContextMenu', () => {
- beforeEach(() => {
- panelProps.mockClear();
- });
-
- afterEach(cleanup);
-
- it('passes its close callback to the context menu panel', () => {
- const close = vi.fn();
- render(
- <AnchoredContextMenu
- hostId="desktop"
- visible
- anchorRect={{ left: 0, top: 0, bottom: 0 }}
- menuType="drawing"
- onRequestClose={close}
- />
- );
-
- fireEvent.keyDown(screen.getByRole('button', { name: 'Context menu item' }), {
- key: 'Escape',
- });
-
- expect(close).toHaveBeenCalledOnce();
+ afterEach(() => {
+ cleanup();
+ injectors.splice(0).forEach((injector) => injector.dispose());
});
it('restores the element focused before the menu opened', () => {
- const { rerender } = render(
+ const { rerender } = renderWithDependencies(
<>
<button type="button">Editor canvas</button>
<AnchoredContextMenu
@@ -129,7 +124,7 @@ describe('AnchoredContextMenu', () => {
/>
</>
);
- screen.getByRole('button', { name: 'Context menu item' }).focus();
+ screen.getByRole('button', { name: /Context menu item/ }).focus();
rerender(
<>
@@ -157,7 +152,7 @@ describe('AnchoredContextMenu', () => {
const container = iframeDocument.createElement('div');
iframeDocument.body.appendChild(container);
- const rendered = render(
+ const rendered = renderWithDependencies(
<>
<button type="button">Embedded editor canvas</button>
<AnchoredContextMenu
@@ -185,7 +180,7 @@ describe('AnchoredContextMenu', () => {
/>
</>
);
- rendered.getByRole('button', { name: 'Context menu item' }).focus();
+ rendered.getByRole('button', { name: /Context menu item/ }).focus();
rendered.rerender(
<>
@@ -205,19 +200,41 @@ describe('AnchoredContextMenu', () => {
iframe.remove();
});
- it('forwards keyboard autofocus to the context menu panel', () => {
- render(
+ it('focuses the first action when opened from the keyboard', async () => {
+ renderWithDependencies(
<AnchoredContextMenu
hostId="desktop"
visible
+ autoFocus
anchorRect={{ left: 0, top: 0, bottom: 0 }}
menuType="drawing"
- autoFocus
onRequestClose={vi.fn()}
/>
);
+ await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('button', { name: /Context menu item/ })));
+ });
- expect(panelProps).toHaveBeenCalledWith(expect.objectContaining({ autoFocus: true }));
+ it('closes on view takeover without returning focus to the editor', () => {
+ const close = vi.fn();
+ const editor = document.createElement('button');
+ document.body.appendChild(editor);
+ editor.focus();
+ const renderMenu = (visible: boolean) => (
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible={visible}
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={close}
+ />
+ );
+ const { injector, rerender } = renderWithDependencies(renderMenu(true));
+ screen.getByRole('textbox', { name: 'Menu value' }).focus();
+ act(() => injector.get(IContextMenuHostService).suspend());
+ expect(close).toHaveBeenCalledOnce();
+ rerender(renderMenu(false));
+ expect(document.activeElement).not.toBe(editor);
+ editor.remove();
});
it('keeps a draft during anchor movement but resets it when the menu reopens', () => {
@@ -232,7 +249,7 @@ describe('AnchoredContextMenu', () => {
onOptionSelect={(option) => selections.push(option as { label: string; value: string })}
/>
);
- const view = render(renderMenu(true, 10));
+ const view = renderWithDependencies(renderMenu(true, 10));
const input = screen.getByRole('textbox', { name: 'Menu value' }) as HTMLInputElement;
input.focus();
fireEvent.change(input, { target: { value: '3' } });
@@ -249,7 +266,7 @@ describe('AnchoredContextMenu', () => {
const reopenedInput = screen.getByRole('textbox', { name: 'Menu value' }) as HTMLInputElement;
expect(reopenedInput.value).toBe('2');
fireEvent.click(reopenedInput.closest('button')!);
- expect(selections).toEqual([{ label: 'test.command.menu-value', value: '2' }]);
+ expect(selections).toEqual([expect.objectContaining({ label: 'test.command.menu-value', value: '2' })]);
});
it.each(['container', 'button', 'input'] as const)(
@@ -257,7 +274,7 @@ describe('AnchoredContextMenu', () => {
(targetKind) => {
const close = vi.fn();
const selection = vi.fn();
- const view = render(
+ const view = renderWithDependencies(
<AnchoredContextMenu
hostId="desktop"
visible
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
index 6aa548330f..1fa0399274 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenu.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenu.spec.tsx
@@ -75,6 +75,28 @@ afterEach(() => {
});
describe('DesktopContextMenu', () => {
+ it('discards a deferred open when another view takes over, even if it exits before the next frame', async () => {
+ const injector = createInjector();
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.get(ILayoutService).registerRootContainerElement(document.body);
+ const contextMenuService = injector.get(IContextMenuService);
+ const menuHost = injector.get(IContextMenuHostService);
+ render(<RediContext.Provider value={{ injector }}><DesktopContextMenu /></RediContext.Provider>);
+ act(() => {
+ contextMenuService.triggerContextMenu({ clientX: 20, clientY: 20, stopPropagation() {} }, 'table');
+ menuHost.suspend().dispose();
+ });
+ await act(async () => {
+ await new Promise(requestAnimationFrame);
+ });
+ expect(contextMenuService.visible).toBe(false);
+ act(() => contextMenuService.triggerContextMenu({ clientX: 20, clientY: 20, stopPropagation() {} }, 'table'));
+ await waitFor(() => expect(contextMenuService.visible).toBe(true));
+ });
+
it.each([
{ id: 'insert-row', commandId: undefined, scoped: false },
{ id: 'table.insert-row', commandId: undefined, scoped: false },
diff --git a/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.ts b/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.ts
deleted file mode 100644
index fb41b59bbf..0000000000
--- a/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * 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 { describe, expect, it } from 'vitest';
-import { ContextMenuPosition } from '../../../../services/menu/types';
-import { resolveMobileCaretMenuPlacement, shouldUseFloatingMobileContextMenu } from '../MobileContextMenu';
-
-describe('MobileContextMenu', () => {
- it('uses a floating menu only for an explicit caret anchor', () => {
- expect(shouldUseFloatingMobileContextMenu(ContextMenuPosition.MAIN_AREA)).toBe(false);
- expect(shouldUseFloatingMobileContextMenu(ContextMenuPosition.MAIN_AREA, { unitId: 'sheet-1' })).toBe(false);
- expect(shouldUseFloatingMobileContextMenu(ContextMenuPosition.MAIN_AREA, {
- unitId: 'doc-1',
- caretAnchor: true,
- })).toBe(true);
- });
-
- it('keeps the pointer aligned with the caret when the compact menu reaches viewport edges', () => {
- expect(resolveMobileCaretMenuPlacement(200, 12, 400, 180)).toEqual({
- menuLeft: 98,
- pointerLeft: 86,
- });
- expect(resolveMobileCaretMenuPlacement(8, 12, 400, 180)).toEqual({
- menuLeft: 0,
- pointerLeft: 12,
- });
- expect(resolveMobileCaretMenuPlacement(420, 12, 400, 180)).toEqual({
- menuLeft: 220,
- pointerLeft: 160,
- });
- });
-});
diff --git a/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.tsx
new file mode 100644
index 0000000000..b7d692e196
--- /dev/null
+++ b/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.tsx
@@ -0,0 +1,144 @@
+/**
+ * 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, render, screen } from '@testing-library/react';
+import {
+ CommandService,
+ ConfigService,
+ ContextService,
+ DesktopLogService,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
+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 { ContextMenuPosition } from '../../../../services/menu/types';
+import {
+ IUIRuntimeScopeService,
+ UIRuntimeScopeService,
+} from '../../../../services/runtime-scope/ui-runtime-scope.service';
+import { MobileContextMenu, resolveMobileCaretMenuPlacement, shouldUseFloatingMobileContextMenu } from '../MobileContextMenu';
+
+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('MobileContextMenu', () => {
+ it.each([false, true])('closes and blocks the mobile menu during host suspension (caret anchor: %s)', (caretAnchor) => {
+ const injector = createInjector();
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: { ...enUS, test: { action: 'Insert row' } } });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.get(ILayoutService).registerRootContainerElement(document.body);
+ injector.get(IMenuManagerService).appendRootMenu({
+ test: {
+ action: {
+ menuItemFactory: () => ({ id: 'insert-row', type: MenuItemType.BUTTON, title: 'test.action' }),
+ },
+ },
+ });
+ const contextMenu = injector.get(IContextMenuService);
+ const host = injector.get(IContextMenuHostService);
+ render(
+ <RediContext.Provider value={{ injector }}>
+ <ConfigProvider mountContainer={document.body}>
+ <MobileContextMenu />
+ </ConfigProvider>
+ </RediContext.Provider>
+ );
+ const open = () => contextMenu.triggerContextMenu(
+ { clientX: 50, clientY: 100, stopPropagation() {} },
+ 'test',
+ { caretAnchor }
+ );
+ act(open);
+ expect(screen.getByRole(caretAnchor ? 'menuitem' : 'button', { name: 'Insert row' })).toBeTruthy();
+ let suspension: ReturnType<IContextMenuHostService['suspend']>;
+ act(() => {
+ suspension = host.suspend();
+ });
+ expect(screen.queryByRole(caretAnchor ? 'menuitem' : 'button', { name: 'Insert row' })).toBeNull();
+ act(open);
+ expect(screen.queryByRole(caretAnchor ? 'menuitem' : 'button', { name: 'Insert row' })).toBeNull();
+ act(() => suspension.dispose());
+ act(open);
+ expect(screen.getByRole(caretAnchor ? 'menuitem' : 'button', { name: 'Insert row' })).toBeTruthy();
+ });
+
+ it('uses a floating menu only for an explicit caret anchor', () => {
+ expect(shouldUseFloatingMobileContextMenu(ContextMenuPosition.MAIN_AREA)).toBe(false);
+ expect(shouldUseFloatingMobileContextMenu(ContextMenuPosition.MAIN_AREA, { unitId: 'sheet-1' })).toBe(false);
+ expect(shouldUseFloatingMobileContextMenu(ContextMenuPosition.MAIN_AREA, {
+ unitId: 'doc-1',
+ caretAnchor: true,
+ })).toBe(true);
+ });
+
+ it('keeps the pointer aligned with the caret when the compact menu reaches viewport edges', () => {
+ expect(resolveMobileCaretMenuPlacement(200, 12, 400, 180)).toEqual({
+ menuLeft: 98,
+ pointerLeft: 86,
+ });
+ expect(resolveMobileCaretMenuPlacement(8, 12, 400, 180)).toEqual({
+ menuLeft: 0,
+ pointerLeft: 12,
+ });
+ expect(resolveMobileCaretMenuPlacement(420, 12, 400, 180)).toEqual({
+ menuLeft: 220,
+ pointerLeft: 160,
+ });
+ });
+});
diff --git a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
index 4411d1f736..aca67bbe9e 100644
--- a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
+++ b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
@@ -15,12 +15,16 @@
*/
import type { ReactElement } from 'react';
-import type { IDialogPartMethodOptions } from '../interface';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { DesktopLogService, ILogService, Injector, LocaleService, LocaleType } from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IDialogPartMethodOptions } from '../interface';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
+import {
+ ContextMenuHostService,
+ IContextMenuHostService,
+} from '../../../../services/contextmenu/contextmenu-host.service';
import { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../../services/dialog/dialog.service';
import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
@@ -32,6 +36,7 @@ import { DialogPart } from '../DialogPart';
function renderWithDependencies(element: ReactElement) {
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([LocaleService]);
diff --git a/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
index fe18e28dda..8ea67417ad 100644
--- a/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
+++ b/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
@@ -26,6 +26,10 @@ import type { IMobileDialogPartMethodOptions } from '../MobileDialogPart';
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 { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../../services/dialog/dialog.service';
import { MobileDialogService } from '../../../../services/dialog/mobile-dialog.service';
@@ -40,6 +44,7 @@ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: tr
function renderWithDependencies(element: ReactElement, mobileService = false, keyboardVisible = false) {
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: mobileService ? MobileDialogService : DesktopDialogService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([LocaleService]);
diff --git a/packages/ui/src/views/components/ribbon/MobileRibbon.tsx b/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
index 22a58b5953..134df1caff 100644
--- a/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
+++ b/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
@@ -33,6 +33,7 @@ import { RibbonPosition, RibbonStartGroup } from '../../../services/menu/types';
import { IRibbonService } from '../../../services/ribbon/ribbon.service';
import { IWorkbenchService } from '../../../services/workbench/workbench.service';
import { useDependency, useObservable } from '../../../utils/di';
+import { useMenuHost } from '../../../utils/use-menu-host';
import { ComponentContainer } from '../ComponentContainer';
import { MobileToolbarItem } from './MobileToolbarItem';
@@ -395,6 +396,7 @@ function MobileCompactTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[]
const { headerMenuComponents, headerMenu = true, ribbon } = props;
const [moreOpen, setMoreOpen] = useState(false);
const moreTriggerRef = useRef<HTMLButtonElement>(null);
+ const menuHost = useMenuHost(() => setMoreOpen(false));
const { mountContainer } = useContext(ConfigContext);
const localeService = useDependency(LocaleService);
const startGroup = ribbon.find((group) => group.key === RibbonPosition.START);
@@ -443,7 +445,6 @@ function MobileCompactTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[]
[&_button]:!univer-w-full [&_button]:!univer-justify-start [&_button]:!univer-gap-3
[&_button]:!univer-rounded-xl [&_button]:!univer-px-4
"
- onClick={() => setMoreOpen(false)}
>
<MobileToolbarItem {...schema.item!} grid showLabel preserveStrokeWidth />
</div>
@@ -491,7 +492,9 @@ function MobileCompactTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[]
dark:!univer-text-gray-200
dark:active:!univer-bg-gray-700
`)}
- onClick={() => setMoreOpen((open) => !open)}
+ onClick={() => {
+ if (!menuHost.suspended) setMoreOpen((open) => !open);
+ }}
>
<MoreHorizontalIcon className="univer-size-5" preserveStrokeWidth />
</button>
diff --git a/packages/ui/src/views/components/ribbon/Ribbon.tsx b/packages/ui/src/views/components/ribbon/Ribbon.tsx
index 49077ec8a8..9950777ccd 100644
--- a/packages/ui/src/views/components/ribbon/Ribbon.tsx
+++ b/packages/ui/src/views/components/ribbon/Ribbon.tsx
@@ -157,6 +157,7 @@ export function Ribbon(props: IRibbonProps) {
className={clsx(`
univer-invisible univer-absolute -univer-left-[99999] -univer-top-[99999] univer-box-border
univer-flex univer-h-10 univer-min-w-min univer-items-center univer-px-3 univer-opacity-0
+ rtl:univer-divide-x-reverse
`, {
'univer-hidden': !fakeToolbarVisible,
}, divideXClassName, borderBottomClassName)}
@@ -320,7 +321,10 @@ export function Ribbon(props: IRibbonProps) {
<div
data-u-comp="ribbon-toolbar"
ref={containerRef}
- className={clsx('univer-flex univer-overflow-hidden', divideXClassName, {
+ className={clsx(`
+ univer-flex univer-overflow-hidden
+ rtl:univer-divide-x-reverse
+ `, divideXClassName, {
'univer-justify-center': ribbonType === 'classic',
})}
role="toolbar"
@@ -353,7 +357,7 @@ export function Ribbon(props: IRibbonProps) {
<div
className={`
univer-pl-2
- rtl:univer-pr-2
+ rtl:univer-pl-0 rtl:univer-pr-2
`}
>
<RibbonOverflow groups={activeGroup.hiddenGroups} />
diff --git a/packages/ui/src/views/components/ribbon/RibbonOverflow.tsx b/packages/ui/src/views/components/ribbon/RibbonOverflow.tsx
index 87cab7e146..bc4513e124 100644
--- a/packages/ui/src/views/components/ribbon/RibbonOverflow.tsx
+++ b/packages/ui/src/views/components/ribbon/RibbonOverflow.tsx
@@ -17,11 +17,10 @@
import { LocaleService } from '@univerjs/core';
import { borderTopClassName, clsx, ConfigContext, Dropdown } from '@univerjs/design';
import { MoreDownIcon, MoreHorizontalIcon, MoreVerticalIcon } from '@univerjs/icons';
-import { useContext, useEffect, useRef, useState } from 'react';
+import { useContext, useRef, useState } from 'react';
import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
-import { IDialogService } from '../../../services/dialog/dialog.service';
-import { ISidebarService } from '../../../services/sidebar/sidebar.service';
import { useDependency } from '../../../utils/di';
+import { useMenuHost } from '../../../utils/use-menu-host';
import { groupRibbonOverflowItems } from './ribbon-grid-layout';
import { toolbarButtonClassName } from './ToolbarButton';
import { ToolbarItem } from './ToolbarItem';
@@ -34,8 +33,6 @@ interface IRibbonOverflowProps {
export function RibbonOverflow({ groups, grid = false }: IRibbonOverflowProps) {
const localeService = useDependency(LocaleService);
- const dialogService = useDependency(IDialogService);
- const sidebarService = useDependency(ISidebarService);
const { direction } = useContext(ConfigContext);
const [openedGroups, setOpenedGroups] = useState<IMenuSchema[] | null>(null);
const open = openedGroups === groups;
@@ -43,28 +40,16 @@ export function RibbonOverflow({ groups, grid = false }: IRibbonOverflowProps) {
const restoreFocusRef = useRef(true);
const label = localeService.t('ui.ribbon.more');
- useEffect(() => {
- if (!open) return;
- const closeForPanel = () => {
- restoreFocusRef.current = false;
- setOpenedGroups(null);
- };
- const sidebar = sidebarService.sidebarOptions$.subscribe((options) => {
- if (options.visible) closeForPanel();
- });
- const dialogs = dialogService.getDialogs$().subscribe((options) => {
- if (options.some((dialog) => dialog.open)) closeForPanel();
- });
- return () => {
- sidebar.unsubscribe();
- dialogs.unsubscribe();
- };
- }, [open, dialogService, sidebarService]);
+ const menuHost = useMenuHost(() => {
+ restoreFocusRef.current = false;
+ setOpenedGroups(null);
+ });
return (
<Dropdown
open={open}
onOpenChange={(visible) => {
+ if (visible && menuHost.suspended) return;
if (visible) restoreFocusRef.current = true;
setOpenedGroups(visible ? groups : null);
}}
diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
index 3f58a164e3..6562871175 100644
--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
@@ -39,11 +39,13 @@ import {
} from 'react';
import { combineLatest, map, merge, of, scan, startWith, switchMap } from 'rxjs';
import type { IMenuItem, IValueOption } from '../../../services/menu/menu';
+import { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { ILayoutService } from '../../../services/layout/layout.service';
import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
import { IShortcutService } from '../../../services/shortcut/shortcut.service';
import { useDependency, useObservable } from '../../../utils/di';
import { getEmbedBoundaryOwner, keepInteractionInsideSameEmbedBoundary } from '../../../utils/embed-boundary';
+import { useMenuHost } from '../../../utils/use-menu-host';
import { CustomLabel } from '../../custom-label/CustomLabel';
import { FONT_FAMILY_ITEM_COMPONENT } from '../../font-family/FontFamilyItem';
@@ -128,8 +130,22 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { d
? toolbarDropdownContext.openDropdownKey === dropdownKey
: localDropdownVisible;
+ const menuHost = useMenuHost(() => {
+ if (dropdownVisible) {
+ triggerFocusRef.current = null;
+ if (dropdownKey && toolbarDropdownContext) {
+ toolbarDropdownContext.setOpenDropdownKey(null);
+ } else {
+ setLocalDropdownVisible(false);
+ }
+ }
+ });
+ const openRevisionRef = useRef(menuHost.revision);
+
const handleChangeDropdownVisible = useCallback((visible: boolean) => {
if (visible) {
+ if (menuHost.suspended) return;
+ openRevisionRef.current = menuHost.revision;
const active = spanRef.current?.ownerDocument.activeElement;
triggerFocusRef.current = active instanceof HTMLElement && spanRef.current?.contains(active) ? active : null;
}
@@ -138,9 +154,13 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { d
} else {
setLocalDropdownVisible(visible);
}
- }, [dropdownKey, toolbarDropdownContext]);
+ }, [dropdownKey, toolbarDropdownContext, menuHost]);
const restoreTriggerFocus = useCallback((event: Event) => {
+ if (openRevisionRef.current !== menuHost.revision || menuHost.suspended) {
+ event.preventDefault();
+ return;
+ }
const trigger = triggerFocusRef.current;
triggerFocusRef.current = null;
if (!trigger?.isConnected) return;
@@ -149,7 +169,7 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { d
event.preventDefault();
trigger.focus({ preventScroll: true });
}
- }, []);
+ }, [menuHost]);
const contextValue = useMemo(() => ({
dropdownVisible,
@@ -313,6 +333,8 @@ export function DropdownMenuWrapper({
dropdownMenuComponent?: ComponentType<IDropdownMenuProps>;
}) {
const { dropdownVisible, setDropdownVisible, restoreTriggerFocus } = useContext(TooltipWrapperContext);
+ const menuHost = useDependency(IContextMenuHostService);
+ const openRevisionRef = useRef(menuHost.revision);
const shortcutService = useDependency(IShortcutService);
const contextService = useDependency(IContextService);
const instanceService = useDependency(IUniverInstanceService);
@@ -404,6 +426,8 @@ export function DropdownMenuWrapper({
function handleVisibleChange(visible: boolean) {
if (visible) {
+ if (menuHost.suspended) return;
+ openRevisionRef.current = menuHost.revision;
const element = document.activeElement;
const workbook = contextService.getContextValue(FOCUSING_SHEET)
? instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)
@@ -424,6 +448,10 @@ export function DropdownMenuWrapper({
function handleCloseAutoFocus(event: Event) {
const editorFocus = editorFocusRef.current;
editorFocusRef.current = null;
+ if (openRevisionRef.current !== menuHost.revision || menuHost.suspended) {
+ event.preventDefault();
+ return;
+ }
if (sheetTargetRef.current && !sheetTargetRef.current.valid) {
event.preventDefault();
const activeElement = document.activeElement;
diff --git a/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx
index 9af5ad11a4..8049564e33 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx
@@ -19,43 +19,29 @@
*/
import { act, cleanup, render } from '@testing-library/react';
-import { Injector, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { Injector, LocaleService, LocaleType, UniverInstanceType } from '@univerjs/core';
import { connectInjector } from '@wendellhu/redi/react-bindings';
import { BehaviorSubject, of } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
+import enUS from '../../../../locale/en-US';
+import { ContextMenuHostService, IContextMenuHostService } from '../../../../services/contextmenu/contextmenu-host.service';
import { IRibbonService } from '../../../../services/ribbon/ribbon.service';
import { IWorkbenchService } from '../../../../services/workbench/workbench.service';
import { MobileRibbon } from '../MobileRibbon';
-describe('MobileRibbon', () => {
- afterEach(cleanup);
+const injectors: Injector[] = [];
- it('keeps a stable hook order when the sheet workbench becomes ready', () => {
- const rootUnitType$ = new BehaviorSubject<UniverInstanceType | null>(null);
- const injector = new Injector([
- [LocaleService, { useValue: { t: (key: string) => key } }],
- [IRibbonService, {
- useValue: {
- ribbon$: of([]),
- activatedTab$: of(''),
- setActivatedTab: () => {},
- },
- }],
- [IWorkbenchService, { useValue: { rootUnitType$ } }],
- ]);
- const ConnectedMobileRibbon = connectInjector(MobileRibbon, injector);
-
- render(<ConnectedMobileRibbon />);
-
- expect(() => {
- act(() => rootUnitType$.next(UniverInstanceType.UNIVER_SHEET));
- }).not.toThrow();
+describe('MobileRibbon', () => {
+ afterEach(() => {
+ cleanup();
+ injectors.splice(0).forEach((injector) => injector.dispose());
});
- it('keeps a stable hook order when the docs workbench becomes ready', () => {
+ it.each([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC])('keeps a stable hook order when workbench %s becomes ready', (unitType) => {
const rootUnitType$ = new BehaviorSubject<UniverInstanceType | null>(null);
const injector = new Injector([
- [LocaleService, { useValue: { t: (key: string) => key } }],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
+ [LocaleService],
[IRibbonService, {
useValue: {
ribbon$: of([]),
@@ -65,12 +51,17 @@ describe('MobileRibbon', () => {
}],
[IWorkbenchService, { useValue: { rootUnitType$ } }],
]);
+ injectors.push(injector);
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
const ConnectedMobileRibbon = connectInjector(MobileRibbon, injector);
render(<ConnectedMobileRibbon />);
expect(() => {
- act(() => rootUnitType$.next(UniverInstanceType.UNIVER_DOC));
+ act(() => rootUnitType$.next(unitType));
}).not.toThrow();
});
});
diff --git a/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx
index 497563d411..a5e8d99c3c 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx
@@ -27,14 +27,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
-import { IDialogService } from '../../../../services/dialog/dialog.service';
+import { ContextMenuHostService, IContextMenuHostService } from '../../../../services/contextmenu/contextmenu-host.service';
import { ILayoutService } from '../../../../services/layout/layout.service';
import { MenuItemType } from '../../../../services/menu/menu';
import { RibbonPosition } from '../../../../services/menu/types';
import { IRibbonOverrideService } from '../../../../services/ribbon/ribbon-override.service';
import { IRibbonService } from '../../../../services/ribbon/ribbon.service';
import { IShortcutService } from '../../../../services/shortcut/shortcut.service';
-import { ISidebarService } from '../../../../services/sidebar/sidebar.service';
import { Ribbon } from '../Ribbon';
describe('Ribbon override chrome', () => {
@@ -59,9 +58,8 @@ describe('Ribbon override chrome', () => {
it('renders a title-only placeholder without the empty toolbar row', () => {
const injector = new Injector([
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ComponentManager],
- [IDialogService, { useValue: { getDialogs$: () => new Subject() } }],
- [ISidebarService, { useValue: { sidebarOptions$: new Subject() } }],
[LocaleService, { useValue: { t: (key: string) => key } }],
[IRibbonService, { useValue: createEmptyRibbonService() }],
[IRibbonOverrideService, {
@@ -100,9 +98,8 @@ describe('Ribbon override chrome', () => {
children: [],
}];
const injector = new Injector([
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ComponentManager],
- [IDialogService, { useValue: { getDialogs$: () => new Subject() } }],
- [ISidebarService, { useValue: { sidebarOptions$: new Subject() } }],
[LocaleService, { useValue: { t: (key: string) => key } }],
[IRibbonService, { useValue: createRibbonService(ribbon, RibbonPosition.INSERT) }],
[IRibbonOverrideService, {
@@ -190,9 +187,8 @@ describe('Ribbon override chrome', () => {
setFakeToolbarVisible: (visible: boolean) => fakeToolbarVisible$.next(visible),
};
const injector = new Injector([
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ComponentManager],
- [IDialogService, { useValue: { getDialogs$: () => new Subject() } }],
- [ISidebarService, { useValue: { sidebarOptions$: new Subject() } }],
[IconManager, { useValue: { get: () => null } }],
[ICommandService, { useValue: { executeCommand: () => {} } }],
[ILayoutService, { useValue: { focus: () => {} } }],
diff --git a/packages/ui/src/views/components/ribbon/__tests__/RibbonGrid.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/RibbonGrid.spec.tsx
index e4b00a680a..245bf107b9 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/RibbonGrid.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/RibbonGrid.spec.tsx
@@ -26,11 +26,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
-import { IDialogService } from '../../../../services/dialog/dialog.service';
+import { ContextMenuHostService, IContextMenuHostService } from '../../../../services/contextmenu/contextmenu-host.service';
import { ILayoutService } from '../../../../services/layout/layout.service';
import { MenuItemType } from '../../../../services/menu/menu';
import { IShortcutService } from '../../../../services/shortcut/shortcut.service';
-import { ISidebarService } from '../../../../services/sidebar/sidebar.service';
import { connectInjector } from '../../../../utils/di';
import { RibbonGrid } from '../RibbonGrid';
@@ -42,14 +41,13 @@ let compactWidths: Record<string, number> = {};
function mountGrid(groups: IMenuSchema[]) {
const injector = new Injector([
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ComponentManager],
[IconManager, { useValue: { get: () => null } }],
[LocaleService, { useValue: { t: (key: string) => key } }],
[ICommandService, { useValue: { executeCommand: async () => true } }],
[ILayoutService, { useValue: { focus: () => {} } }],
[IShortcutService, { useValue: { shortcutChanged$: new Subject(), getShortcutDisplayOfCommand: () => null } }],
- [IDialogService, { useValue: { getDialogs$: () => new Subject() } }],
- [ISidebarService, { useValue: { sidebarOptions$: new Subject() } }],
]);
injectors.push(injector);
const ConnectedGrid = connectInjector(RibbonGrid, injector) as ComponentType<{ groups: IMenuSchema[]; title: string }>;
diff --git a/packages/ui/src/views/components/ribbon/__tests__/RibbonOverflow.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/RibbonOverflow.spec.tsx
index b5d54518e6..44b6cd991f 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/RibbonOverflow.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/RibbonOverflow.spec.tsx
@@ -20,17 +20,22 @@
import type { ComponentType } from 'react';
import { act, cleanup, fireEvent, render, waitFor, within } from '@testing-library/react';
-import { ContextService, ICommandService, IContextService, ILogService, Injector, IUniverInstanceService, LocaleService, UniverInstanceService } from '@univerjs/core';
+import { ContextService, ICommandService, IContextService, ILogService, Injector, IUniverInstanceService, LocaleService, LocaleType, UniverInstanceService } from '@univerjs/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';
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 { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../../services/dialog/dialog.service';
import { ILayoutService } from '../../../../services/layout/layout.service';
import { MenuItemType } from '../../../../services/menu/menu';
import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';
+import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
import { IShortcutService } from '../../../../services/shortcut/shortcut.service';
+import { DesktopSidebarService } from '../../../../services/sidebar/desktop-sidebar.service';
import { ISidebarService } from '../../../../services/sidebar/sidebar.service';
import { connectInjector } from '../../../../utils/di';
import { RibbonOverflow } from '../RibbonOverflow';
@@ -38,13 +43,12 @@ import { RibbonOverflow } from '../RibbonOverflow';
const injectors: Injector[] = [];
function mountOverflow(groups: IMenuSchema[]) {
- const sidebarOptions$ = new Subject<{ visible: boolean }>();
- const dialogs$ = new Subject<Array<{ id: string; open: boolean }>>();
const executeCommand = vi.fn(async () => true);
const injector = new Injector([
[ComponentManager],
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[IconManager, { useValue: { get: () => null } }],
- [LocaleService, { useValue: { t: (key: string) => key } }],
+ [LocaleService],
[ICommandService, { useValue: { executeCommand } }],
[ILayoutService, { useValue: { focus: () => document.getElementById('editor')?.focus() } }],
[IContextService, { useClass: ContextService }],
@@ -52,10 +56,15 @@ function mountOverflow(groups: IMenuSchema[]) {
[IUniverInstanceService, { useClass: UniverInstanceService }],
[IMenuManagerService, { useValue: { menuChanged$: new Subject(), getMenuByPositionKey: () => [] } }],
[IShortcutService, { useValue: { shortcutChanged$: new Subject(), getShortcutDisplayOfCommand: () => null, forceEscape: () => ({ dispose: () => {} }) } }],
- [IDialogService, { useValue: { getDialogs$: () => dialogs$ } }],
- [ISidebarService, { useValue: { sidebarOptions$ } }],
+ [IDialogService, { useClass: DesktopDialogService }],
+ [ISidebarService, { useClass: DesktopSidebarService }],
+ [IUIPartsService, { useClass: UIPartsService }],
]);
injectors.push(injector);
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
injector.get(ComponentManager).register('FontField', () => <input aria-label="Font" defaultValue="Arial" />);
const ConnectedOverflow = connectInjector(RibbonOverflow, injector) as ComponentType<{ groups: IMenuSchema[]; grid?: boolean }>;
return { ...render(
@@ -63,7 +72,7 @@ function mountOverflow(groups: IMenuSchema[]) {
<input id="editor" aria-label="Editor" />
<ConnectedOverflow groups={groups} grid />
</>
- ), executeCommand, sidebarOptions$, dialogs$, ConnectedOverflow };
+ ), injector, executeCommand, ConnectedOverflow };
}
function createGroups(disabled$ = new BehaviorSubject(false)): IMenuSchema[] {
@@ -85,29 +94,47 @@ afterEach(() => {
});
describe('RibbonOverflow', () => {
+ it('closes More when an independent viewer takes over and keeps it closed until exit', async () => {
+ const groups: IMenuSchema[] = [{ key: 'tools', order: 0, children: [{
+ key: 'history',
+ order: 0,
+ item: { id: 'history', type: MenuItemType.BUTTON, title: 'History' },
+ }] }];
+ const { injector, getByRole, queryByRole, executeCommand } = mountOverflow(groups);
+ const menuHost = injector.get(IContextMenuHostService);
+ let viewer: ReturnType<IContextMenuHostService['suspend']> | undefined;
+ executeCommand.mockImplementationOnce(async () => {
+ viewer = menuHost.suspend();
+ return true;
+ });
+ fireEvent.click(getByRole('button', { name: 'More' }));
+ fireEvent.click(getByRole('button', { name: 'History' }));
+ await waitFor(() => expect(queryByRole('dialog', { name: 'More' })).toBeNull());
+ fireEvent.click(getByRole('button', { name: 'More' }));
+ expect(queryByRole('dialog', { name: 'More' })).toBeNull();
+ act(() => viewer?.dispose());
+ fireEvent.click(getByRole('button', { name: 'More' }));
+ expect(getByRole('button', { name: 'History' })).toBeTruthy();
+ });
+
it('keeps formatting available after editor focus and respects live disabled state', () => {
const disabled$ = new BehaviorSubject(false);
const { getByRole, executeCommand } = mountOverflow(createGroups(disabled$));
- fireEvent.click(getByRole('button', { name: 'ui.ribbon.more' }));
+ fireEvent.click(getByRole('button', { name: 'More' }));
+ fireEvent.change(getByRole('textbox', { name: 'Font' }), { target: { value: 'Courier New' } });
fireEvent.click(getByRole('button', { name: 'Bold' }));
+ expect((getByRole('textbox', { name: 'Font' }) as HTMLInputElement).value).toBe('Courier New');
expect(executeCommand).toHaveBeenCalledWith('bold', undefined);
expect(document.activeElement).toBe(getByRole('textbox', { name: 'Editor' }));
- expect(getByRole('dialog', { name: 'ui.ribbon.more' })).toBeTruthy();
+ expect(getByRole('dialog', { name: 'More' })).toBeTruthy();
act(() => disabled$.next(true));
fireEvent.click(getByRole('button', { name: 'Bold' }));
expect(executeCommand).toHaveBeenCalledTimes(1);
});
- it('preserves custom controls without duplicating their label', () => {
- const { getByRole, queryByText } = mountOverflow(createGroups());
- fireEvent.click(getByRole('button', { name: 'ui.ribbon.more' }));
- expect(getByRole('textbox', { name: 'Font' }).getAttribute('value')).toBe('Arial');
- expect(queryByText('Font family')).toBeNull();
- });
-
it('closes nested selectors before More and returns keyboard focus to their triggers', async () => {
const { getByRole, queryByRole } = mountOverflow(createGroups());
- const more = getByRole('button', { name: 'ui.ribbon.more' });
+ const more = getByRole('button', { name: 'More' });
more.focus();
fireEvent.keyDown(more, { key: 'Enter' });
fireEvent.click(more);
@@ -118,28 +145,41 @@ describe('RibbonOverflow', () => {
fireEvent.keyDown(getByRole('menu'), { key: 'Escape' });
await waitFor(() => expect(queryByRole('menu')).toBeNull());
await waitFor(() => expect(document.activeElement).toBe(alignment));
- expect(getByRole('dialog', { name: 'ui.ribbon.more' })).toBeTruthy();
+ expect(getByRole('dialog', { name: 'More' })).toBeTruthy();
fireEvent.keyDown(alignment, { key: 'Escape' });
await waitFor(() => expect(queryByRole('dialog')).toBeNull());
await waitFor(() => expect(document.activeElement).toBe(more));
});
it.each(['sidebar', 'dialog'] as const)('closes when an independent %s opens', async (surface) => {
- const { getByRole, queryByRole, sidebarOptions$, dialogs$ } = mountOverflow(createGroups());
- fireEvent.click(getByRole('button', { name: 'ui.ribbon.more' }));
+ const { getByRole, queryByRole, injector } = mountOverflow(createGroups());
+ fireEvent.click(getByRole('button', { name: 'More' }));
act(() => {
- if (surface === 'sidebar') sidebarOptions$.next({ visible: true });
- else dialogs$.next([{ id: 'format', open: true }]);
+ if (surface === 'sidebar') {
+ injector.get(ISidebarService).open({ id: 'format' });
+ } else {
+ injector.get(IDialogService).open({ id: 'format' });
+ }
});
await waitFor(() => expect(queryByRole('dialog')).toBeNull());
+ fireEvent.click(getByRole('button', { name: 'More' }));
+ act(() => {
+ if (surface === 'sidebar') {
+ injector.get(ISidebarService).close();
+ } else {
+ injector.get(IDialogService).open({ id: 'format', width: 500 });
+ injector.get(IDialogService).close('format');
+ }
+ });
+ expect(getByRole('dialog', { name: 'More' })).toBeTruthy();
});
it('replaces an open menu when its groups change', () => {
const { getByRole, queryByRole, rerender, ConnectedOverflow } = mountOverflow(createGroups());
- fireEvent.click(getByRole('button', { name: 'ui.ribbon.more' }));
+ fireEvent.click(getByRole('button', { name: 'More' }));
rerender(<ConnectedOverflow groups={[{ key: 'new', order: 0, title: 'New group', children: [{ key: 'new-action', order: 0, item: { id: 'new-action', type: MenuItemType.BUTTON, title: 'New action' } }] }]} />);
expect(queryByRole('dialog')).toBeNull();
- fireEvent.click(getByRole('button', { name: 'ui.ribbon.more' }));
+ fireEvent.click(getByRole('button', { name: 'More' }));
const popup = getByRole('dialog');
expect(within(popup).queryByRole('button', { name: 'Bold' })).toBeNull();
expect(within(popup).getByRole('button', { name: 'New action' })).toBeTruthy();
diff --git a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
index a8ec2086af..65206b998e 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
@@ -31,6 +31,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import type { IIconProps } from '../../../../common/icon-manager';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
+import { ContextMenuHostService, IContextMenuHostService } from '../../../../services/contextmenu/contextmenu-host.service';
import { ILayoutService } from '../../../../services/layout/layout.service';
import { MenuItemType } from '../../../../services/menu/menu';
import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';
@@ -77,7 +78,7 @@ class TestLogService {
const testInjectors: Injector[] = [];
function renderWithDependencies(element: ReactElement) {
- const injector = new Injector();
+ const injector = new Injector([[IContextMenuHostService, { useClass: ContextMenuHostService }]]);
testInjectors.push(injector);
injector.add([LocaleService, { useClass: TestLocaleService as never }]);
injector.add([ICommandService, { useClass: TestCommandService as never }]);
diff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
index ac3b18e2d3..232e4e8f72 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
@@ -42,9 +42,10 @@ import { useState } from 'react';
import { afterEach, describe, expect, it, vi } 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 { FontService, IFontService } from '../../../../services/font.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 { IPlatformService, PlatformService } from '../../../../services/platform/platform.service';
import { IUIRuntimeScopeService, UIRuntimeScopeService } from '../../../../services/runtime-scope/ui-runtime-scope.service';
@@ -75,11 +76,8 @@ function NestedDialogDropdown() {
);
}
-function renderWithDependencies(
- element: ReactElement,
- menuItems: ReturnType<IMenuManagerService['getMenuByPositionKey']> = []
-) {
- const injector = new Injector();
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector([[IContextMenuHostService, { useClass: ContextMenuHostService }]]);
testInjectors.push(injector);
injector.add([LocaleService]);
injector.add([ILogService, { useClass: DesktopLogService }]);
@@ -95,15 +93,9 @@ function renderWithDependencies(
injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);
injector.add([IShortcutService, { useClass: ShortcutService }]);
const localeService = injector.get(LocaleService);
- localeService.load({ [LocaleType.EN_US]: { Reset: 'Reset' } });
+ localeService.load({ [LocaleType.EN_US]: enUS });
localeService.setLocale(LocaleType.EN_US);
localeService.setDirection('ltr');
- injector.get(IMenuManagerService).appendRootMenu({
- 'test-menu': Object.fromEntries(menuItems.map((item) => [item.key, {
- order: item.order,
- menuItemFactory: () => item.item!,
- }])),
- });
const forceEscape = vi.spyOn(injector.get(IShortcutService), 'forceEscape');
injector.get(ComponentManager).register('TestDynamicOption', ({ onChange }: { onChange: (value: string) => void }) => (
<button type="button" onClick={() => onChange('dynamic-value')}>Choose dynamic value</button>
@@ -136,7 +128,6 @@ describe('ToolbarTooltip', () => {
fireEvent.mouseEnter(trigger);
const tooltip = getByRole('tooltip');
expect(tooltip.textContent).toBe('Fill');
- expect(tooltip.classList.contains('univer-pointer-events-none')).toBe(true);
rerender(renderTooltip(true));
expect(queryByRole('tooltip')).toBeNull();
@@ -233,7 +224,7 @@ describe('DropdownMenuLabel', () => {
describe('DropdownWrapper', () => {
it('keeps an enabled dropdown open when a sibling is disabled', () => {
- const { getByRole, queryByText } = render(
+ const { getByRole, queryByText } = renderWithDependencies(
<ToolbarDropdownProvider>
<TooltipWrapper dropdownKey="disabled-dropdown">
<DropdownWrapper disabled overlay={<div>Disabled content</div>}>
@@ -254,7 +245,7 @@ describe('DropdownWrapper', () => {
});
it('opens toward the left in RTL layouts', async () => {
- const { findByText, getByRole } = render(
+ const { findByText, getByRole } = renderWithDependencies(
<ConfigProvider direction="rtl" mountContainer={document.body}>
<ToolbarDropdownProvider>
<TooltipWrapper dropdownKey="test-dropdown">
@@ -273,7 +264,7 @@ describe('DropdownWrapper', () => {
});
it('closes on an outside pointerdown even when no click follows', async () => {
- const { findByText, getByRole, queryByText } = render(
+ const { findByText, getByRole, queryByText } = renderWithDependencies(
<ToolbarDropdownProvider>
<TooltipWrapper dropdownKey="test-dropdown">
<DropdownWrapper overlay={<div>Dropdown content</div>}>
@@ -291,7 +282,7 @@ describe('DropdownWrapper', () => {
});
it('keeps the toolbar dropdown open when interacting with a nested portaled dropdown', () => {
- const { getByRole } = render(
+ const { getByRole } = renderWithDependencies(
<ConfigProvider mountContainer={document.body}>
<ToolbarDropdownProvider>
<TooltipWrapper dropdownKey="border-dropdown">
@@ -451,7 +442,7 @@ describe('DropdownMenuWrapper', () => {
}
);
- it('renders a single embedded custom panel flush with the dropdown edge', async () => {
+ it('releases shortcut Escape handling when a custom option closes the menu', async () => {
const { findByRole, forceEscape, getByRole } = renderWithDependencies(
<ToolbarDropdownProvider>
<TooltipWrapper dropdownKey="test-custom-panel">
@@ -475,11 +466,7 @@ describe('DropdownMenuWrapper', () => {
fireEvent.pointerDown(getByRole('button', { name: 'Open custom panel' }), { button: 0, ctrlKey: false });
const option = await findByRole('button', { name: 'Choose dynamic value' });
- const menuItem = option.closest('[data-slot="dropdown-menu-item"]');
- const menuContent = option.closest('[data-slot="dropdown-menu-content"]');
- expect(menuItem?.className).toContain('!univer-p-0');
- expect(menuContent?.className).toContain('!univer-p-0');
expect(forceEscape).toHaveBeenCalledOnce();
const disposeShortcutEscape = vi.spyOn(forceEscape.mock.results[0].value, 'dispose');
@@ -487,7 +474,7 @@ describe('DropdownMenuWrapper', () => {
await waitFor(() => expect(disposeShortcutEscape).toHaveBeenCalledOnce());
});
- it('uses only the shared menu padding around the font list and selects its font value', async () => {
+ it('selects a font and closes the font list', async () => {
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
const onOptionSelect = vi.fn();
const { findByRole, getByRole, queryByRole, injector } = renderWithDependencies(
@@ -514,81 +501,9 @@ describe('DropdownMenuWrapper', () => {
fireEvent.pointerDown(getByRole('button', { name: 'Open fonts' }), { button: 0, ctrlKey: false });
const option = await findByRole('button', { name: 'Courier New' });
- expect(option.closest('[data-slot="dropdown-menu-item"]')?.className).toContain('!univer-p-0');
- expect(getByRole('menu').className).not.toContain('!univer-p-0');
fireEvent.click(option);
expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({ value: 'Courier New' }));
await waitFor(() => expect(queryByRole('menu')).toBeNull());
});
-
- it('keeps padding around a non-embedded custom panel', async () => {
- const { findByRole, getByRole } = renderWithDependencies(
- <ToolbarDropdownProvider>
- <TooltipWrapper dropdownKey="test-non-embedded-custom-panel">
- <DropdownMenuWrapper
- menuId="test-menu"
- options={[{
- label: {
- name: 'TestDynamicOption',
- hoverable: false,
- selectable: false,
- },
- }]}
- onOptionSelect={vi.fn()}
- >
- <button type="button">Open non-embedded custom panel</button>
- </DropdownMenuWrapper>
- </TooltipWrapper>
- </ToolbarDropdownProvider>
- );
-
- fireEvent.pointerDown(getByRole('button', { name: 'Open non-embedded custom panel' }), { button: 0, ctrlKey: false });
- const option = await findByRole('button', { name: 'Choose dynamic value' });
- const menuItem = option.closest('[data-slot="dropdown-menu-item"]');
- const menuContent = option.closest('[data-slot="dropdown-menu-content"]');
-
- expect(menuItem?.className).not.toContain('!univer-p-0');
- expect(menuContent?.className).not.toContain('!univer-p-0');
- });
-
- it('keeps padding around a custom panel when menu actions follow it', async () => {
- const { findByRole, getByRole } = renderWithDependencies(
- <ToolbarDropdownProvider>
- <TooltipWrapper dropdownKey="test-custom-panel-with-action">
- <DropdownMenuWrapper
- menuId="test-menu"
- options={[{
- label: {
- name: 'TestDynamicOption',
- hoverable: false,
- selectable: false,
- props: { embedded: true },
- },
- }]}
- onOptionSelect={vi.fn()}
- >
- <button type="button">Open custom panel with action</button>
- </DropdownMenuWrapper>
- </TooltipWrapper>
- </ToolbarDropdownProvider>,
- [{
- key: 'reset',
- order: 0,
- item: {
- id: 'reset',
- type: MenuItemType.BUTTON,
- title: 'Reset',
- },
- }]
- );
-
- fireEvent.pointerDown(getByRole('button', { name: 'Open custom panel with action' }), { button: 0, ctrlKey: false });
- const option = await findByRole('button', { name: 'Choose dynamic value' });
- const menuItem = option.closest('[data-slot="dropdown-menu-item"]');
- const menuContent = option.closest('[data-slot="dropdown-menu-content"]');
-
- expect(menuItem?.className).not.toContain('!univer-p-0');
- expect(menuContent?.className).not.toContain('!univer-p-0');
- });
});
diff --git a/packages/ui/src/views/components/sidebar/__tests__/MobileSidebar.spec.tsx b/packages/ui/src/views/components/sidebar/__tests__/MobileSidebar.spec.tsx
index 1e3061d42b..f9a1e77bcb 100644
--- a/packages/ui/src/views/components/sidebar/__tests__/MobileSidebar.spec.tsx
+++ b/packages/ui/src/views/components/sidebar/__tests__/MobileSidebar.spec.tsx
@@ -20,6 +20,10 @@ 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 { DesktopSidebarService } from '../../../../services/sidebar/desktop-sidebar.service';
import { ISidebarService } from '../../../../services/sidebar/sidebar.service';
import { RediProvider } from '../../../../utils/di';
@@ -37,6 +41,7 @@ describe('MobileSidebar', () => {
it('renders sidebar content in a modal drawer that can be closed', () => {
injector = new Injector([
+ [IContextMenuHostService, { useClass: ContextMenuHostService }],
[ISidebarService, { useClass: DesktopSidebarService }],
[ILogService, { useClass: DesktopLogService }],
[LocaleService],
diff --git a/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx b/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx
index 21a08b8476..6d6a405c88 100644
--- a/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx
+++ b/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx
@@ -21,6 +21,10 @@ 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 { DesktopSidebarService } from '../../../../services/sidebar/desktop-sidebar.service';
import { ISidebarService } from '../../../../services/sidebar/sidebar.service';
import { RediProvider } from '../../../../utils/di';
@@ -30,6 +34,7 @@ import { Sidebar } from '../Sidebar';
function renderWithDependencies(element: ReactElement) {
const injector = new Injector();
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([LocaleService]);
diff --git a/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsx b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsx
index 218805253f..82fb0e030f 100644
--- a/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsx
+++ b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsx
@@ -43,6 +43,10 @@ import { afterEach, describe, expect, it, vi } 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 { DesktopDialogService } from '../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../services/dialog/dialog.service';
import { IUIPartsService, UIPartsService } from '../../../services/parts/parts.service';
@@ -314,6 +318,7 @@ describe('workbench object permission dialog', () => {
injector.add([ComponentManager]);
injector.add([IconManager]);
injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.get(ComponentManager).register(OBJECT_PERMISSION_DIALOG, ObjectPermissionDialog);
const openDialog = () => {
diff --git a/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsx b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsx
index 2692a15aec..e34aebf535 100644
--- a/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsx
+++ b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsx
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { IObjectPermissionButtonProps } from '../ObjectPermissionButton';
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import {
CommandType,
@@ -31,7 +30,12 @@ import {
} from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
import { afterEach, expect, it, vi } from 'vitest';
+import type { IObjectPermissionButtonProps } from '../ObjectPermissionButton';
import enUS from '../../../locale/en-US';
+import {
+ ContextMenuHostService,
+ IContextMenuHostService,
+} from '../../../services/contextmenu/contextmenu-host.service';
import { DesktopSidebarService } from '../../../services/sidebar/desktop-sidebar.service';
import { ISidebarService } from '../../../services/sidebar/sidebar.service';
import { RediProvider } from '../../../utils/di';
@@ -59,6 +63,7 @@ it('does not enumerate collapsed scopes or rescan them on editing commands, and
const rules = injector.get(TestRuleModel);
injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, [UnitObject.Document, UnitObject.DocumentSection]);
injector.get(ObjectPermissionService).registerRuleModel(UnitObject.Document, rules, 'test.mutation.permission');
+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
let enumerated = 0;
function* getTargets(): Iterable<IObjectPermissionButtonProps> {