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