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