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