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