diff --git a/docs/content/1.guide/16.hub.md b/docs/content/1.guide/16.hub.md index a05464b5..69085c29 100644 --- a/docs/content/1.guide/16.hub.md +++ b/docs/content/1.guide/16.hub.md @@ -160,6 +160,42 @@ async function runBuild() { } ``` +## Dock context menu + +A user opens the context menu of a dock button with a right-click, Shift+F10 or the Menu key. The reference hub UI shows its own items there: pin, hide, refresh and edge mode. A dock entry can add items of its own with `contextMenu`. Each item runs a command, so a click on the dock button can toggle a tool and the context menu can open its settings. + +```ts +ctx.commands.register({ id: 'inspector:settings', title: 'Inspector settings', handler: openSettings }) +ctx.commands.register({ id: 'inspector:hold-mode', title: 'Hold mode', handler: toggleHoldMode }) + +const dock = ctx.docks.register({ + type: 'action', + id: 'inspector', + title: 'Inspector', + icon: 'ph:cursor-click-duotone', + action: { importFrom: 'my-inspector/client' }, + toggle: true, + contextMenu: [ + { command: 'inspector:settings', icon: 'ph:gear-duotone' }, + { type: 'separator' }, + { command: 'inspector:hold-mode', checked: false }, + ], +}) +``` + +An item has these fields: + +| Field | Description | +| --- | --- | +| `command` | Id of a server command or a client command. | +| `args` | Arguments for the command: strings, numbers, booleans or `null`. | +| `title`, `titleLocales` | Label of the item. The default is the title of the command. | +| `icon` | Icon of the item. The default is the icon of the command. | +| `when` | The item shows only when this expression is true. | +| `checked` | Shows a check mark. To change it, call `dock.update({ contextMenu })` with the new value. | + +The hub UI hides an item when its `when` is false or when the `when` of the command is false. It also hides an item when no command has its id, or when a client command has no `action`. The menu does not show the children of a command. A `{ type: 'separator' }` item draws a line. The hub UI removes separators at the start and the end, and merges two or more in a row into one. The items of the entry come first, then a separator, then the built-in items. + ## Mounting a devframe into a hub `ctx.install(def)` registers a `DevframeDefinition` as a dock and runs its `setup(ctx)`, the imperative counterpart to `initHub`'s `devframes` list. diff --git a/docs/content/1.guide/22.build-your-own-hub-ui.md b/docs/content/1.guide/22.build-your-own-hub-ui.md index dad1c6ea..2bca8645 100644 --- a/docs/content/1.guide/22.build-your-own-hub-ui.md +++ b/docs/content/1.guide/22.build-your-own-hub-ui.md @@ -51,7 +51,9 @@ Honor `when` / `visibility`, `category` grouping (order from `DEFAULT_CATEGORIES_ORDER`, `@devframes/hub/constants`), and the `hub:docks:activate` broadcast. Show titles through `resolveTitle(entry, locale)` so a registrant's `titleLocales` translations -reach the user. +reach the user. If your hub UI has a context menu for dock buttons, you can +show the items of an entry's [`contextMenu`](/guide/hub#dock-context-menu). +Run each item with `hub:commands:execute`. An `iframe` entry serving a [remote assets package](/guide/client-assets) can report it unreachable: its fallback page posts a `RemoteAssetsErrorMessage` diff --git a/examples/hub-vite/vite.config.ts b/examples/hub-vite/vite.config.ts index 5333449f..690a08fd 100644 --- a/examples/hub-vite/vite.config.ts +++ b/examples/hub-vite/vite.config.ts @@ -1,3 +1,4 @@ +import type { DevframeDockContextMenuItem } from '@devframes/hub' import type { DevframeJsonRenderSpec } from '@devframes/json-render' import type { DevframeJsonRenderDockEntry } from '@devframes/json-render/hub' import { createUi } from '@devframes/hub-ui' @@ -115,7 +116,37 @@ export default defineConfig({ jsonRenderUiRenderer(), ], configure(ctx) { - ctx.docks.register(jsonRenderDock) + const dock = ctx.docks.register(jsonRenderDock) + + // Right-click the JSON Render dock button: its context menu lists + // these commands above the built-in items. `checked` shows a check + // mark, so the toggle updates the entry each time it runs. + let compact = false + const contextMenu = (): DevframeDockContextMenuItem[] => [ + { command: 'example:hub-vite:json-render-ping', title: 'Ping', icon: 'ph:bell-duotone' }, + { type: 'separator' }, + { command: 'example:hub-vite:json-render-compact', title: 'Compact Mode', checked: compact }, + ] + ctx.commands.register({ + id: 'example:hub-vite:json-render-ping', + title: 'JSON Render · Ping', + category: 'kit', + handler: () => 'pong', + }) + ctx.commands.register({ + id: 'example:hub-vite:json-render-compact', + title: 'JSON Render · Toggle Compact Mode', + category: 'kit', + handler: () => { + compact = !compact + dock.update({ + contextMenu: contextMenu(), + }) + }, + }) + dock.update({ + contextMenu: contextMenu(), + }) }, // Gate with devframe's interactive OTP (the default): the hub prints a // 6-digit code + magic link on startup, and the reference UI's diff --git a/packages/hub-ui/src/client/components/dock/DockContextMenu.ts b/packages/hub-ui/src/client/components/dock/DockContextMenu.ts index 81ba9d06..e71d1732 100644 --- a/packages/hub-ui/src/client/components/dock/DockContextMenu.ts +++ b/packages/hub-ui/src/client/components/dock/DockContextMenu.ts @@ -1,27 +1,56 @@ -import type { DevframeDockEntry } from '@devframes/hub' +import type { DevframeDockEntry, DevframeDockEntryIcon } from '@devframes/hub' import type { DocksContext } from '@devframes/hub/client' import { defineComponent, h, nextTick, onMounted, ref } from 'vue' -import { t } from '../../i18n' +import { locale, t } from '../../i18n' +import { resolveDockContextMenu } from '../../state/dock-context-menu' import { setDockContextMenu } from '../../state/floating-tooltip' import { isDockPopupSupported, requestDockPopupOpen, useIsDockPopupOpen } from '../../state/popup' +import DockIcon from './DockIcon.vue' // @unocss-include -interface DockMenuItem { +interface DockMenuButton { + type?: 'button' label: string - icon: string + /** A UnoCSS icon class for a built-in item, an Iconify name for an item from `contextMenu`. */ + icon?: string | { type: 'iconify', icon: DevframeDockEntryIcon } + checked?: boolean action: () => void - visible: boolean +} + +type DockMenuItem = DockMenuButton | { type: 'separator' } + +const MENU_ITEM_SELECTOR = '[role="menuitem"],[role="menuitemcheckbox"]' + +function renderIcon(icon: DockMenuButton['icon']) { + const box = 'size-4.5 flex-none flex items-center justify-center text-base op60' + if (!icon) + return h('div', { class: box }) + if (typeof icon === 'string') { + return h('div', { class: box }, [ + h('div', { class: icon }), + ]) + } + return h(DockIcon, { icon: icon.icon, class: box }) } function renderMenuItem(item: DockMenuItem) { + if (item.type === 'separator') + return h('div', { role: 'separator', class: 'my1 border-t border-base' }) + const isCheckbox = item.checked !== undefined return h('button', { - role: 'menuitem', - class: 'flex items-center gap-2 px3 py1.5 rounded hover:bg-active focus-visible:bg-active outline-none transition text-left', - onClick: item.action, + 'role': isCheckbox ? 'menuitemcheckbox' : 'menuitem', + 'aria-checked': isCheckbox + ? String(item.checked) + : undefined, + 'class': 'flex items-center gap-2 px3 py1.5 rounded hover:bg-active focus-visible:bg-active outline-none transition text-left', + 'onClick': item.action, }, [ - h('div', { class: `${item.icon} text-base op60` }), - h('span', item.label), + renderIcon(item.icon), + h('span', { class: 'flex-auto' }, item.label), + isCheckbox && item.checked + ? h('div', { 'class': 'i-ph-check text-base op60', 'aria-hidden': 'true' }) + : null, ]) } @@ -39,7 +68,7 @@ const DockContextMenuList = defineComponent({ }, setup(props) { const root = ref() - const buttons = () => Array.from(root.value?.querySelectorAll('[role="menuitem"]') ?? []) + const buttons = () => Array.from(root.value?.querySelectorAll(MENU_ITEM_SELECTOR) ?? []) onMounted(() => nextTick(() => buttons()[0]?.focus({ preventScroll: true }))) @@ -125,6 +154,24 @@ function canRefresh(entry: DevframeDockEntry) { return entry.type === 'iframe' } +/** Items from the entry's `contextMenu`. */ +function getEntryMenuItems(context: DocksContext, entry: DevframeDockEntry): DockMenuItem[] { + const resolved = resolveDockContextMenu(entry.contextMenu, context.commands.commands, context.when.context, locale.value) + return resolved.map((item): DockMenuItem => item.type === 'separator' + ? item + : { + label: item.title, + icon: item.icon + ? { type: 'iconify', icon: item.icon } + : undefined, + checked: item.checked, + action: () => { + setDockContextMenu(null) + context.commands.execute(item.command, ...item.args).catch(console.error) + }, + }) +} + export function openDockContextMenu(options: { context: DocksContext entry: DevframeDockEntry @@ -134,7 +181,7 @@ export function openDockContextMenu(options: { const { context, entry, el, gap = 6 } = options const isEdgeMode = context.panel.store.mode === 'edge' const isPinned = context.docks.settings.value().docksPinned.includes(entry.id) - const items: DockMenuItem[] = [ + const builtinItems = [ { label: isPinned ? t('docks.unpin') @@ -200,8 +247,21 @@ export function openDockContextMenu(options: { }, visible: isDockPopupSupported() && !useIsDockPopupOpen().value && context.clientType === 'embedded', }, - ].filter(item => item.visible) + ] + .filter(item => item.visible) + .map(({ visible: _, ...item }): DockMenuButton => item) + const entryItems = getEntryMenuItems(context, entry) + const items: DockMenuItem[] = entryItems.length && builtinItems.length + ? [ + ...entryItems, + { type: 'separator' }, + ...builtinItems, + ] + : [ + ...entryItems, + ...builtinItems, + ] if (items.length === 0) return diff --git a/packages/hub-ui/src/client/state/dock-context-menu.test.ts b/packages/hub-ui/src/client/state/dock-context-menu.test.ts new file mode 100644 index 00000000..a95e16be --- /dev/null +++ b/packages/hub-ui/src/client/state/dock-context-menu.test.ts @@ -0,0 +1,113 @@ +import type { DevframeCommandEntry } from '@devframes/hub' +import type { WhenContext } from 'devframe/utils/when' +import { describe, expect, it } from 'vitest' +import { resolveDockContextMenu } from './dock-context-menu' + +const ctx: WhenContext = { + clientType: 'embedded', + dockOpen: false, + paletteOpen: false, + dockSelectedId: '', +} + +const commands: DevframeCommandEntry[] = [ + { + id: 'svelte:settings', + title: 'Inspector Settings', + icon: 'ph:gear-duotone', + source: 'server', + }, + { + id: 'svelte:hold', + title: 'Hold Mode', + source: 'client', + action: () => {}, + }, + { + id: 'svelte:group', + title: 'Group', + source: 'client', + children: [ + { + id: 'svelte:child', + title: 'Child', + source: 'client', + action: () => {}, + }, + ], + }, + { + id: 'svelte:standalone-only', + title: 'Standalone', + source: 'client', + when: 'clientType == standalone', + action: () => {}, + }, +] + +describe('resolveDockContextMenu', () => { + it('returns nothing without items', () => { + expect(resolveDockContextMenu(undefined, commands, ctx, 'en')).toEqual([]) + }) + + it('falls back to the title and icon of the command', () => { + expect(resolveDockContextMenu([ + { command: 'svelte:settings' }, + ], commands, ctx, 'en')).toEqual([ + { + type: 'command', + command: 'svelte:settings', + args: [], + title: 'Inspector Settings', + icon: 'ph:gear-duotone', + checked: undefined, + }, + ]) + }) + + it('uses the item title, locales, icon, args and checked', () => { + const [item] = resolveDockContextMenu([ + { + command: 'svelte:hold', + title: 'Hold', + titleLocales: { fr: 'Maintenir' }, + icon: 'ph:hand-duotone', + args: [true], + checked: true, + }, + ], commands, ctx, 'fr') + expect(item).toEqual({ + type: 'command', + command: 'svelte:hold', + args: [true], + title: 'Maintenir', + icon: 'ph:hand-duotone', + checked: true, + }) + }) + + it('drops unknown, unavailable and action-less commands', () => { + const items = resolveDockContextMenu([ + { command: 'missing' }, + { command: 'svelte:standalone-only' }, + { command: 'svelte:group' }, + { command: 'svelte:hold', when: 'clientType == standalone' }, + { command: 'svelte:child' }, + ], commands, ctx, 'en') + expect(items.map(item => item.type === 'command' && item.command)).toEqual(['svelte:child']) + }) + + it('trims and merges separators', () => { + const items = resolveDockContextMenu([ + { type: 'separator' }, + { command: 'svelte:settings' }, + { type: 'separator' }, + { command: 'missing' }, + { type: 'separator' }, + { command: 'svelte:hold' }, + { type: 'separator' }, + { type: 'separator' }, + ], commands, ctx, 'en') + expect(items.map(item => item.type)).toEqual(['command', 'separator', 'command']) + }) +}) diff --git a/packages/hub-ui/src/client/state/dock-context-menu.ts b/packages/hub-ui/src/client/state/dock-context-menu.ts new file mode 100644 index 00000000..9cae61c8 --- /dev/null +++ b/packages/hub-ui/src/client/state/dock-context-menu.ts @@ -0,0 +1,76 @@ +import type { DevframeCommandEntry, DevframeDockContextMenuArg, DevframeDockContextMenuCommand, DevframeDockContextMenuItem, DevframeDockEntryIcon } from '@devframes/hub' +import type { WhenContext } from 'devframe/utils/when' +import { resolveTitle } from '@devframes/hub/client' +import { evaluateWhen } from 'devframe/utils/when' +import { filterCommandsByWhen, findCommandDeep } from './keybindings' + +export type ResolvedDockMenuItem + = | { + type: 'command' + command: string + args: readonly DevframeDockContextMenuArg[] + title: string + icon?: DevframeDockEntryIcon + checked?: boolean + } + | { type: 'separator' } + +function resolveCommandItem( + item: DevframeDockContextMenuCommand, + available: DevframeCommandEntry[], + ctx: WhenContext, + locale: string | undefined, +): ResolvedDockMenuItem | undefined { + if (item.when && !evaluateWhen(item.when, ctx)) + return + const command = findCommandDeep(available, item.command) + if (!command || (command.source === 'client' && !command.action)) + return + return { + type: 'command', + command: command.id, + args: item.args ?? [], + title: item.title + ? resolveTitle({ title: item.title, titleLocales: item.titleLocales }, locale) + : command.title, + icon: item.icon ?? command.icon, + checked: item.checked, + } +} + +/** Drop separators at the start and the end, and merge runs of them into one. */ +function collapseSeparators(items: ResolvedDockMenuItem[]): ResolvedDockMenuItem[] { + const result: ResolvedDockMenuItem[] = [] + for (const item of items) { + if (item.type === 'separator' && (!result.length || result.at(-1)!.type === 'separator')) + continue + result.push(item) + } + if (result.at(-1)?.type === 'separator') + result.pop() + return result +} + +/** + * Turn the `contextMenu` of a dock entry into the items to show. + * + * An item is dropped when its own `when` is false, when no available command + * has its id, or when it points to a client command with no action. Title and + * icon fall back to the values of the command. + */ +export function resolveDockContextMenu( + items: readonly DevframeDockContextMenuItem[] | undefined, + commands: DevframeCommandEntry[], + ctx: WhenContext, + locale: string | undefined, +): ResolvedDockMenuItem[] { + if (!items?.length) + return [] + const available = filterCommandsByWhen(commands, ctx) + const resolved = items.flatMap(item => item.type === 'separator' + ? [ + { type: 'separator' } as const, + ] + : resolveCommandItem(item, available, ctx, locale) ?? []) + return collapseSeparators(resolved) +} diff --git a/packages/hub/src/types/docks.ts b/packages/hub/src/types/docks.ts index 64293c10..00a21016 100644 --- a/packages/hub/src/types/docks.ts +++ b/packages/hub/src/types/docks.ts @@ -177,6 +177,68 @@ export interface DevframeDockEntryBase { * @see {@link DevframeViewGroup} */ groupId?: string + /** + * Extra items for the dock button's context menu. The user opens this menu + * with a right-click, Shift+F10 or the Menu key. Each item runs a command + * from `ctx.commands` (server) or `context.commands` (client). + * + * A viewer shows these items above its own items (pin, hide, refresh, ...) + * and puts a separator between the two blocks. Use it for actions that + * belong to the tool but do not need a dock entry of their own. For + * example, a click toggles an inspector and the context menu opens its + * settings. + * + * @see {@link DevframeDockContextMenuItem} + */ + contextMenu?: readonly DevframeDockContextMenuItem[] +} + +/** One item in {@link DevframeDockEntryBase.contextMenu}. */ +export type DevframeDockContextMenuItem + = | DevframeDockContextMenuCommand + | DevframeDockContextMenuSeparator + +/** + * A context menu item that runs a command. The item is serializable, so a + * node-side devframe can declare it and an out-of-process viewer can show it. + */ +export interface DevframeDockContextMenuCommand { + type?: 'command' + /** Id of the command to run. A server command or a client command. */ + command: string + /** Positional arguments for the command. */ + args?: readonly DevframeDockContextMenuArg[] + /** Label of the item. The default is the `title` of the command. */ + title?: string + /** Translations of `title` by BCP 47 tag; see `resolveTitle()` from `@devframes/hub`. */ + titleLocales?: DevframeTitleLocales + /** Icon of the item. The default is the `icon` of the command. */ + icon?: DevframeDockEntryIcon + /** + * Conditional visibility expression, same syntax as command `when` clauses. + * The viewer also hides the item when the `when` of the command is false, + * or when no command with this id exists. + */ + when?: string + /** + * Shows a check mark next to the item, for an on/off setting. To change + * it, update the entry with `docks.update()`. + */ + checked?: boolean +} + +/** + * One argument of a context menu item. Only primitive values, so that the + * item can cross the wire in shared state. + */ +export type DevframeDockContextMenuArg = string | number | boolean | null + +/** + * A line between two groups of items. A viewer removes separators at the + * start and at the end, and merges two or more in a row into one. + */ +export interface DevframeDockContextMenuSeparator { + type: 'separator' } export interface ClientScriptEntry { diff --git a/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts index 2e0043b2..885500fa 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/hub/index.snapshot.d.ts @@ -84,6 +84,19 @@ export interface DevframeDockActivation { dockId: string; params?: Record; } +export interface DevframeDockContextMenuCommand { + type?: 'command'; + command: string; + args?: readonly DevframeDockContextMenuArg[]; + title?: string; + titleLocales?: DevframeTitleLocales; + icon?: DevframeDockEntryIcon; + when?: string; + checked?: boolean; +} +export interface DevframeDockContextMenuSeparator { + type: 'separator'; +} export interface DevframeDockEntryBase { id: string; title: string; @@ -97,6 +110,7 @@ export interface DevframeDockEntryBase { badge?: string; badgeVariant?: DevframeDockBadgeVariant; groupId?: string; + contextMenu?: readonly DevframeDockContextMenuItem[]; } export interface DevframeDockEntryRegistry { 'iframe': DevframeViewIframe; @@ -371,6 +385,8 @@ export interface RemoteDockOptions { // #region Types export type DevframeCommandEntry = DevframeServerCommandEntry | DevframeClientCommand; export type DevframeDockBadgeVariant = 'default' | 'info' | 'success' | 'warning' | 'danger'; +export type DevframeDockContextMenuArg = string | number | boolean | null; +export type DevframeDockContextMenuItem = DevframeDockContextMenuCommand | DevframeDockContextMenuSeparator; export type DevframeDockEntriesGrouped = [category: string, entries: DevframeDockEntry[]][]; export type DevframeDockEntry = DevframeDockUserEntry; export type DevframeDockEntryCategory = 'framework' | 'app' | 'ui' | 'data' | 'web' | 'performance' | 'advanced' | 'docs' | 'default' | '~builtin' | (string & {}); diff --git a/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts b/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts index b5bfa454..4d8e4990 100644 --- a/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/@devframes/hub/types.snapshot.d.ts @@ -84,6 +84,19 @@ export interface DevframeDockActivation { dockId: string; params?: Record; } +export interface DevframeDockContextMenuCommand { + type?: 'command'; + command: string; + args?: readonly DevframeDockContextMenuArg[]; + title?: string; + titleLocales?: DevframeTitleLocales; + icon?: DevframeDockEntryIcon; + when?: string; + checked?: boolean; +} +export interface DevframeDockContextMenuSeparator { + type: 'separator'; +} export interface DevframeDockEntryBase { id: string; title: string; @@ -97,6 +110,7 @@ export interface DevframeDockEntryBase { badge?: string; badgeVariant?: DevframeDockBadgeVariant; groupId?: string; + contextMenu?: readonly DevframeDockContextMenuItem[]; } export interface DevframeDockEntryRegistry { 'iframe': DevframeViewIframe; @@ -371,6 +385,8 @@ export interface RemoteDockOptions { // #region Types export type DevframeCommandEntry = DevframeServerCommandEntry | DevframeClientCommand; export type DevframeDockBadgeVariant = 'default' | 'info' | 'success' | 'warning' | 'danger'; +export type DevframeDockContextMenuArg = string | number | boolean | null; +export type DevframeDockContextMenuItem = DevframeDockContextMenuCommand | DevframeDockContextMenuSeparator; export type DevframeDockEntriesGrouped = [category: string, entries: DevframeDockEntry[]][]; export type DevframeDockEntry = DevframeDockUserEntry; export type DevframeDockEntryCategory = 'framework' | 'app' | 'ui' | 'data' | 'web' | 'performance' | 'advanced' | 'docs' | 'default' | '~builtin' | (string & {});