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