Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

363 lines11.2 KB

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