Open History to see the last commit
1import {
2 type KeybindingRule,
3 type KeybindingShortcut,
4 type KeybindingWhenNode,
5 MAX_KEYBINDINGS_COUNT,
6 MAX_WHEN_EXPRESSION_DEPTH,
7 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
8 type ResolvedKeybindingRule,
9 type ResolvedKeybindingsConfig,
10 THREAD_JUMP_KEYBINDING_COMMANDS,
11} from "@t3tools/contracts";
12
13export interface ShortcutEventLike {
14 getModifierState?: (key: "AltGraph") => boolean;
15 type?: string;
16 code?: string;
17 key: string;
18 repeat?: boolean;
19 metaKey: boolean;
20 ctrlKey: boolean;
21 shiftKey: boolean;
22 altKey: boolean;
23}
24
25export interface ShortcutModifierStateLike {
26 metaKey: boolean;
27 ctrlKey: boolean;
28 shiftKey: boolean;
29 altKey: boolean;
30}
31
32export const EVENT_CODE_SHORTCUT_KEYS: Readonly<Record<string, string>> = {
33 Backquote: "`",
34 Backslash: "\\",
35 BracketLeft: "[",
36 BracketRight: "]",
37 Comma: ",",
38 Digit0: "0",
39 Digit1: "1",
40 Digit2: "2",
41 Digit3: "3",
42 Digit4: "4",
43 Digit5: "5",
44 Digit6: "6",
45 Digit7: "7",
46 Digit8: "8",
47 Digit9: "9",
48 Equal: "=",
49 Minus: "-",
50 Period: ".",
51 Quote: "'",
52 Semicolon: ";",
53 Slash: "/",
54};
55
56export const US_SHIFTED_TO_UNSHIFTED_KEYS: ReadonlyMap<string, string> = new Map([
57 ["!", "1"],
58 ["@", "2"],
59 ["#", "3"],
60 ["$", "4"],
61 ["%", "5"],
62 ["^", "6"],
63 ["&", "7"],
64 ["*", "8"],
65 ["(", "9"],
66 [")", "0"],
67 ["~", "`"],
68 ["_", "-"],
69 ["+", "="],
70 ["{", "["],
71 ["}", "]"],
72 ["|", "\\"],
73 [":", ";"],
74 ['"', "'"],
75 ["<", ","],
76 [">", "."],
77 ["?", "/"],
78]);
79
80export function isMacPlatform(platform: string): boolean {
81 return /mac|iphone|ipad|ipod/i.test(platform);
82}
83
84export function normalizeEventKey(key: string): string {
85 const normalized = key.toLowerCase();
86 if (normalized === "esc") return "escape";
87 return normalized;
88}
89
90export function shortcutKeyFromEvent(event: Pick<ShortcutEventLike, "key" | "code">): string {
91 const layoutKey = normalizeEventKey(event.key);
92 if (/^[a-z]$/.test(layoutKey)) return layoutKey;
93 const physicalKey = event.code ? EVENT_CODE_SHORTCUT_KEYS[event.code] : undefined;
94 return physicalKey ?? layoutKey;
95}
96
97export function resolveEventKeys(event: ShortcutEventLike): Set<string> {
98 const layoutKey = normalizeEventKey(event.key);
99 const keys = new Set([layoutKey]);
100 const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1];
101 if (letterCode && !/^[a-z]$/.test(layoutKey)) {
102 keys.add(letterCode.toLowerCase());
103 }
104 keys.add(shortcutKeyFromEvent(event));
105 return keys;
106}
107
108export function matchesKeybindingShortcutModifiers(
109 event: ShortcutModifierStateLike,
110 shortcut: KeybindingShortcut,
111 platform: string,
112): boolean {
113 const useMetaForMod = isMacPlatform(platform);
114 const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
115 const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
116 return (
117 event.metaKey === expectedMeta &&
118 event.ctrlKey === expectedCtrl &&
119 event.shiftKey === shortcut.shiftKey &&
120 event.altKey === shortcut.altKey
121 );
122}
123
124export function matchesKeybindingShortcut(
125 event: ShortcutEventLike,
126 shortcut: KeybindingShortcut,
127 platform: string,
128): boolean {
129 if (
130 !isMacPlatform(platform) &&
131 event.getModifierState?.("AltGraph") &&
132 !/^[a-z0-9]$/i.test(event.key)
133 )
134 return false;
135 if (!matchesKeybindingShortcutModifiers(event, shortcut, platform)) return false;
136 return resolveEventKeys(event).has(shortcut.key);
137}
138
139type WhenToken =
140 | { type: "identifier"; value: string }
141 | { type: "not" }
142 | { type: "and" }
143 | { type: "or" }
144 | { type: "lparen" }
145 | { type: "rparen" };
146
147export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
148 { key: "mod+b", command: "sidebar.toggle" },
149 { key: "f6", command: "workspace.focusNext" },
150 { key: "shift+f6", command: "workspace.focusPrevious" },
151 // Some browsers keep plain F6 for their own toolbars; mod+F6 reaches the page in all of them.
152 { key: "mod+f6", command: "workspace.focusNext" },
153 { key: "mod+shift+f6", command: "workspace.focusPrevious" },
154 { key: "mod+[", command: "navigation.back", when: "!terminalFocus" },
155 { key: "mod+]", command: "navigation.forward", when: "!terminalFocus" },
156 { key: "mod+j", command: "terminal.toggle" },
157 { key: "mod+alt+b", command: "rightPanel.toggle" },
158 { key: "mod+shift+b", command: "threadPanel.toggle", when: "!terminalFocus" },
159 { key: "mod+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
160 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
161 { key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
162 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
163 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
164 { key: "mod+w", command: "rightPanel.close", when: "!terminalFocus" },
165 { key: "mod+shift+t", command: "view.reopenClosed" },
166 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
167 { key: "mod+shift+j", command: "preview.toggle" },
168 { key: "mod+r", command: "preview.refresh", when: "previewFocus" },
169 { key: "mod+l", command: "preview.focusUrl", when: "previewFocus" },
170 { key: "mod+=", command: "preview.zoomIn", when: "previewFocus" },
171 { key: "mod++", command: "preview.zoomIn", when: "previewFocus" },
172 { key: "mod+-", command: "preview.zoomOut", when: "previewFocus" },
173 { key: "mod+0", command: "preview.resetZoom", when: "previewFocus" },
174 { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
175 { key: "mod+p", command: "filePicker.toggle", when: "!terminalFocus" },
176 { key: "mod+shift+f", command: "projectSearch.toggle", when: "!terminalFocus" },
177 { key: "mod+u", command: "usage.open", when: "!terminalFocus" },
178 { key: "mod+alt+a", command: "theme.select", when: "!terminalFocus" },
179 { key: "mod+alt+shift+a", command: "appearance.cycle", when: "!terminalFocus" },
180 { key: "mod+alt+shift+t", command: "themeEditor.toggle" },
181 { key: "mod+s", command: "composer.stash", when: "!terminalFocus" },
182 { key: "mod+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" },
183 { key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" },
184 { key: "mod+enter", command: "composer.sendAlternate", when: "composerFocus && turnRunning" },
185 {
186 key: "mod+enter",
187 command: "composer.sendBackground",
188 when: "composerFocus && draftThreadRoute",
189 },
190 {
191 key: "mod+alt+enter",
192 command: "composer.sendBackground",
193 when: "composerFocus && draftThreadRoute",
194 },
195 {
196 key: "mod+alt+enter",
197 command: "composer.sendAndNewThread",
198 when: "composerFocus && !draftThreadRoute",
199 },
200 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
201 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
202 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
203 { key: "mod+alt+n", command: "chat.newWithoutProject", when: "!terminalFocus" },
204 { key: "mod+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },
205 { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
206 { key: "mod+shift+h", command: "composer.host", when: "!terminalFocus" },
207 { key: "mod+shift+e", command: "composer.effort", when: "!terminalFocus" },
208 { key: "mod+shift+a", command: "composer.mode", when: "!terminalFocus" },
209 { key: "mod+shift+x", command: "composer.workspace", when: "!terminalFocus" },
210 { key: "mod+shift+g", command: "composer.branch", when: "!terminalFocus" },
211 { key: "mod+shift+l", command: "composer.previousWorktree", when: "!terminalFocus" },
212 { key: "mod+shift+k", command: "pullRequest.copyNumber", when: "!terminalFocus" },
213 { key: "mod+shift+arrowup", command: "modelPicker.previousProvider", when: "modelPickerOpen" },
214 { key: "mod+shift+arrowdown", command: "modelPicker.nextProvider", when: "modelPickerOpen" },
215 { key: "mod+o", command: "editor.openFavorite" },
216 { key: "mod+shift+[", command: "thread.previous" },
217 { key: "mod+shift+]", command: "thread.next" },
218 { key: "mod+shift+c", command: "thread.copyReference", when: "!terminalFocus" },
219 { key: "mod+shift+s", command: "thread.settle", when: "!terminalFocus" },
220 { key: "mod+shift+p", command: "thread.pin", when: "!terminalFocus" },
221 { key: "mod+z", command: "thread.undo", when: "!terminalFocus && !editableFocus" },
222 ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
223 key: `mod+${index + 1}`,
224 command,
225 when: "!modelPickerOpen && isDesktop",
226 })),
227 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
228 key: `mod+${index + 1}`,
229 command,
230 when: "modelPickerOpen && isDesktop",
231 })),
232 { key: "c", command: "usage.cost", when: "usagePageOpen" },
233 { key: "t", command: "usage.tokens", when: "usagePageOpen" },
234 { key: "l", command: "usage.limits", when: "usagePageOpen" },
235 { key: "mod+shift+1", command: "usage.period.day", when: "usagePageOpen" },
236 { key: "mod+shift+2", command: "usage.period.week", when: "usagePageOpen" },
237 { key: "mod+shift+3", command: "usage.period.month", when: "usagePageOpen" },
238 { key: "mod+shift+4", command: "usage.period.quarter", when: "usagePageOpen" },
239];
240
241function normalizeKeyToken(token: string): string {
242 if (token === "space") return " ";
243 if (token === "esc") return "escape";
244 return token;
245}
246
247export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
248 const rawTokens = value
249 .toLowerCase()
250 .split("+")
251 .map((token) => token.trim());
252 const tokens = [...rawTokens];
253 let trailingEmptyCount = 0;
254 while (tokens[tokens.length - 1] === "") {
255 trailingEmptyCount += 1;
256 tokens.pop();
257 }
258 if (trailingEmptyCount > 0) {
259 tokens.push("+");
260 }
261 if (tokens.some((token) => token.length === 0)) {
262 return null;
263 }
264 if (tokens.length === 0) return null;
265
266 let key: string | null = null;
267 let metaKey = false;
268 let ctrlKey = false;
269 let shiftKey = false;
270 let altKey = false;
271 let modKey = false;
272
273 for (const token of tokens) {
274 switch (token) {
275 case "cmd":
276 case "meta":
277 metaKey = true;
278 break;
279 case "ctrl":
280 case "control":
281 ctrlKey = true;
282 break;
283 case "shift":
284 shiftKey = true;
285 break;
286 case "alt":
287 case "option":
288 altKey = true;
289 break;
290 case "mod":
291 modKey = true;
292 break;
293 default: {
294 if (key !== null) return null;
295 key = normalizeKeyToken(token);
296 }
297 }
298 }
299
300 if (key === null) return null;
301 return {
302 key,
303 metaKey,
304 ctrlKey,
305 shiftKey,
306 altKey,
307 modKey,
308 };
309}
310
311function tokenizeWhenExpression(expression: string): WhenToken[] | null {
312 const tokens: WhenToken[] = [];
313 let index = 0;
314
315 while (index < expression.length) {
316 const current = expression[index];
317 if (!current) break;
318
319 if (/\s/.test(current)) {
320 index += 1;
321 continue;
322 }
323 if (expression.startsWith("&&", index)) {
324 tokens.push({ type: "and" });
325 index += 2;
326 continue;
327 }
328 if (expression.startsWith("||", index)) {
329 tokens.push({ type: "or" });
330 index += 2;
331 continue;
332 }
333 if (current === "!") {
334 tokens.push({ type: "not" });
335 index += 1;
336 continue;
337 }
338 if (current === "(") {
339 tokens.push({ type: "lparen" });
340 index += 1;
341 continue;
342 }
343 if (current === ")") {
344 tokens.push({ type: "rparen" });
345 index += 1;
346 continue;
347 }
348
349 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
350 if (!identifier) {
351 return null;
352 }
353 tokens.push({ type: "identifier", value: identifier[0] });
354 index += identifier[0].length;
355 }
356
357 return tokens;
358}
359
360export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
361 const tokens = tokenizeWhenExpression(expression);
362 if (!tokens || tokens.length === 0) return null;
363 let index = 0;
364
365 const parsePrimary = (depth: number): KeybindingWhenNode | null => {
366 if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
367 return null;
368 }
369 const token = tokens[index];
370 if (!token) return null;
371
372 if (token.type === "identifier") {
373 index += 1;
374 return { type: "identifier", name: token.value };
375 }
376
377 if (token.type === "lparen") {
378 index += 1;
379 const expressionNode = parseOr(depth + 1);
380 const closeToken = tokens[index];
381 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
382 return null;
383 }
384 index += 1;
385 return expressionNode;
386 }
387
388 return null;
389 };
390
391 const parseUnary = (depth: number): KeybindingWhenNode | null => {
392 let notCount = 0;
393 while (tokens[index]?.type === "not") {
394 index += 1;
395 notCount += 1;
396 if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
397 return null;
398 }
399 }
400
401 let node = parsePrimary(depth);
402 if (!node) return null;
403
404 while (notCount > 0) {
405 node = { type: "not", node };
406 notCount -= 1;
407 }
408
409 return node;
410 };
411
412 const parseAnd = (depth: number): KeybindingWhenNode | null => {
413 let left = parseUnary(depth);
414 if (!left) return null;
415
416 while (tokens[index]?.type === "and") {
417 index += 1;
418 const right = parseUnary(depth);
419 if (!right) return null;
420 left = { type: "and", left, right };
421 }
422
423 return left;
424 };
425
426 const parseOr = (depth: number): KeybindingWhenNode | null => {
427 let left = parseAnd(depth);
428 if (!left) return null;
429
430 while (tokens[index]?.type === "or") {
431 index += 1;
432 const right = parseAnd(depth);
433 if (!right) return null;
434 left = { type: "or", left, right };
435 }
436
437 return left;
438 };
439
440 const ast = parseOr(0);
441 if (!ast || index !== tokens.length) return null;
442 return ast;
443}
444
445export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
446 const shortcut = parseKeybindingShortcut(rule.key);
447 if (!shortcut) return null;
448
449 if (rule.when !== undefined) {
450 const whenAst = parseKeybindingWhenExpression(rule.when);
451 if (!whenAst) return null;
452 return {
453 command: rule.command,
454 shortcut,
455 whenAst,
456 };
457 }
458
459 return {
460 command: rule.command,
461 shortcut,
462 };
463}
464
465export function compileResolvedKeybindingsConfig(
466 config: ReadonlyArray<KeybindingRule>,
467): ResolvedKeybindingsConfig {
468 const compiled: ResolvedKeybindingRule[] = [];
469 for (const rule of config) {
470 const result = compileResolvedKeybindingRule(rule);
471 if (result) {
472 compiled.push(result);
473 }
474 }
475 return compiled.slice(-MAX_KEYBINDINGS_COUNT);
476}
477
478export const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
479
480export function mergeWithDefaultKeybindings(
481 custom: ResolvedKeybindingsConfig,
482): ResolvedKeybindingsConfig {
483 if (custom.length === 0) {
484 return [...DEFAULT_RESOLVED_KEYBINDINGS];
485 }
486
487 const overriddenCommands = new Set(custom.map((binding) => binding.command));
488 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
489 (binding) => !overriddenCommands.has(binding.command),
490 );
491 const merged = [...retainedDefaults, ...custom];
492
493 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
494 return merged;
495 }
496
497 return merged.slice(-MAX_KEYBINDINGS_COUNT);
498}