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

keybindings.ts

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