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 as SharedShortcutEventLike,
19 type ShortcutModifierStateLike,
20 type ShortcutKeyboardLayoutMap,
21 shortcutKeyFromEvent as sharedShortcutKeyFromEvent,
22} from "@t3tools/shared/keybindings";
23import { isElectron } from "./env";
24import { isEditableFocused } from "./lib/editableFocus";
25import { projectScriptIdFromCommand } from "./projectScripts";
26import { getKeyboardLayoutMap } from "./keyboardLayout";
27
28export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings";
29export function shortcutKeyFromEvent(
30 event: Pick<ShortcutEventLike, "key" | "code" | "shiftKey" | "altKey">,
31 platform: string,
32) {
33 return sharedShortcutKeyFromEvent(
34 event,
35 isMacPlatform(platform) && event.altKey ? getKeyboardLayoutMap() : undefined,
36 );
37}
38
39export interface ShortcutEventLike extends SharedShortcutEventLike {
40 target?: EventTarget | null;
41}
42
43export interface ShortcutMatchContext {
44 terminalFocus: boolean;
45 terminalOpen: boolean;
46 previewFocus: boolean;
47 previewOpen: boolean;
48 isWeb: boolean;
49 isDesktop: boolean;
50 editableFocus?: boolean;
51 [key: string]: boolean;
52}
53
54interface ShortcutMatchOptions {
55 platform?: string;
56 keyboardLayoutMap?: ShortcutKeyboardLayoutMap;
57 context?: Partial<ShortcutMatchContext>;
58}
59
60interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
61 platform?: string;
62}
63
64const TERMINAL_WORD_BACKWARD = "\u001bb";
65const TERMINAL_WORD_FORWARD = "\u001bf";
66const TERMINAL_LINE_START = "\u0001";
67const TERMINAL_LINE_END = "\u0005";
68const TERMINAL_DELETE_TO_LINE_START = "\u0015";
69function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
70 return options?.platform ?? navigator.platform;
71}
72
73function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
74 return {
75 terminalFocus: false,
76 terminalOpen: false,
77 previewFocus: false,
78 previewOpen: false,
79 isWeb: !isElectron,
80 isDesktop: isElectron,
81 editableFocus: false,
82 isMac: isMacPlatform(resolvePlatform(options)),
83 ...options?.context,
84 };
85}
86
87function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
88 switch (node.type) {
89 case "identifier":
90 if (node.name === "true") return true;
91 if (node.name === "false") return false;
92 return Object.hasOwn(context, node.name) && Boolean(context[node.name]);
93 case "not":
94 return !evaluateWhenNode(node.node, context);
95 case "and":
96 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
97 case "or":
98 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
99 }
100}
101
102function matchesWhenClause(
103 whenAst: KeybindingWhenNode | undefined,
104 context: ShortcutMatchContext,
105): boolean {
106 if (!whenAst) return true;
107 return evaluateWhenNode(whenAst, context);
108}
109
110export function shortcutConflictKey(
111 shortcut: KeybindingShortcut,
112 platform = navigator.platform,
113): string {
114 const useMetaForMod = isMacPlatform(platform);
115 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
116 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
117 return [
118 shortcut.key,
119 metaKey ? "meta" : "",
120 ctrlKey ? "ctrl" : "",
121 shortcut.shiftKey ? "shift" : "",
122 shortcut.altKey ? "alt" : "",
123 ].join("|");
124}
125
126export function shortcutForContext(
127 binding: ResolvedKeybindingRule,
128 context: Partial<ShortcutMatchContext>,
129) {
130 const shortcut = binding.shortcut;
131 // Resolve persisted Mod+Enter against send preference without rewriting saved shortcuts.
132 if (
133 context.composerRequiresModifier &&
134 (binding.command === "composer.sendAlternate" ||
135 binding.command === "composer.sendBackground") &&
136 shortcut.key === "enter" &&
137 shortcut.modKey &&
138 !shortcut.metaKey &&
139 !shortcut.ctrlKey &&
140 !shortcut.altKey &&
141 !shortcut.shiftKey
142 ) {
143 return { ...shortcut, shiftKey: true };
144 }
145 return shortcut;
146}
147
148export function effectiveShortcutsForCommand(
149 keybindings: ResolvedKeybindingsConfig,
150 command: KeybindingCommand,
151 options?: ShortcutMatchOptions,
152): KeybindingShortcut[] {
153 const platform = resolvePlatform(options);
154 const context = resolveContext(options);
155 const claimedShortcuts = new Set<string>();
156 const effective: KeybindingShortcut[] = [];
157
158 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
159 const binding = keybindings[index];
160 if (!binding) continue;
161 if (!matchesWhenClause(binding.whenAst, context)) continue;
162
163 const shortcut = shortcutForContext(binding, context);
164 const conflictKey = shortcutConflictKey(shortcut, platform);
165 if (claimedShortcuts.has(conflictKey)) {
166 continue;
167 }
168
169 claimedShortcuts.add(conflictKey);
170 if (binding.command === command) {
171 effective.push(shortcut);
172 }
173 }
174
175 return effective;
176}
177
178function findEffectiveShortcutForCommand(
179 keybindings: ResolvedKeybindingsConfig,
180 command: KeybindingCommand,
181 options?: ShortcutMatchOptions,
182): KeybindingShortcut | null {
183 return effectiveShortcutsForCommand(keybindings, command, options)[0] ?? null;
184}
185
186function matchesCommandShortcut(
187 event: ShortcutEventLike,
188 keybindings: ResolvedKeybindingsConfig,
189 command: KeybindingCommand,
190 options?: ShortcutMatchOptions,
191): boolean {
192 return resolveShortcutCommand(event, keybindings, options) === command;
193}
194
195export function resolveShortcutCommand(
196 event: ShortcutEventLike,
197 keybindings: ResolvedKeybindingsConfig,
198 options?: ShortcutMatchOptions,
199): KeybindingCommand | null {
200 const match = (fallback: boolean) => matchShortcutCommand(event, keybindings, options, fallback);
201 return match(false) ?? (event.key.toLowerCase() === "i\u0307" ? match(true) : null);
202}
203
204function matchShortcutCommand(
205 event: ShortcutEventLike,
206 keybindings: ResolvedKeybindingsConfig,
207 options: ShortcutMatchOptions | undefined,
208 allowDottedIFallback: boolean,
209): KeybindingCommand | null {
210 const platform = resolvePlatform(options);
211 const context = resolveContext(options);
212 if (options?.context?.editableFocus === undefined && typeof document !== "undefined") {
213 context.editableFocus = isEditableFocused(event.target ?? document.activeElement);
214 }
215
216 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
217 const binding = keybindings[index];
218 if (!binding) continue;
219 if (!matchesWhenClause(binding.whenAst, context)) continue;
220 if (
221 !matchesKeybindingShortcut(
222 event,
223 shortcutForContext(binding, context),
224 platform,
225 options?.keyboardLayoutMap ?? getKeyboardLayoutMap(),
226 allowDottedIFallback,
227 )
228 )
229 continue;
230 return binding.command;
231 }
232 return null;
233}
234
235export function resolveChatShortcutCommand(
236 event: ShortcutEventLike,
237 primaryKeybindings: ResolvedKeybindingsConfig,
238 activeKeybindings: ResolvedKeybindingsConfig,
239 options?: ShortcutMatchOptions,
240): KeybindingCommand | null {
241 const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);
242 if (primaryCommand !== null && projectScriptIdFromCommand(primaryCommand) === null) {
243 return primaryCommand;
244 }
245
246 const activeCommand = resolveShortcutCommand(event, activeKeybindings, options);
247 return activeCommand !== null && projectScriptIdFromCommand(activeCommand) !== null
248 ? activeCommand
249 : null;
250}
251
252export function formatShortcutKeyLabel(key: string): string {
253 if (key === " ") return "Space";
254 if (key.length === 1) return key.toUpperCase();
255 if (key === "escape") return "Esc";
256 if (key === "arrowup") return "Up";
257 if (key === "arrowdown") return "Down";
258 if (key === "arrowleft") return "Left";
259 if (key === "arrowright") return "Right";
260 if (key === "pageup") return "PageUp";
261 if (key === "pagedown") return "PageDown";
262 return key.slice(0, 1).toUpperCase() + key.slice(1);
263}
264
265export function formatShortcutKeyParts(
266 shortcut: KeybindingShortcut,
267 platform = navigator.platform,
268): readonly string[] {
269 const useMetaForMod = isMacPlatform(platform);
270 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
271 const showAlt = shortcut.altKey;
272 const showShift = shortcut.shiftKey;
273 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
274 const parts: string[] = [];
275 if (showCtrl) parts.push(useMetaForMod ? "\u2303" : "Ctrl");
276 if (showAlt) parts.push(useMetaForMod ? "\u2325" : "Alt");
277 if (showShift) parts.push(useMetaForMod ? "\u21e7" : "Shift");
278 if (showMeta) parts.push(useMetaForMod ? "\u2318" : "Meta");
279 parts.push(formatShortcutKeyLabel(shortcut.key));
280 return parts;
281}
282
283export function formatShortcutLabel(
284 shortcut: KeybindingShortcut,
285 platform = navigator.platform,
286): string {
287 const parts = formatShortcutKeyParts(shortcut, platform);
288 return isMacPlatform(platform) ? parts.join("") : parts.join("+");
289}
290
291export function shortcutLabelForCommand(
292 keybindings: ResolvedKeybindingsConfig,
293 command: KeybindingCommand | null,
294 options?: string | ResolvedShortcutLabelOptions,
295): string | null {
296 if (command === null) return null;
297 const resolvedOptions =
298 typeof options === "string"
299 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
300 : options;
301 const platform = resolvePlatform(resolvedOptions);
302 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
303 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
304}
305
306export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
307 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
308}
309
310export function threadJumpIndexFromCommand(command: string): number | null {
311 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
312 return index === -1 ? null : index;
313}
314
315export function threadTraversalDirectionFromCommand(
316 command: string | null,
317): "previous" | "next" | null {
318 if (command === "thread.previous") return "previous";
319 if (command === "thread.next") return "next";
320 return null;
321}
322
323export function isThreadNavigationShortcut(
324 event: ShortcutEventLike,
325 keybindings: ResolvedKeybindingsConfig,
326 options?: ShortcutMatchOptions,
327): boolean {
328 const command = resolveShortcutCommand(event, keybindings, options);
329 return (
330 threadTraversalDirectionFromCommand(command) !== null ||
331 threadJumpIndexFromCommand(command ?? "") !== null
332 );
333}
334
335export function shouldShowThreadJumpHintsForModifiers(
336 modifiers: ShortcutModifierStateLike,
337 keybindings: ResolvedKeybindingsConfig,
338 options?: ShortcutMatchOptions,
339): boolean {
340 // Holding a modifier is routine in a shell (Ctrl+C, Ctrl+R), so don't flash hints over it.
341 if (resolveContext(options).terminalFocus) {
342 return false;
343 }
344
345 const platform = resolvePlatform(options);
346
347 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
348 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
349 if (!shortcut) continue;
350 if (matchesKeybindingShortcutModifiers(modifiers, shortcut, platform)) {
351 return true;
352 }
353 }
354
355 return false;
356}
357
358export function modelPickerJumpCommandForIndex(
359 index: number,
360): ModelPickerJumpKeybindingCommand | null {
361 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
362}
363
364export function modelPickerJumpIndexFromCommand(command: string): number | null {
365 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
366 command as ModelPickerJumpKeybindingCommand,
367 );
368 return index === -1 ? null : index;
369}
370
371export function isTerminalToggleShortcut(
372 event: ShortcutEventLike,
373 keybindings: ResolvedKeybindingsConfig,
374 options?: ShortcutMatchOptions,
375): boolean {
376 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
377}
378
379export function isTerminalSplitShortcut(
380 event: ShortcutEventLike,
381 keybindings: ResolvedKeybindingsConfig,
382 options?: ShortcutMatchOptions,
383): boolean {
384 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
385}
386
387export function isTerminalSplitVerticalShortcut(
388 event: ShortcutEventLike,
389 keybindings: ResolvedKeybindingsConfig,
390 options?: ShortcutMatchOptions,
391): boolean {
392 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
393}
394
395export function isTerminalNewShortcut(
396 event: ShortcutEventLike,
397 keybindings: ResolvedKeybindingsConfig,
398 options?: ShortcutMatchOptions,
399): boolean {
400 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
401}
402
403export function isTerminalCycleShortcut(
404 event: ShortcutEventLike,
405 keybindings: ResolvedKeybindingsConfig,
406 options?: ShortcutMatchOptions,
407): boolean {
408 const command = resolveShortcutCommand(event, keybindings, options);
409 return command === "terminal.previous" || command === "terminal.next";
410}
411
412export function isTerminalCloseShortcut(
413 event: ShortcutEventLike,
414 keybindings: ResolvedKeybindingsConfig,
415 options?: ShortcutMatchOptions,
416): boolean {
417 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
418}
419
420export function isDiffToggleShortcut(
421 event: ShortcutEventLike,
422 keybindings: ResolvedKeybindingsConfig,
423 options?: ShortcutMatchOptions,
424): boolean {
425 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
426}
427
428export function isSidebarToggleShortcut(
429 event: ShortcutEventLike,
430 keybindings: ResolvedKeybindingsConfig,
431 options?: ShortcutMatchOptions,
432): boolean {
433 // A focused terminal owns Ctrl chords, such as tmux's Ctrl+B prefix; Cmd never reaches it.
434 if (event.ctrlKey && options?.context?.terminalFocus) return false;
435 return matchesCommandShortcut(event, keybindings, "sidebar.toggle", options);
436}
437
438export function isOpenFavoriteEditorShortcut(
439 event: ShortcutEventLike,
440 keybindings: ResolvedKeybindingsConfig,
441 options?: ShortcutMatchOptions,
442): boolean {
443 return (
444 event.repeat !== true &&
445 matchesCommandShortcut(event, keybindings, "editor.openFavorite", options)
446 );
447}
448
449/**
450 * Whether the keypress should bold text in the rich-text composer: Mod+B
451 * without extra modifiers, with text selected. Tiptap binds the same chord, so
452 * app shortcuts captured ahead of the editor yield only in that case. With no
453 * selection an app binding on the chord wins (the sidebar toggle by default).
454 */
455export function isRichTextBoldShortcut(
456 event: ShortcutEventLike,
457 selection: Pick<Selection, "isCollapsed"> | null,
458): boolean {
459 if (event.type !== undefined && event.type !== "keydown") {
460 return false;
461 }
462 return (
463 selection !== null &&
464 !selection.isCollapsed &&
465 resolveEventKeys(event).has("b") &&
466 (event.metaKey || event.ctrlKey) &&
467 !event.altKey &&
468 !event.shiftKey
469 );
470}
471
472/** Mod+B, Mod+I and Mod+E, the mark chords the rich-text composer binds. */
473export function isRichTextFormattingShortcut(event: ShortcutEventLike): boolean {
474 if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return false;
475 const keys = resolveEventKeys(event);
476 return keys.has("b") || keys.has("i") || keys.has("e");
477}
478
479export function isTerminalClearShortcut(
480 event: ShortcutEventLike,
481 platform = navigator.platform,
482): boolean {
483 if (event.type !== undefined && event.type !== "keydown") {
484 return false;
485 }
486
487 const key = event.key.toLowerCase();
488
489 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
490 return true;
491 }
492
493 return (
494 isMacPlatform(platform) &&
495 key === "k" &&
496 event.metaKey &&
497 !event.ctrlKey &&
498 !event.altKey &&
499 !event.shiftKey
500 );
501}
502
503export function terminalDeleteShortcutData(
504 event: ShortcutEventLike,
505 platform = navigator.platform,
506): string | null {
507 if (event.type !== undefined && event.type !== "keydown") {
508 return null;
509 }
510
511 if (!isMacPlatform(platform)) {
512 return null;
513 }
514
515 const key = normalizeEventKey(event.key);
516 if (key !== "backspace") {
517 return null;
518 }
519
520 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
521 ? TERMINAL_DELETE_TO_LINE_START
522 : null;
523}
524
525export function terminalNavigationShortcutData(
526 event: ShortcutEventLike,
527 platform = navigator.platform,
528): string | null {
529 if (event.type !== undefined && event.type !== "keydown") {
530 return null;
531 }
532
533 if (event.shiftKey) return null;
534
535 const key = normalizeEventKey(event.key);
536 if (key !== "arrowleft" && key !== "arrowright") {
537 return null;
538 }
539
540 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
541 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
542
543 if (isMacPlatform(platform)) {
544 if (event.altKey && !event.metaKey && !event.ctrlKey) {
545 return moveWord;
546 }
547 if (event.metaKey && !event.altKey && !event.ctrlKey) {
548 return moveLine;
549 }
550 return null;
551 }
552
553 if (event.altKey && !event.metaKey && !event.ctrlKey) {
554 return moveWord;
555 }
556
557 return null;
558}