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