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