refactor(editor): add slash menu config extension entry (#10641)

Close [BS-2744](https://linear.app/affine-design/issue/BS-2744/slash-menu%E6%8F%92%E4%BB%B6%E5%8C%96%EF%BC%9Aaction%E6%B3%A8%E5%86%8C%E5%85%A5%E5%8F%A3)

This PR mainly focus  on providing an entry point for configuring the SlashMenu feature. Therefore, it strives to retain the original code to ensure that the modifications are simple and easy to review. Subsequent PRs will focus on moving different configurations into separate blocks.

### How to use?
Here is the type definition for the slash menu configuration.  An important change is the new field `group`, which indicates the sorting and grouping of the menu item. See the comments for details.

```ts
// types.ts
export type SlashMenuContext = {
  std: BlockStdScope;
  model: BlockModel;
};

export type SlashMenuItemBase = {
  name: string;
  description?: string;
  icon?: TemplateResult;
  /**
   * This field defines sorting and grouping of menu items like VSCode.
   * The first number indicates the group index, the second number indicates the item index in the group.
   * The group name is the string between `_` and `@`.
   * You can find an example figure in https://code.visualstudio.com/api/references/contribution-points#menu-example
   */
  group?: `${number}_${string}@${number}`;

  /**
   * The condition to show the menu item.
   */
  when?: (ctx: SlashMenuContext) => boolean;
};

export type SlashMenuActionItem = SlashMenuItemBase & {
  action: (ctx: SlashMenuContext) => void;
  tooltip?: SlashMenuTooltip;

  /**
   * The alias of the menu item for search.
   */
  searchAlias?: string[];
};

export type SlashMenuSubMenu = SlashMenuItemBase & {
  subMenu: SlashMenuItem[];
};

export type SlashMenuItem = SlashMenuActionItem | SlashMenuSubMenu;

export type SlashMenuConfig = {
  /**
   * The items in the slash menu. It can be generated dynamically with the context.
   */
  items: SlashMenuItem[] | ((ctx: SlashMenuContext) => SlashMenuItem[]);

  /**
   * Slash menu will not be triggered when the condition is true.
   */
  disableWhen?: (ctx: SlashMenuContext) => boolean;
};

// extensions.ts

/**
 * The extension to add a slash menu items or configure.
 */
export function SlashMenuConfigExtension(ext: {
  id: string;
  config: SlashMenuConfig;
}): ExtensionType {
  return {
    setup: di => {
      di.addImpl(SlashMenuConfigIdentifier(ext.id), ext.config);
    },
  };
}
```

Here is an example, `XXXSlashMenuConfig` adds a `Delete` action to the slash menu, which is assigned to the 8th group named `Actions` at position 0.
```ts
import { SlashMenuConfigExtension, type SlashMenuConfig } from '@blocksuite/affine-widget-slash-menu';

const XXXSlashMenuConfig = SlashMenuConfigExtension({
  id: 'XXX',
  config: {
    items: [
      {
        name: 'Delete',
        description: 'Remove a block.',
        searchAlias: ['remove'],
        icon: DeleteIcon,
        group: '8_Actions@0',
        action: ({ std, model }) => {
          std.host.doc.deleteBlock(model);
        },
      },
    ],
  },
});
```
This commit is contained in:
L-Sun
2025-03-06 16:12:06 +00:00
parent 62d8c0c7cb
commit 750c8a44dc
15 changed files with 547 additions and 488 deletions

View File

@@ -1,3 +1,4 @@
import type { SlashMenuActionItem } from '@blocksuite/blocks';
import { expect } from '@playwright/test';
import { addNote, switchEditorMode } from './utils/actions/edgeless.js';
@@ -387,6 +388,7 @@ test.describe('slash menu should show and hide correctly', () => {
const slashItems = slashMenu.locator('icon-button');
await type(page, '/');
await slashMenu.waitFor({ state: 'visible' });
await pressArrowDown(page, 4);
await expect(slashItems.nth(4)).toHaveAttribute('hover', 'true');
await expect(slashItems.nth(4).locator('.text')).toHaveText([
@@ -760,6 +762,7 @@ test('should insert database', async ({ page }) => {
expect(await defaultRows.count()).toBe(3);
});
// TODO(@L-Sun): Refactor this test after refactoring the slash menu
test.describe('slash menu with customize menu', () => {
test('can remove specified menus', async ({ page }) => {
await enterPlaygroundRoom(page);
@@ -777,15 +780,17 @@ test.describe('slash menu with customize menu', () => {
const SlashMenuWidget = window.$blocksuite.blocks.AffineSlashMenuWidget;
class CustomSlashMenu extends SlashMenuWidget {
override config = {
...SlashMenuWidget.DEFAULT_CONFIG,
items: [
{ groupName: 'custom-group' },
...SlashMenuWidget.DEFAULT_CONFIG.items
override get config() {
return {
items: super.config.items
.filter(item => 'action' in item)
.slice(0, 5),
],
};
.slice(0, 5)
.map<SlashMenuActionItem>((item, index) => ({
...item,
group: `0_custom-group@${index++}`,
})),
};
}
}
// Fix `Illegal constructor` error
// see https://stackoverflow.com/questions/41521812/illegal-constructor-with-ecmascript-6
@@ -836,29 +841,17 @@ test.describe('slash menu with customize menu', () => {
const SlashMenuWidget = window.$blocksuite.blocks.AffineSlashMenuWidget;
class CustomSlashMenu extends SlashMenuWidget {
override config = {
...SlashMenuWidget.DEFAULT_CONFIG,
items: [
{ groupName: 'Custom Menu' },
{
name: 'Custom Menu Item',
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
icon: '' as any,
action: () => {
// do nothing
},
},
{
name: 'Custom Menu Item',
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
icon: '' as any,
action: () => {
// do nothing
},
showWhen: () => false,
},
],
};
override get config() {
return {
items: [
{
name: 'Custom Menu Item',
group: '0_custom-group@0',
action: () => {},
} satisfies SlashMenuActionItem,
],
};
}
}
// Fix `Illegal constructor` error
// see https://stackoverflow.com/questions/41521812/illegal-constructor-with-ecmascript-6