Compare commits

...
Author SHA1 Message Date
Julius Marminge db5681ec87 Migrate web keyboard shortcuts to TanStack hotkeys manager
- replace window keydown listeners with `@tanstack/react-hotkeys` registrations in chat, sidebar, and context menu flows
- add `shortcutToRawHotkey` and `shortcutsForCommands` helpers for normalized, deduplicated hotkey mappings
- add focused keybinding tests and lockfile/package updates for new hotkeys deps
2026-02-17 21:26:22 -08:00
7 changed files with 265 additions and 100 deletions

No files matched your search

+1
View File
@@ -13,6 +13,7 @@
"dependencies": {
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-hotkeys": "^0.1.0",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
+116 -68
View File
@@ -26,6 +26,7 @@ import {
useRef,
useState,
} from "react";
import { getHotkeyManager, useHotkey } from "@tanstack/react-hotkeys";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
@@ -66,6 +67,7 @@ import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
isOpenFavoriteEditorShortcut,
shortcutsForCommands,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
@@ -524,6 +526,16 @@ export default function ChatView() {
() => shortcutLabelForCommand(keybindings, "terminal.close"),
[keybindings],
);
const terminalHotkeys = useMemo(
() =>
shortcutsForCommands(keybindings, [
"terminal.toggle",
"terminal.split",
"terminal.close",
"terminal.new",
]),
[keybindings],
);
const envLocked = Boolean(
activeThread &&
@@ -716,22 +728,19 @@ export default function ChatView() {
};
}, [revokePreviewUrls]);
/**
* Close expanded image on Escape key
*/
useEffect(() => {
if (!expandedImage) {
return;
}
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key !== "Escape") return;
useHotkey(
"Escape",
() => {
setExpandedImage(null);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [expandedImage]);
},
{
enabled: expandedImage !== null,
ignoreInputs: false,
preventDefault: false,
stopPropagation: false,
target: typeof window === "undefined" ? null : window,
},
);
const activeWorktreePath = activeThread?.worktreePath;
@@ -786,56 +795,74 @@ export default function ChatView() {
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
};
const handler = (event: globalThis.KeyboardEvent) => {
if (!activeThreadId || event.defaultPrevented) return;
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(activeThread?.terminalOpen),
};
const manager = getHotkeyManager();
const handles = terminalHotkeys.map((hotkey) =>
manager.register(
hotkey,
(event) => {
if (!activeThreadId || event.defaultPrevented) return;
const shortcutContext = {
terminalFocus: isTerminalFocused(),
terminalOpen: Boolean(activeThread?.terminalOpen),
};
if (isTerminalToggleShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
toggleTerminalVisibility();
return;
}
if (isTerminalToggleShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
toggleTerminalVisibility();
return;
}
if (isTerminalSplitShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
splitTerminal();
return;
}
if (isTerminalSplitShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
splitTerminal();
return;
}
if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) return;
closeTerminal(activeThread.activeTerminalId);
return;
}
if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) return;
closeTerminal(activeThread.activeTerminalId);
return;
}
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
createNewTerminal();
},
{
enabled: Boolean(activeThreadId),
conflictBehavior: "allow",
ignoreInputs: false,
preventDefault: false,
stopPropagation: false,
target: window,
},
),
);
return () => {
for (const handle of handles) {
handle.unregister();
}
createNewTerminal();
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
@@ -845,6 +872,7 @@ export default function ChatView() {
dispatch,
splitTerminal,
keybindings,
terminalHotkeys,
toggleTerminalVisibility,
]);
@@ -2095,19 +2123,39 @@ const OpenInPicker = memo(function OpenInPicker({
() => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
[keybindings],
);
const openFavoriteHotkeys = useMemo(
() => shortcutsForCommands(keybindings, ["editor.openFavorite"]),
[keybindings],
);
useEffect(() => {
const handler = (e: globalThis.KeyboardEvent) => {
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!api || !activeProject) return;
const manager = getHotkeyManager();
const handles = openFavoriteHotkeys.map((hotkey) =>
manager.register(
hotkey,
(event) => {
if (!isOpenFavoriteEditorShortcut(event, keybindings)) return;
if (!api || !activeProject) return;
e.preventDefault();
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, lastEditor);
event.preventDefault();
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, lastEditor);
},
{
conflictBehavior: "allow",
ignoreInputs: false,
preventDefault: false,
stopPropagation: false,
target: window,
},
),
);
return () => {
for (const handle of handles) {
handle.unregister();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [api, activeProject, activeThread, keybindings, lastEditor]);
}, [activeProject, activeThread, api, keybindings, lastEditor, openFavoriteHotkeys]);
return (
<Group aria-label="Subscription actions">
+42 -23
View File
@@ -1,13 +1,14 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { getHotkeyManager } from "@tanstack/react-hotkeys";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutsForCommands } from "../keybindings";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -385,32 +386,50 @@ export default function Sidebar() {
[api, dispatch, state.projects, state.threads],
);
const chatHotkeys = useMemo(
() => shortcutsForCommands(keybindings, ["chat.new", "chat.newLocal"]),
[keybindings],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
return;
}
const manager = getHotkeyManager();
const handles = chatHotkeys.map((hotkey) =>
manager.register(
hotkey,
(event) => {
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
return;
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
};
window.addEventListener("keydown", onWindowKeyDown);
if (!isChatNewShortcut(event, keybindings)) return;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId, {
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
},
{
conflictBehavior: "allow",
ignoreInputs: false,
preventDefault: false,
stopPropagation: false,
target: window,
},
),
);
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
for (const handle of handles) {
handle.unregister();
}
};
}, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
}, [chatHotkeys, handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
+20 -9
View File
@@ -1,3 +1,5 @@
import { getHotkeyManager } from "@tanstack/react-hotkeys";
/**
* Imperative DOM-based context menu for non-Electron environments.
* Shows a positioned dropdown and returns a promise that resolves
@@ -10,6 +12,7 @@ export function showContextMenuFallback<T extends string>(
return new Promise<T | null>((resolve) => {
const overlay = document.createElement("div");
overlay.style.cssText = "position:fixed;inset:0;z-index:9999";
let cleanedUp = false;
const menu = document.createElement("div");
menu.className =
@@ -19,23 +22,31 @@ export function showContextMenuFallback<T extends string>(
const y = position?.y ?? 0;
menu.style.top = `${y}px`;
menu.style.left = `${x}px`;
const escapeHandle = getHotkeyManager().register(
"Escape",
(event) => {
event.preventDefault();
cleanup(null);
},
{
conflictBehavior: "allow",
ignoreInputs: false,
preventDefault: false,
stopPropagation: false,
target: document,
},
);
function cleanup(result: T | null) {
document.removeEventListener("keydown", onKeyDown);
if (cleanedUp) return;
cleanedUp = true;
escapeHandle.unregister();
overlay.remove();
menu.remove();
resolve(result);
}
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
e.preventDefault();
cleanup(null);
}
}
overlay.addEventListener("mousedown", () => cleanup(null));
document.addEventListener("keydown", onKeyDown);
for (const item of items) {
const btn = document.createElement("button");
+32
View File
@@ -16,6 +16,8 @@ import {
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
shortcutToRawHotkey,
shortcutsForCommands,
shortcutLabelForCommand,
terminalNavigationShortcutData,
type ShortcutEventLike,
@@ -360,6 +362,36 @@ describe("formatShortcutLabel", () => {
});
});
describe("shortcutToRawHotkey", () => {
it("normalizes special key aliases and preserves modifiers", () => {
assert.deepStrictEqual(shortcutToRawHotkey(modShortcut("esc", { shiftKey: true })), {
key: "Escape",
mod: true,
shift: true,
});
assert.deepStrictEqual(shortcutToRawHotkey(modShortcut("arrowleft")), {
key: "ArrowLeft",
mod: true,
});
});
});
describe("shortcutsForCommands", () => {
it("returns filtered deduplicated hotkeys in config order", () => {
const keybindings = compile([
{ shortcut: modShortcut("n"), command: "chat.new" },
{ shortcut: modShortcut("n"), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
]);
assert.deepStrictEqual(shortcutsForCommands(keybindings, ["chat.new", "chat.newLocal"]), [
{ key: "N", mod: true },
{ key: "N", mod: true, shift: true },
]);
});
});
describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => {
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"));
+49
View File
@@ -1,3 +1,7 @@
import {
type RawHotkey,
normalizeKeyName,
} from "@tanstack/react-hotkeys";
import {
type KeybindingCommand,
type KeybindingShortcut,
@@ -26,6 +30,17 @@ interface ShortcutMatchOptions {
context?: Partial<ShortcutMatchContext>;
}
function shortcutSignature(shortcut: KeybindingShortcut): string {
return [
shortcut.key,
shortcut.metaKey ? "1" : "0",
shortcut.ctrlKey ? "1" : "0",
shortcut.shiftKey ? "1" : "0",
shortcut.altKey ? "1" : "0",
shortcut.modKey ? "1" : "0",
].join("|");
}
const TERMINAL_WORD_BACKWARD = "\u001bb";
const TERMINAL_WORD_FORWARD = "\u001bf";
const TERMINAL_LINE_START = "\u0001";
@@ -166,6 +181,40 @@ export function shortcutLabelForCommand(
return null;
}
export function shortcutToRawHotkey(shortcut: KeybindingShortcut): RawHotkey {
return {
key: normalizeKeyName(shortcut.key),
...(shortcut.modKey ? { mod: true } : {}),
...(shortcut.metaKey ? { meta: true } : {}),
...(shortcut.ctrlKey ? { ctrl: true } : {}),
...(shortcut.shiftKey ? { shift: true } : {}),
...(shortcut.altKey ? { alt: true } : {}),
};
}
export function shortcutsForCommands(
keybindings: ResolvedKeybindingsConfig,
commands: readonly KeybindingCommand[],
): RawHotkey[] {
if (commands.length === 0 || keybindings.length === 0) {
return [];
}
const commandSet = new Set(commands);
const seen = new Set<string>();
const hotkeys: RawHotkey[] = [];
for (const binding of keybindings) {
if (!commandSet.has(binding.command)) continue;
const signature = shortcutSignature(binding.shortcut);
if (seen.has(signature)) continue;
seen.add(signature);
hotkeys.push(shortcutToRawHotkey(binding.shortcut));
}
return hotkeys;
}
export function isTerminalToggleShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
+5
View File
@@ -53,6 +53,7 @@
"dependencies": {
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-hotkeys": "^0.1.0",
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
@@ -428,10 +429,14 @@
"@tanstack/devtools-event-client": ["@tanstack/[email protected]", "", {}, "sha512-RPfGuk2bDZgcu9bAJodvO2lnZeHuz4/71HjZ0bGb/SPg8+lyTA+RLSKQvo7fSmPSi8/vcH3aKQ8EM9ywf1olaw=="],
"@tanstack/hotkeys": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "^0.8.0" } }, "sha512-2ypLO3C2vKxMbCjiOfA3RzDaUIUYsQtyLc+Qwl6oKzQvWxReGlQN7DOQZSeKyX9D395d3E65e2v7Fm14BzUGew=="],
"@tanstack/pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.0", "@tanstack/store": "^0.8.0" } }, "sha512-qhCRSFei0hokQr3xYcQXqxsRD/LKlgHCxHXtKHrQoImp4x2Zu6tUOpUGVH4y2qexIrzSu3aibQBNNfC3Eay6Mg=="],
"@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg=="],
"@tanstack/react-hotkeys": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/hotkeys": "0.1.0", "@tanstack/react-store": "^0.8.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-Hteo+hdPKdR2G7uAwTmScu1JUHM/f03lVihxVfR/A3XMyVJmbzi4SJieRk/kLgYKeXFRGIUx/xSI3mHeVc6DbQ=="],
"@tanstack/react-pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/pacer": "0.18.0", "@tanstack/react-store": "^0.8.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-coj8ULAuR0qFpjAKD44gTgRuZyjxU6Xu+IX5MwwYvr4e61OtZcJshaExoOBKpCGde0Edb12jDnzzj2Im13Qm9Q=="],
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],