Add configurable keybindings via `~/.t3/keybindings.json` #52
Mergedjuliusmarmingemerged 24 commits into
main fromcodething/f54ac31emerged by juliusmarminge View on GitHub- @@ -410,4 +461,7 @@410461 return undefined;411462412463 case WS_METHODS.serverGetConfig:413- return { cwd };464+ return {465+ cwd,466+ keybindings: readKeybindingsConfig(logger),467+ };@@ -8,0 +39,21 @@39+40+interface ShortcutMatchOptions {41+ platform?: string;42+ context?: Partial<ShortcutMatchContext>;43+}44+45+type WhenNode =46+ | { type: "identifier"; name: string }47+ | { type: "not"; node: WhenNode }48+ | { type: "and"; left: WhenNode; right: WhenNode }49+ | { type: "or"; left: WhenNode; right: WhenNode };50+51+type WhenToken =52+ | { type: "identifier"; value: string }53+ | { type: "not" }54+ | { type: "and" }55+ | { type: "or" }56+ | { type: "lparen" }57+ | { type: "rparen" };58+59+const WHEN_AST_CACHE = new Map<string, WhenNode | null>();@@ -47 +171 @@47171 it("matches Cmd+K on macOS", () => {
- apps/web/src/keybindings.ts line 142OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -14,6 +125,18 @@125+}126+127+function normalizeEventKey(key: string): string {128+ const normalized = key.toLowerCase();129+ if (normalized === "esc") return "escape";130+ return normalized;131+}132+133+function matchesShortcutValue(14134 event: ShortcutEventLike,135+ shortcutValue: string,15136 platform = navigator.platform,16137 ): boolean {17- const key = event.key.toLowerCase();18- if (key !== "j") return false;19- if (event.shiftKey || event.altKey) return false;138+ const parsed = parseShortcutValue(shortcutValue);139+ if (!parsed) return false;140+141+ const key = normalizeEventKey(event.key);142+ if (key !== parsed.key) return false;
- apps/web/src/keybindings.ts lines 302 to 367OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -25,0 +347,21 @@347+348+export function resolveTerminalKeybindings(349+ input: KeybindingsConfig | null | undefined,350+): ResolvedTerminalKeybindings {351+ if (!input || input.length === 0) {352+ return [...DEFAULT_TERMINAL_KEYBINDINGS];353+ }354+355+ const normalizedInput = input356+ .map((binding) => normalizeConfiguredKeybinding(binding))357+ .filter((binding): binding is ResolvedTerminalKeybinding => binding !== null);358+ if (normalizedInput.length === 0) {359+ return [...DEFAULT_TERMINAL_KEYBINDINGS];360+ }361+362+ const overriddenCommands = new Set(normalizedInput.map((binding) => binding.command));363+ const retainedDefaults = DEFAULT_TERMINAL_KEYBINDINGS.filter(364+ (binding) => !overriddenCommands.has(binding.command),365+ );366+ return [...retainedDefaults, ...normalizedInput];367+}
- apps/web/src/keybindings.ts line 75Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +259,21 @@259+ if (!right) return null;260+ left = { type: "or", left, right };261+ }262+263+ return left;264+ };265+266+ const ast = parseOr();267+ if (!ast || index !== tokens.length) return null;268+ return ast;269+}270+271+function evaluateWhenNode(node: WhenNode, context: ShortcutMatchContext): boolean {272+ switch (node.type) {273+ case "identifier":274+ return Boolean(context[node.name]);275+ case "not":276+ return !evaluateWhenNode(node.node, context);277+ case "and":278+ return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);279+ case "or":
- apps/web/src/keybindings.ts line 62OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +42,21 @@42+ | { type: "and" }43+ | { type: "or" }44+ | { type: "lparen" }45+ | { type: "rparen" };46+47+const WHEN_AST_CACHE = new Map<string, WhenNode | null>();48+49+function isMacPlatform(platform: string): boolean {50+ return /mac|iphone|ipad|ipod/i.test(platform);51+}52+53+function normalizeKeyToken(token: string): string {54+ if (token === "space") return " ";55+ if (token === "esc") return "escape";56+ return token;57+}58+59+function parseShortcutValue(value: string): ParsedShortcut | null {60+ const tokens = value61+ .toLowerCase()62+ .split("+")
juliusmarminge changed the title
- apps/server/src/wsServer.ts lines 216 to 218OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -70,0 +198,21 @@198+ if (custom.length === 0) {199+ return [...DEFAULT_KEYBINDINGS];200+ }201+202+ const overriddenCommands = new Set(custom.map((binding) => binding.command));203+ const retainedDefaults = DEFAULT_KEYBINDINGS.filter(204+ (binding) => !overriddenCommands.has(binding.command),205+ );206+ const merged = [...retainedDefaults, ...custom];207+208+ if (merged.length <= 256) {209+ return merged;210+ }211+212+ // Keep the latest rules when the config exceeds max size; later rules have higher precedence.213+ return merged.slice(-256);214+}215+216+function readKeybindingsConfig(logger: ReturnType<typeof createLogger>): KeybindingsConfig {217+ const configPath = path.join(os.homedir(), ".t3", "keybindings.json");218+ try {
- apps/server/src/wsServer.ts line 158OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -70,0 +138,21 @@138+ if (!compiled) {139+ invalidEntries += 1;140+ continue;141+ }142+ sanitized.push(compiled);143+ continue;144+ }145+ invalidEntries += 1;146+ }147+ if (invalidEntries > 0) {148+ logger.warn("ignoring invalid keybinding entries", {149+ path: configPath,150+ invalidEntries,151+ totalEntries: parsed.length,152+ });153+ }154+ const overriddenCommands = new Set(sanitized.map((entry) => entry.command));155+ const mergedBeforeCapLength =156+ DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))157+ .length + sanitized.length;158+ const merged = mergeWithDefaultKeybindings(sanitized);
- @@ -0,0 +17,21 @@17+ when: keybindingWhenSchema.optional(),18+});19+20+export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);21+22+export const keybindingShortcutSchema = z.object({23+ key: z.string().trim().min(1).max(32),24+ metaKey: z.boolean(),25+ ctrlKey: z.boolean(),26+ shiftKey: z.boolean(),27+ altKey: z.boolean(),28+ modKey: z.boolean(),29+});30+31+export type KeybindingWhenNode =32+ | { type: "identifier"; name: string }33+ | { type: "not"; node: KeybindingWhenNode }34+ | { type: "and"; left: KeybindingWhenNode; right: KeybindingWhenNode }35+ | { type: "or"; left: KeybindingWhenNode; right: KeybindingWhenNode };36+37+export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(() =>
- apps/server/src/wsServer.ts line 137OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -70,0 +117,21 @@117+118+function readKeybindingsConfig(119+ logger: ReturnType<typeof createLogger>,120+): ResolvedKeybindingsConfig {121+ const configPath = path.join(os.homedir(), ".t3", "keybindings.json");122+ try {123+ const raw = fs.readFileSync(configPath, "utf8");124+ const parsed = JSON.parse(raw) as unknown;125+ if (!Array.isArray(parsed)) {126+ logger.warn("ignoring keybindings config with unsupported format; expected array", {127+ path: configPath,128+ });129+ return [...DEFAULT_RESOLVED_KEYBINDINGS];130+ }131+132+ const sanitized: ResolvedKeybindingsConfig = [];133+ let invalidEntries = 0;134+ for (const entry of parsed) {135+ const result = keybindingRuleSchema.safeParse(entry);136+ if (result.success) {137+ const compiled = compileResolvedKeybindingRule(result.data);
- @@ -4,3 +4,11 @@44 export function cn(...inputs: CxOptions) {55 return twMerge(cx(inputs));66 }7+8+export function isMacPlatform(platform: string): boolean {9+ return /mac|iphone|ipad|ipod/i.test(platform);10+}11+12+export function isWindowsPlatform(platform: string): boolean {13+ return /win|windows/i.test(platform);14+}@@ -0,0 +1,19 @@1+import type { NativeApi } from "@t3tools/contracts";2+import { queryOptions } from "@tanstack/react-query";3+4+export const serverQueryKeys = {5+ all: ["server"] as const,6+ config: () => ["server", "config"] as const,7+};8+9+export function serverConfigQueryOptions(api: NativeApi | undefined) {10+ return queryOptions({11+ queryKey: serverQueryKeys.config(),12+ queryFn: async () => {13+ if (!api || !api.server || typeof api.server.getConfig !== "function") {14+ throw new Error("Server config is unavailable.");15+ }16+ return api.server.getConfig();17+ },18+ enabled: !!api && !!api.server && typeof api.server.getConfig === "function",19+ });
juliusmarminge merged this8dd1074
juliusmarminge closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
Walkthrough#
Server now reads and validates
~/.t3/keybindings.jsonand returns resolved keybindings viaserver.getConfig; contracts add keybindings/server schemas; web resolves and merges bindings with defaults, formats labels, and applies terminal toggle/split/new shortcuts with when-expression context handling.Changes#
KEYBINDINGS.mdkey,command,when), syntax, semantics, defaults, precedence, and examples.apps/server/src/wsServer.ts,apps/server/src/wsServer.test.ts~/.t3/keybindings.json, validates viakeybindingRuleSchema, sanitizes/merges with defaults, truncates to 256 entries, logs warnings for malformed/invalid data, and includeskeybindingsinserverGetConfigresponse; tests added for success and multiple failure cases.packages/contracts/src/keybindings.ts,packages/contracts/src/server.ts,packages/contracts/src/index.ts,packages/contracts/src/ipc.tsKeybindingCommand,KeybindingRule,KeybindingsConfig,ServerConfig), re-exportskeybindingsandserver, and extendsNativeApiwithserver.getConfig(): Promise<ServerConfig>.apps/web/src/keybindings.ts,apps/web/src/keybindings.test.ts,apps/web/src/terminal-shortcuts.ts,apps/web/src/terminal-shortcuts.test.tsisTerminalToggle/Split/New/ClearShortcut,resolveTerminalKeybindings,shortcutLabelForCommand); tests added/updated.apps/web/src/components/ChatView.tsx,apps/web/src/components/ThreadTerminalDrawer.tsxterminalFocus/terminalOpenand handle toggle/split/new shortcuts;ThreadTerminalDraweracceptssplitShortcutLabelandnewShortcutLabeland displays labels.apps/web/src/wsNativeApi.tsserver.getConfigthat forwardsWS_METHODS.serverGetConfigvia transport request.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
main✨ Finishing touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.