Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

547 lines16.6 KB

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 );
38​
39export interface ShortcutEventLike extends SharedShortcutEventLike {
40 target?: EventTarget | null;
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;
53​
54interface ShortcutMatchOptions {
55 platform?: string;
56 keyboardLayoutMap?: ShortcutKeyboardLayoutMap;
57 context?: Partial<ShortcutMatchContext>;
59​
60interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
61 platform?: string;
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;
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 };
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 }
101​
102function matchesWhenClause(
103 whenAst: KeybindingWhenNode | undefined,
104 context: ShortcutMatchContext,
105): boolean {
106 if (!whenAst) return true;
107 return evaluateWhenNode(whenAst, context);
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("|");
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;
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;
177​
178function findEffectiveShortcutForCommand(
179 keybindings: ResolvedKeybindingsConfig,
180 command: KeybindingCommand,
181 options?: ShortcutMatchOptions,
182): KeybindingShortcut | null {
183 return effectiveShortcutsForCommand(keybindings, command, options)[0] ?? null;
185​
186function matchesCommandShortcut(
187 event: ShortcutEventLike,
188 keybindings: ResolvedKeybindingsConfig,
189 command: KeybindingCommand,
190 options?: ShortcutMatchOptions,
191): boolean {
192 return resolveShortcutCommand(event, keybindings, options) === command;
194​
195export function resolveShortcutCommand(
196 event: ShortcutEventLike,
197 keybindings: ResolvedKeybindingsConfig,
198 options?: ShortcutMatchOptions,
199): KeybindingCommand | null {
200 const platform = resolvePlatform(options);
201 const context = resolveContext(options);
202 if (options?.context?.editableFocus === undefined && typeof document !== "undefined") {
203 context.editableFocus = isEditableFocused(event.target ?? document.activeElement);
204 }
205​
206 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
207 const binding = keybindings[index];
208 if (!binding) continue;
209 if (!matchesWhenClause(binding.whenAst, context)) continue;
210 if (
211 !matchesKeybindingShortcut(
212 event,
213 shortcutForContext(binding, context),
214 platform,
215 options?.keyboardLayoutMap ?? getKeyboardLayoutMap(),
216 )
217 )
218 continue;
219 return binding.command;
220 }
221 return null;
223​
224export function resolveChatShortcutCommand(
225 event: ShortcutEventLike,
226 primaryKeybindings: ResolvedKeybindingsConfig,
227 activeKeybindings: ResolvedKeybindingsConfig,
228 options?: ShortcutMatchOptions,
229): KeybindingCommand | null {
230 const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);
231 if (primaryCommand !== null && projectScriptIdFromCommand(primaryCommand) === null) {
232 return primaryCommand;
233 }
234​
235 const activeCommand = resolveShortcutCommand(event, activeKeybindings, options);
236 return activeCommand !== null && projectScriptIdFromCommand(activeCommand) !== null
237 ? activeCommand
238 : null;
240​
241export function formatShortcutKeyLabel(key: string): string {
242 if (key === " ") return "Space";
243 if (key.length === 1) return key.toUpperCase();
244 if (key === "escape") return "Esc";
245 if (key === "arrowup") return "Up";
246 if (key === "arrowdown") return "Down";
247 if (key === "arrowleft") return "Left";
248 if (key === "arrowright") return "Right";
249 if (key === "pageup") return "PageUp";
250 if (key === "pagedown") return "PageDown";
251 return key.slice(0, 1).toUpperCase() + key.slice(1);
253​
254export function formatShortcutKeyParts(
255 shortcut: KeybindingShortcut,
256 platform = navigator.platform,
257): readonly string[] {
258 const useMetaForMod = isMacPlatform(platform);
259 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
260 const showAlt = shortcut.altKey;
261 const showShift = shortcut.shiftKey;
262 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
263 const parts: string[] = [];
264 if (showCtrl) parts.push(useMetaForMod ? "\u2303" : "Ctrl");
265 if (showAlt) parts.push(useMetaForMod ? "\u2325" : "Alt");
266 if (showShift) parts.push(useMetaForMod ? "\u21e7" : "Shift");
267 if (showMeta) parts.push(useMetaForMod ? "\u2318" : "Meta");
268 parts.push(formatShortcutKeyLabel(shortcut.key));
269 return parts;
271​
272export function formatShortcutLabel(
273 shortcut: KeybindingShortcut,
274 platform = navigator.platform,
275): string {
276 const parts = formatShortcutKeyParts(shortcut, platform);
277 return isMacPlatform(platform) ? parts.join("") : parts.join("+");
279​
280export function shortcutLabelForCommand(
281 keybindings: ResolvedKeybindingsConfig,
282 command: KeybindingCommand | null,
283 options?: string | ResolvedShortcutLabelOptions,
284): string | null {
285 if (command === null) return null;
286 const resolvedOptions =
287 typeof options === "string"
288 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
289 : options;
290 const platform = resolvePlatform(resolvedOptions);
291 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
292 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
294​
295export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
296 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
298​
299export function threadJumpIndexFromCommand(command: string): number | null {
300 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
301 return index === -1 ? null : index;
303​
304export function threadTraversalDirectionFromCommand(
305 command: string | null,
306): "previous" | "next" | null {
307 if (command === "thread.previous") return "previous";
308 if (command === "thread.next") return "next";
309 return null;
311​
312export function isThreadNavigationShortcut(
313 event: ShortcutEventLike,
314 keybindings: ResolvedKeybindingsConfig,
315 options?: ShortcutMatchOptions,
316): boolean {
317 const command = resolveShortcutCommand(event, keybindings, options);
318 return (
319 threadTraversalDirectionFromCommand(command) !== null ||
320 threadJumpIndexFromCommand(command ?? "") !== null
321 );
323​
324export function shouldShowThreadJumpHintsForModifiers(
325 modifiers: ShortcutModifierStateLike,
326 keybindings: ResolvedKeybindingsConfig,
327 options?: ShortcutMatchOptions,
328): boolean {
329 // Holding a modifier is routine in a shell (Ctrl+C, Ctrl+R), so don't flash hints over it.
330 if (resolveContext(options).terminalFocus) {
331 return false;
332 }
333​
334 const platform = resolvePlatform(options);
335​
336 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
337 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
338 if (!shortcut) continue;
339 if (matchesKeybindingShortcutModifiers(modifiers, shortcut, platform)) {
340 return true;
341 }
342 }
343​
344 return false;
346​
347export function modelPickerJumpCommandForIndex(
348 index: number,
349): ModelPickerJumpKeybindingCommand | null {
350 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
352​
353export function modelPickerJumpIndexFromCommand(command: string): number | null {
354 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
355 command as ModelPickerJumpKeybindingCommand,
356 );
357 return index === -1 ? null : index;
359​
360export function isTerminalToggleShortcut(
361 event: ShortcutEventLike,
362 keybindings: ResolvedKeybindingsConfig,
363 options?: ShortcutMatchOptions,
364): boolean {
365 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
367​
368export function isTerminalSplitShortcut(
369 event: ShortcutEventLike,
370 keybindings: ResolvedKeybindingsConfig,
371 options?: ShortcutMatchOptions,
372): boolean {
373 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
375​
376export function isTerminalSplitVerticalShortcut(
377 event: ShortcutEventLike,
378 keybindings: ResolvedKeybindingsConfig,
379 options?: ShortcutMatchOptions,
380): boolean {
381 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
383​
384export function isTerminalNewShortcut(
385 event: ShortcutEventLike,
386 keybindings: ResolvedKeybindingsConfig,
387 options?: ShortcutMatchOptions,
388): boolean {
389 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
391​
392export function isTerminalCycleShortcut(
393 event: ShortcutEventLike,
394 keybindings: ResolvedKeybindingsConfig,
395 options?: ShortcutMatchOptions,
396): boolean {
397 const command = resolveShortcutCommand(event, keybindings, options);
398 return command === "terminal.previous" || command === "terminal.next";
400​
401export function isTerminalCloseShortcut(
402 event: ShortcutEventLike,
403 keybindings: ResolvedKeybindingsConfig,
404 options?: ShortcutMatchOptions,
405): boolean {
406 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
408​
409export function isDiffToggleShortcut(
410 event: ShortcutEventLike,
411 keybindings: ResolvedKeybindingsConfig,
412 options?: ShortcutMatchOptions,
413): boolean {
414 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
416​
417export function isSidebarToggleShortcut(
418 event: ShortcutEventLike,
419 keybindings: ResolvedKeybindingsConfig,
420 options?: ShortcutMatchOptions,
421): boolean {
422 // A focused terminal owns Ctrl chords, such as tmux's Ctrl+B prefix; Cmd never reaches it.
423 if (event.ctrlKey && options?.context?.terminalFocus) return false;
424 return matchesCommandShortcut(event, keybindings, "sidebar.toggle", options);
426​
427export function isOpenFavoriteEditorShortcut(
428 event: ShortcutEventLike,
429 keybindings: ResolvedKeybindingsConfig,
430 options?: ShortcutMatchOptions,
431): boolean {
432 return (
433 event.repeat !== true &&
434 matchesCommandShortcut(event, keybindings, "editor.openFavorite", options)
435 );
437​
438/**
439 * Whether the keypress should bold text in the rich-text composer: Mod+B
440 * without extra modifiers, with text selected. Tiptap binds the same chord, so
441 * app shortcuts captured ahead of the editor yield only in that case. With no
442 * selection an app binding on the chord wins (the sidebar toggle by default).
443 */
444export function isRichTextBoldShortcut(
445 event: ShortcutEventLike,
446 selection: Pick<Selection, "isCollapsed"> | null,
447): boolean {
448 if (event.type !== undefined && event.type !== "keydown") {
449 return false;
450 }
451 return (
452 selection !== null &&
453 !selection.isCollapsed &&
454 resolveEventKeys(event).has("b") &&
455 (event.metaKey || event.ctrlKey) &&
456 !event.altKey &&
457 !event.shiftKey
458 );
460​
461/** Mod+B, Mod+I and Mod+E, the mark chords the rich-text composer binds. */
462export function isRichTextFormattingShortcut(event: ShortcutEventLike): boolean {
463 if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return false;
464 const keys = resolveEventKeys(event);
465 return keys.has("b") || keys.has("i") || keys.has("e");
467​
468export function isTerminalClearShortcut(
469 event: ShortcutEventLike,
470 platform = navigator.platform,
471): boolean {
472 if (event.type !== undefined && event.type !== "keydown") {
473 return false;
474 }
475​
476 const key = event.key.toLowerCase();
477​
478 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
479 return true;
480 }
481​
482 return (
483 isMacPlatform(platform) &&
484 key === "k" &&
485 event.metaKey &&
486 !event.ctrlKey &&
487 !event.altKey &&
488 !event.shiftKey
489 );
491​
492export function terminalDeleteShortcutData(
493 event: ShortcutEventLike,
494 platform = navigator.platform,
495): string | null {
496 if (event.type !== undefined && event.type !== "keydown") {
497 return null;
498 }
499​
500 if (!isMacPlatform(platform)) {
501 return null;
502 }
503​
504 const key = normalizeEventKey(event.key);
505 if (key !== "backspace") {
506 return null;
507 }
508​
509 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
510 ? TERMINAL_DELETE_TO_LINE_START
511 : null;
513​
514export function terminalNavigationShortcutData(
515 event: ShortcutEventLike,
516 platform = navigator.platform,
517): string | null {
518 if (event.type !== undefined && event.type !== "keydown") {
519 return null;
520 }
521​
522 if (event.shiftKey) return null;
523​
524 const key = normalizeEventKey(event.key);
525 if (key !== "arrowleft" && key !== "arrowright") {
526 return null;
527 }
528​
529 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
530 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
531​
532 if (isMacPlatform(platform)) {
533 if (event.altKey && !event.metaKey && !event.ctrlKey) {
534 return moveWord;
535 }
536 if (event.metaKey && !event.altKey && !event.ctrlKey) {
537 return moveLine;
538 }
539 return null;
540 }
541​
542 if (event.altKey && !event.metaKey && !event.ctrlKey) {
543 return moveWord;
544 }
545​
546 return null;