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

keybindings.ts

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