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