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

keybindings.ts

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