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