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