Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(ui): support ui menu facade (#4304)

Wenzhao Hu34fc17d5d51d
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 7d04e2d208..fc2e784115 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -41,8 +41,8 @@ import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
import { UniverUIPlugin } from '@univerjs/ui';
-import { enUS, faIR, frFR, ruRU, viVN, zhCN, zhTW } from '../locales';
+import { enUS, faIR, frFR, ruRU, viVN, zhCN, zhTW } from '../locales';
import '@univerjs/sheets/facade';
import '@univerjs/ui/facade';
import '@univerjs/docs-ui/facade';
@@ -54,8 +54,8 @@ import '@univerjs/sheets-formula/facade';
import '@univerjs/sheets-numfmt/facade';
import '@univerjs/sheets-hyper-link-ui/facade';
import '@univerjs/sheets-thread-comment/facade';
-import '@univerjs/sheets-conditional-formatting/facade';
+import '@univerjs/sheets-conditional-formatting/facade';
import '../global.css';
/* eslint-disable-next-line node/prefer-global/process */
diff --git a/packages/ui/src/controllers/menus/menu.schema.ts b/packages/ui/src/controllers/menus/menu.schema.ts
index 15c3d05b16..20c5839ff4 100644
--- a/packages/ui/src/controllers/menus/menu.schema.ts
+++ b/packages/ui/src/controllers/menus/menu.schema.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import { RedoCommand, UndoCommand } from '@univerjs/core';
import type { MenuSchemaType } from '../../services/menu/menu-manager.service';
-import { RibbonStartGroup } from '../../services/menu/types';
+import { RedoCommand, UndoCommand } from '@univerjs/core';
import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';
+import { RibbonStartGroup } from '../../services/menu/types';
import { ShortcutPanelMenuItemFactory } from '../shortcut-display/menu';
import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus';
diff --git a/packages/ui/src/controllers/menus/menus.ts b/packages/ui/src/controllers/menus/menus.ts
index e14ec92222..615ee556e8 100644
--- a/packages/ui/src/controllers/menus/menus.ts
+++ b/packages/ui/src/controllers/menus/menus.ts
@@ -14,11 +14,10 @@
* limitations under the License.
*/
-import { IUndoRedoService, RedoCommand, UndoCommand } from '@univerjs/core';
import type { IAccessor } from '@univerjs/core';
-import { map } from 'rxjs/operators';
-
import type { IMenuButtonItem } from '../../services/menu/menu';
+import { IUndoRedoService, RedoCommand, UndoCommand } from '@univerjs/core';
+import { map } from 'rxjs/operators';
import { MenuItemType } from '../../services/menu/menu';
export function UndoMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
diff --git a/packages/ui/src/facade/f-menu-builder.ts b/packages/ui/src/facade/f-menu-builder.ts
new file mode 100644
index 0000000000..52ff38cc0c
--- /dev/null
+++ b/packages/ui/src/facade/f-menu-builder.ts
@@ -0,0 +1,225 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import type { IMenuButtonItem, IMenuItem, MenuSchemaType } from '@univerjs/ui';
+import { CommandType, FBase, ICommandService, Inject, Injector, Tools } from '@univerjs/core';
+import { IMenuManagerService, MenuItemType, MenuManagerPosition, RibbonPosition, RibbonStartGroup } from '@univerjs/ui';
+
+export interface IFacadeMenuItem {
+ /**
+ * The unique identifier of the menu item.
+ */
+ id: string;
+ /**
+ * Icon of the menu item.
+ */
+ icon?: string;
+ /**
+ * Title of the menu item.
+ */
+ title: string;
+ /**
+ * The tooltip to show when the mouse hovers over the menu item.
+ */
+ tooltip?: string;
+ /**
+ * The command to execute when the menu item is clicked. It can also be a callback function to
+ * execute any custom logic.
+ */
+ action: string | (() => void);
+ /**
+ * The order of the menu item in the submenu.
+ */
+ order?: number;
+}
+
+export interface IFacadeSubmenuItem {
+ /**
+ * The unique identifier of the menu item.
+ */
+ id: string;
+ /**
+ * Icon of the menu item.
+ */
+ icon?: string;
+ /**
+ * Title of the menu item.
+ */
+ title: string;
+ /**
+ * The tooltip to show when the mouse hovers over the menu item.
+ */
+ tooltip?: string;
+ /**
+ * The order of the menu item in the submenu.
+ */
+ order?: number;
+}
+
+type FAllMenu = FMenu | FSubmenu;
+
+/**
+ * This is a build for adding a menu to Univer. Please notice that until the `appendTo` method is called,
+ * the menu item is not added to the UI. Please note that this menu cannot have submenus. If you want to
+ * have submenus, please use `FSubmenu`.
+ */
+export class FMenu extends FBase {
+ static RibbonStartGroup = RibbonStartGroup;
+ static RibbonPosition = RibbonPosition;
+ static MenuManagerPosition = MenuManagerPosition;
+
+ private _commandToRegister = new Map<string, (accessor: IAccessor) => void>();
+ private _buildingSchema: {
+ order?: number;
+ menuItemFactory?: (accessor: IAccessor) => IMenuItem;
+ };
+
+ constructor(
+ private readonly _item: IFacadeMenuItem,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @ICommandService protected readonly _commandService: ICommandService,
+ @IMenuManagerService protected readonly _menuManagerService: IMenuManagerService
+ ) {
+ super();
+
+ const commandId = typeof _item.action === 'string' ? _item.action : Tools.generateRandomId(12);
+ if (commandId !== _item.action) {
+ this._commandToRegister.set(commandId, _item.action as unknown as () => void);
+ }
+
+ this._buildingSchema = {
+ // eslint-disable-next-line ts/explicit-function-return-type
+ menuItemFactory: () => ({
+ id: _item.id,
+ type: MenuItemType.BUTTON, // we only support button for now
+ icon: _item.icon,
+ title: _item.title,
+ tooltip: _item.tooltip,
+ commandId,
+ } as IMenuButtonItem),
+ };
+
+ if (typeof _item.order !== 'undefined') {
+ this._buildingSchema.order = _item.order;
+ }
+ }
+
+ /** @ignore */
+ __getSchema(): { [key: string]: MenuSchemaType } {
+ this._commandToRegister.forEach((command, id) => {
+ if (!this._commandService.hasCommand(id)) {
+ this._commandService.registerCommand({
+ id,
+ type: CommandType.COMMAND,
+ handler: command,
+ });
+ }
+ });
+
+ return { [this._item.id]: this._buildingSchema };
+ }
+
+ /**
+ * Append the menu to any menu position on Univer UI.
+ * @param path Some predefined path to append the menu.
+ */
+ appendTo(path: string): void {
+ const schema = this.__getSchema();
+ this._menuManagerService.mergeMenu({
+ [path]: schema,
+ });
+ }
+}
+
+export class FSubmenu extends FBase {
+ private _menuByGroups: FAllMenu[][] = [];
+ private _submenus: FAllMenu[] = [];
+
+ private _buildingSchema: {
+ order?: number;
+ menuItemFactory?: (accessor: IAccessor) => IMenuItem;
+ };
+
+ constructor(
+ private readonly _item: IFacadeSubmenuItem,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IMenuManagerService protected readonly _menuManagerService: IMenuManagerService
+ ) {
+ super();
+
+ this._buildingSchema = {
+ // eslint-disable-next-line ts/explicit-function-return-type
+ menuItemFactory: () => ({
+ id: _item.id,
+ type: MenuItemType.SUBITEMS,
+ icon: _item.icon,
+ title: _item.title,
+ tooltip: _item.tooltip,
+ }),
+ };
+
+ if (typeof _item.order !== 'undefined') {
+ this._buildingSchema.order = _item.order;
+ }
+ }
+
+ /**
+ * Add a menu to the submenu. It can be a {@link FMenu} or a {@link FSubmenu}.
+ * @param submenu Menu to add to the submenu.
+ * @returns The FSubmenu itself for chaining calls.
+ */
+ addSubmenu(submenu: FMenu | FSubmenu): this {
+ this._submenus.push(submenu);
+ return this;
+ }
+
+ /**
+ * Add a separator to the submenu.
+ * @returns The FSubmenu itself for chaining calls.
+ */
+ addSeparator(): this {
+ this._menuByGroups.push(this._submenus);
+ this._submenus = [];
+ return this;
+ }
+
+ /**
+ * Append the menu to any menu position on Univer UI.
+ * @param path Some predefined path to append the menu.
+ */
+ appendTo(path: string): void {
+ const schema = this.__getSchema();
+ this._menuManagerService.mergeMenu({
+ [path]: schema,
+ });
+ }
+
+ __getSchema(): { [key: string]: MenuSchemaType } {
+ const schema: { [key: string]: MenuSchemaType } = {};
+ this.addSeparator();
+ this._menuByGroups.forEach((group, index) => {
+ const groupSchema: MenuSchemaType = {};
+ group.forEach((menu) => {
+ Object.assign(groupSchema, menu.__getSchema());
+ });
+
+ schema[`${this._item.id}-group-${index}`] = groupSchema;
+ });
+
+ return { [this._item.id]: Object.assign(this._buildingSchema, schema) };
+ }
+}
diff --git a/packages/ui/src/facade/f-univer.ts b/packages/ui/src/facade/f-univer.ts
index 6517b19cfb..293608c1df 100644
--- a/packages/ui/src/facade/f-univer.ts
+++ b/packages/ui/src/facade/f-univer.ts
@@ -17,8 +17,10 @@
import type { IDisposable } from '@univerjs/core';
import type { IMessageOptions } from '@univerjs/design';
import type { IDialogPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';
+import type { IFacadeMenuItem, IFacadeSubmenuItem } from './f-menu-builder';
import { FUniver } from '@univerjs/core';
import { ComponentManager, CopyCommand, IDialogService, IMessageService, ISidebarService, PasteCommand } from '@univerjs/ui';
+import { FMenu, FSubmenu } from './f-menu-builder';
export interface IFUniverUIMixin {
/**
@@ -31,6 +33,42 @@ export interface IFUniverUIMixin {
*/
paste(): Promise<boolean>;
+ /**
+ * Create a menu build object. You can insert new menus into the UI.
+ * @param {IFacadeMenuItem} menuItem the menu item
+ *
+ * @example
+ * ```ts
+ * univerAPI.createMenu({
+ * id: 'custom-menu',
+ * title: 'Custom Menu',
+ * action: () => {},
+ * }).appendTo('ribbon.start.others');
+ * ```
+ *
+ * @returns the {@link FMenu} object
+ */
+ createMenu(menuItem: IFacadeMenuItem): FMenu;
+
+ /**
+ * Create a menu that contains submenus, and later you can append this menu and its submenus to the UI.
+ * @param submenuItem the submenu item
+ *
+ * @example
+ * ```ts
+ * univerAPI.createSubmenu({ id: 'custom-submenu', title: 'Custom Submenu' })
+ * .addSubmenu(univerAPI.createSubmenu({ id: 'submenu-nested', title: 'Nested Submenu' })
+ * .addSubmenu(univerAPI.createMenu({ id: 'submenu-nested-1', title: 'Item 1', action: () => {} }))
+ * .addSeparator()
+ * .addSubmenu(univerAPI.createMenu({ id: 'submenu-nested-2', title: 'Item 2', action: () => {} }))
+ * )
+ * .appendTo('contextMenu.others');
+ * ```
+ *
+ * @returns the {@link FSubmenu} object
+ */
+ createSubmenu(submenuItem: IFacadeSubmenuItem): FSubmenu;
+
/**
* Open a sidebar.
*
@@ -83,6 +121,14 @@ export class FUniverUIMixin extends FUniver implements IFUniverUIMixin {
return this._commandService.executeCommand(PasteCommand.id);
}
+ override createMenu(menuItem: IFacadeMenuItem): FMenu {
+ return this._injector.createInstance(FMenu, menuItem);
+ }
+
+ override createSubmenu(submenuItem: IFacadeSubmenuItem): FSubmenu {
+ return this._injector.createInstance(FSubmenu, submenuItem);
+ }
+
override openSiderbar(params: ISidebarMethodOptions): IDisposable {
const sideBarService = this._injector.get(ISidebarService);
return sideBarService.open(params);
diff --git a/packages/ui/src/facade/index.ts b/packages/ui/src/facade/index.ts
index ec8f19f3a0..1d8842c948 100644
--- a/packages/ui/src/facade/index.ts
+++ b/packages/ui/src/facade/index.ts
@@ -16,6 +16,8 @@
import './f-univer';
import './f-hooks';
+import './f-menu-builder';
export type * from './f-hooks';
+export type * from './f-menu-builder';
export type * from './f-univer';