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