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