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

keybindings.ts

409 lines12.6 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​
13export {
14 EVENT_CODE_SHORTCUT_KEYS,
15 isMacPlatform,
16 matchesKeybindingShortcut,
17 matchesKeybindingShortcutModifiers,
18 normalizeEventKey,
19 resolveEventKeys,
20 shortcutKeyFromEvent,
21 type ShortcutEventLike,
22 type ShortcutModifierStateLike,
23} from "./keybindingMatching.ts";
24​
25export const US_SHIFTED_TO_UNSHIFTED_KEYS: ReadonlyMap<string, string> = new Map([
26 ["!", "1"],
27 ["@", "2"],
28 ["#", "3"],
29 ["$", "4"],
30 ["%", "5"],
31 ["^", "6"],
32 ["&", "7"],
33 ["*", "8"],
34 ["(", "9"],
35 [")", "0"],
36 ["~", "`"],
37 ["_", "-"],
38 ["+", "="],
39 ["{", "["],
40 ["}", "]"],
41 ["|", "\\"],
42 [":", ";"],
43 ['"', "'"],
44 ["<", ","],
45 [">", "."],
46 ["?", "/"],
47]);
48​
49type WhenToken =
50 | { type: "identifier"; value: string }
51 | { type: "not" }
52 | { type: "and" }
53 | { type: "or" }
54 | { type: "lparen" }
55 | { type: "rparen" };
56​
57export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
58 { key: "mod+b", command: "sidebar.toggle" },
59 { key: "f6", command: "workspace.focusNext" },
60 { key: "shift+f6", command: "workspace.focusPrevious" },
61 // Some browsers keep plain F6 for their own toolbars; mod+F6 reaches the page in all of them.
62 { key: "mod+f6", command: "workspace.focusNext" },
63 { key: "mod+shift+f6", command: "workspace.focusPrevious" },
64 { key: "mod+[", command: "navigation.back", when: "!terminalFocus" },
65 { key: "mod+]", command: "navigation.forward", when: "!terminalFocus" },
66 { key: "mod+j", command: "terminal.toggle" },
67 { key: "mod+alt+b", command: "rightPanel.toggle" },
68 { key: "mod+shift+b", command: "threadPanel.toggle", when: "!terminalFocus" },
69 { key: "mod+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
70 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
71 { key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
72 { key: "mod+shift+d", command: "composer.dictation", when: "!terminalFocus" },
73 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
74 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
75 { key: "mod+w", command: "rightPanel.close", when: "!terminalFocus" },
76 { key: "mod+shift+t", command: "view.reopenClosed" },
77 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
78 { key: "mod+shift+j", command: "preview.toggle" },
79 { key: "mod+r", command: "preview.refresh", when: "previewFocus" },
80 { key: "mod+l", command: "preview.focusUrl", when: "previewFocus" },
81 { key: "mod+=", command: "preview.zoomIn", when: "previewFocus" },
82 { key: "mod++", command: "preview.zoomIn", when: "previewFocus" },
83 { key: "mod+-", command: "preview.zoomOut", when: "previewFocus" },
84 { key: "mod+0", command: "preview.resetZoom", when: "previewFocus" },
85 { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
86 { key: "mod+p", command: "filePicker.toggle", when: "!terminalFocus" },
87 { key: "mod+shift+f", command: "projectSearch.toggle", when: "!terminalFocus" },
88 { key: "mod+u", command: "usage.open", when: "!terminalFocus" },
89 { key: "mod+alt+a", command: "theme.select", when: "!terminalFocus" },
90 { key: "mod+alt+shift+a", command: "appearance.cycle", when: "!terminalFocus" },
91 { key: "mod+alt+shift+t", command: "themeEditor.toggle" },
92 { key: "mod+s", command: "composer.stash", when: "!terminalFocus" },
93 { key: "mod+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" },
94 { key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" },
95 { key: "mod+enter", command: "composer.sendAlternate", when: "composerFocus && turnRunning" },
96 {
97 key: "mod+enter",
98 command: "composer.sendBackground",
99 when: "composerFocus && draftThreadRoute",
100 },
101 {
102 key: "mod+alt+enter",
103 command: "composer.sendBackground",
104 when: "composerFocus && draftThreadRoute",
105 },
106 {
107 key: "mod+alt+enter",
108 command: "composer.sendAndNewThread",
109 when: "composerFocus && !draftThreadRoute",
110 },
111 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
112 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
113 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
114 { key: "mod+alt+n", command: "chat.newWithoutProject", when: "!terminalFocus" },
115 { key: "mod+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },
116 { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
117 { key: "mod+shift+h", command: "composer.host", when: "!terminalFocus" },
118 { key: "mod+shift+e", command: "composer.effort", when: "!terminalFocus" },
119 { key: "mod+shift+a", command: "composer.mode", when: "!terminalFocus" },
120 { key: "mod+shift+x", command: "composer.workspace", when: "!terminalFocus" },
121 { key: "mod+shift+g", command: "composer.branch", when: "!terminalFocus" },
122 { key: "mod+shift+l", command: "composer.previousWorktree", when: "!terminalFocus" },
123 { key: "mod+shift+k", command: "pullRequest.copyNumber", when: "!terminalFocus" },
124 { key: "mod+shift+arrowup", command: "modelPicker.previousProvider", when: "modelPickerOpen" },
125 { key: "mod+shift+arrowdown", command: "modelPicker.nextProvider", when: "modelPickerOpen" },
126 { key: "mod+o", command: "editor.openFavorite" },
127 { key: "mod+shift+[", command: "thread.previous" },
128 { key: "mod+shift+]", command: "thread.next" },
129 { key: "mod+shift+c", command: "thread.copyReference", when: "!terminalFocus" },
130 { key: "mod+shift+s", command: "thread.settle", when: "!terminalFocus" },
131 { key: "mod+shift+p", command: "thread.pin", when: "!terminalFocus" },
132 { key: "mod+z", command: "thread.undo", when: "!terminalFocus && !editableFocus" },
133 ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
134 key: `mod+${index + 1}`,
135 command,
136 when: "!modelPickerOpen && isDesktop",
137 })),
138 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
139 key: `mod+${index + 1}`,
140 command,
141 when: "modelPickerOpen && isDesktop",
142 })),
143 { key: "c", command: "usage.cost", when: "usagePageOpen" },
144 { key: "t", command: "usage.tokens", when: "usagePageOpen" },
145 { key: "l", command: "usage.limits", when: "usagePageOpen" },
146 { key: "mod+shift+1", command: "usage.period.day", when: "usagePageOpen" },
147 { key: "mod+shift+2", command: "usage.period.week", when: "usagePageOpen" },
148 { key: "mod+shift+3", command: "usage.period.month", when: "usagePageOpen" },
149 { key: "mod+shift+4", command: "usage.period.quarter", when: "usagePageOpen" },
150];
151​
152function normalizeKeyToken(token: string): string {
153 if (token === "space") return " ";
154 if (token === "esc") return "escape";
155 return token;
157​
158export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
159 const rawTokens = value
160 .toLowerCase()
161 .split("+")
162 .map((token) => token.trim());
163 const tokens = [...rawTokens];
164 let trailingEmptyCount = 0;
165 while (tokens[tokens.length - 1] === "") {
166 trailingEmptyCount += 1;
167 tokens.pop();
168 }
169 if (trailingEmptyCount > 0) {
170 tokens.push("+");
171 }
172 if (tokens.some((token) => token.length === 0)) {
173 return null;
174 }
175 if (tokens.length === 0) return null;
176​
177 let key: string | null = null;
178 let metaKey = false;
179 let ctrlKey = false;
180 let shiftKey = false;
181 let altKey = false;
182 let modKey = false;
183​
184 for (const token of tokens) {
185 switch (token) {
186 case "cmd":
187 case "meta":
188 metaKey = true;
189 break;
190 case "ctrl":
191 case "control":
192 ctrlKey = true;
193 break;
194 case "shift":
195 shiftKey = true;
196 break;
197 case "alt":
198 case "option":
199 altKey = true;
200 break;
201 case "mod":
202 modKey = true;
203 break;
204 default: {
205 if (key !== null) return null;
206 key = normalizeKeyToken(token);
207 }
208 }
209 }
210​
211 if (key === null) return null;
212 return {
213 key,
214 metaKey,
215 ctrlKey,
216 shiftKey,
217 altKey,
218 modKey,
219 };
221​
222function tokenizeWhenExpression(expression: string): WhenToken[] | null {
223 const tokens: WhenToken[] = [];
224 let index = 0;
225​
226 while (index < expression.length) {
227 const current = expression[index];
228 if (!current) break;
229​
230 if (/\s/.test(current)) {
231 index += 1;
232 continue;
233 }
234 if (expression.startsWith("&&", index)) {
235 tokens.push({ type: "and" });
236 index += 2;
237 continue;
238 }
239 if (expression.startsWith("||", index)) {
240 tokens.push({ type: "or" });
241 index += 2;
242 continue;
243 }
244 if (current === "!") {
245 tokens.push({ type: "not" });
246 index += 1;
247 continue;
248 }
249 if (current === "(") {
250 tokens.push({ type: "lparen" });
251 index += 1;
252 continue;
253 }
254 if (current === ")") {
255 tokens.push({ type: "rparen" });
256 index += 1;
257 continue;
258 }
259​
260 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
261 if (!identifier) {
262 return null;
263 }
264 tokens.push({ type: "identifier", value: identifier[0] });
265 index += identifier[0].length;
266 }
267​
268 return tokens;
270​
271export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
272 const tokens = tokenizeWhenExpression(expression);
273 if (!tokens || tokens.length === 0) return null;
274 let index = 0;
275​
276 const parsePrimary = (depth: number): KeybindingWhenNode | null => {
277 if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
278 return null;
279 }
280 const token = tokens[index];
281 if (!token) return null;
282​
283 if (token.type === "identifier") {
284 index += 1;
285 return { type: "identifier", name: token.value };
286 }
287​
288 if (token.type === "lparen") {
289 index += 1;
290 const expressionNode = parseOr(depth + 1);
291 const closeToken = tokens[index];
292 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
293 return null;
294 }
295 index += 1;
296 return expressionNode;
297 }
298​
299 return null;
300 };
301​
302 const parseUnary = (depth: number): KeybindingWhenNode | null => {
303 let notCount = 0;
304 while (tokens[index]?.type === "not") {
305 index += 1;
306 notCount += 1;
307 if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
308 return null;
309 }
310 }
311​
312 let node = parsePrimary(depth);
313 if (!node) return null;
314​
315 while (notCount > 0) {
316 node = { type: "not", node };
317 notCount -= 1;
318 }
319​
320 return node;
321 };
322​
323 const parseAnd = (depth: number): KeybindingWhenNode | null => {
324 let left = parseUnary(depth);
325 if (!left) return null;
326​
327 while (tokens[index]?.type === "and") {
328 index += 1;
329 const right = parseUnary(depth);
330 if (!right) return null;
331 left = { type: "and", left, right };
332 }
333​
334 return left;
335 };
336​
337 const parseOr = (depth: number): KeybindingWhenNode | null => {
338 let left = parseAnd(depth);
339 if (!left) return null;
340​
341 while (tokens[index]?.type === "or") {
342 index += 1;
343 const right = parseAnd(depth);
344 if (!right) return null;
345 left = { type: "or", left, right };
346 }
347​
348 return left;
349 };
350​
351 const ast = parseOr(0);
352 if (!ast || index !== tokens.length) return null;
353 return ast;
355​
356export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
357 const shortcut = parseKeybindingShortcut(rule.key);
358 if (!shortcut) return null;
359​
360 if (rule.when !== undefined) {
361 const whenAst = parseKeybindingWhenExpression(rule.when);
362 if (!whenAst) return null;
363 return {
364 command: rule.command,
365 shortcut,
366 whenAst,
367 };
368 }
369​
370 return {
371 command: rule.command,
372 shortcut,
373 };
375​
376export function compileResolvedKeybindingsConfig(
377 config: ReadonlyArray<KeybindingRule>,
378): ResolvedKeybindingsConfig {
379 const compiled: ResolvedKeybindingRule[] = [];
380 for (const rule of config) {
381 const result = compileResolvedKeybindingRule(rule);
382 if (result) {
383 compiled.push(result);
384 }
385 }
386 return compiled.slice(-MAX_KEYBINDINGS_COUNT);
388​
389export const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
390​
391export function mergeWithDefaultKeybindings(
392 custom: ResolvedKeybindingsConfig,
393): ResolvedKeybindingsConfig {
394 if (custom.length === 0) {
395 return [...DEFAULT_RESOLVED_KEYBINDINGS];
396 }
397​
398 const overriddenCommands = new Set(custom.map((binding) => binding.command));
399 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
400 (binding) => !overriddenCommands.has(binding.command),
401 );
402 const merged = [...retainedDefaults, ...custom];
403​
404 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
405 return merged;
406 }
407​
408 return merged.slice(-MAX_KEYBINDINGS_COUNT);