Skip to content

Commit f3ca21e

Browse files
authored
feat(hub): let dock entries add items to the context menu (#501)
* feat(hub): add contextMenu to dock entries * feat(hub-ui): show dock entry contextMenu items in the dock menu * chore(examples): demo dock contextMenu in hub-vite * docs(hub): document dock contextMenu
1 parent eaa9f7b commit f3ca21e

9 files changed

Lines changed: 427 additions & 15 deletions

File tree

‎docs/content/1.guide/16.hub.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,42 @@ async function runBuild() {
160160
}
161161
```
162162

163+
## Dock context menu
164+
165+
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.
166+
167+
```ts
168+
ctx.commands.register({ id: 'inspector:settings', title: 'Inspector settings', handler: openSettings })
169+
ctx.commands.register({ id: 'inspector:hold-mode', title: 'Hold mode', handler: toggleHoldMode })
170+
171+
const dock = ctx.docks.register({
172+
type: 'action',
173+
id: 'inspector',
174+
title: 'Inspector',
175+
icon: 'ph:cursor-click-duotone',
176+
action: { importFrom: 'my-inspector/client' },
177+
toggle: true,
178+
contextMenu: [
179+
{ command: 'inspector:settings', icon: 'ph:gear-duotone' },
180+
{ type: 'separator' },
181+
{ command: 'inspector:hold-mode', checked: false },
182+
],
183+
})
184+
```
185+
186+
An item has these fields:
187+
188+
| Field | Description |
189+
| --- | --- |
190+
| `command` | Id of a server command or a client command. |
191+
| `args` | Arguments for the command: strings, numbers, booleans or `null`. |
192+
| `title`, `titleLocales` | Label of the item. The default is the title of the command. |
193+
| `icon` | Icon of the item. The default is the icon of the command. |
194+
| `when` | The item shows only when this expression is true. |
195+
| `checked` | Shows a check mark. To change it, call `dock.update({ contextMenu })` with the new value. |
196+
197+
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.
198+
163199
## Mounting a devframe into a hub
164200

165201
`ctx.install(def)` registers a `DevframeDefinition` as a dock and runs its `setup(ctx)`, the imperative counterpart to `initHub`'s `devframes` list.

‎docs/content/1.guide/22.build-your-own-hub-ui.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ Honor `when` / `visibility`, `category` grouping (order from
5151
`DEFAULT_CATEGORIES_ORDER`, `@devframes/hub/constants`), and the
5252
`hub:docks:activate` broadcast. Show titles through
5353
`resolveTitle(entry, locale)` so a registrant's `titleLocales` translations
54-
reach the user.
54+
reach the user. If your hub UI has a context menu for dock buttons, you can
55+
show the items of an entry's [`contextMenu`](/guide/hub#dock-context-menu).
56+
Run each item with `hub:commands:execute`.
5557

5658
An `iframe` entry serving a [remote assets package](/guide/client-assets) can
5759
report it unreachable: its fallback page posts a `RemoteAssetsErrorMessage`

‎examples/hub-vite/vite.config.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { DevframeDockContextMenuItem } from '@devframes/hub'
12
import type { DevframeJsonRenderSpec } from '@devframes/json-render'
23
import type { DevframeJsonRenderDockEntry } from '@devframes/json-render/hub'
34
import { createUi } from '@devframes/hub-ui'
@@ -115,7 +116,37 @@ export default defineConfig({
115116
jsonRenderUiRenderer(),
116117
],
117118
configure(ctx) {
118-
ctx.docks.register(jsonRenderDock)
119+
const dock = ctx.docks.register(jsonRenderDock)
120+
121+
// Right-click the JSON Render dock button: its context menu lists
122+
// these commands above the built-in items. `checked` shows a check
123+
// mark, so the toggle updates the entry each time it runs.
124+
let compact = false
125+
const contextMenu = (): DevframeDockContextMenuItem[] => [
126+
{ command: 'example:hub-vite:json-render-ping', title: 'Ping', icon: 'ph:bell-duotone' },
127+
{ type: 'separator' },
128+
{ command: 'example:hub-vite:json-render-compact', title: 'Compact Mode', checked: compact },
129+
]
130+
ctx.commands.register({
131+
id: 'example:hub-vite:json-render-ping',
132+
title: 'JSON Render · Ping',
133+
category: 'kit',
134+
handler: () => 'pong',
135+
})
136+
ctx.commands.register({
137+
id: 'example:hub-vite:json-render-compact',
138+
title: 'JSON Render · Toggle Compact Mode',
139+
category: 'kit',
140+
handler: () => {
141+
compact = !compact
142+
dock.update({
143+
contextMenu: contextMenu(),
144+
})
145+
},
146+
})
147+
dock.update({
148+
contextMenu: contextMenu(),
149+
})
119150
},
120151
// Gate with devframe's interactive OTP (the default): the hub prints a
121152
// 6-digit code + magic link on startup, and the reference UI's

‎packages/hub-ui/src/client/components/dock/DockContextMenu.ts‎

Lines changed: 73 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,56 @@
1-
import type { DevframeDockEntry } from '@devframes/hub'
1+
import type { DevframeDockEntry, DevframeDockEntryIcon } from '@devframes/hub'
22
import type { DocksContext } from '@devframes/hub/client'
33
import { defineComponent, h, nextTick, onMounted, ref } from 'vue'
4-
import { t } from '../../i18n'
4+
import { locale, t } from '../../i18n'
5+
import { resolveDockContextMenu } from '../../state/dock-context-menu'
56
import { setDockContextMenu } from '../../state/floating-tooltip'
67
import { isDockPopupSupported, requestDockPopupOpen, useIsDockPopupOpen } from '../../state/popup'
8+
import DockIcon from './DockIcon.vue'
79

810
// @unocss-include
911

10-
interface DockMenuItem {
12+
interface DockMenuButton {
13+
type?: 'button'
1114
label: string
12-
icon: string
15+
/** A UnoCSS icon class for a built-in item, an Iconify name for an item from `contextMenu`. */
16+
icon?: string | { type: 'iconify', icon: DevframeDockEntryIcon }
17+
checked?: boolean
1318
action: () => void
14-
visible: boolean
19+
}
20+
21+
type DockMenuItem = DockMenuButton | { type: 'separator' }
22+
23+
const MENU_ITEM_SELECTOR = '[role="menuitem"],[role="menuitemcheckbox"]'
24+
25+
function renderIcon(icon: DockMenuButton['icon']) {
26+
const box = 'size-4.5 flex-none flex items-center justify-center text-base op60'
27+
if (!icon)
28+
return h('div', { class: box })
29+
if (typeof icon === 'string') {
30+
return h('div', { class: box }, [
31+
h('div', { class: icon }),
32+
])
33+
}
34+
return h(DockIcon, { icon: icon.icon, class: box })
1535
}
1636

1737
function renderMenuItem(item: DockMenuItem) {
38+
if (item.type === 'separator')
39+
return h('div', { role: 'separator', class: 'my1 border-t border-base' })
40+
const isCheckbox = item.checked !== undefined
1841
return h('button', {
19-
role: 'menuitem',
20-
class: 'flex items-center gap-2 px3 py1.5 rounded hover:bg-active focus-visible:bg-active outline-none transition text-left',
21-
onClick: item.action,
42+
'role': isCheckbox ? 'menuitemcheckbox' : 'menuitem',
43+
'aria-checked': isCheckbox
44+
? String(item.checked)
45+
: undefined,
46+
'class': 'flex items-center gap-2 px3 py1.5 rounded hover:bg-active focus-visible:bg-active outline-none transition text-left',
47+
'onClick': item.action,
2248
}, [
23-
h('div', { class: `${item.icon} text-base op60` }),
24-
h('span', item.label),
49+
renderIcon(item.icon),
50+
h('span', { class: 'flex-auto' }, item.label),
51+
isCheckbox && item.checked
52+
? h('div', { 'class': 'i-ph-check text-base op60', 'aria-hidden': 'true' })
53+
: null,
2554
])
2655
}
2756

@@ -39,7 +68,7 @@ const DockContextMenuList = defineComponent({
3968
},
4069
setup(props) {
4170
const root = ref<HTMLElement>()
42-
const buttons = () => Array.from(root.value?.querySelectorAll<HTMLButtonElement>('[role="menuitem"]') ?? [])
71+
const buttons = () => Array.from(root.value?.querySelectorAll<HTMLButtonElement>(MENU_ITEM_SELECTOR) ?? [])
4372

4473
onMounted(() => nextTick(() => buttons()[0]?.focus({ preventScroll: true })))
4574

@@ -125,6 +154,24 @@ function canRefresh(entry: DevframeDockEntry) {
125154
return entry.type === 'iframe'
126155
}
127156

157+
/** Items from the entry's `contextMenu`. */
158+
function getEntryMenuItems(context: DocksContext, entry: DevframeDockEntry): DockMenuItem[] {
159+
const resolved = resolveDockContextMenu(entry.contextMenu, context.commands.commands, context.when.context, locale.value)
160+
return resolved.map((item): DockMenuItem => item.type === 'separator'
161+
? item
162+
: {
163+
label: item.title,
164+
icon: item.icon
165+
? { type: 'iconify', icon: item.icon }
166+
: undefined,
167+
checked: item.checked,
168+
action: () => {
169+
setDockContextMenu(null)
170+
context.commands.execute(item.command, ...item.args).catch(console.error)
171+
},
172+
})
173+
}
174+
128175
export function openDockContextMenu(options: {
129176
context: DocksContext
130177
entry: DevframeDockEntry
@@ -134,7 +181,7 @@ export function openDockContextMenu(options: {
134181
const { context, entry, el, gap = 6 } = options
135182
const isEdgeMode = context.panel.store.mode === 'edge'
136183
const isPinned = context.docks.settings.value().docksPinned.includes(entry.id)
137-
const items: DockMenuItem[] = [
184+
const builtinItems = [
138185
{
139186
label: isPinned
140187
? t('docks.unpin')
@@ -200,8 +247,21 @@ export function openDockContextMenu(options: {
200247
},
201248
visible: isDockPopupSupported() && !useIsDockPopupOpen().value && context.clientType === 'embedded',
202249
},
203-
].filter(item => item.visible)
250+
]
251+
.filter(item => item.visible)
252+
.map(({ visible: _, ...item }): DockMenuButton => item)
204253

254+
const entryItems = getEntryMenuItems(context, entry)
255+
const items: DockMenuItem[] = entryItems.length && builtinItems.length
256+
? [
257+
...entryItems,
258+
{ type: 'separator' },
259+
...builtinItems,
260+
]
261+
: [
262+
...entryItems,
263+
...builtinItems,
264+
]
205265
if (items.length === 0)
206266
return
207267

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import type { DevframeCommandEntry } from '@devframes/hub'
2+
import type { WhenContext } from 'devframe/utils/when'
3+
import { describe, expect, it } from 'vitest'
4+
import { resolveDockContextMenu } from './dock-context-menu'
5+
6+
const ctx: WhenContext = {
7+
clientType: 'embedded',
8+
dockOpen: false,
9+
paletteOpen: false,
10+
dockSelectedId: '',
11+
}
12+
13+
const commands: DevframeCommandEntry[] = [
14+
{
15+
id: 'svelte:settings',
16+
title: 'Inspector Settings',
17+
icon: 'ph:gear-duotone',
18+
source: 'server',
19+
},
20+
{
21+
id: 'svelte:hold',
22+
title: 'Hold Mode',
23+
source: 'client',
24+
action: () => {},
25+
},
26+
{
27+
id: 'svelte:group',
28+
title: 'Group',
29+
source: 'client',
30+
children: [
31+
{
32+
id: 'svelte:child',
33+
title: 'Child',
34+
source: 'client',
35+
action: () => {},
36+
},
37+
],
38+
},
39+
{
40+
id: 'svelte:standalone-only',
41+
title: 'Standalone',
42+
source: 'client',
43+
when: 'clientType == standalone',
44+
action: () => {},
45+
},
46+
]
47+
48+
describe('resolveDockContextMenu', () => {
49+
it('returns nothing without items', () => {
50+
expect(resolveDockContextMenu(undefined, commands, ctx, 'en')).toEqual([])
51+
})
52+
53+
it('falls back to the title and icon of the command', () => {
54+
expect(resolveDockContextMenu([
55+
{ command: 'svelte:settings' },
56+
], commands, ctx, 'en')).toEqual([
57+
{
58+
type: 'command',
59+
command: 'svelte:settings',
60+
args: [],
61+
title: 'Inspector Settings',
62+
icon: 'ph:gear-duotone',
63+
checked: undefined,
64+
},
65+
])
66+
})
67+
68+
it('uses the item title, locales, icon, args and checked', () => {
69+
const [item] = resolveDockContextMenu([
70+
{
71+
command: 'svelte:hold',
72+
title: 'Hold',
73+
titleLocales: { fr: 'Maintenir' },
74+
icon: 'ph:hand-duotone',
75+
args: [true],
76+
checked: true,
77+
},
78+
], commands, ctx, 'fr')
79+
expect(item).toEqual({
80+
type: 'command',
81+
command: 'svelte:hold',
82+
args: [true],
83+
title: 'Maintenir',
84+
icon: 'ph:hand-duotone',
85+
checked: true,
86+
})
87+
})
88+
89+
it('drops unknown, unavailable and action-less commands', () => {
90+
const items = resolveDockContextMenu([
91+
{ command: 'missing' },
92+
{ command: 'svelte:standalone-only' },
93+
{ command: 'svelte:group' },
94+
{ command: 'svelte:hold', when: 'clientType == standalone' },
95+
{ command: 'svelte:child' },
96+
], commands, ctx, 'en')
97+
expect(items.map(item => item.type === 'command' && item.command)).toEqual(['svelte:child'])
98+
})
99+
100+
it('trims and merges separators', () => {
101+
const items = resolveDockContextMenu([
102+
{ type: 'separator' },
103+
{ command: 'svelte:settings' },
104+
{ type: 'separator' },
105+
{ command: 'missing' },
106+
{ type: 'separator' },
107+
{ command: 'svelte:hold' },
108+
{ type: 'separator' },
109+
{ type: 'separator' },
110+
], commands, ctx, 'en')
111+
expect(items.map(item => item.type)).toEqual(['command', 'separator', 'command'])
112+
})
113+
})

0 commit comments

Comments
 (0)