Open History to see the last commit
1import {
2 type KeybindingCommand,
3 type KeybindingShortcut,
4 type KeybindingWhenNode,
5 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
6 type ResolvedKeybindingsConfig,
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8 type ModelPickerJumpKeybindingCommand,
9 type ThreadJumpKeybindingCommand,
10} from "@t3tools/contracts";
11import { isMacPlatform } from "./lib/utils";
12
13export interface ShortcutEventLike {
14 type?: string;
15 code?: string;
16 key: string;
17 metaKey: boolean;
18 ctrlKey: boolean;
19 shiftKey: boolean;
20 altKey: boolean;
21}
22
23export interface ShortcutModifierStateLike {
24 metaKey: boolean;
25 ctrlKey: boolean;
26 shiftKey: boolean;
27 altKey: boolean;
28}
29
30export interface ShortcutMatchContext {
31 terminalFocus: boolean;
32 terminalOpen: boolean;
33 [key: string]: boolean;
34}
35
36interface ShortcutMatchOptions {
37 platform?: string;
38 context?: Partial<ShortcutMatchContext>;
39}
40
41interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
42 platform?: string;
43}
44
45const TERMINAL_WORD_BACKWARD = "\u001bb";
46const TERMINAL_WORD_FORWARD = "\u001bf";
47const TERMINAL_LINE_START = "\u0001";
48const TERMINAL_LINE_END = "\u0005";
49const TERMINAL_DELETE_TO_LINE_START = "\u0015";
50const EVENT_CODE_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {
51 BracketLeft: ["["],
52 BracketRight: ["]"],
53 Digit0: ["0"],
54 Digit1: ["1"],
55 Digit2: ["2"],
56 Digit3: ["3"],
57 Digit4: ["4"],
58 Digit5: ["5"],
59 Digit6: ["6"],
60 Digit7: ["7"],
61 Digit8: ["8"],
62 Digit9: ["9"],
63};
64
65function normalizeEventKey(key: string): string {
66 const normalized = key.toLowerCase();
67 if (normalized === "esc") return "escape";
68 return normalized;
69}
70
71function resolveEventKeys(event: ShortcutEventLike): Set<string> {
72 const keys = new Set([normalizeEventKey(event.key)]);
73 const aliases = event.code ? EVENT_CODE_KEY_ALIASES[event.code] : undefined;
74 if (!aliases) return keys;
75
76 for (const alias of aliases) {
77 keys.add(alias);
78 }
79 return keys;
80}
81
82function matchesShortcutModifiers(
83 event: ShortcutModifierStateLike,
84 shortcut: KeybindingShortcut,
85 platform = navigator.platform,
86): boolean {
87 const useMetaForMod = isMacPlatform(platform);
88 const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
89 const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
90 return (
91 event.metaKey === expectedMeta &&
92 event.ctrlKey === expectedCtrl &&
93 event.shiftKey === shortcut.shiftKey &&
94 event.altKey === shortcut.altKey
95 );
96}
97
98function matchesShortcut(
99 event: ShortcutEventLike,
100 shortcut: KeybindingShortcut,
101 platform = navigator.platform,
102): boolean {
103 if (!matchesShortcutModifiers(event, shortcut, platform)) return false;
104 return resolveEventKeys(event).has(shortcut.key);
105}
106
107function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
108 return options?.platform ?? navigator.platform;
109}
110
111function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
112 return {
113 terminalFocus: false,
114 terminalOpen: false,
115 ...options?.context,
116 };
117}
118
119function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
120 switch (node.type) {
121 case "identifier":
122 if (node.name === "true") return true;
123 if (node.name === "false") return false;
124 return Boolean(context[node.name]);
125 case "not":
126 return !evaluateWhenNode(node.node, context);
127 case "and":
128 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
129 case "or":
130 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
131 }
132}
133
134function matchesWhenClause(
135 whenAst: KeybindingWhenNode | undefined,
136 context: ShortcutMatchContext,
137): boolean {
138 if (!whenAst) return true;
139 return evaluateWhenNode(whenAst, context);
140}
141
142function shortcutConflictKey(shortcut: KeybindingShortcut, platform = navigator.platform): string {
143 const useMetaForMod = isMacPlatform(platform);
144 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
145 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
146
147 return [
148 shortcut.key,
149 metaKey ? "meta" : "",
150 ctrlKey ? "ctrl" : "",
151 shortcut.shiftKey ? "shift" : "",
152 shortcut.altKey ? "alt" : "",
153 ].join("|");
154}
155
156function findEffectiveShortcutForCommand(
157 keybindings: ResolvedKeybindingsConfig,
158 command: KeybindingCommand,
159 options?: ShortcutMatchOptions,
160): KeybindingShortcut | null {
161 const platform = resolvePlatform(options);
162 const context = resolveContext(options);
163 const claimedShortcuts = new Set<string>();
164
165 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
166 const binding = keybindings[index];
167 if (!binding) continue;
168 if (!matchesWhenClause(binding.whenAst, context)) continue;
169
170 const conflictKey = shortcutConflictKey(binding.shortcut, platform);
171 if (claimedShortcuts.has(conflictKey)) {
172 continue;
173 }
174
175 claimedShortcuts.add(conflictKey);
176 if (binding.command === command) {
177 return binding.shortcut;
178 }
179 }
180
181 return null;
182}
183
184function matchesCommandShortcut(
185 event: ShortcutEventLike,
186 keybindings: ResolvedKeybindingsConfig,
187 command: KeybindingCommand,
188 options?: ShortcutMatchOptions,
189): boolean {
190 return resolveShortcutCommand(event, keybindings, options) === command;
191}
192
193export function resolveShortcutCommand(
194 event: ShortcutEventLike,
195 keybindings: ResolvedKeybindingsConfig,
196 options?: ShortcutMatchOptions,
197): KeybindingCommand | null {
198 const platform = resolvePlatform(options);
199 const context = resolveContext(options);
200
201 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
202 const binding = keybindings[index];
203 if (!binding) continue;
204 if (!matchesWhenClause(binding.whenAst, context)) continue;
205 if (!matchesShortcut(event, binding.shortcut, platform)) continue;
206 return binding.command;
207 }
208 return null;
209}
210
211function formatShortcutKeyLabel(key: string): string {
212 if (key === " ") return "Space";
213 if (key.length === 1) return key.toUpperCase();
214 if (key === "escape") return "Esc";
215 if (key === "arrowup") return "Up";
216 if (key === "arrowdown") return "Down";
217 if (key === "arrowleft") return "Left";
218 if (key === "arrowright") return "Right";
219 return key.slice(0, 1).toUpperCase() + key.slice(1);
220}
221
222export function formatShortcutLabel(
223 shortcut: KeybindingShortcut,
224 platform = navigator.platform,
225): string {
226 const keyLabel = formatShortcutKeyLabel(shortcut.key);
227 const useMetaForMod = isMacPlatform(platform);
228 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
229 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
230 const showAlt = shortcut.altKey;
231 const showShift = shortcut.shiftKey;
232
233 if (useMetaForMod) {
234 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
235 }
236
237 const parts: string[] = [];
238 if (showCtrl) parts.push("Ctrl");
239 if (showAlt) parts.push("Alt");
240 if (showShift) parts.push("Shift");
241 if (showMeta) parts.push("Meta");
242 parts.push(keyLabel);
243 return parts.join("+");
244}
245
246export function shortcutLabelForCommand(
247 keybindings: ResolvedKeybindingsConfig,
248 command: KeybindingCommand,
249 options?: string | ResolvedShortcutLabelOptions,
250): string | null {
251 const resolvedOptions =
252 typeof options === "string"
253 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
254 : options;
255 const platform = resolvePlatform(resolvedOptions);
256 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
257 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
258}
259
260export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
261 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
262}
263
264export function threadJumpIndexFromCommand(command: string): number | null {
265 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
266 return index === -1 ? null : index;
267}
268
269export function threadTraversalDirectionFromCommand(
270 command: string | null,
271): "previous" | "next" | null {
272 if (command === "thread.previous") return "previous";
273 if (command === "thread.next") return "next";
274 return null;
275}
276
277export function shouldShowThreadJumpHints(
278 event: ShortcutEventLike,
279 keybindings: ResolvedKeybindingsConfig,
280 options?: ShortcutMatchOptions,
281): boolean {
282 return shouldShowThreadJumpHintsForModifiers(event, keybindings, options);
283}
284
285export function shouldShowThreadJumpHintsForModifiers(
286 modifiers: ShortcutModifierStateLike,
287 keybindings: ResolvedKeybindingsConfig,
288 options?: ShortcutMatchOptions,
289): boolean {
290 const platform = resolvePlatform(options);
291
292 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
293 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
294 if (!shortcut) continue;
295 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
296 return true;
297 }
298 }
299
300 return false;
301}
302
303export function modelPickerJumpCommandForIndex(
304 index: number,
305): ModelPickerJumpKeybindingCommand | null {
306 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
307}
308
309export function modelPickerJumpIndexFromCommand(command: string): number | null {
310 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
311 command as ModelPickerJumpKeybindingCommand,
312 );
313 return index === -1 ? null : index;
314}
315
316export function shouldShowModelPickerJumpHints(
317 event: ShortcutEventLike,
318 keybindings: ResolvedKeybindingsConfig,
319 options?: ShortcutMatchOptions,
320): boolean {
321 return shouldShowModelPickerJumpHintsForModifiers(event, keybindings, options);
322}
323
324export function shouldShowModelPickerJumpHintsForModifiers(
325 modifiers: ShortcutModifierStateLike,
326 keybindings: ResolvedKeybindingsConfig,
327 options?: ShortcutMatchOptions,
328): boolean {
329 const platform = resolvePlatform(options);
330
331 for (const command of MODEL_PICKER_JUMP_KEYBINDING_COMMANDS) {
332 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
333 if (!shortcut) continue;
334 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
335 return true;
336 }
337 }
338
339 return false;
340}
341
342export function isTerminalToggleShortcut(
343 event: ShortcutEventLike,
344 keybindings: ResolvedKeybindingsConfig,
345 options?: ShortcutMatchOptions,
346): boolean {
347 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
348}
349
350export function isTerminalSplitShortcut(
351 event: ShortcutEventLike,
352 keybindings: ResolvedKeybindingsConfig,
353 options?: ShortcutMatchOptions,
354): boolean {
355 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
356}
357
358export function isTerminalNewShortcut(
359 event: ShortcutEventLike,
360 keybindings: ResolvedKeybindingsConfig,
361 options?: ShortcutMatchOptions,
362): boolean {
363 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
364}
365
366export function isTerminalCloseShortcut(
367 event: ShortcutEventLike,
368 keybindings: ResolvedKeybindingsConfig,
369 options?: ShortcutMatchOptions,
370): boolean {
371 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
372}
373
374export function isDiffToggleShortcut(
375 event: ShortcutEventLike,
376 keybindings: ResolvedKeybindingsConfig,
377 options?: ShortcutMatchOptions,
378): boolean {
379 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
380}
381
382export function isChatNewShortcut(
383 event: ShortcutEventLike,
384 keybindings: ResolvedKeybindingsConfig,
385 options?: ShortcutMatchOptions,
386): boolean {
387 return matchesCommandShortcut(event, keybindings, "chat.new", options);
388}
389
390export function isChatNewLocalShortcut(
391 event: ShortcutEventLike,
392 keybindings: ResolvedKeybindingsConfig,
393 options?: ShortcutMatchOptions,
394): boolean {
395 return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
396}
397
398export function isOpenFavoriteEditorShortcut(
399 event: ShortcutEventLike,
400 keybindings: ResolvedKeybindingsConfig,
401 options?: ShortcutMatchOptions,
402): boolean {
403 return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
404}
405
406export function isTerminalClearShortcut(
407 event: ShortcutEventLike,
408 platform = navigator.platform,
409): boolean {
410 if (event.type !== undefined && event.type !== "keydown") {
411 return false;
412 }
413
414 const key = event.key.toLowerCase();
415
416 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
417 return true;
418 }
419
420 return (
421 isMacPlatform(platform) &&
422 key === "k" &&
423 event.metaKey &&
424 !event.ctrlKey &&
425 !event.altKey &&
426 !event.shiftKey
427 );
428}
429
430export function terminalDeleteShortcutData(
431 event: ShortcutEventLike,
432 platform = navigator.platform,
433): string | null {
434 if (event.type !== undefined && event.type !== "keydown") {
435 return null;
436 }
437
438 if (!isMacPlatform(platform)) {
439 return null;
440 }
441
442 const key = normalizeEventKey(event.key);
443 if (key !== "backspace") {
444 return null;
445 }
446
447 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
448 ? TERMINAL_DELETE_TO_LINE_START
449 : null;
450}
451
452export function terminalNavigationShortcutData(
453 event: ShortcutEventLike,
454 platform = navigator.platform,
455): string | null {
456 if (event.type !== undefined && event.type !== "keydown") {
457 return null;
458 }
459
460 if (event.shiftKey) return null;
461
462 const key = normalizeEventKey(event.key);
463 if (key !== "arrowleft" && key !== "arrowright") {
464 return null;
465 }
466
467 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
468 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
469
470 if (isMacPlatform(platform)) {
471 if (event.altKey && !event.metaKey && !event.ctrlKey) {
472 return moveWord;
473 }
474 if (event.metaKey && !event.altKey && !event.ctrlKey) {
475 return moveLine;
476 }
477 return null;
478 }
479
480 if (event.ctrlKey && !event.metaKey && !event.altKey) {
481 return moveWord;
482 }
483
484 if (event.altKey && !event.metaKey && !event.ctrlKey) {
485 return moveWord;
486 }
487
488 return null;
489}