Skip to content
Open
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
19 changes: 18 additions & 1 deletion packages/hub-ui/src/client/components/views/ViewIframe.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import type { IframePanes } from 'iframe-pane'
import type { CSSProperties } from 'vue'
import { stripRemoteConnectionFromUrl, watchFrameLocation } from '@devframes/hub/client'
import { DEVFRAME_REMOTE_ASSETS_ERROR_MESSAGE_TYPE } from '@devframes/hub/constants'
import { computed, nextTick, onMounted, onUnmounted, ref, useTemplateRef, watchEffect } from 'vue'
import { useEventListener } from '@vueuse/core'
import { computed, nextTick, onMounted, onUnmounted, ref, shallowRef, useTemplateRef, watchEffect } from 'vue'
import { t } from '../../i18n'
import { handleMessagesPaletteShortcut } from '../../state/commands'
import { localizeTitle } from '../../state/locale'
import { useSettings } from '../../state/settings-defaults'
import ViewAssetsError from './ViewAssetsError.vue'
Expand Down Expand Up @@ -212,6 +214,13 @@ function openExternally() {
catch {}
}

// A click on a message or its heading leaves focus on the panel document's body.
// Keep keystrokes on focused controls, such as the search field, inside the panel.
const messagesBody = shallowRef<HTMLElement | null>(null)
useEventListener(messagesBody, ['keydown', 'keyup'], (event) => {
handleMessagesPaletteShortcut(event, props.context.commands)
})

let mountedTarget: HTMLDivElement | null = null
let onIframeLoad: (() => void) | undefined
let stopLocationWatch: (() => void) | undefined
Expand Down Expand Up @@ -269,7 +278,15 @@ onMounted(() => {
})

// Listen for iframe load events
function bindMessagesBody() {
const body = iframe.contentDocument?.body
messagesBody.value = body?.id === 'devframes-messages'
? body
: null
}
bindMessagesBody()
onIframeLoad = () => {
bindMessagesBody()
isIframeLoading.value = false
}
iframe.addEventListener('load', onIframeLoad)
Expand Down
2 changes: 2 additions & 0 deletions packages/hub-ui/src/client/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export const TERMINALS_DOCK_ID = 'devframes_plugin_terminals'
*/
export const MESSAGES_DOCK_ID = 'devframes_plugin_messages'

export const TOGGLE_PALETTE_COMMAND_ID = 'devframes:toggle-palette'

