From bb7338aa9f5ba2227d8cde70efaaf3f5f79a7859 Mon Sep 17 00:00:00 2001 From: Kevin Van Cott Date: Fri, 27 Nov 2026 22:45:45 -0600 Subject: [PATCH 1/2] feat(devtools): Handle keyboard shortcuts with TanStack Hotkeys Every keyboard handler in @tanstack/devtools now registers with @tanstack/solid-hotkeys, bundled with the devtools' own Solid copy. @tanstack/hotkeys becomes a dependency, so an app that also uses it shares one hotkey manager. @solid-primitives/keyboard and the devtools' own key matching are removed. - openHotkey is a hotkey string ('Control+~'). inspectHotkey takes modifier names, with Mod in place of CtrlOrMeta. Saved settings in the old format fall back to the config or the default. - The settings tab records the open shortcut and rejects one the app already registered. - Escape yields to an open dialog or popover of the app. In the modal host it targets the host dialog, and a close request that reaches the host closes the panel. - The trigger's Escape is live only during a drag or throw, so it doesn't shadow the app's own Escape hotkey. - Widget keys (resize separators, pane splitters, keyboard tab moves, the marketplace section header) target their elements. - The devtools bundle size limit moves from 86 KB to 102 KB. --- .changeset/devtools-tanstack-hotkeys.md | 14 + docs/configuration.md | 23 +- docs/source-inspector.md | 9 +- docs/vite-plugin.md | 2 +- package.json | 2 +- .../skills/devtools-vite-plugin/SKILL.md | 2 +- packages/devtools/package.json | 3 +- .../skills/devtools-app-setup/SKILL.md | 4 +- .../devtools/src/components/content-panel.tsx | 50 +-- .../src/components/plugin-workspace.tsx | 298 +++++++++++------- .../src/components/source-inspector.tsx | 16 +- .../devtools/src/components/trigger.test.tsx | 97 +++++- packages/devtools/src/components/trigger.tsx | 61 +++- .../src/context/devtools-context.test.ts | 44 +++ .../devtools/src/context/devtools-context.tsx | 43 ++- .../devtools/src/context/devtools-store.ts | 31 +- packages/devtools/src/devtools.tsx | 88 ++++-- packages/devtools/src/hooks/use-modal-host.ts | 32 +- packages/devtools/src/tabs/hotkey-config.tsx | 213 ++++++++----- .../src/tabs/marketplace/plugin-section.tsx | 22 +- .../devtools/src/tabs/settings-tab.test.tsx | 60 ++++ packages/devtools/src/tabs/settings-tab.tsx | 19 +- packages/devtools/src/utils/constants.ts | 5 + packages/devtools/src/utils/hotkey.test.ts | 109 ------- packages/devtools/src/utils/hotkey.ts | 66 ---- packages/devtools/src/utils/sanitize.test.ts | 52 +-- packages/devtools/src/utils/sanitize.ts | 22 -- packages/devtools/tests/index.test.ts | 2 +- packages/devtools/tests/workbench.test.tsx | 31 +- packages/devtools/tsup.config.ts | 6 +- pnpm-lock.yaml | 133 ++++++-- 31 files changed, 940 insertions(+), 619 deletions(-) create mode 100644 .changeset/devtools-tanstack-hotkeys.md delete mode 100644 packages/devtools/src/utils/hotkey.test.ts delete mode 100644 packages/devtools/src/utils/hotkey.ts diff --git a/.changeset/devtools-tanstack-hotkeys.md b/.changeset/devtools-tanstack-hotkeys.md new file mode 100644 index 000000000..b8894a3f0 --- /dev/null +++ b/.changeset/devtools-tanstack-hotkeys.md @@ -0,0 +1,14 @@ +--- +'@tanstack/devtools': minor +--- + +Handle every devtools keyboard shortcut with TanStack Hotkeys. + +- **Breaking:** `openHotkey` is a hotkey string in TanStack Hotkeys syntax, such as `'Control+~'` (the default) or `'Mod+Shift+D'`. Arrays such as `['Control', '~']` are no longer accepted. +- **Breaking:** `inspectHotkey` takes modifier names only. `CtrlOrMeta` is now `Mod`, which is Command on macOS and Control on other platforms. The default is `['Shift', 'Alt', 'Mod']`. +- Saved settings in the old format are ignored, and the config or the default applies instead. +- The Settings tab records the open shortcut from a key press, and rejects a shortcut that the app already registered with TanStack Hotkeys. +- Escape no longer closes the devtools when it closes an open dialog or popover of the app. Escape while moving a pane with the keyboard cancels the move and leaves the panel open. +- Alt+M for magnetic trigger mode now works on macOS, and it no longer fires while you type in a text field. +- The devtools hotkeys are in the `tanstack-devtools` scope. In an app that also uses TanStack Hotkeys, an enabled devtools hotkey runs instead of the app's global hotkey for the same key, such as Escape while the panel is open. An app with an exclusive scope can keep the devtools hotkeys working with `exclusive: { allow: ['tanstack-devtools'] }`. +- `@tanstack/hotkeys` is a new dependency, and `@solid-primitives/keyboard` is removed. An app that already uses TanStack Hotkeys shares one hotkey manager with the devtools. diff --git a/docs/configuration.md b/docs/configuration.md index 041a1d31d..5e483686f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -47,22 +47,29 @@ The `config` object is mainly focused around user interaction with the devtools { panelLocation: 'top' | 'bottom' } ``` -- `openHotkey` - The hotkey set to open the devtools +- `openHotkey` - The hotkey that opens and closes the devtools, written in [TanStack Hotkeys](https://tanstack.com/hotkeys) syntax. `Mod` is Command on macOS and Control on other platforms. The hotkey does not fire while you type in a text field. The default is `'Control+~'`. ```ts -type ModifierKey = 'Alt' | 'Control' | 'Meta' | 'Shift' | 'CtrlOrMeta'; -type KeyboardKey = ModifierKey | (string & {}); +import type { Hotkey } from '@tanstack/hotkeys' -{ openHotkey: Array } +{ openHotkey: Hotkey } ``` -- `inspectHotkey` - The hotkey set to open the source inspector +- `inspectHotkey` - The modifier keys to hold for the [source inspector](./source-inspector). The inspector is active while you hold exactly these keys. The default is `['Shift', 'Alt', 'Mod']`. ```ts -type ModifierKey = 'Alt' | 'Control' | 'Meta' | 'Shift' | 'CtrlOrMeta'; -type KeyboardKey = ModifierKey | (string & {}); +type ResolvableModifier = 'Control' | 'Shift' | 'Alt' | 'Meta' | 'Mod' -{ inspectHotkey: Array } +{ inspectHotkey: Array } +``` + +If your app also uses TanStack Hotkeys, the devtools share its hotkey manager and register their hotkeys in the `tanstack-devtools` scope: + +- While a devtools hotkey is enabled, it runs instead of your app's global hotkey for the same key. For example, while the devtools panel is open, Escape closes the panel and your app's global `Escape` hotkey doesn't run. +- While your app has an exclusive scope active, the devtools hotkeys don't fire. To keep them, add the devtools scope to `allow`: + +```tsx + ``` - `requireUrlFlag` - Requires a flag present in the url to enable devtools diff --git a/docs/source-inspector.md b/docs/source-inspector.md index 3d862526c..a455ffc2d 100644 --- a/docs/source-inspector.md +++ b/docs/source-inspector.md @@ -30,17 +30,14 @@ The Vite plugin uses oxc-parser to parse your JSX/TSX files during development. ## Activating the Inspector -There are two ways to activate the source inspector: +Hold the `inspectHotkey` keys to show the inspector overlay. The default is Shift+Alt+Ctrl, or Shift+Option+Command on macOS. The overlay stays while you hold exactly those keys. -- **Hotkey**: Hold Shift+Alt+Ctrl (or Shift+Alt+Meta on Mac) — this is the default `inspectHotkey`. While held, the inspector overlay appears. -- **Settings panel**: The inspect hotkey can be customized in the devtools Settings tab. - -The hotkey can also be configured programmatically: +To change the keys, use the **Source Inspector** buttons in the devtools **Settings** tab, or set `inspectHotkey` in the config. `Mod` is Command on macOS and Control on other platforms: ```ts ``` diff --git a/docs/vite-plugin.md b/docs/vite-plugin.md index 4fefa7749..ae3ed9214 100644 --- a/docs/vite-plugin.md +++ b/docs/vite-plugin.md @@ -222,7 +222,7 @@ graph TD The "Go to Source" feature lets you click on any element in your browser and open its source file in your editor at the exact line where it's defined. It works by injecting `data-tsd-source` attributes into your components via an AST transformation during development. These attributes encode the file path and line number of each element. -To use it, activate the source inspector by holding the inspect hotkey (default: Shift+Alt+Ctrl/Meta). An overlay will highlight elements under your cursor and display their source location. Clicking on a highlighted element opens the corresponding file in your editor at the exact line, powered by `launch-editor` under the hood. +To use it, activate the source inspector by holding the inspect hotkey (default: Shift+Alt+Ctrl, or Shift+Option+Command on macOS). An overlay will highlight elements under your cursor and display their source location. Clicking on a highlighted element opens the corresponding file in your editor at the exact line, powered by `launch-editor` under the hood. For a complete guide on configuration and usage, see the [Source Inspector](./source-inspector) docs. diff --git a/package.json b/package.json index 1a7eebdb7..c549d097c 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "size-limit": [ { "path": "packages/devtools/dist/index.js", - "limit": "86 KB" + "limit": "102 KB" }, { "path": "packages/event-bus-client/dist/esm/plugin.js", diff --git a/packages/devtools-vite/skills/devtools-vite-plugin/SKILL.md b/packages/devtools-vite/skills/devtools-vite-plugin/SKILL.md index 8b5e92772..358999eef 100644 --- a/packages/devtools-vite/skills/devtools-vite-plugin/SKILL.md +++ b/packages/devtools-vite/skills/devtools-vite-plugin/SKILL.md @@ -81,7 +81,7 @@ From `packages/devtools-vite/src/index.ts`: ### Source Injection -Adds `data-tsd-source="::"` attributes to every JSX opening element via oxc-parser + MagicString. This powers the "Go to Source" feature -- hold the inspect hotkey (default: Shift+Alt+Ctrl/Meta), hover over elements, click to open in editor. +Adds `data-tsd-source="::"` attributes to every JSX opening element via oxc-parser + MagicString. This powers the "Go to Source" feature -- hold the inspect hotkey (default: Shift+Alt+Ctrl, or Shift+Option+Command on macOS), hover over elements, click to open in editor. **Key behaviors:** diff --git a/packages/devtools/package.json b/packages/devtools/package.json index 1f546481b..1e2120877 100644 --- a/packages/devtools/package.json +++ b/packages/devtools/package.json @@ -67,19 +67,20 @@ "@neodrag/core": "3.0.0-next.11", "@tanstack/devtools-client": "workspace:*", "@tanstack/devtools-event-bus": "workspace:*", + "@tanstack/hotkeys": "^0.37.0", "clsx": "^2.1.1", "goober": "^2.1.16" }, "devDependencies": { "@babel/core": "^7.28.0", "@solid-primitives/event-listener": "^3.0.0", - "@solid-primitives/keyboard": "^2.0.0", "@solid-primitives/resize-observer": "^4.0.0", "@solidjs/babel-plugin": "^2.0.0", "@solidjs/testing-library": "^1.0.0-rc.2", "@solidjs/vite-plugin": "^3.0.0", "@solidjs/web": "^2.0.0", "@tanstack/devtools-ui": "workspace:*", + "@tanstack/solid-hotkeys": "^0.27.0", "solid-js": "^2.0.0", "tsup": "^8.5.0", "tsup-preset-solid": "^2.2.0" diff --git a/packages/devtools/skills/devtools-app-setup/SKILL.md b/packages/devtools/skills/devtools-app-setup/SKILL.md index 4fbb1a718..d2bca42ca 100644 --- a/packages/devtools/skills/devtools-app-setup/SKILL.md +++ b/packages/devtools/skills/devtools-app-setup/SKILL.md @@ -171,8 +171,8 @@ All config properties are optional. Defaults shown below: position: 'bottom-right', // used when triggerMode is 'fixed': 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'middle-left' | 'middle-right' triggerMode: 'floating', // 'floating' (default, draggable) | 'fixed' panelLocation: 'bottom', // panel position: 'top' | 'bottom' - openHotkey: ['Control', '~'], - inspectHotkey: ['Shift', 'Alt', 'CtrlOrMeta'], + openHotkey: 'Control+~', // TanStack Hotkeys syntax; Mod is Cmd on macOS, Ctrl elsewhere + inspectHotkey: ['Shift', 'Alt', 'Mod'], // modifiers to hold for the source inspector requireUrlFlag: false, // require URL param to show devtools urlFlag: 'tanstack-devtools', // the URL param name when requireUrlFlag is true theme: 'dark', // 'light' | 'dark' (defaults to system preference) diff --git a/packages/devtools/src/components/content-panel.tsx b/packages/devtools/src/components/content-panel.tsx index 72373430f..992022507 100644 --- a/packages/devtools/src/components/content-panel.tsx +++ b/packages/devtools/src/components/content-panel.tsx @@ -1,3 +1,5 @@ +import { createSignal } from 'solid-js' +import { createHotkeys } from '@tanstack/solid-hotkeys' import { createDevtoolsSettings, createHeight, @@ -24,26 +26,34 @@ export const ContentPanel = (props: { Math.floor(window.innerHeight * PANEL_MAX_VIEWPORT_RATIO) const clampedHeight = () => Math.min(maxHeight(), Math.max(PANEL_CLOSE_THRESHOLD, Math.round(height()))) - const resizeWithKeyboard: JSX.EventHandlerUnion< - HTMLDivElement, - KeyboardEvent - > = (event) => { - const step = event.shiftKey ? 50 : 10 - const grows = - (settings().panelLocation === 'bottom' && event.key === 'ArrowUp') || - (settings().panelLocation === 'top' && event.key === 'ArrowDown') - const shrinks = - (settings().panelLocation === 'bottom' && event.key === 'ArrowDown') || - (settings().panelLocation === 'top' && event.key === 'ArrowUp') - let nextHeight: number | undefined - if (grows) nextHeight = clampedHeight() + step - if (shrinks) nextHeight = clampedHeight() - step - if (event.key === 'Home') nextHeight = PANEL_CLOSE_THRESHOLD - if (event.key === 'End') nextHeight = maxHeight() - if (nextHeight === undefined) return - event.preventDefault() + const [resizeHandle, setResizeHandle] = createSignal() + const setHeight = (nextHeight: number) => props.handleHeightChange?.(Math.min(maxHeight(), nextHeight)) - } + // The arrow towards the page grows the panel, by more with Shift. Home closes + // it and End makes it as tall as it gets. + const growBy = (step: number) => () => + setHeight( + clampedHeight() + (settings().panelLocation === 'bottom' ? step : -step), + ) + createHotkeys( + [ + { hotkey: 'ArrowUp', callback: growBy(10) }, + { hotkey: 'Shift+ArrowUp', callback: growBy(50) }, + { hotkey: 'ArrowDown', callback: growBy(-10) }, + { hotkey: 'Shift+ArrowDown', callback: growBy(-50) }, + { hotkey: 'Home', callback: () => setHeight(PANEL_CLOSE_THRESHOLD) }, + { hotkey: 'End', callback: () => setHeight(maxHeight()) }, + ], + () => ({ + // The handle isn't rendered in the PiP window, but its ref keeps the old + // element. + target: + props.handleDragStart && pip().pipWindow === null + ? (resizeHandle() ?? null) + : null, + meta: { name: 'Resize the devtools panel' }, + }), + ) return (
{props.handleDragStart && pip().pipWindow === null ? (
) : null} {props.children} diff --git a/packages/devtools/src/components/plugin-workspace.tsx b/packages/devtools/src/components/plugin-workspace.tsx index 489164558..878a87552 100644 --- a/packages/devtools/src/components/plugin-workspace.tsx +++ b/packages/devtools/src/components/plugin-workspace.tsx @@ -8,6 +8,7 @@ import { onCleanup, } from 'solid-js' import { Portal } from '@solidjs/web' +import { createHotkeys } from '@tanstack/solid-hotkeys' import { PackageIcon, X } from '@tanstack/devtools-ui/icons' import { createSortable } from '../utils/create-sortable' import { @@ -45,6 +46,7 @@ import { zoneAt, } from '../utils/layout-tree' import type { DropZone, Rect, SplitterHandle } from '../utils/layout-tree' +import type { Hotkey } from '@tanstack/solid-hotkeys' type Box = { w: number; h: number } @@ -93,6 +95,94 @@ const KEYBOARD_STEP_COARSE = 0.1 */ const DRAG_HOLD_MS = 500 +/** The keyboard version of dragging a tab, from `PluginWorkspace`. */ +type TabMoveKeys = { + isHolding: (tabId: string) => boolean + pickUpOrDrop: (tabId: string) => void + cancel: (tabId: string) => void + aim: (tabId: string, zone: DropZone) => void +} + +/** + * Enter or Space picks the focused tab up or drops it, the arrows aim it and + * Escape puts it back. Escape stops there, so it doesn't also close the panel. + */ +const createTabMoveHotkeys = ( + tabId: string, + button: () => HTMLButtonElement | undefined, + keys: TabMoveKeys, +) => + createHotkeys( + () => { + const holding = keys.isHolding(tabId) + const aim = (zone: DropZone) => ({ + callback: () => keys.aim(tabId, zone), + options: { enabled: holding }, + }) + return [ + { hotkey: 'Enter', callback: () => keys.pickUpOrDrop(tabId) }, + { hotkey: 'Space', callback: () => keys.pickUpOrDrop(tabId) }, + { + hotkey: 'Escape', + callback: () => keys.cancel(tabId), + options: { enabled: holding, stopPropagation: true }, + }, + { hotkey: 'ArrowLeft', ...aim('left') }, + { hotkey: 'ArrowRight', ...aim('right') }, + { hotkey: 'ArrowUp', ...aim('top') }, + { hotkey: 'ArrowDown', ...aim('bottom') }, + ] + }, + () => ({ + target: button() ?? null, + meta: { name: 'Move a devtools pane' }, + }), + ) + +/** + * How far each key moves a gutter, as a fraction of the split: the arrows + * along the split, by more with Shift. Home and End move it all the way. + */ +const SPLITTER_KEYS: Record< + SplitterHandle['dir'], + ReadonlyArray +> = { + row: [ + ['ArrowLeft', -KEYBOARD_STEP], + ['Shift+ArrowLeft', -KEYBOARD_STEP_COARSE], + ['ArrowRight', KEYBOARD_STEP], + ['Shift+ArrowRight', KEYBOARD_STEP_COARSE], + ['Home', -1], + ['End', 1], + ], + col: [ + ['ArrowUp', -KEYBOARD_STEP], + ['Shift+ArrowUp', -KEYBOARD_STEP_COARSE], + ['ArrowDown', KEYBOARD_STEP], + ['Shift+ArrowDown', KEYBOARD_STEP_COARSE], + ['Home', -1], + ['End', 1], + ], +} + +const createSplitterHotkeys = ( + splitter: () => HTMLDivElement | undefined, + handle: () => SplitterHandle, + resizeBy: (handle: SplitterHandle, delta: number) => void, +) => + createHotkeys( + () => + SPLITTER_KEYS[handle().dir].map(([hotkey, delta]) => ({ + hotkey, + // Read at key time: the gutter may have been re-measured since. + callback: () => resizeBy(handle(), delta), + })), + () => ({ + target: splitter() ?? null, + meta: { name: 'Resize devtools panes' }, + }), + ) + /** * One group's tab bar. Split out so each bar can own its own `createSortable` * binding — the primitive is per-container, and all bars share a `group` so a tab @@ -116,7 +206,7 @@ const GroupTabBar = (props: { onSelect: (tabId: string) => void onClose: (tabId: string) => void onPointerDown: (tabId: string, event: PointerEvent) => void - onKeyDown: (tabId: string, event: KeyboardEvent) => void + moveKeys: TabMoveKeys }) => { const styles = createStyles() // Plugin ids are the items: a primitive is its own key, so no key accessor is @@ -148,53 +238,59 @@ const GroupTabBar = (props: { }} > - {(tabId, index) => ( - - {/* Only this span carries the sortable key. The drag engine listens + {(tabId, index) => { + const [tabButton, setTabButton] = createSignal() + createTabMoveHotkeys(tabId, tabButton, props.moveKeys) + return ( + + {/* Only this span carries the sortable key. The drag engine listens globally and walks *up* from whatever the pointer hit looking for that key, so anything inside here is a drag surface no matter what its own handlers do — `stopPropagation` cannot help. Keeping the close button outside is what makes clicking it never start a drag. */} - + + + + {/* Sibling of the row, laid over its right end. */} - {/* Sibling of the row, laid over its right end. */} - - - )} + ) + }}
) @@ -616,21 +712,8 @@ export const PluginWorkspace = (props: { setLayout(resetSplit(layout(), handle.path, handle.gutterIndex)) } - const resizeFromKeyboard = (handle: SplitterHandle, event: KeyboardEvent) => { - const step = event.shiftKey ? KEYBOARD_STEP_COARSE : KEYBOARD_STEP - const grows = - handle.dir === 'row' - ? event.key === 'ArrowRight' - : event.key === 'ArrowDown' - const shrinks = - handle.dir === 'row' ? event.key === 'ArrowLeft' : event.key === 'ArrowUp' - let delta: number | undefined - if (grows) delta = step - if (shrinks) delta = -step - if (event.key === 'Home') delta = -1 - if (event.key === 'End') delta = 1 - if (delta === undefined) return - event.preventDefault() + /** Moves a gutter by a fraction of the split; -1 or 1 moves it all the way. */ + const resizeSplitterBy = (handle: SplitterHandle, delta: number) => { const minFraction = handle.extent > 0 ? (handle.dir === 'row' ? MIN_PANE_SIZE.w : MIN_PANE_SIZE.h) / @@ -647,17 +730,14 @@ export const PluginWorkspace = (props: { * mouse can do to the layout is reachable this way, which matters because the * pointer gestures are suppressed while detached into a PiP window. */ - const moveModeKeys = (tabId: string, event: KeyboardEvent) => { - const holding = held()?.tabId === tabId - if (event.key === 'Escape' && holding) { - event.preventDefault() + const tabMoveKeys: TabMoveKeys = { + isHolding: (tabId) => held()?.tabId === tabId, + cancel: (tabId) => { clearDrag() announce(`${titleOf(tabId)} left where it was`) - return - } - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - if (!holding) { + }, + pickUpOrDrop: (tabId) => { + if (held()?.tabId !== tabId) { setHeld({ tabId }) setDropTarget(null) announce( @@ -676,56 +756,46 @@ export const PluginWorkspace = (props: { `${titleOf(tabId)} ${target.willStack ? 'stacked as a tab' : `split to the ${target.zone}`}`, ) } - return - } - if (!holding) return - - const zoneForKey: Record = { - ArrowLeft: 'left', - ArrowRight: 'right', - ArrowUp: 'top', - ArrowDown: 'bottom', - } - const zone = zoneForKey[event.key] - if (zone === undefined) return - event.preventDefault() - const group = groupOf(tabId) - if (group === null) return - // Aim at the neighbour in that direction if there is one, otherwise split - // the tab's own group, which is how a lone pane gets divided by keyboard. - const rect = groupRects()[group.id] - const neighbour = groups().find((entry) => { - if (entry.id === group.id) return false - const other = groupRects()[entry.id] - if (!other || !rect) return false - return zone === 'left' - ? other.left + other.width <= rect.left + 1 - : zone === 'right' - ? other.left >= rect.left + rect.width - 1 - : zone === 'top' - ? other.top + other.height <= rect.top + 1 - : other.top >= rect.top + rect.height - 1 - }) - setDropTarget( - neighbour - ? { groupId: neighbour.id, zone: 'center', willStack: true } - : resolveTarget(group.id, { - x: - (rect?.left ?? 0) + - (zone === 'left' - ? 1 - : zone === 'right' - ? (rect?.width ?? 0) - 1 - : (rect?.width ?? 0) / 2), - y: - (rect?.top ?? 0) + - (zone === 'top' - ? 1 - : zone === 'bottom' - ? (rect?.height ?? 0) - 1 - : (rect?.height ?? 0) / 2), - }), - ) + }, + aim: (tabId, zone) => { + const group = groupOf(tabId) + if (group === null) return + // Aim at the neighbour in that direction if there is one, otherwise split + // the tab's own group, which is how a lone pane gets divided by keyboard. + const rect = groupRects()[group.id] + const neighbour = groups().find((entry) => { + if (entry.id === group.id) return false + const other = groupRects()[entry.id] + if (!other || !rect) return false + return zone === 'left' + ? other.left + other.width <= rect.left + 1 + : zone === 'right' + ? other.left >= rect.left + rect.width - 1 + : zone === 'top' + ? other.top + other.height <= rect.top + 1 + : other.top >= rect.top + rect.height - 1 + }) + setDropTarget( + neighbour + ? { groupId: neighbour.id, zone: 'center', willStack: true } + : resolveTarget(group.id, { + x: + (rect?.left ?? 0) + + (zone === 'left' + ? 1 + : zone === 'right' + ? (rect?.width ?? 0) - 1 + : (rect?.width ?? 0) / 2), + y: + (rect?.top ?? 0) + + (zone === 'top' + ? 1 + : zone === 'bottom' + ? (rect?.height ?? 0) - 1 + : (rect?.height ?? 0) / 2), + }), + ) + }, } /** The highlight for where a held tab would land. */ @@ -791,7 +861,7 @@ export const PluginWorkspace = (props: { onSelect={(tabId) => setLayout(activateTab(layout(), tabId))} onClose={(tabId) => setLayout(closeTab(layout(), tabId))} onPointerDown={startTabDrag} - onKeyDown={moveModeKeys} + moveKeys={tabMoveKeys} /> )} @@ -853,8 +923,11 @@ export const PluginWorkspace = (props: { // geometry (two equal panes) after a third pane opens or the // workspace is re-measured. const rect = () => expandSplitterRect(handle(), PANE_CARD_INSET) + const [splitter, setSplitter] = createSignal() + createSplitterHotkeys(splitter, handle, resizeSplitterBy) return (
startSplitterDrag(handle(), event)} onDblClick={() => resetSplitterDrag(handle())} - onKeyDown={(event) => resizeFromKeyboard(handle(), event)} /> ) }} diff --git a/packages/devtools/src/components/source-inspector.tsx b/packages/devtools/src/components/source-inspector.tsx index ab4453f25..fe3d731b3 100644 --- a/packages/devtools/src/components/source-inspector.tsx +++ b/packages/devtools/src/components/source-inspector.tsx @@ -1,10 +1,9 @@ import { createEffect, createMemo, createSignal, createStore } from 'solid-js' import { createElementSize } from '@solid-primitives/resize-observer' -import { useKeyDownList as getKeyDownList } from '@solid-primitives/keyboard' import { createEventListener } from '@solid-primitives/event-listener' +import { createHeldKeys, resolveModifier } from '@tanstack/solid-hotkeys' import { createDevtoolsSettings } from '../context/use-devtools-context' -import { isHotkeyCombinationPressed } from '../utils/hotkey' export const SourceInspector = () => { const { settings } = createDevtoolsSettings() @@ -30,12 +29,21 @@ export const SourceInspector = () => { }) }) - const downList = getKeyDownList() + const heldKeys = createHeldKeys() const [disabledAfterClick, setDisabledAfterClick] = createSignal(false) + // Exactly the inspect keys: holding another key as well turns it off. const isHighlightingKeysHeld = createMemo(() => { - return isHotkeyCombinationPressed(downList(), settings().inspectHotkey) + const keys = new Set( + settings().inspectHotkey.map((key) => resolveModifier(key)), + ) + const held = heldKeys() + return ( + keys.size > 0 && + held.length === keys.size && + held.every((key) => keys.has(key)) + ) }) createEffect(isHighlightingKeysHeld, (held) => { diff --git a/packages/devtools/src/components/trigger.test.tsx b/packages/devtools/src/components/trigger.test.tsx index 9fe6e4875..1dbb2ef29 100644 --- a/packages/devtools/src/components/trigger.test.tsx +++ b/packages/devtools/src/components/trigger.test.tsx @@ -1,7 +1,9 @@ import { fireEvent, render } from '@solidjs/testing-library' import { createSignal, flush } from 'solid-js' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { HotkeysProvider, getHotkeyManager } from '@tanstack/solid-hotkeys' import { DevtoolsProvider } from '../context/devtools-context' +import { DEVTOOLS_HOTKEY_SCOPE } from '../utils/constants' import { TANSTACK_DEVTOOLS_SETTINGS } from '../utils/storage' import { Trigger, @@ -358,6 +360,56 @@ describe('the drag tooltip', () => { }) }) +describe('magnetic mode hotkey', () => { + beforeEach(() => localStorage.clear()) + + const altM = () => + document.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'm', + code: 'KeyM', + altKey: true, + bubbles: true, + cancelable: true, + }), + ) + + it('toggles magnetic mode with Alt+M while the trigger floats', () => { + const { getByLabelText } = renderTrigger({ triggerMode: 'floating' }) + const button = getByLabelText('Open TanStack Devtools') + const idle = button.className + + altM() + flush() + expect(button.className).not.toBe(idle) + + altM() + flush() + expect(button.className).toBe(idle) + }) + + it('ignores Alt+M while typing in a text field', () => { + const { getByLabelText } = renderTrigger({ triggerMode: 'floating' }) + const button = getByLabelText('Open TanStack Devtools') + const idle = button.className + const input = document.body.appendChild(document.createElement('input')) + input.focus() + + input.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'm', + code: 'KeyM', + altKey: true, + bubbles: true, + cancelable: true, + }), + ) + flush() + expect(button.className).toBe(idle) + input.remove() + }) +}) + describe('escape during a trigger drag', () => { beforeEach(() => { localStorage.clear() @@ -378,7 +430,7 @@ describe('escape during a trigger drag', () => { ) const escape = () => - window.dispatchEvent( + document.dispatchEvent( new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }), ) @@ -421,6 +473,49 @@ describe('escape during a trigger drag', () => { expect(storedSettings().triggerCoords).toEqual({ x: 100, y: 100 }) }) + it('cancels with Shift still held from magnetizing the drag', () => { + const { container, getByLabelText } = renderTrigger({ + triggerMode: 'floating', + }) + const button = getByLabelText('Open TanStack Devtools') + + drag(button, 'pointerdown', 8, 8) + drag(button, 'pointermove', 1016, 760) + document.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'Escape', + shiftKey: true, + bubbles: true, + }), + ) + expect(container.querySelector('[data-tsd-hot-corner]')).toBeNull() + expect(storedSettings().triggerCoords).toEqual({ x: 0, y: 0 }) + }) + + it("leaves Escape to the app's own hotkey when nothing is moving", () => { + // The devtools scope outranks the app's global hotkeys, so a live + // devtools Escape would shadow this one. + const appEscape = vi.fn() + const registration = getHotkeyManager().register('Escape', appEscape) + const [isOpen, setIsOpen] = createSignal(false) + const { unmount } = render(() => ( + + + + + + )) + try { + escape() + expect(appEscape).toHaveBeenCalledOnce() + } finally { + unmount() + registration.unregister() + } + }) + it('leaves a settled trigger alone', () => { const { getByLabelText } = renderTrigger({ triggerMode: 'floating' }) const button = getByLabelText('Open TanStack Devtools') diff --git a/packages/devtools/src/components/trigger.tsx b/packages/devtools/src/components/trigger.tsx index 0bc0cbd08..fa12611a0 100644 --- a/packages/devtools/src/components/trigger.tsx +++ b/packages/devtools/src/components/trigger.tsx @@ -7,6 +7,7 @@ import { onCleanup, } from 'solid-js' import clsx from 'clsx' +import { createFormatForDisplay, createHotkeys } from '@tanstack/solid-hotkeys' import { createDevtoolsSettings } from '../context/use-devtools-context' import { createStyles } from '../styles/use-styles' import { @@ -224,6 +225,7 @@ export const Trigger = (props: { const [magneticMode, setMagneticMode] = createSignal(false) const [shiftMagnetic, setShiftMagnetic] = createSignal(false) const styles = createStyles() + const formatForDisplay = createFormatForDisplay() const isFloating = createMemo(() => settings().triggerMode === 'floating') const docked = createMemo(() => isFloating() && dockedEdge() !== null) @@ -286,11 +288,17 @@ export const Trigger = (props: { let snoozedCorner: TriggerCorner | null = null let tooltipShowTimer: ReturnType | undefined let tooltipHideTimer: ReturnType | undefined + // Mirrors `dragging || raf`, so the Escape hotkey is live only while there + // is a gesture to cancel. A live devtools hotkey outranks the app's own + // global hotkeys for the same key. + const [gestureActive, setGestureActive] = createSignal(false) + const syncGesture = () => setGestureActive(dragging || raf !== undefined) const cancelThrow = () => { if (raf !== undefined) { cancelAnimationFrame(raf) raf = undefined + syncGesture() } } @@ -430,6 +438,7 @@ export const Trigger = (props: { const cancelGesture = () => { if (dragging) { dragging = false + syncGesture() vx = 0 vy = 0 cancelHold() @@ -468,6 +477,7 @@ export const Trigger = (props: { const current = coords() if (!el || !current) { raf = undefined + syncGesture() return } const b = bounds(el) @@ -482,6 +492,7 @@ export const Trigger = (props: { raf = requestAnimationFrame(tick) } else { raf = undefined + syncGesture() setShiftMagnetic(false) flush() const corner = hotCorner() @@ -490,6 +501,7 @@ export const Trigger = (props: { } } raf = requestAnimationFrame(tick) + syncGesture() } const onPointerDown = (e: PointerEvent) => { @@ -512,6 +524,7 @@ export const Trigger = (props: { setPinnedCorner(null) setHotCorner(null) dragging = true + syncGesture() moved = false setShiftMagnetic(e.shiftKey) activePointer = e.pointerId @@ -615,6 +628,7 @@ export const Trigger = (props: { const endDrag = (e: PointerEvent, canThrow: boolean) => { if (!dragging) return dragging = false + syncGesture() cancelHold() hideTooltip() snoozedCorner = null @@ -719,18 +733,29 @@ export const Trigger = (props: { }, ) - createEffect(isFloating, (floating) => { - if (!floating) return - const onKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape' && cancelGesture()) event.stopPropagation() - if (event.altKey && event.key.toLowerCase() === 'm') { - setMagneticMode((v) => !v) - event.stopPropagation() - } - } - window.addEventListener('keydown', onKeyDown) - return () => window.removeEventListener('keydown', onKeyDown) - }) + createHotkeys(() => [ + // Shift may still be held from magnetizing the drag. + ...(['Escape', 'Shift+Escape'] as const).map((hotkey) => ({ + hotkey, + callback: () => cancelGesture(), + options: { + enabled: gestureActive(), + preventDefault: false, + // Escape also closes the panel; both run, as they always have. + conflictBehavior: 'allow' as const, + meta: { name: 'Cancel moving the devtools trigger' }, + }, + })), + ...(['Alt+M', 'Alt+Shift+M'] as const).map((hotkey) => ({ + hotkey, + callback: () => setMagneticMode((v) => !v), + options: { + enabled: isFloating(), + stopPropagation: true, + meta: { name: 'Toggle magnetic mode for the devtools trigger' }, + }, + })), + ]) // Keep the trigger at the same relative spot when the window is resized. createEffect(isFloating, (floating) => { @@ -858,10 +883,14 @@ export const Trigger = (props: { diff --git a/packages/devtools/src/context/devtools-context.test.ts b/packages/devtools/src/context/devtools-context.test.ts index 58c6e6614..516bb298b 100644 --- a/packages/devtools/src/context/devtools-context.test.ts +++ b/packages/devtools/src/context/devtools-context.test.ts @@ -370,6 +370,50 @@ describe('getExistingStateFromStorage - integration tests', () => { expect(state.settings.theme).toBe('light') expect(flattenTabs(state.state.layout)).toEqual(['plugin1']) }) + + it('keeps saved hotkeys that this version can use', () => { + localStorage.setItem( + TANSTACK_DEVTOOLS_SETTINGS, + JSON.stringify({ openHotkey: 'Mod+Shift+D', inspectHotkey: ['Alt'] }), + ) + + const { settings } = getExistingStateFromStorage( + { openHotkey: 'Control+~' } as any, + [], + ) + expect(settings.openHotkey).toBe('Mod+Shift+D') + expect(settings.inspectHotkey).toEqual(['Alt']) + }) + + it('replaces saved hotkeys from older versions with the config, then the defaults', () => { + // The format before TanStack Hotkeys: arrays of keys and `CtrlOrMeta`. + localStorage.setItem( + TANSTACK_DEVTOOLS_SETTINGS, + JSON.stringify({ + openHotkey: ['Control', '~'], + inspectHotkey: ['Shift', 'Alt', 'CtrlOrMeta'], + theme: 'dark', + }), + ) + + const { settings } = getExistingStateFromStorage( + { openHotkey: 'Alt+D' } as any, + [], + ) + expect(settings.openHotkey).toBe('Alt+D') + expect(settings.inspectHotkey).toEqual(['Shift', 'Alt', 'Mod']) + // Other saved settings are kept. + expect(settings.theme).toBe('dark') + }) + + it('ignores config hotkeys in the old format', () => { + const { settings } = getExistingStateFromStorage( + { openHotkey: ['Control', '~'], inspectHotkey: ['CtrlOrMeta'] } as any, + [], + ) + expect(settings.openHotkey).toBe('Control+~') + expect(settings.inspectHotkey).toEqual(['Shift', 'Alt', 'Mod']) + }) }) describe('provider resilience', () => { diff --git a/packages/devtools/src/context/devtools-context.tsx b/packages/devtools/src/context/devtools-context.tsx index 43278a978..10d227ed1 100644 --- a/packages/devtools/src/context/devtools-context.tsx +++ b/packages/devtools/src/context/devtools-context.tsx @@ -5,6 +5,7 @@ import { createStore, reconcile, } from 'solid-js' +import { validateHotkey } from '@tanstack/hotkeys' import { getDefaultActivePlugins } from '../utils/get-default-active-plugins' import { flattenTabs, repairLayout, singleGroup } from '../utils/layout-tree' import { tryParseJson } from '../utils/sanitize' @@ -16,6 +17,7 @@ import { } from '../utils/storage' import { initialState } from './devtools-store' import type { DevtoolsStore, TanStackDevtoolsTheme } from './devtools-store' +import type { ResolvableModifier } from '@tanstack/hotkeys' import type { JSX } from '@solidjs/web' export interface TanStackDevtoolsPluginProps { @@ -120,12 +122,43 @@ interface ContextProps { ) => void } +const inspectModifiers: ReadonlyArray = [ + 'Shift', + 'Alt', + 'Control', + 'Meta', + 'Mod', +] satisfies Array + +/** + * Drops keyboard settings this version can't use, so the next source (the + * config, then the default) applies. Older versions saved `openHotkey` as an + * array of keys and spelled `Mod` as `CtrlOrMeta`. + */ +const withUsableHotkeys = >( + settings: T | undefined, +): Partial => { + if (!settings) return {} + const { openHotkey, inspectHotkey, ...rest } = settings + const usable: Partial = {} + if (typeof openHotkey === 'string' && validateHotkey(openHotkey).valid) { + usable.openHotkey = openHotkey + } + if ( + Array.isArray(inspectHotkey) && + inspectHotkey.length > 0 && + inspectHotkey.every((key) => inspectModifiers.includes(key)) + ) { + usable.inspectHotkey = inspectHotkey + } + return { ...rest, ...usable } as Partial +} + const getSettings = () => { const settingsString = getStorageItem(TANSTACK_DEVTOOLS_SETTINGS) - const settings = tryParseJson(settingsString) - return { - ...settings, - } + return withUsableHotkeys( + tryParseJson(settingsString), + ) } const generatePluginId = (plugin: TanStackDevtoolsPlugin, index: number) => { @@ -208,7 +241,7 @@ export const getExistingStateFromStorage = ( }, settings: { ...initialState.settings, - ...config, + ...withUsableHotkeys(config), ...settings, // Not in the settings tab, so the config wins over a stored value. hideInAutomation: diff --git a/packages/devtools/src/context/devtools-store.ts b/packages/devtools/src/context/devtools-store.ts index e0eb9988b..2d672901e 100644 --- a/packages/devtools/src/context/devtools-store.ts +++ b/packages/devtools/src/context/devtools-store.ts @@ -1,3 +1,4 @@ +import type { Hotkey, ResolvableModifier } from '@tanstack/hotkeys' import type { TabName } from '../tabs' import type { LayoutNode } from '../utils/layout-tree' import type { TanStackDevtoolsPlugin } from './devtools-context' @@ -6,17 +7,6 @@ import type { TanStackDevtoolsPlugin } from './devtools-context' // public types of this package do not import devtools-ui, which is bundled. export type TanStackDevtoolsTheme = 'light' | 'dark' -type ModifierKey = 'Alt' | 'Control' | 'Meta' | 'Shift' | 'CtrlOrMeta' -type KeyboardKey = ModifierKey | (string & {}) -export type { ModifierKey, KeyboardKey } -export const keyboardModifiers: Array = [ - 'Alt', - 'Control', - 'Meta', - 'Shift', - 'CtrlOrMeta', -] - type TriggerPosition = | 'top-left' | 'top-right' @@ -94,15 +84,18 @@ export type DevtoolsStore = { */ panelLocation: 'top' | 'bottom' /** - * The hotkey to open the dev tools - * @default ["Control", "~"] + * The hotkey that opens and closes the dev tools, in TanStack Hotkeys + * syntax. `Mod` is Command on macOS and Control elsewhere. + * @default "Control+~" */ - openHotkey: Array + openHotkey: Hotkey /** - * The hotkey to open the source inspector - * @default ["Shift", "Alt", "CtrlOrMeta"] + * The modifiers to hold for the source inspector. It is active while + * exactly these keys are held. `Mod` is Command on macOS and Control + * elsewhere. + * @default ["Shift", "Alt", "Mod"] */ - inspectHotkey: Array + inspectHotkey: Array /** * Whether to require the URL flag to open the dev tools * @default false @@ -210,8 +203,8 @@ export const initialState: DevtoolsStore = { triggerCorner: undefined, triggerEdge: undefined, panelLocation: 'bottom', - openHotkey: ['Control', '~'], - inspectHotkey: ['Shift', 'Alt', 'CtrlOrMeta'], + openHotkey: 'Control+~', + inspectHotkey: ['Shift', 'Alt', 'Mod'], requireUrlFlag: false, urlFlag: 'tanstack-devtools', hideInAutomation: false, diff --git a/packages/devtools/src/devtools.tsx b/packages/devtools/src/devtools.tsx index 69d2defbe..7f55341a1 100644 --- a/packages/devtools/src/devtools.tsx +++ b/packages/devtools/src/devtools.tsx @@ -5,8 +5,8 @@ import { createSignal, onCleanup, } from 'solid-js' -import { createShortcut } from '@solid-primitives/keyboard' import { Portal } from '@solidjs/web' +import { HotkeysProvider, createHotkeys } from '@tanstack/solid-hotkeys' import { ThemeContextProvider } from '@tanstack/devtools-ui' import { devtoolsEventClient } from '@tanstack/devtools-client' import { @@ -20,7 +20,6 @@ import { import { createDisableTabbing } from './hooks/use-disable-tabbing' import { createModalHost } from './hooks/use-modal-host' import { TANSTACK_DEVTOOLS } from './utils/storage' -import { getHotkeyPermutations } from './utils/hotkey' import { Trigger } from './components/trigger' import { MainPanel } from './components/main-panel' import { ContentPanel } from './components/content-panel' @@ -29,7 +28,11 @@ import { createPiPWindow } from './context/pip-context' import { SourceInspector } from './components/source-inspector' import { WorkbenchHeader } from './components/workbench-header' import { PluginsStrip } from './components/plugins-strip' -import { PANEL_CLOSE_THRESHOLD } from './utils/constants' +import { + DEVTOOLS_HOTKEY_SCOPE, + OPEN_HOTKEY_NAME, + PANEL_CLOSE_THRESHOLD, +} from './utils/constants' const themeDocumentOwners = new WeakMap>() const previousThemeAttributes = new WeakMap() @@ -69,7 +72,24 @@ const clearDocumentTheme = (document: Document, owner: symbol) => { previousThemeAttributes.delete(document) } +/** + * Every devtools hotkey is in one scope, so an app with an exclusive scope can + * let them through with `exclusive: { allow: ['tanstack-devtools'] }`. The + * devtools never stopped key presses from reaching the app's own listeners, so + * no hotkey stops propagation unless it says so. + */ export default function DevTools() { + return ( + + + + ) +} + +function DevtoolsShell() { const { settings } = createDevtoolsSettings() const { state } = createDevtoolsState() const { setHeight } = createHeight() @@ -152,14 +172,13 @@ export default function DevTools() { document.addEventListener('mouseup', stop) } - const onEscape = (event: KeyboardEvent) => { - if (event.key === 'Escape' && isOpen() && !hiddenInAutomation()) - toggleOpen() - } - window.addEventListener('keydown', onEscape) - onCleanup(() => window.removeEventListener('keydown', onEscape)) createDisableTabbing(isOpen) - createModalHost(() => settings().openAsModal, rootEl, isOpen) + const modalHost = createModalHost( + () => settings().openAsModal, + rootEl, + isOpen, + toggleOpen, + ) createEffect(rootEl, (element) => { if (element) { element.style.setProperty( @@ -168,22 +187,39 @@ export default function DevTools() { ) } }) - const isEditableTarget = (element: Element | null) => { - if (!element || !(element instanceof HTMLElement)) return false - if (element.isContentEditable) return true - if (['INPUT', 'TEXTAREA', 'SELECT'].includes(element.tagName)) return true - return element.getAttribute('role') === 'textbox' - } - // A memo owns what it creates, so changing the hotkey disposes the old - // shortcuts before registering the new ones. - createMemo(() => { - for (const permutation of getHotkeyPermutations(settings().openHotkey)) { - createShortcut(permutation, () => { - if (!hiddenInAutomation() && !isEditableTarget(document.activeElement)) - toggleOpen() - }) - } - }) + createHotkeys(() => [ + { + hotkey: settings().openHotkey, + callback: toggleOpen, + options: { + enabled: !hiddenInAutomation(), + // Never while typing in a field, whatever the hotkey. + ignoreInputs: true, + requireReset: true, + meta: { + name: OPEN_HOTKEY_NAME, + description: 'Opens and closes TanStack Devtools', + }, + }, + }, + { + hotkey: 'Escape', + callback: toggleOpen, + options: { + enabled: isOpen() && !hiddenInAutomation(), + // An Escape for an open dialog or popover of the app goes to it, not + // here. In the modal host the devtools are the topmost dialog, and only + // a hotkey inside it keeps Escape. + target: modalHost() ?? document, + // Only in the modal host: it keeps the browser from also closing the + // app dialog under the host. + preventDefault: modalHost() !== undefined, + // The trigger's Escape cancels a drag; both run, as they always have. + conflictBehavior: 'allow', + meta: { name: 'Close TanStack Devtools' }, + }, + }, + ]) const { theme } = createTheme() createEffect( diff --git a/packages/devtools/src/hooks/use-modal-host.ts b/packages/devtools/src/hooks/use-modal-host.ts index 85d0c722d..750a490e5 100644 --- a/packages/devtools/src/hooks/use-modal-host.ts +++ b/packages/devtools/src/hooks/use-modal-host.ts @@ -1,4 +1,4 @@ -import { createEffect } from 'solid-js' +import { createEffect, createSignal } from 'solid-js' import type { Accessor } from 'solid-js' /** @@ -10,14 +10,21 @@ import type { Accessor } from 'solid-js' * devtools root into a modal dialog of its own, shown on top of the app's. It * moves the root back when the panel or the app dialog closes. The app dialog * is inert in the meantime. + * + * Returns the host dialog while it is open. Escape then has to be handled + * inside the host, the topmost dialog, so the app dialog under it stays open. + * A close request that reaches the host anyway, such as Escape with the focus + * outside it, calls `onCancel` instead of closing the host. */ export function createModalHost( enabled: Accessor, root: Accessor, isOpen: Accessor, -) { + onCancel: () => void, +): Accessor { // Set while a host is installed, so the open state can re-sync it. let syncHost: (() => void) | undefined + const [openHost, setOpenHost] = createSignal() createEffect( () => (enabled() ? root() : undefined), @@ -30,16 +37,14 @@ export function createModalHost( // out against the viewport. host.style.cssText = 'position:fixed;inset:0;width:0;height:0;max-width:none;max-height:none;margin:0;padding:0;border:0;overflow:visible;background:transparent' - // Escape closes the panel through the devtools' own keydown handler, which - // also closes this dialog. Without preventDefault the browser then sends - // the same Escape to the app dialog and closes it too. The capture phase - // on the window sees the key wherever the focus is. - const onKeyDown = (event: KeyboardEvent) => { - if (host.open && event.key === 'Escape') event.preventDefault() - } - doc.defaultView?.addEventListener('keydown', onKeyDown, true) + // Focusable, so a click on plain text in the devtools focuses the host + // instead of the page body, and Escape reaches the host's hotkey. + host.tabIndex = -1 // The dialog must never close by itself, or the root stays hidden in it. - host.addEventListener('cancel', (event) => event.preventDefault()) + host.addEventListener('cancel', (event) => { + event.preventDefault() + onCancel() + }) let home: Node | null = null const sync = () => { @@ -59,6 +64,7 @@ export function createModalHost( home?.appendChild(element) host.remove() } + setOpenHost(host.open ? host : undefined) } // `showModal()` and `close()` toggle the `open` attribute. Removing an open @@ -89,16 +95,18 @@ export function createModalHost( return () => { syncHost = undefined - doc.defaultView?.removeEventListener('keydown', onKeyDown, true) observer.disconnect() if (host.open) { host.close() home?.appendChild(element) } host.remove() + setOpenHost(undefined) } }, ) createEffect(isOpen, () => syncHost?.()) + + return openHost } diff --git a/packages/devtools/src/tabs/hotkey-config.tsx b/packages/devtools/src/tabs/hotkey-config.tsx index f7c0cd9de..f7a34a2d6 100644 --- a/packages/devtools/src/tabs/hotkey-config.tsx +++ b/packages/devtools/src/tabs/hotkey-config.tsx @@ -1,107 +1,150 @@ -import { Show } from 'solid-js' -import { Button, Input } from '@tanstack/devtools-ui' +import { For, Show, createSignal } from 'solid-js' +import { + createFormatForDisplay, + createHotkeyRecorder, + resolveModifier, +} from '@tanstack/solid-hotkeys' +import { Button } from '@tanstack/devtools-ui' -import { uppercaseFirstLetter } from '../utils/sanitize' import { createStyles } from '../styles/use-styles' -import type { KeyboardKey } from '../context/devtools-store' +import { OPEN_HOTKEY_NAME } from '../utils/constants' +import type { + Hotkey, + RecorderRejection, + ResolvableModifier, +} from '@tanstack/solid-hotkeys' -interface HotkeyConfigProps { +const rejectionMessage = (rejection: RecorderRejection) => { + if (rejection.reason === 'conflict') { + const names = (rejection.conflicts ?? []).map( + ({ registration }) => + registration.options.meta?.name ?? registration.hotkey, + ) + return `Already used by ${names.join(', ')}. Press another shortcut.` + } + return "That shortcut can't be used. Press another one." +} + +/** Records the open shortcut from a key press. */ +export const OpenHotkeyConfig = (props: { title: string description: string - hotkey: Array - modifiers: Array - onHotkeyChange: (hotkey: Array) => void -} + hotkey: Hotkey + onHotkeyChange: (hotkey: Hotkey) => void +}) => { + const styles = createStyles() + const formatForDisplay = createFormatForDisplay() + const [rejection, setRejection] = createSignal(null) + const recorder = createHotkeyRecorder({ + onRecord: (hotkey) => { + setRejection(null) + props.onHotkeyChange(hotkey) + }, + onReject: (rejected) => setRejection(rejectionMessage(rejected)), + onCancel: () => setRejection(null), + onClear: () => setRejection(null), + // The current open hotkey is the one being replaced, not a conflict. + detectConflicts: { + exclude: (registration) => + registration.options.meta?.name === OPEN_HOTKEY_NAME, + }, + }) -const MODIFIER_DISPLAY_NAMES: Record = { - Shift: 'Shift', - Alt: 'Alt', - Meta: 'Meta', - Control: 'Control', - CtrlOrMeta: 'Ctrl Or Meta', + return ( +
+

{props.title}

+

{props.description}

+
+ +
+ + {(message) => ( + + )} + +

+ Shortcut is{' '} + + {formatForDisplay(props.hotkey)} + +

+
+ ) } -export const HotkeyConfig = (props: HotkeyConfigProps) => { +/** Picks the modifiers to hold, for the source inspector. */ +export const HeldModifiersConfig = (props: { + title: string + description: string + modifiers: Array + value: Array + onChange: (value: Array) => void +}) => { const styles = createStyles() + const formatForDisplay = createFormatForDisplay() + const label = (modifier: ResolvableModifier) => + formatForDisplay(resolveModifier(modifier), { useSymbols: false }) + // `Mod` and the key it stands for on this platform are the same key. + const sameKey = (a: ResolvableModifier, b: ResolvableModifier) => + resolveModifier(a) === resolveModifier(b) + const isHeld = (modifier: ResolvableModifier) => + props.value.some((key) => sameKey(key, modifier)) + // A configured key with no button of its own, such as `Control` on macOS, + // gets one so it can be turned off. + const buttons = () => [ + ...props.modifiers, + ...props.value.filter( + (key) => !props.modifiers.some((modifier) => sameKey(key, modifier)), + ), + ] - const toggleModifier = (modifier: KeyboardKey) => { - if (props.hotkey.includes(modifier)) { - props.onHotkeyChange(props.hotkey.filter((key) => key !== modifier)) - } else { - const existingModifiers = props.hotkey.filter((key) => - props.modifiers.includes(key as any), - ) - const otherKeys = props.hotkey.filter( - (key) => !props.modifiers.includes(key as any), - ) - props.onHotkeyChange([...existingModifiers, modifier, ...otherKeys]) - } - } - - const getNonModifierValue = () => { - return props.hotkey - .filter((key) => !props.modifiers.includes(key as any)) - .join('+') - } - - const handleKeyInput = (input: string) => { - const makeModifierArray = (key: string) => { - if (key.length === 1) return [uppercaseFirstLetter(key)] - const modifiersArray: Array = [] - for (const character of key) { - const newLetter = uppercaseFirstLetter(character) - if (!modifiersArray.includes(newLetter)) modifiersArray.push(newLetter) - } - return modifiersArray - } - - const hotkeyModifiers = props.hotkey.filter((key) => - props.modifiers.includes(key as any), + const toggle = (modifier: ResolvableModifier) => + props.onChange( + isHeld(modifier) + ? props.value.filter((key) => !sameKey(key, modifier)) + : [...props.value, modifier], ) - const newKeys = input - .split('+') - .flatMap((key) => makeModifierArray(key)) - .filter(Boolean) - props.onHotkeyChange([...hotkeyModifiers, ...newKeys]) - } - - const getDisplayHotkey = () => { - return props.hotkey.join(' + ') - } return (
- {/* `title` names the shortcut, `description` explains it — before, the - description was rendered as the heading and `title` went unused. */}

{props.title}

{props.description}

- - {props.modifiers.map((modifier) => { - const enabled = props.hotkey.includes(modifier) - return ( - - ) - })} - + + {(modifier) => ( + + )} +
-

- Final shortcut is{' '} - {getDisplayHotkey()} + Hold{' '} + + {props.value.map(label).join(' + ')} +

) diff --git a/packages/devtools/src/tabs/marketplace/plugin-section.tsx b/packages/devtools/src/tabs/marketplace/plugin-section.tsx index eea6b4406..e59b2df84 100644 --- a/packages/devtools/src/tabs/marketplace/plugin-section.tsx +++ b/packages/devtools/src/tabs/marketplace/plugin-section.tsx @@ -1,4 +1,5 @@ -import { For, Show } from 'solid-js' +import { For, Show, createSignal } from 'solid-js' +import { createHotkeys } from '@tanstack/solid-hotkeys' import { ChevronDownIcon } from '@tanstack/devtools-ui' import { createStyles } from '../../styles/use-styles' import { PluginCardComponent } from './plugin-card' @@ -39,6 +40,18 @@ const MailIcon = () => ( export const PluginSectionComponent = (props: PluginSectionComponentProps) => { const styles = createStyles() + // A div with the button role: Enter and Space press it, like a button. + const [header, setHeader] = createSignal() + createHotkeys( + [ + { hotkey: 'Enter', callback: () => props.onToggleCollapse() }, + { hotkey: 'Space', callback: () => props.onToggleCollapse() }, + ], + () => ({ + target: header() ?? null, + meta: { name: 'Expand or collapse a marketplace section' }, + }), + ) return (
@@ -48,13 +61,8 @@ export const PluginSectionComponent = (props: PluginSectionComponentProps) => { aria-expanded={props.isCollapsed() ? 'false' : 'true'} data-tsd-control class={styles().pluginMarketplaceSectionHeader} + ref={setHeader} onClick={props.onToggleCollapse} - onKeyDown={(event) => { - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - props.onToggleCollapse() - } - }} >
{ fireEvent.click(getByRole('button', { name: 'Reset' })) expect(select.value).toBe('1') }) + + describe('keyboard', () => { + const savedSettings = () => + JSON.parse(localStorage.getItem(TANSTACK_DEVTOOLS_SETTINGS) ?? '{}') + const pressCtrlK = () => + document.activeElement!.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'k', + code: 'KeyK', + ctrlKey: true, + bubbles: true, + cancelable: true, + }), + ) + + it('records the open shortcut from a key press', () => { + const { getByRole, getByText } = renderSettingsTab() + const record = getByRole('button', { name: 'Record shortcut' }) + fireEvent.click(record) + record.focus() + pressCtrlK() + flush() + + expect(savedSettings().openHotkey).toMatch(/\+K$/) + expect(getByText('Ctrl+K')).toBeTruthy() + }) + + it('rejects a shortcut the app already uses', () => { + const search = getHotkeyManager().register('Mod+K', () => {}, { + meta: { name: 'Search' }, + }) + try { + const { getByRole } = renderSettingsTab() + const record = getByRole('button', { name: 'Record shortcut' }) + fireEvent.click(record) + record.focus() + pressCtrlK() + flush() + + expect(getByRole('alert').textContent).toContain('Search') + expect(savedSettings().openHotkey).toBeUndefined() + } finally { + search.unregister() + } + }) + + it('toggles the modifiers held for the source inspector, but never the last one', () => { + const { getByRole, setSettings } = renderSettingsTab() + setSettings({ inspectHotkey: ['Shift', 'Alt'] }) + + fireEvent.click(getByRole('button', { name: 'Alt' })) + expect(savedSettings().inspectHotkey).toEqual(['Shift']) + expect(getByRole('button', { name: 'Shift' })).toBeDisabled() + + fireEvent.click(getByRole('button', { name: 'Ctrl' })) + expect(savedSettings().inspectHotkey).toEqual(['Shift', 'Mod']) + }) + }) }) diff --git a/packages/devtools/src/tabs/settings-tab.tsx b/packages/devtools/src/tabs/settings-tab.tsx index 603347c4a..b358f594e 100644 --- a/packages/devtools/src/tabs/settings-tab.tsx +++ b/packages/devtools/src/tabs/settings-tab.tsx @@ -17,13 +17,11 @@ import { } from '@tanstack/devtools-ui/icons' import { createDevtoolsSettings } from '../context/use-devtools-context' import { createStyles } from '../styles/use-styles' -import { HotkeyConfig } from './hotkey-config' -import type { KeyboardKey } from '../context/devtools-store' +import { HeldModifiersConfig, OpenHotkeyConfig } from './hotkey-config' export const SettingsTab = () => { const { setSettings, settings } = createDevtoolsSettings() const styles = createStyles() - const modifiers: Array = ['CtrlOrMeta', 'Alt', 'Shift'] return (
{ Customize keyboard shortcuts for quick access.
- setSettings({ openHotkey: hotkey })} /> - - setSettings({ inspectHotkey: hotkey }) - } + description="Keys to hold for the source inspector" + modifiers={['Mod', 'Alt', 'Shift']} + value={settings().inspectHotkey} + onChange={(keys) => setSettings({ inspectHotkey: keys })} />
diff --git a/packages/devtools/src/utils/constants.ts b/packages/devtools/src/utils/constants.ts index 47a3d6647..939b5fc9e 100644 --- a/packages/devtools/src/utils/constants.ts +++ b/packages/devtools/src/utils/constants.ts @@ -60,3 +60,8 @@ export const TRIGGER_EDGE_TAB_LENGTH = 44 export const TRIGGER_EDGE_TAB_PAD = 8 /** How long (ms) the floating trigger's hint stays up before it gets out of the way. */ export const TRIGGER_TOOLTIP_MS = 1500 + +/** The TanStack Hotkeys scope of every devtools hotkey. */ +export const DEVTOOLS_HOTKEY_SCOPE = 'tanstack-devtools' +/** `meta.name` of the open hotkey, so the settings recorder can skip it. */ +export const OPEN_HOTKEY_NAME = 'Toggle TanStack Devtools' diff --git a/packages/devtools/src/utils/hotkey.test.ts b/packages/devtools/src/utils/hotkey.test.ts deleted file mode 100644 index ea654e4b5..000000000 --- a/packages/devtools/src/utils/hotkey.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - getHotkeyPermutations, - isHotkeyCombinationPressed, - normalizeHotkey, -} from './hotkey' -import type { KeyboardKey } from '../context/devtools-store' - -describe('hotkey utilities', () => { - describe('normalizeHotkey', () => { - it('should return unchanged array when CtrlOrMeta is not present', () => { - const hotkey: Array = ['Shift', 'A'] - const result = normalizeHotkey(hotkey) - expect(result).toEqual([['Shift', 'A']]) - }) - - it('should expand CtrlOrMeta to Control and Meta variants', () => { - const hotkey: Array = ['Shift', 'CtrlOrMeta'] - const result = normalizeHotkey(hotkey) - expect(result).toHaveLength(2) - expect(result).toContainEqual(['Shift', 'Control']) - expect(result).toContainEqual(['Shift', 'Meta']) - }) - }) - - describe('getHotkeyPermutations', () => { - it('should generate permutations for modifiers in any order', () => { - const hotkey: Array = ['Shift', 'Control', 'A'] - const result = getHotkeyPermutations(hotkey) - expect(result).toContainEqual(['Shift', 'Control', 'A']) - expect(result).toContainEqual(['Control', 'Shift', 'A']) - }) - - it('should handle CtrlOrMeta expansion with multiple permutations', () => { - const hotkey: Array = ['Shift', 'CtrlOrMeta'] - const result = getHotkeyPermutations(hotkey) - expect(result).toContainEqual(['Shift', 'Control']) - expect(result).toContainEqual(['Control', 'Shift']) - expect(result).toContainEqual(['Shift', 'Meta']) - expect(result).toContainEqual(['Meta', 'Shift']) - }) - - it('should handle single key hotkey with no modifiers', () => { - const hotkey: Array = ['A'] - const result = getHotkeyPermutations(hotkey) - expect(result).toEqual([['A']]) - }) - - it('should not have duplicate permutations', () => { - const hotkey: Array = ['Shift', 'Alt', 'A'] - const result = getHotkeyPermutations(hotkey) - const stringified = result.map((combo) => JSON.stringify(combo)) - const unique = new Set(stringified) - expect(unique.size).toBe(stringified.length) - }) - }) - - describe('isHotkeyCombinationPressed', () => { - it('should match exact key combination', () => { - expect(isHotkeyCombinationPressed(['Shift', 'A'], ['Shift', 'A'])).toBe( - true, - ) - }) - - it('should be case-insensitive', () => { - expect(isHotkeyCombinationPressed(['shift', 'a'], ['Shift', 'A'])).toBe( - true, - ) - }) - - it('should match regardless of modifier order', () => { - expect( - isHotkeyCombinationPressed( - ['A', 'Control', 'Shift'], - ['Shift', 'Control', 'A'], - ), - ).toBe(true) - }) - - it('should handle CtrlOrMeta with Control', () => { - expect( - isHotkeyCombinationPressed( - ['Shift', 'Control'], - ['Shift', 'CtrlOrMeta'], - ), - ).toBe(true) - }) - - it('should handle CtrlOrMeta with Meta', () => { - expect( - isHotkeyCombinationPressed(['Shift', 'Meta'], ['Shift', 'CtrlOrMeta']), - ).toBe(true) - }) - - it('should reject incomplete key combinations', () => { - expect(isHotkeyCombinationPressed(['Shift'], ['Shift', 'A'])).toBe(false) - }) - - it('should reject extra keys', () => { - expect( - isHotkeyCombinationPressed(['Shift', 'A', 'B'], ['Shift', 'A']), - ).toBe(false) - }) - - it('should handle single key hotkey', () => { - expect(isHotkeyCombinationPressed(['A'], ['A'])).toBe(true) - }) - }) -}) diff --git a/packages/devtools/src/utils/hotkey.ts b/packages/devtools/src/utils/hotkey.ts deleted file mode 100644 index fe46db8b3..000000000 --- a/packages/devtools/src/utils/hotkey.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { keyboardModifiers } from '../context/devtools-store' -import { getAllPermutations } from './sanitize' - -import type { KeyboardKey, ModifierKey } from '../context/devtools-store' - -/** Expands CtrlOrMeta into separate Control and Meta variants */ -export const normalizeHotkey = ( - keys: Array, -): Array> => { - // no normalization needed if CtrlOrMeta not used - if (!keys.includes('CtrlOrMeta')) { - return [keys] - } - - return [ - keys.map((key) => (key === 'CtrlOrMeta' ? 'Control' : key)), - keys.map((key) => (key === 'CtrlOrMeta' ? 'Meta' : key)), - ] -} - -/** - * Generates all keyboard permutations for a given hotkey configuration - * Handles CtrlOrMeta expansion and creates all possible combinations - */ -export const getHotkeyPermutations = ( - hotkey: Array, -): Array> => { - const normalizedHotkeys = normalizeHotkey(hotkey) - - return normalizedHotkeys.flatMap((normalizedHotkey) => { - const modifiers = normalizedHotkey.filter((key) => - keyboardModifiers.includes(key as any), - ) as Array - - const nonModifiers = normalizedHotkey.filter( - (key) => !keyboardModifiers.includes(key as any), - ) - - // handle case with no modifiers (just non-modifier keys) - if (modifiers.length === 0) { - return [nonModifiers] - } - - const allModifierCombinations = getAllPermutations(modifiers) - return allModifierCombinations.map((combo) => [...combo, ...nonModifiers]) - }) -} - -/** Checks if the currently pressed keys match any of the hotkey permutations */ -export const isHotkeyCombinationPressed = ( - keys: Array, - hotkey: Array, -): boolean => { - const permutations = getHotkeyPermutations(hotkey) - const pressedKeys = keys.map((key) => key.toUpperCase()) - - return permutations.some( - (combo) => - // every key in the combo must be pressed - combo.every((key) => pressedKeys.includes(String(key).toUpperCase())) && - // and no extra keys beyond the combo - pressedKeys.every((key) => - combo.map((k) => String(k).toUpperCase()).includes(key), - ), - ) -} diff --git a/packages/devtools/src/utils/sanitize.test.ts b/packages/devtools/src/utils/sanitize.test.ts index 1c97f4dc6..dae7331f5 100644 --- a/packages/devtools/src/utils/sanitize.test.ts +++ b/packages/devtools/src/utils/sanitize.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - getAllPermutations, - tryParseJson, - uppercaseFirstLetter, -} from './sanitize' +import { tryParseJson } from './sanitize' describe('tryParseJson', () => { it('should parse a valid JSON string into an object', () => { @@ -28,49 +24,3 @@ describe('tryParseJson', () => { expect(result).toEqual([1, 2, 3]) }) }) - -describe('uppercaseFirstLetter', () => { - it('should uppercase the first letter of a string', () => { - expect(uppercaseFirstLetter('foo')).toBe('Foo') - }) - - it('should return an empty string unchanged', () => { - expect(uppercaseFirstLetter('')).toBe('') - }) - - it('should not modify strings that already start with uppercase', () => { - expect(uppercaseFirstLetter('Bar')).toBe('Bar') - }) - - it('should uppercase only the first letter', () => { - expect(uppercaseFirstLetter('hello world')).toBe('Hello world') - }) -}) - -describe('getAllPermutations', () => { - it('should return 2 permutations for a 2-element array', () => { - const result = getAllPermutations(['a', 'b']) - expect(result).toHaveLength(2) - }) - - it('should return [["a"]] for a single-element array', () => { - const result = getAllPermutations(['a']) - expect(result).toEqual([['a']]) - }) - - it('should return 6 permutations for a 3-element array', () => { - const result = getAllPermutations(['a', 'b', 'c']) - expect(result).toHaveLength(6) - }) - - it('should contain all permutations for a 2-element array', () => { - const result = getAllPermutations(['a', 'b']) - expect(result).toContainEqual(['a', 'b']) - expect(result).toContainEqual(['b', 'a']) - }) - - it('should return an empty array for an empty input', () => { - const result = getAllPermutations([]) - expect(result).toEqual([]) - }) -}) diff --git a/packages/devtools/src/utils/sanitize.ts b/packages/devtools/src/utils/sanitize.ts index 2a1a32ff0..c7dae6578 100644 --- a/packages/devtools/src/utils/sanitize.ts +++ b/packages/devtools/src/utils/sanitize.ts @@ -6,25 +6,3 @@ export const tryParseJson = (json: string | null): T | undefined => { return undefined } } - -export const uppercaseFirstLetter = (value: string) => - value.charAt(0).toUpperCase() + value.slice(1) - -export const getAllPermutations = (arr: Array) => { - const res: Array> = [] - - function permutate(arr: Array, start: number) { - if (start === arr.length - 1) { - res.push([...arr] as any) - return - } - for (let i = start; i < arr.length; i++) { - ;[arr[start], arr[i]] = [arr[i]!, arr[start]!] - permutate(arr, start + 1) - ;[arr[start], arr[i]] = [arr[i]!, arr[start]] - } - } - permutate(arr, 0) - - return res -} diff --git a/packages/devtools/tests/index.test.ts b/packages/devtools/tests/index.test.ts index 886214d50..513cfffce 100644 --- a/packages/devtools/tests/index.test.ts +++ b/packages/devtools/tests/index.test.ts @@ -94,7 +94,7 @@ describe('devtools core boundaries', () => { mountShell({ requireUrlFlag: true, urlFlag: 'tanstack-devtools', - openHotkey: ['Control', '~'], + openHotkey: 'Control+~', }) expect( document.querySelector('[aria-label="Open TanStack Devtools"]'), diff --git a/packages/devtools/tests/workbench.test.tsx b/packages/devtools/tests/workbench.test.tsx index be71180c3..a5b2f06ef 100644 --- a/packages/devtools/tests/workbench.test.tsx +++ b/packages/devtools/tests/workbench.test.tsx @@ -266,7 +266,9 @@ describe('workbench', { timeout: 30_000 }, () => { ) mountWorkbench([plugin('one')], { hideInAutomation: true }) - window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) + document.dispatchEvent( + new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }), + ) const stored = JSON.parse(localStorage.getItem(TANSTACK_DEVTOOLS_STATE)!) expect(stored.persistOpen).toBe(true) @@ -1480,6 +1482,33 @@ describe('workbench', { timeout: 30_000 }, () => { expect(events).not.toContain('destroy:one') }) + it('cancels a keyboard tab move with Escape without closing the panel', () => { + mountWorkbench(['one', 'two'].map(plugin)) + for (const name of ['Plugin one', 'Plugin two']) click(name) + const panel = document.querySelector( + '[data-testid="tanstack-devtools-panel"]', + ) + const tab = document.querySelector( + '[data-testid="plugin-tab-two"]', + )! + const held = () => tab.closest('[data-tsd-held]') + const press = (key: string) => + tab.dispatchEvent( + new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }), + ) + tab.focus() + + press('Enter') + expect(held()).not.toBeNull() + press('Escape') + expect(held()).toBeNull() + expect(panel).toHaveAttribute('data-open', 'true') + + // With nothing held, Escape closes the panel. + press('Escape') + expect(panel).toHaveAttribute('data-open', 'false') + }) + it('gives three active plugins equal shares and a draggable gutter between each', () => { mountWorkbench(['one', 'two', 'three'].map(plugin)) for (const name of ['Plugin one', 'Plugin two', 'Plugin three']) click(name) diff --git a/packages/devtools/tsup.config.ts b/packages/devtools/tsup.config.ts index 1ef462270..3fac75fc1 100644 --- a/packages/devtools/tsup.config.ts +++ b/packages/devtools/tsup.config.ts @@ -61,7 +61,11 @@ export default defineConfig(() => { const parsed_data = parsePresetOptions(preset_options) const tsup_options = withSolidV2(generateTsupOptions(parsed_data), { // Bundled with their Solid copy; see `withSolidV2`. - bundleSolid: [/^@solid-primitives\//, /^@tanstack\/devtools-ui(\/|$)/], + bundleSolid: [ + /^@solid-primitives\//, + /^@tanstack\/devtools-ui(\/|$)/, + /^@tanstack\/solid-hotkeys(\/|$)/, + ], }) return tsup_options.map((option) => ({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8b3b56620..5a381e69e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1563,6 +1563,9 @@ importers: '@tanstack/devtools-event-bus': specifier: workspace:* version: link:../event-bus + '@tanstack/hotkeys': + specifier: ^0.37.0 + version: 0.37.0 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -1576,9 +1579,6 @@ importers: '@solid-primitives/event-listener': specifier: ^3.0.0 version: 3.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) - '@solid-primitives/keyboard': - specifier: ^2.0.0 - version: 2.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) '@solid-primitives/resize-observer': specifier: ^4.0.0 version: 4.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) @@ -1590,22 +1590,25 @@ importers: version: 1.0.0-rc.2(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) '@solidjs/vite-plugin': specifier: ^3.0.0 - version: 3.0.0(@babel/core@7.29.0)(@solidjs/babel-plugin@2.0.0(@babel/core@7.29.0))(@solidjs/web@2.0.0(solid-js@2.0.0))(@testing-library/jest-dom@6.9.1)(solid-js@2.0.0)(vite@8.0.12(@types/node@22.19.15)(esbuild@0.27.4)(jiti@2.7.0)(less@4.6.4)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)) + version: 3.0.0(@babel/core@7.29.0)(@solidjs/babel-plugin@2.0.0(@babel/core@7.29.0))(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0)(vite@8.0.12(esbuild@0.27.4)) '@solidjs/web': specifier: ^2.0.0 version: 2.0.0(solid-js@2.0.0) '@tanstack/devtools-ui': specifier: workspace:* version: link:../devtools-ui + '@tanstack/solid-hotkeys': + specifier: ^0.27.0 + version: 0.27.0(solid-js@2.0.0) solid-js: specifier: ^2.0.0 version: 2.0.0 tsup: specifier: ^8.5.0 - version: 8.5.1(@microsoft/api-extractor@7.47.7(@types/node@22.19.15))(jiti@2.7.0)(postcss@8.5.14)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.3) + version: 8.5.1(postcss@8.5.14) tsup-preset-solid: specifier: ^2.2.0 - version: 2.2.0(esbuild@0.27.4)(solid-js@2.0.0)(tsup@8.5.1(@microsoft/api-extractor@7.47.7(@types/node@22.19.15))(jiti@2.7.0)(postcss@8.5.14)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.3)) + version: 2.2.0(esbuild@0.27.4)(solid-js@2.0.0)(tsup@8.5.1(postcss@8.5.14)) packages/devtools-a11y: dependencies: @@ -5125,12 +5128,6 @@ packages: peerDependencies: solid-js: ^1.6.12 - '@solid-primitives/keyboard@2.0.0': - resolution: {integrity: sha512-ZDYb84vkDQxBsFf15gddBAssQVblAHHTlCDeo1o5G/sBGXL8sHT+rqQwg0w6KPa6CMxHl1sy2qFRtzng4FQ01g==} - peerDependencies: - '@solidjs/web': ^2.0.0 - solid-js: ^2.0.0 - '@solid-primitives/media@2.3.5': resolution: {integrity: sha512-LX9fB5WDaK87FMDtUB1qokBOfT2et9Uobv/zZaKLH9caFSz4+P70MBKEIBHcZQy+9MV5M2XvGYLTbLskjkzMjA==} peerDependencies: @@ -5551,6 +5548,10 @@ packages: resolution: {integrity: sha512-DR9t6lfLVdrjgCwpglrR9DR7Ok8/HlXjcOE+goWXF3zyuLUO/ug7vMbSFxTqrQTtbRghJfyhmIZ0S6LhPIy44w==} engines: {node: '>=20.19'} + '@tanstack/hotkeys@0.37.0': + resolution: {integrity: sha512-6d+n+3zhgq3Iw6uuR+kB7P0GpymVO7OPLJ7B5eZBXuRxLp0kO2ZyAu7bcCLmdplZIPyus6IdUnqBTH5JkD77dg==} + engines: {node: '>=20'} + '@tanstack/intent@0.0.14': resolution: {integrity: sha512-83cjen+tYll6z0MIN0JC9GuMljUkfYfHFDOLhmROz4XMmbD/0ZjvKNOsFgpO7eq957XHB/qyK+hCO+3OS/D6HQ==} hasBin: true @@ -5773,6 +5774,12 @@ packages: resolution: {integrity: sha512-xyiLWEKjfBAVhauDSSjXxyf7s8elU6SM+V050sbkofvGmIIvkwPFtDsX7Gvwh14kBd6iCwAT+RiPvXTxAptY0Q==} engines: {node: '>=20.19'} + '@tanstack/solid-hotkeys@0.27.0': + resolution: {integrity: sha512-hM6HkqqteRaZNEDq1M3M3fX//kWLnY6Sp+8ajE1tNlwPLcu9pDCDw2dQmBeU0ojIWBxUKBzpRKJhiaGatHQ+vg==} + engines: {node: '>=22.12.0'} + peerDependencies: + solid-js: ^2.0.0 + '@tanstack/solid-query-devtools@6.0.0-rc.5': resolution: {integrity: sha512-T3FPk9vQkUP9tPLhGl0KXQdN1wWXn+RpDZ9WZwlf7U6r2UAPJJiWp+qBICJsAFRkaumiRB3tm2WOPv0j1msISw==} peerDependencies: @@ -13536,13 +13543,6 @@ snapshots: '@tybys/wasm-util': 0.10.2 optional: true - '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': - dependencies: - '@emnapi/core': 1.10.0 - '@emnapi/runtime': 1.10.0 - '@tybys/wasm-util': 0.10.1 - optional: true - '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: '@emnapi/core': 1.11.3 @@ -13550,6 +13550,13 @@ snapshots: '@tybys/wasm-util': 0.10.1 optional: true + '@napi-rs/wasm-runtime@1.2.7(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + dependencies: + '@emnapi/core': 1.10.0 + '@emnapi/runtime': 1.10.0 + '@tybys/wasm-util': 0.10.4 + optional: true + '@napi-rs/wasm-runtime@1.2.7(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: '@emnapi/core': 1.11.3 @@ -14031,7 +14038,7 @@ snapshots: dependencies: '@emnapi/core': 1.10.0 '@emnapi/runtime': 1.10.0 - '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/wasm-runtime': 1.2.7(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) optional: true '@rolldown/binding-wasm32-wasi@1.0.0-rc.4(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': @@ -14478,14 +14485,6 @@ snapshots: '@solid-primitives/utils': 6.4.0(solid-js@2.0.0) solid-js: 2.0.0 - '@solid-primitives/keyboard@2.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0)': - dependencies: - '@solid-primitives/event-listener': 3.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) - '@solid-primitives/rootless': 2.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) - '@solid-primitives/utils': 7.0.0(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0) - '@solidjs/web': 2.0.0(solid-js@2.0.0) - solid-js: 2.0.0 - '@solid-primitives/media@2.3.5(solid-js@2.0.0)': dependencies: '@solid-primitives/event-listener': 2.4.5(solid-js@2.0.0) @@ -14624,6 +14623,20 @@ snapshots: '@solidjs/babel-plugin': 2.0.0(@babel/core@7.29.0) '@testing-library/jest-dom': 6.9.1 + '@solidjs/vite-plugin@3.0.0(@babel/core@7.29.0)(@solidjs/babel-plugin@2.0.0(@babel/core@7.29.0))(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0)(vite@8.0.12(esbuild@0.27.4))': + dependencies: + '@ampproject/remapping': 2.3.0 + '@solidjs/compiler': 2.0.0 + '@solidjs/web': 2.0.0(solid-js@2.0.0) + magic-string: 0.30.21 + merge-anything: 5.1.7 + solid-js: 2.0.0 + vite: 8.0.12(esbuild@0.27.4) + vitefu: 1.1.2(vite@8.0.12(esbuild@0.27.4)) + optionalDependencies: + '@babel/core': 7.29.0 + '@solidjs/babel-plugin': 2.0.0(@babel/core@7.29.0) + '@solidjs/web@2.0.0(solid-js@2.0.0)': dependencies: csstype: 3.2.3 @@ -14927,6 +14940,8 @@ snapshots: '@tanstack/history@1.162.1': {} + '@tanstack/hotkeys@0.37.0': {} + '@tanstack/intent@0.0.14': dependencies: yaml: 2.8.3 @@ -15265,6 +15280,11 @@ snapshots: transitivePeerDependencies: - supports-color + '@tanstack/solid-hotkeys@0.27.0(solid-js@2.0.0)': + dependencies: + '@tanstack/hotkeys': 0.37.0 + solid-js: 2.0.0 + '@tanstack/solid-query-devtools@6.0.0-rc.5(@tanstack/solid-query@6.0.0-rc.5(@solidjs/web@2.0.0(solid-js@2.0.0))(solid-js@2.0.0))(solid-js@2.0.0)': dependencies: '@tanstack/query-devtools': 5.101.4 @@ -19984,6 +20004,12 @@ snapshots: tsx: 4.21.0 yaml: 2.8.3 + postcss-load-config@6.0.1(postcss@8.5.14): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + postcss: 8.5.14 + postcss-media-query-parser@0.2.3: {} postcss-safe-parser@7.0.1(postcss@8.5.14): @@ -21178,6 +21204,15 @@ snapshots: - solid-js - supports-color + tsup-preset-solid@2.2.0(esbuild@0.27.4)(solid-js@2.0.0)(tsup@8.5.1(postcss@8.5.14)): + dependencies: + esbuild-plugin-solid: 0.5.0(esbuild@0.27.4)(solid-js@2.0.0) + tsup: 8.5.1(postcss@8.5.14) + transitivePeerDependencies: + - esbuild + - solid-js + - supports-color + tsup@8.5.1(@microsoft/api-extractor@7.47.7(@types/node@22.19.15))(jiti@2.7.0)(postcss@8.5.14)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.3): dependencies: bundle-require: 5.1.0(esbuild@0.27.4) @@ -21207,6 +21242,33 @@ snapshots: - tsx - yaml + tsup@8.5.1(postcss@8.5.14): + dependencies: + bundle-require: 5.1.0(esbuild@0.27.4) + cac: 6.7.14 + chokidar: 4.0.3 + consola: 3.4.2 + debug: 4.4.3 + esbuild: 0.27.4 + fix-dts-default-cjs-exports: 1.0.1 + joycon: 3.1.1 + picocolors: 1.1.1 + postcss-load-config: 6.0.1(postcss@8.5.14) + resolve-from: 5.0.0 + rollup: 4.60.1 + source-map: 0.7.6 + sucrase: 3.35.1 + tinyexec: 0.3.2 + tinyglobby: 0.2.16 + tree-kill: 1.2.2 + optionalDependencies: + postcss: 8.5.14 + transitivePeerDependencies: + - jiti + - supports-color + - tsx + - yaml + tsx@4.21.0: dependencies: esbuild: 0.27.4 @@ -21564,10 +21626,25 @@ snapshots: tsx: 4.21.0 yaml: 2.8.3 + vite@8.0.12(esbuild@0.27.4): + dependencies: + lightningcss: 1.32.0 + picomatch: 4.0.5 + postcss: 8.5.14 + rolldown: 1.0.0 + tinyglobby: 0.2.16 + optionalDependencies: + esbuild: 0.27.4 + fsevents: 2.3.3 + vitefu@1.1.2(vite@8.0.12(@types/node@22.19.15)(esbuild@0.27.4)(jiti@2.7.0)(less@4.6.4)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3)): optionalDependencies: vite: 8.0.12(@types/node@22.19.15)(esbuild@0.27.4)(jiti@2.7.0)(less@4.6.4)(sass@1.99.0)(tsx@4.21.0)(yaml@2.8.3) + vitefu@1.1.2(vite@8.0.12(esbuild@0.27.4)): + optionalDependencies: + vite: 8.0.12(esbuild@0.27.4) + vitest@4.1.10(@opentelemetry/api@1.10.0)(@types/node@22.19.15)(happy-dom@20.9.0)(jsdom@27.4.0)(vite@7.3.2(@types/node@22.19.15)(jiti@2.7.0)(less@4.6.4)(lightningcss@1.32.0)(sass@1.97.3)(tsx@4.21.0)(yaml@2.8.3)): dependencies: '@vitest/expect': 4.1.10 From cd7a133af920d7de3788658797fbee2f3d6f1848 Mon Sep 17 00:00:00 2001 From: Kevin Van Cott Date: Fri, 27 Nov 2026 22:56:30 -0600 Subject: [PATCH 2/2] test(e2e): Press the open hotkey with the keyboard The react-vite specs dispatched synthetic keydown events on window, the target @solid-primitives/keyboard listened on. TanStack Hotkeys listens on the document, so press Control+Shift+Backquote, which types ~. --- e2e/apps/react-vite/tests/hotkey.spec.ts | 19 +++---------------- .../react-vite/tests/open-as-modal.spec.ts | 13 ++----------- 2 files changed, 5 insertions(+), 27 deletions(-) diff --git a/e2e/apps/react-vite/tests/hotkey.spec.ts b/e2e/apps/react-vite/tests/hotkey.spec.ts index 038c9bc18..36e2bc7ec 100644 --- a/e2e/apps/react-vite/tests/hotkey.spec.ts +++ b/e2e/apps/react-vite/tests/hotkey.spec.ts @@ -1,23 +1,10 @@ import { test, expect } from '@playwright/test' import { DevtoolsPage } from '@tanstack/devtools-e2e' -// The shell's open hotkey is ["Control", "~"] and it is matched against -// `KeyboardEvent.key` via @solid-primitives/keyboard. Playwright's -// `keyboard.press('~')` would require Shift (which adds an extra key and breaks -// the match), so we dispatch the exact keydown events the shell listens for: -// Control first (so the modifier becomes the first held key), then "~" with -// ctrlKey set. This mirrors a real Ctrl+~ press without the Shift artifact. +// The default open hotkey is 'Control+~'. On a US keyboard `~` is Shift+`, +// and TanStack Hotkeys matches the Shift that typing `~` needs. async function pressOpenHotkey(page: import('@playwright/test').Page) { - await page.evaluate(() => { - window.dispatchEvent( - new KeyboardEvent('keydown', { key: 'Control', ctrlKey: true }), - ) - window.dispatchEvent( - new KeyboardEvent('keydown', { key: '~', ctrlKey: true }), - ) - window.dispatchEvent(new KeyboardEvent('keyup', { key: '~' })) - window.dispatchEvent(new KeyboardEvent('keyup', { key: 'Control' })) - }) + await page.keyboard.press('Control+Shift+Backquote') } test.describe('open hotkey', () => { diff --git a/e2e/apps/react-vite/tests/open-as-modal.spec.ts b/e2e/apps/react-vite/tests/open-as-modal.spec.ts index 73f1aa104..f9c426db2 100644 --- a/e2e/apps/react-vite/tests/open-as-modal.spec.ts +++ b/e2e/apps/react-vite/tests/open-as-modal.spec.ts @@ -2,18 +2,9 @@ import { test, expect } from '@playwright/test' import { DevtoolsPage, SELECTORS } from '@tanstack/devtools-e2e' import type { Page } from '@playwright/test' -// See hotkey.spec.ts: dispatch the exact keydown events of Control+~. +// See hotkey.spec.ts: the default open hotkey, Control+~. async function pressOpenHotkey(page: Page) { - await page.evaluate(() => { - window.dispatchEvent( - new KeyboardEvent('keydown', { key: 'Control', ctrlKey: true }), - ) - window.dispatchEvent( - new KeyboardEvent('keydown', { key: '~', ctrlKey: true }), - ) - window.dispatchEvent(new KeyboardEvent('keyup', { key: '~' })) - window.dispatchEvent(new KeyboardEvent('keyup', { key: 'Control' })) - }) + await page.keyboard.press('Control+Shift+Backquote') } /** Whether a click at the center of the close button reaches it. */