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 {
12 isMacPlatform,
13 matchesKeybindingShortcut,
14 matchesKeybindingShortcutModifiers,
15 normalizeEventKey,
16 resolveEventKeys,
17 type ShortcutEventLike,
18 type ShortcutModifierStateLike,
19} from "@t3tools/shared/keybindings";
20import { isElectron } from "./env";
21import { projectScriptIdFromCommand } from "./projectScripts";
22
23export type { ShortcutEventLike, ShortcutModifierStateLike } from "@t3tools/shared/keybindings";
24export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings";
25
26export interface ShortcutMatchContext {
27 terminalFocus: boolean;
28 terminalOpen: boolean;
29 previewFocus: boolean;
30 previewOpen: boolean;
31 isWeb: boolean;
32 isDesktop: boolean;
33 editableFocus?: boolean;
34 [key: string]: boolean;
35}
36
37interface ShortcutMatchOptions {
38 platform?: string;
39 context?: Partial<ShortcutMatchContext>;
40}
41
42interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
43 platform?: string;
44}
45
46const TERMINAL_WORD_BACKWARD = "\u001bb";
47const TERMINAL_WORD_FORWARD = "\u001bf";
48const TERMINAL_LINE_START = "\u0001";
49const TERMINAL_LINE_END = "\u0005";
50const TERMINAL_DELETE_TO_LINE_START = "\u0015";
51function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
52 return options?.platform ?? navigator.platform;
53}
54
55function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
56 return {
57 terminalFocus: false,
58 terminalOpen: false,
59 previewFocus: false,
60 previewOpen: false,
61 isWeb: !isElectron,
62 isDesktop: isElectron,
63 editableFocus: false,
64 ...options?.context,
65 };
66}
67
68function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
69 switch (node.type) {
70 case "identifier":
71 if (node.name === "true") return true;
72 if (node.name === "false") return false;
73 return Boolean(context[node.name]);
74 case "not":
75 return !evaluateWhenNode(node.node, context);
76 case "and":
77 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
78 case "or":
79 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
80 }
81}
82
83function matchesWhenClause(
84 whenAst: KeybindingWhenNode | undefined,
85 context: ShortcutMatchContext,
86): boolean {
87 if (!whenAst) return true;
88 return evaluateWhenNode(whenAst, context);
89}
90
91export function shortcutConflictKey(
92 shortcut: KeybindingShortcut,
93 platform = navigator.platform,
94): string {
95 const useMetaForMod = isMacPlatform(platform);
96 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
97 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
98 return [
99 shortcut.key,
100 metaKey ? "meta" : "",
101 ctrlKey ? "ctrl" : "",
102 shortcut.shiftKey ? "shift" : "",
103 shortcut.altKey ? "alt" : "",
104 ].join("|");
105}
106
107export function effectiveShortcutsForCommand(
108 keybindings: ResolvedKeybindingsConfig,
109 command: KeybindingCommand,
110 options?: ShortcutMatchOptions,
111): KeybindingShortcut[] {
112 const platform = resolvePlatform(options);
113 const context = resolveContext(options);
114 const claimedShortcuts = new Set<string>();
115 const effective: KeybindingShortcut[] = [];
116
117 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
118 const binding = keybindings[index];
119 if (!binding) continue;
120 if (!matchesWhenClause(binding.whenAst, context)) continue;
121
122 const conflictKey = shortcutConflictKey(binding.shortcut, platform);
123 if (claimedShortcuts.has(conflictKey)) {
124 continue;
125 }
126
127 claimedShortcuts.add(conflictKey);
128 if (binding.command === command) {
129 effective.push(binding.shortcut);
130 }
131 }
132
133 return effective;
134}
135
136function findEffectiveShortcutForCommand(
137 keybindings: ResolvedKeybindingsConfig,
138 command: KeybindingCommand,
139 options?: ShortcutMatchOptions,
140): KeybindingShortcut | null {
141 return effectiveShortcutsForCommand(keybindings, command, options)[0] ?? null;
142}
143
144function matchesCommandShortcut(
145 event: ShortcutEventLike,
146 keybindings: ResolvedKeybindingsConfig,
147 command: KeybindingCommand,
148 options?: ShortcutMatchOptions,
149): boolean {
150 return resolveShortcutCommand(event, keybindings, options) === command;
151}
152
153export function resolveShortcutCommand(
154 event: ShortcutEventLike,
155 keybindings: ResolvedKeybindingsConfig,
156 options?: ShortcutMatchOptions,
157): KeybindingCommand | null {
158 const platform = resolvePlatform(options);
159 const context = resolveContext(options);
160
161 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
162 const binding = keybindings[index];
163 if (!binding) continue;
164 if (!matchesWhenClause(binding.whenAst, context)) continue;
165 if (!matchesKeybindingShortcut(event, binding.shortcut, platform)) continue;
166 return binding.command;
167 }
168 return null;
169}
170
171export function resolveChatShortcutCommand(
172 event: ShortcutEventLike,
173 primaryKeybindings: ResolvedKeybindingsConfig,
174 activeKeybindings: ResolvedKeybindingsConfig,
175 options?: ShortcutMatchOptions,
176): KeybindingCommand | null {
177 const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);
178 if (primaryCommand !== null && projectScriptIdFromCommand(primaryCommand) === null) {
179 return primaryCommand;
180 }
181
182 const activeCommand = resolveShortcutCommand(event, activeKeybindings, options);
183 return activeCommand !== null && projectScriptIdFromCommand(activeCommand) !== null
184 ? activeCommand
185 : null;
186}
187
188export function formatShortcutKeyLabel(key: string): string {
189 if (key === " ") return "Space";
190 if (key.length === 1) return key.toUpperCase();
191 if (key === "escape") return "Esc";
192 if (key === "arrowup") return "Up";
193 if (key === "arrowdown") return "Down";
194 if (key === "arrowleft") return "Left";
195 if (key === "arrowright") return "Right";
196 return key.slice(0, 1).toUpperCase() + key.slice(1);
197}
198
199export function formatShortcutLabel(
200 shortcut: KeybindingShortcut,
201 platform = navigator.platform,
202): string {
203 const keyLabel = formatShortcutKeyLabel(shortcut.key);
204 const useMetaForMod = isMacPlatform(platform);
205 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
206 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
207 const showAlt = shortcut.altKey;
208 const showShift = shortcut.shiftKey;
209
210 if (useMetaForMod) {
211 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
212 }
213
214 const parts: string[] = [];
215 if (showCtrl) parts.push("Ctrl");
216 if (showAlt) parts.push("Alt");
217 if (showShift) parts.push("Shift");
218 if (showMeta) parts.push("Meta");
219 parts.push(keyLabel);
220 return parts.join("+");
221}
222
223export function shortcutLabelForCommand(
224 keybindings: ResolvedKeybindingsConfig,
225 command: KeybindingCommand | null,
226 options?: string | ResolvedShortcutLabelOptions,
227): string | null {
228 if (command === null) return null;
229 const resolvedOptions =
230 typeof options === "string"
231 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
232 : options;
233 const platform = resolvePlatform(resolvedOptions);
234 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
235 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
236}
237
238export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
239 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
240}
241
242export function threadJumpIndexFromCommand(command: string): number | null {
243 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
244 return index === -1 ? null : index;
245}
246
247export function threadTraversalDirectionFromCommand(
248 command: string | null,
249): "previous" | "next" | null {
250 if (command === "thread.previous") return "previous";
251 if (command === "thread.next") return "next";
252 return null;
253}
254
255export function shouldShowThreadJumpHintsForModifiers(
256 modifiers: ShortcutModifierStateLike,
257 keybindings: ResolvedKeybindingsConfig,
258 options?: ShortcutMatchOptions,
259): boolean {
260 // The embedded terminal owns keystrokes while it has focus: the Ghostty surface encodes the
261 // keydown and can write the pressed key into the shell before our window-level shortcut handling
262 // ever runs, regardless of any configured `when` clause on the jump command.
263 if (resolveContext(options).terminalFocus) {
264 return false;
265 }
266
267 const platform = resolvePlatform(options);
268
269 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
270 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
271 if (!shortcut) continue;
272 if (matchesKeybindingShortcutModifiers(modifiers, shortcut, platform)) {
273 return true;
274 }
275 }
276
277 return false;
278}
279
280export function modelPickerJumpCommandForIndex(
281 index: number,
282): ModelPickerJumpKeybindingCommand | null {
283 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
284}
285
286export function modelPickerJumpIndexFromCommand(command: string): number | null {
287 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
288 command as ModelPickerJumpKeybindingCommand,
289 );
290 return index === -1 ? null : index;
291}
292
293export function isTerminalToggleShortcut(
294 event: ShortcutEventLike,
295 keybindings: ResolvedKeybindingsConfig,
296 options?: ShortcutMatchOptions,
297): boolean {
298 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
299}
300
301export function isTerminalSplitShortcut(
302 event: ShortcutEventLike,
303 keybindings: ResolvedKeybindingsConfig,
304 options?: ShortcutMatchOptions,
305): boolean {
306 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
307}
308
309export function isTerminalSplitVerticalShortcut(
310 event: ShortcutEventLike,
311 keybindings: ResolvedKeybindingsConfig,
312 options?: ShortcutMatchOptions,
313): boolean {
314 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
315}
316
317export function isTerminalNewShortcut(
318 event: ShortcutEventLike,
319 keybindings: ResolvedKeybindingsConfig,
320 options?: ShortcutMatchOptions,
321): boolean {
322 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
323}
324
325export function isTerminalCloseShortcut(
326 event: ShortcutEventLike,
327 keybindings: ResolvedKeybindingsConfig,
328 options?: ShortcutMatchOptions,
329): boolean {
330 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
331}
332
333export function isDiffToggleShortcut(
334 event: ShortcutEventLike,
335 keybindings: ResolvedKeybindingsConfig,
336 options?: ShortcutMatchOptions,
337): boolean {
338 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
339}
340
341export function isOpenFavoriteEditorShortcut(
342 event: ShortcutEventLike,
343 keybindings: ResolvedKeybindingsConfig,
344 options?: ShortcutMatchOptions,
345): boolean {
346 return (
347 event.repeat !== true &&
348 matchesCommandShortcut(event, keybindings, "editor.openFavorite", options)
349 );
350}
351
352/**
353 * Whether the keypress is the rich-text bold chord (Mod+B without extra
354 * modifiers). Tiptap binds the same chord, so app shortcuts captured ahead
355 * of the editor must yield when the rich-text composer is focused.
356 */
357export function isRichTextBoldShortcut(event: ShortcutEventLike): boolean {
358 if (event.type !== undefined && event.type !== "keydown") {
359 return false;
360 }
361 return (
362 resolveEventKeys(event).has("b") &&
363 (event.metaKey || event.ctrlKey) &&
364 !event.altKey &&
365 !event.shiftKey
366 );
367}
368
369export function isTerminalClearShortcut(
370 event: ShortcutEventLike,
371 platform = navigator.platform,
372): boolean {
373 if (event.type !== undefined && event.type !== "keydown") {
374 return false;
375 }
376
377 const key = event.key.toLowerCase();
378
379 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
380 return true;
381 }
382
383 return (
384 isMacPlatform(platform) &&
385 key === "k" &&
386 event.metaKey &&
387 !event.ctrlKey &&
388 !event.altKey &&
389 !event.shiftKey
390 );
391}
392
393export function terminalDeleteShortcutData(
394 event: ShortcutEventLike,
395 platform = navigator.platform,
396): string | null {
397 if (event.type !== undefined && event.type !== "keydown") {
398 return null;
399 }
400
401 if (!isMacPlatform(platform)) {
402 return null;
403 }
404
405 const key = normalizeEventKey(event.key);
406 if (key !== "backspace") {
407 return null;
408 }
409
410 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
411 ? TERMINAL_DELETE_TO_LINE_START
412 : null;
413}
414
415export function terminalNavigationShortcutData(
416 event: ShortcutEventLike,
417 platform = navigator.platform,
418): string | null {
419 if (event.type !== undefined && event.type !== "keydown") {
420 return null;
421 }
422
423 if (event.shiftKey) return null;
424
425 const key = normalizeEventKey(event.key);
426 if (key !== "arrowleft" && key !== "arrowright") {
427 return null;
428 }
429
430 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
431 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
432
433 if (isMacPlatform(platform)) {
434 if (event.altKey && !event.metaKey && !event.ctrlKey) {
435 return moveWord;
436 }
437 if (event.metaKey && !event.altKey && !event.ctrlKey) {
438 return moveLine;
439 }
440 return null;
441 }
442
443 if (event.ctrlKey && !event.metaKey && !event.altKey) {
444 return moveWord;
445 }
446
447 if (event.altKey && !event.metaKey && !event.ctrlKey) {
448 return moveWord;
449 }
450
451 return null;
452}