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

keybindings.ts

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