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

keybindings.ts

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