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