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

keybindings.ts

493 lines14.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 interface ShortcutEventLike {
14 getModifierState?: (key: "AltGraph") => boolean;
15 type?: string;
16 code?: string;
17 key: string;
18 repeat?: boolean;
19 metaKey: boolean;
20 ctrlKey: boolean;
21 shiftKey: boolean;
22 altKey: boolean;
24​
25export interface ShortcutModifierStateLike {
26 metaKey: boolean;
27 ctrlKey: boolean;
28 shiftKey: boolean;
29 altKey: boolean;
31​
32export const EVENT_CODE_SHORTCUT_KEYS: Readonly<Record<string, string>> = {
33 Backquote: "`",
34 Backslash: "\\",
35 BracketLeft: "[",
36 BracketRight: "]",
37 Comma: ",",
38 Digit0: "0",
39 Digit1: "1",
40 Digit2: "2",
41 Digit3: "3",
42 Digit4: "4",
43 Digit5: "5",
44 Digit6: "6",
45 Digit7: "7",
46 Digit8: "8",
47 Digit9: "9",
48 Equal: "=",
49 Minus: "-",
50 Period: ".",
51 Quote: "'",
52 Semicolon: ";",
53 Slash: "/",
54};
55​
56export const US_SHIFTED_TO_UNSHIFTED_KEYS: ReadonlyMap<string, string> = new Map([
57 ["!", "1"],
58 ["@", "2"],
59 ["#", "3"],
60 ["$", "4"],
61 ["%", "5"],
62 ["^", "6"],
63 ["&", "7"],
64 ["*", "8"],
65 ["(", "9"],
66 [")", "0"],
67 ["~", "`"],
68 ["_", "-"],
69 ["+", "="],
70 ["{", "["],
71 ["}", "]"],
72 ["|", "\\"],
73 [":", ";"],
74 ['"', "'"],
75 ["<", ","],
76 [">", "."],
77 ["?", "/"],
78]);
79​
80export function isMacPlatform(platform: string): boolean {
81 return /mac|iphone|ipad|ipod/i.test(platform);
83​
84export function normalizeEventKey(key: string): string {
85 const normalized = key.toLowerCase();
86 if (normalized === "esc") return "escape";
87 return normalized;
89​
90export function shortcutKeyFromEvent(event: Pick<ShortcutEventLike, "key" | "code">): string {
91 const layoutKey = normalizeEventKey(event.key);
92 if (/^[a-z]$/.test(layoutKey)) return layoutKey;
93 const physicalKey = event.code ? EVENT_CODE_SHORTCUT_KEYS[event.code] : undefined;
94 return physicalKey ?? layoutKey;
96​
97export function resolveEventKeys(event: ShortcutEventLike): Set<string> {
98 const layoutKey = normalizeEventKey(event.key);
99 const keys = new Set([layoutKey]);
100 const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1];
101 if (letterCode && !/^[a-z]$/.test(layoutKey)) {
102 keys.add(letterCode.toLowerCase());
103 }
104 keys.add(shortcutKeyFromEvent(event));
105 return keys;
107​
108export function matchesKeybindingShortcutModifiers(
109 event: ShortcutModifierStateLike,
110 shortcut: KeybindingShortcut,
111 platform: string,
112): boolean {
113 const useMetaForMod = isMacPlatform(platform);
114 const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
115 const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
116 return (
117 event.metaKey === expectedMeta &&
118 event.ctrlKey === expectedCtrl &&
119 event.shiftKey === shortcut.shiftKey &&
120 event.altKey === shortcut.altKey
121 );
123​
124export function matchesKeybindingShortcut(
125 event: ShortcutEventLike,
126 shortcut: KeybindingShortcut,
127 platform: string,
128): boolean {
129 if (
130 !isMacPlatform(platform) &&
131 event.getModifierState?.("AltGraph") &&
132 !/^[a-z0-9]$/i.test(event.key)
133 )
134 return false;
135 if (!matchesKeybindingShortcutModifiers(event, shortcut, platform)) return false;
136 return resolveEventKeys(event).has(shortcut.key);
138​
139type WhenToken =
140 | { type: "identifier"; value: string }
141 | { type: "not" }
142 | { type: "and" }
143 | { type: "or" }
144 | { type: "lparen" }
145 | { type: "rparen" };
146​
147export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
148 { key: "mod+b", command: "sidebar.toggle" },
149 { key: "mod+[", command: "navigation.back", when: "!terminalFocus" },
150 { key: "mod+]", command: "navigation.forward", when: "!terminalFocus" },
151 { key: "mod+j", command: "terminal.toggle" },
152 { key: "mod+alt+b", command: "rightPanel.toggle" },
153 { key: "mod+shift+b", command: "threadPanel.toggle", when: "!terminalFocus" },
154 { key: "mod+t", command: "rightPanel.new", when: "rightPanelOpen && !terminalFocus" },
155 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
156 { key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
157 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
158 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
159 { key: "mod+w", command: "rightPanel.close", when: "!terminalFocus" },
160 { key: "mod+shift+t", command: "view.reopenClosed" },
161 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
162 { key: "mod+shift+j", command: "preview.toggle" },
163 { key: "mod+r", command: "preview.refresh", when: "previewFocus" },
164 { key: "mod+l", command: "preview.focusUrl", when: "previewFocus" },
165 { key: "mod+=", command: "preview.zoomIn", when: "previewFocus" },
166 { key: "mod++", command: "preview.zoomIn", when: "previewFocus" },
167 { key: "mod+-", command: "preview.zoomOut", when: "previewFocus" },
168 { key: "mod+0", command: "preview.resetZoom", when: "previewFocus" },
169 { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
170 { key: "mod+p", command: "filePicker.toggle", when: "!terminalFocus" },
171 { key: "mod+shift+f", command: "projectSearch.toggle", when: "!terminalFocus" },
172 { key: "mod+u", command: "usage.open", when: "!terminalFocus" },
173 { key: "mod+alt+a", command: "theme.select", when: "!terminalFocus" },
174 { key: "mod+alt+shift+a", command: "appearance.cycle", when: "!terminalFocus" },
175 { key: "mod+alt+shift+t", command: "themeEditor.toggle" },
176 { key: "mod+s", command: "composer.stash", when: "!terminalFocus" },
177 { key: "mod+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" },
178 { key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" },
179 { key: "mod+enter", command: "composer.sendAlternate", when: "composerFocus && turnRunning" },
180 {
181 key: "mod+enter",
182 command: "composer.sendBackground",
183 when: "composerFocus && draftThreadRoute",
184 },
185 {
186 key: "mod+alt+enter",
187 command: "composer.sendBackground",
188 when: "composerFocus && draftThreadRoute",
189 },
190 {
191 key: "mod+alt+enter",
192 command: "composer.sendAndNewThread",
193 when: "composerFocus && !draftThreadRoute",
194 },
195 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
196 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
197 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
198 { key: "mod+alt+n", command: "chat.newWithoutProject", when: "!terminalFocus" },
199 { key: "mod+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },
200 { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
201 { key: "mod+shift+h", command: "composer.host", when: "!terminalFocus" },
202 { key: "mod+shift+e", command: "composer.effort", when: "!terminalFocus" },
203 { key: "mod+shift+a", command: "composer.mode", when: "!terminalFocus" },
204 { key: "mod+shift+x", command: "composer.workspace", when: "!terminalFocus" },
205 { key: "mod+shift+g", command: "composer.branch", when: "!terminalFocus" },
206 { key: "mod+shift+l", command: "composer.previousWorktree", when: "!terminalFocus" },
207 { key: "mod+shift+k", command: "pullRequest.copyNumber", when: "!terminalFocus" },
208 { key: "mod+shift+arrowup", command: "modelPicker.previousProvider", when: "modelPickerOpen" },
209 { key: "mod+shift+arrowdown", command: "modelPicker.nextProvider", when: "modelPickerOpen" },
210 { key: "mod+o", command: "editor.openFavorite" },
211 { key: "mod+shift+[", command: "thread.previous" },
212 { key: "mod+shift+]", command: "thread.next" },
213 { key: "mod+shift+c", command: "thread.copyReference", when: "!terminalFocus" },
214 { key: "mod+shift+s", command: "thread.settle", when: "!terminalFocus" },
215 { key: "mod+shift+p", command: "thread.pin", when: "!terminalFocus" },
216 { key: "mod+z", command: "thread.undo", when: "!terminalFocus && !editableFocus" },
217 ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
218 key: `mod+${index + 1}`,
219 command,
220 when: "!modelPickerOpen && isDesktop",
221 })),
222 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
223 key: `mod+${index + 1}`,
224 command,
225 when: "modelPickerOpen && isDesktop",
226 })),
227 { key: "c", command: "usage.cost", when: "usagePageOpen" },
228 { key: "t", command: "usage.tokens", when: "usagePageOpen" },
229 { key: "l", command: "usage.limits", when: "usagePageOpen" },
230 { key: "mod+shift+1", command: "usage.period.day", when: "usagePageOpen" },
231 { key: "mod+shift+2", command: "usage.period.week", when: "usagePageOpen" },
232 { key: "mod+shift+3", command: "usage.period.month", when: "usagePageOpen" },
233 { key: "mod+shift+4", command: "usage.period.quarter", when: "usagePageOpen" },
234];
235​
236function normalizeKeyToken(token: string): string {
237 if (token === "space") return " ";
238 if (token === "esc") return "escape";
239 return token;
241​
242export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
243 const rawTokens = value
244 .toLowerCase()
245 .split("+")
246 .map((token) => token.trim());
247 const tokens = [...rawTokens];
248 let trailingEmptyCount = 0;
249 while (tokens[tokens.length - 1] === "") {
250 trailingEmptyCount += 1;
251 tokens.pop();
252 }
253 if (trailingEmptyCount > 0) {
254 tokens.push("+");
255 }
256 if (tokens.some((token) => token.length === 0)) {
257 return null;
258 }
259 if (tokens.length === 0) return null;
260​
261 let key: string | null = null;
262 let metaKey = false;
263 let ctrlKey = false;
264 let shiftKey = false;
265 let altKey = false;
266 let modKey = false;
267​
268 for (const token of tokens) {
269 switch (token) {
270 case "cmd":
271 case "meta":
272 metaKey = true;
273 break;
274 case "ctrl":
275 case "control":
276 ctrlKey = true;
277 break;
278 case "shift":
279 shiftKey = true;
280 break;
281 case "alt":
282 case "option":
283 altKey = true;
284 break;
285 case "mod":
286 modKey = true;
287 break;
288 default: {
289 if (key !== null) return null;
290 key = normalizeKeyToken(token);
291 }
292 }
293 }
294​
295 if (key === null) return null;
296 return {
297 key,
298 metaKey,
299 ctrlKey,
300 shiftKey,
301 altKey,
302 modKey,
303 };
305​
306function tokenizeWhenExpression(expression: string): WhenToken[] | null {
307 const tokens: WhenToken[] = [];
308 let index = 0;
309​
310 while (index < expression.length) {
311 const current = expression[index];
312 if (!current) break;
313​
314 if (/\s/.test(current)) {
315 index += 1;
316 continue;
317 }
318 if (expression.startsWith("&&", index)) {
319 tokens.push({ type: "and" });
320 index += 2;
321 continue;
322 }
323 if (expression.startsWith("||", index)) {
324 tokens.push({ type: "or" });
325 index += 2;
326 continue;
327 }
328 if (current === "!") {
329 tokens.push({ type: "not" });
330 index += 1;
331 continue;
332 }
333 if (current === "(") {
334 tokens.push({ type: "lparen" });
335 index += 1;
336 continue;
337 }
338 if (current === ")") {
339 tokens.push({ type: "rparen" });
340 index += 1;
341 continue;
342 }
343​
344 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
345 if (!identifier) {
346 return null;
347 }
348 tokens.push({ type: "identifier", value: identifier[0] });
349 index += identifier[0].length;
350 }
351​
352 return tokens;
354​
355export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
356 const tokens = tokenizeWhenExpression(expression);
357 if (!tokens || tokens.length === 0) return null;
358 let index = 0;
359​
360 const parsePrimary = (depth: number): KeybindingWhenNode | null => {
361 if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
362 return null;
363 }
364 const token = tokens[index];
365 if (!token) return null;
366​
367 if (token.type === "identifier") {
368 index += 1;
369 return { type: "identifier", name: token.value };
370 }
371​
372 if (token.type === "lparen") {
373 index += 1;
374 const expressionNode = parseOr(depth + 1);
375 const closeToken = tokens[index];
376 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
377 return null;
378 }
379 index += 1;
380 return expressionNode;
381 }
382​
383 return null;
384 };
385​
386 const parseUnary = (depth: number): KeybindingWhenNode | null => {
387 let notCount = 0;
388 while (tokens[index]?.type === "not") {
389 index += 1;
390 notCount += 1;
391 if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
392 return null;
393 }
394 }
395​
396 let node = parsePrimary(depth);
397 if (!node) return null;
398​
399 while (notCount > 0) {
400 node = { type: "not", node };
401 notCount -= 1;
402 }
403​
404 return node;
405 };
406​
407 const parseAnd = (depth: number): KeybindingWhenNode | null => {
408 let left = parseUnary(depth);
409 if (!left) return null;
410​
411 while (tokens[index]?.type === "and") {
412 index += 1;
413 const right = parseUnary(depth);
414 if (!right) return null;
415 left = { type: "and", left, right };
416 }
417​
418 return left;
419 };
420​
421 const parseOr = (depth: number): KeybindingWhenNode | null => {
422 let left = parseAnd(depth);
423 if (!left) return null;
424​
425 while (tokens[index]?.type === "or") {
426 index += 1;
427 const right = parseAnd(depth);
428 if (!right) return null;
429 left = { type: "or", left, right };
430 }
431​
432 return left;
433 };
434​
435 const ast = parseOr(0);
436 if (!ast || index !== tokens.length) return null;
437 return ast;
439​
440export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
441 const shortcut = parseKeybindingShortcut(rule.key);
442 if (!shortcut) return null;
443​
444 if (rule.when !== undefined) {
445 const whenAst = parseKeybindingWhenExpression(rule.when);
446 if (!whenAst) return null;
447 return {
448 command: rule.command,
449 shortcut,
450 whenAst,
451 };
452 }
453​
454 return {
455 command: rule.command,
456 shortcut,
457 };
459​
460export function compileResolvedKeybindingsConfig(
461 config: ReadonlyArray<KeybindingRule>,
462): ResolvedKeybindingsConfig {
463 const compiled: ResolvedKeybindingRule[] = [];
464 for (const rule of config) {
465 const result = compileResolvedKeybindingRule(rule);
466 if (result) {
467 compiled.push(result);
468 }
469 }
470 return compiled.slice(-MAX_KEYBINDINGS_COUNT);
472​
473export const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
474​
475export function mergeWithDefaultKeybindings(
476 custom: ResolvedKeybindingsConfig,
477): ResolvedKeybindingsConfig {
478 if (custom.length === 0) {
479 return [...DEFAULT_RESOLVED_KEYBINDINGS];
480 }
481​
482 const overriddenCommands = new Set(custom.map((binding) => binding.command));
483 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
484 (binding) => !overriddenCommands.has(binding.command),
485 );
486 const merged = [...retainedDefaults, ...custom];
487​
488 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
489 return merged;
490 }
491​
492 return merged.slice(-MAX_KEYBINDINGS_COUNT);