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