Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/content/1.guide/16.hub.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion docs/content/1.guide/22.build-your-own-hub-ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
33 changes: 32 additions & 1 deletion examples/hub-vite/vite.config.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
Expand Down
86 changes: 73 additions & 13 deletions packages/hub-ui/src/client/components/dock/DockContextMenu.ts
Original file line number Diff line number Diff line change
@@ -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,
])
}

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

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

Expand Down Expand Up @@ -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
Expand All @@ -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')
Expand Down Expand Up @@ -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

Expand Down
113 changes: 113 additions & 0 deletions packages/hub-ui/src/client/state/dock-context-menu.test.ts
Original file line number Diff line number Diff line change
@@ -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'])
})
})
Loading
Loading