export const BUILTIN_ENTRY_CLIENT_AUTH_NOTICE: DevframeViewBuiltin = Object.freeze({
type: '~builtin',
category: '~builtin',
Expand Down
61 changes: 54 additions & 7 deletions packages/hub-ui/src/client/state/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { WhenContext } from 'devframe/utils/when'
import type { ShallowRef } from 'vue'
import { evaluateWhen } from 'devframe/utils/when'
import { computed, markRaw, reactive, ref, watch } from 'vue'
import { TOGGLE_PALETTE_COMMAND_ID } from '../constants'
import { sharedStateToRef } from './docks'
import { collectAllKeybindings, filterCommandsByWhen, findCommandDeep, normalizeKeyEvent } from './keybindings'
import { localizeCommand } from './locale'
Expand Down Expand Up @@ -141,7 +142,33 @@ export async function createCommandsContext(
return commandsContext
}

// --- Shortcut system ---
// The key that opened the palette can keep repeating after focus moves out of Messages.
const heldMessagesKey = new WeakMap<EventTarget, string>()

// A release or a fresh press can reach either Messages or the viewer.
function updateHeldMessagesKey(host: EventTarget, event: KeyboardEvent): boolean {
if (heldMessagesKey.get(host) !== (event.code || event.key))
return false
if (event.type === 'keydown' && event.repeat)
return true
heldMessagesKey.delete(host)
return false
}

export function handleMessagesPaletteShortcut(event: KeyboardEvent, commands: CommandsContext) {
const host = event.view?.parent
if (!event.isTrusted || !host)
return
if (updateHeldMessagesKey(host, event) || event.type !== 'keydown' || event.defaultPrevented || event.isComposing || event.repeat || event.target !== event.currentTarget)
return
const pressed = normalizeKeyEvent(event)
if (!commands.getKeybindings(TOGGLE_PALETTE_COMMAND_ID).some(binding => binding.key === pressed))
return

event.preventDefault()
heldMessagesKey.set(host, event.code || event.key)
commands.execute(TOGGLE_PALETTE_COMMAND_ID).catch(console.error)
}

function setupShortcutListener(
getWhenContext: () => WhenContext,
Expand All @@ -150,6 +177,16 @@ function setupShortcutListener(
execute: (id: string, ...args: any[]) => Promise<unknown>,
) {
const handler = (e: KeyboardEvent) => {
const host = e.currentTarget
if (host && updateHeldMessagesKey(host, e)) {
e.preventDefault()
// The embedded dock visibility shortcut also listens on this window.
e.stopImmediatePropagation()
return
}
if (e.type === 'keyup')
return

// Let the shortcut editor record keys without executing their commands.
// composedPath reaches the input through shadow DOM; structural checks also
// work for elements belonging to the popup window's realm.
Expand Down Expand Up @@ -184,12 +221,22 @@ function setupShortcutListener(

// Attach to the host window. This covers embedded (shadow DOM) mode and the
// host page while a popup is open.
window.addEventListener('keydown', handler, { capture: true })

watch(useDockPopupWindow(), (popup, prev) => {
if (prev)
prev.removeEventListener('keydown', handler, { capture: true })
function listen(host: Window) {
// Another document can receive both the release and the next press.
const onBlur = () => heldMessagesKey.delete(host)
host.addEventListener('blur', onBlur)
host.addEventListener('keydown', handler, true)
host.addEventListener('keyup', handler, true)
return () => {
onBlur()
host.removeEventListener('blur', onBlur)
host.removeEventListener('keydown', handler, true)
host.removeEventListener('keyup', handler, true)
}
}
listen(window)
watch(useDockPopupWindow(), (popup, _, onCleanup) => {
if (popup)
popup.addEventListener('keydown', handler, { capture: true })
onCleanup(listen(popup))
})
}
4 changes: 2 additions & 2 deletions packages/hub-ui/src/client/state/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { DEFAULT_STATE_USER_SETTINGS, DOCK_RENDERERS_STATE_KEY, HUB_EVENTS } fro
import { DEVFRAME_EVENTS } from 'devframe/constants'
import { createEventEmitter } from 'devframe/utils/events'
import { computed, markRaw, reactive, ref, toRefs, watch, watchEffect } from 'vue'
import { BUILTIN_ENTRIES, BUILTIN_ENTRY_SETTINGS, DEFAULT_CATEGORIES_ORDER, HUB_UI_HIDE_EVENT } from '../constants'
import { BUILTIN_ENTRIES, BUILTIN_ENTRY_SETTINGS, DEFAULT_CATEGORIES_ORDER, HUB_UI_HIDE_EVENT, TOGGLE_PALETTE_COMMAND_ID } from '../constants'
import { t } from '../i18n'
import { useBranding } from './branding'
import { createCommandsContext } from './commands'
Expand Down Expand Up @@ -546,7 +546,7 @@ export async function createDocksContext(
cleanupBuiltinCommands?.()
cleanupBuiltinCommands = commandsContext.register([
{
id: 'devframes:toggle-palette',
id: TOGGLE_PALETTE_COMMAND_ID,
source: 'client',
title: t('command.togglePalette'),
icon: 'ph:magnifying-glass-duotone',
Expand Down
2 changes: 1 addition & 1 deletion plugins/messages/app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
html, body, #app { height: 100%; margin: 0; }
</style>
</head>
<body>
<body id="devframes-messages">
<div id="app"></div>
<script type="module" src="./main.ts"></script>
</body>
Expand Down
166 changes: 166 additions & 0 deletions tests/e2e/messages-palette.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import type { DevframeDocksUserSettings } from '@devframes/hub'
import type { AddressInfo } from 'node:net'
import { once } from 'node:events'
import { createServer } from 'node:http'
import { createUi } from '@devframes/hub-ui'
import { HUB_EVENTS } from '@devframes/hub/constants'
import { initHub } from '@devframes/hub/initiate'
import { createMessagesDevframe } from '@devframes/plugin-messages'
import { test as base, expect } from '@playwright/test'

const test = base.extend<{
viewer: { hub: ReturnType<typeof initHub>, origin: string, checkpoints: number[], count: () => number }
}>({
viewer: async ({ page }, use, testInfo) => {
let calls = 0
const checkpoints: number[] = []
const hub = initHub({
base: '/__devframes/',
auth: false,
mcp: false,
register: false,
getStorageDir: scope => testInfo.outputPath('storage', scope),
ui: createUi({ locale: 'en' }),
devframes: [
createMessagesDevframe(),
],
configure(ctx) {
ctx.messages.add({ level: 'info', message: 'Build complete' })
ctx.commands.register({
id: 'test:count',
title: 'Count invocations',
keybindings: [
{ key: 'Mod+K' },
],
handler: () => ++calls,
})
// This command takes a snapshot after earlier shortcut calls reach the server.
ctx.commands.register({
id: 'test:checkpoint',
title: 'Record invocation count',
keybindings: [
{ key: 'F8' },
],
handler: () => checkpoints.push(calls),
})
},
})
const server = createServer((req, res) => {
if (req.url === '/') {
res.setHeader('content-type', 'text/html')
res.end(`<!doctype html><input aria-label="Host input"><iframe title="Other panel" srcdoc="<input>"></iframe><script type="module" src="${hub.base}embedded.js"></script>`)
return
}
hub.nodeMiddleware(req, res)
})
const detach = hub.attach(server)
try {
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const { port } = server.address() as AddressInfo
await use({
hub,
origin: `http://127.0.0.1:${port}`,
checkpoints,
count: () => calls,
})
}
finally {
await page.close()
detach()
await hub.close()
await new Promise<void>((resolve, reject) => server.close(error => error
? reject(error)
: resolve()))
}
},
})

test('opens the palette once from Messages when another command shares its shortcut', async ({ page, viewer }) => {
const { hub, origin, checkpoints, count } = viewer
await page.goto(origin + hub.base)
await page.getByRole('button', { name: 'Messages', exact: true }).click()
const panel = page.frameLocator('iframe[title="Messages"]')
await panel.getByText('Build complete', { exact: true }).click()
await page.keyboard.down('ControlOrMeta')
await page.keyboard.down('k')
const palette = page.getByPlaceholder('Type a command...')
await expect(palette).toBeFocused()

// The repeat reaches the focused palette. A fresh press goes through the normal command order.
await page.keyboard.down('k')
await page.keyboard.up('k')
await page.keyboard.up('ControlOrMeta')
await expect(palette).toBeFocused()
await page.keyboard.press('F8')
await expect.poll(() => checkpoints).toEqual([0])
await page.keyboard.press('ControlOrMeta+k')
await page.keyboard.press('F8')
await expect.poll(() => checkpoints).toEqual([0, 1])
await page.keyboard.press('Escape')
await expect(palette).toBeHidden()

const search = panel.getByRole('searchbox')
await search.click()
await page.keyboard.press('ControlOrMeta+k')
await expect(search).toBeFocused()
await expect(palette).toBeHidden()
expect(count()).toBe(1)
})

test('keeps a held palette shortcut separate from the embedded dock shortcut', async ({ page, viewer }) => {
const ctx = await viewer.hub.context
const settings = await ctx.rpc.sharedState.get<DevframeDocksUserSettings>(HUB_EVENTS.sharedState.userSettings)
settings.mutate((state) => {
state.commandShortcuts['devframes:toggle-palette'] = [
{ key: 'Alt+Shift+D' },
]
})
await page.goto(viewer.origin)
const dock = page.locator('#devframes-dock')
await dock.hover()
await page.getByRole('button', { name: 'Messages', exact: true }).click()
const panel = page.frameLocator('iframe[title="Messages"]')
await panel.getByText('Build complete', { exact: true }).click()
const palette = page.getByPlaceholder('Type a command...')
await page.keyboard.down('Alt')
await page.keyboard.down('Shift')
await page.keyboard.down('d')
await expect(palette).toBeFocused()
await page.keyboard.down('d')
await expect(palette).toBeFocused()
await page.keyboard.up('d')
await page.keyboard.up('Shift')
await page.keyboard.up('Alt')
await page.keyboard.press('Alt+Shift+d')
await expect(dock).toBeHidden()
})

for (const releaseIn of ['Messages', 'other iframe'] as const) {
test(`accepts a new press after the opening key is released in ${releaseIn}`, async ({ page, viewer }) => {
await page.goto(viewer.origin)
await page.locator('#devframes-dock').hover()
await page.getByRole('button', { name: 'Messages', exact: true }).click()
const panel = page.frameLocator('iframe[title="Messages"]')
await panel.getByText('Build complete', { exact: true }).click()
const palette = page.getByPlaceholder('Type a command...')
await page.keyboard.down('ControlOrMeta')
await page.keyboard.down('k')
await expect(palette).toBeFocused()
await page.keyboard.up('ControlOrMeta')
await page.keyboard.press('Escape')
await expect(palette).toBeHidden()
const field = releaseIn === 'Messages'
? panel.getByRole('searchbox')
: page.frameLocator('iframe[title="Other panel"]').getByRole('textbox')
await field.focus()
await page.keyboard.up('k')

await page.keyboard.down('k')
const input = page.getByRole('textbox', { name: 'Host input' })
await input.focus()
await page.keyboard.down('k')
await page.keyboard.up('k')
await expect(input).toHaveValue('k')
})
}
Loading