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

keybindings.ts

514 lines14.9 KB

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 { isElectron } from "./env";
12import { isMacPlatform } from "./lib/utils";
13​
14export interface ShortcutEventLike {
15 getModifierState?: (key: "AltGraph") => boolean;
16 type?: string;
17 code?: string;
18 key: string;
19 metaKey: boolean;
20 ctrlKey: boolean;
21 shiftKey: boolean;
22 altKey: boolean;
24​
25export interface ShortcutModifierStateLike {
26 metaKey: boolean;
27 ctrlKey: boolean;
28 shiftKey: boolean;
29 altKey: boolean;
31​
32export interface ShortcutMatchContext {
33 terminalFocus: boolean;
34 terminalOpen: boolean;
35 previewFocus: boolean;
36 previewOpen: boolean;
37 isWeb: boolean;
38 isDesktop: boolean;
39 [key: string]: boolean;
41​
42interface ShortcutMatchOptions {
43 platform?: string;
44 context?: Partial<ShortcutMatchContext>;
46​
47interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
48 platform?: string;
50​
51const TERMINAL_WORD_BACKWARD = "\u001bb";
52const TERMINAL_WORD_FORWARD = "\u001bf";
53const TERMINAL_LINE_START = "\u0001";
54const TERMINAL_LINE_END = "\u0005";
55const TERMINAL_DELETE_TO_LINE_START = "\u0015";
56const EVENT_CODE_SHORTCUT_KEYS: Readonly<Record<string, string>> = {
57 Backquote: "`",
58 Backslash: "\\",
59 BracketLeft: "[",
60 BracketRight: "]",
61 Comma: ",",
62 Digit0: "0",
63 Digit1: "1",
64 Digit2: "2",
65 Digit3: "3",
66 Digit4: "4",
67 Digit5: "5",
68 Digit6: "6",
69 Digit7: "7",
70 Digit8: "8",
71 Digit9: "9",
72 Equal: "=",
73 Minus: "-",
74 Period: ".",
75 Quote: "'",
76 Semicolon: ";",
77 Slash: "/",
78};
79​
80function normalizeEventKey(key: string): string {
81 const normalized = key.toLowerCase();
82 if (normalized === "esc") return "escape";
83 return normalized;
85​
86export function shortcutKeyFromEvent(event: Pick<ShortcutEventLike, "key" | "code">): string {
87 const layoutKey = normalizeEventKey(event.key);
88 if (/^[a-z]$/.test(layoutKey)) return layoutKey;
89 const physicalKey = event.code ? EVENT_CODE_SHORTCUT_KEYS[event.code] : undefined;
90 return physicalKey ?? layoutKey;
92​
93function resolveEventKeys(event: ShortcutEventLike): Set<string> {
94 const layoutKey = normalizeEventKey(event.key);
95 const keys = new Set([layoutKey]);
96 // The physical-position fallback exists for layouts that type non-Latin
97 // letters (Cyrillic, Greek) and for Option-modified symbols on macOS.
98 // When the layout already produces a Latin letter, match on it alone;
99 // otherwise a remapped physical key triggers shortcuts for two different
100 // letters at once and shadows system shortcuts on non-QWERTY layouts.
101 const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1];
102 if (letterCode && !/^[a-z]$/.test(layoutKey)) {
103 keys.add(letterCode.toLowerCase());
104 }
105 keys.add(shortcutKeyFromEvent(event));
106 return keys;
108​
109function matchesShortcutModifiers(
110 event: ShortcutModifierStateLike,
111 shortcut: KeybindingShortcut,
112 platform = navigator.platform,
113): boolean {
114 const useMetaForMod = isMacPlatform(platform);
115 const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
116 const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
117 return (
118 event.metaKey === expectedMeta &&
119 event.ctrlKey === expectedCtrl &&
120 event.shiftKey === shortcut.shiftKey &&
121 event.altKey === shortcut.altKey
122 );
124​
125function matchesShortcut(
126 event: ShortcutEventLike,
127 shortcut: KeybindingShortcut,
128 platform = navigator.platform,
129): boolean {
130 if (
131 !isMacPlatform(platform) &&
132 event.getModifierState?.("AltGraph") &&
133 !/^[a-z0-9]$/i.test(event.key)
134 )
135 return false;
136 if (!matchesShortcutModifiers(event, shortcut, platform)) return false;
137 return resolveEventKeys(event).has(shortcut.key);
139​
140function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
141 return options?.platform ?? navigator.platform;
143​
144function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
145 return {
146 terminalFocus: false,
147 terminalOpen: false,
148 previewFocus: false,
149 previewOpen: false,
150 isWeb: !isElectron,
151 isDesktop: isElectron,
152 ...options?.context,
153 };
155​
156function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
157 switch (node.type) {
158 case "identifier":
159 if (node.name === "true") return true;
160 if (node.name === "false") return false;
161 return Boolean(context[node.name]);
162 case "not":
163 return !evaluateWhenNode(node.node, context);
164 case "and":
165 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
166 case "or":
167 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
168 }
170​
171function matchesWhenClause(
172 whenAst: KeybindingWhenNode | undefined,
173 context: ShortcutMatchContext,
174): boolean {
175 if (!whenAst) return true;
176 return evaluateWhenNode(whenAst, context);
178​
179export function shortcutConflictKey(
180 shortcut: KeybindingShortcut,
181 platform = navigator.platform,
182): string {
183 const useMetaForMod = isMacPlatform(platform);
184 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
185 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
186 return [
187 shortcut.key,
188 metaKey ? "meta" : "",
189 ctrlKey ? "ctrl" : "",
190 shortcut.shiftKey ? "shift" : "",
191 shortcut.altKey ? "alt" : "",
192 ].join("|");
194​
195function findEffectiveShortcutForCommand(
196 keybindings: ResolvedKeybindingsConfig,
197 command: KeybindingCommand,
198 options?: ShortcutMatchOptions,
199): KeybindingShortcut | null {
200 const platform = resolvePlatform(options);
201 const context = resolveContext(options);
202 const claimedShortcuts = new Set<string>();
203​
204 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
205 const binding = keybindings[index];
206 if (!binding) continue;
207 if (!matchesWhenClause(binding.whenAst, context)) continue;
208​
209 const conflictKey = shortcutConflictKey(binding.shortcut, platform);
210 if (claimedShortcuts.has(conflictKey)) {
211 continue;
212 }
213​
214 claimedShortcuts.add(conflictKey);
215 if (binding.command === command) {
216 return binding.shortcut;
217 }
218 }
219​
220 return null;
222​
223function matchesCommandShortcut(
224 event: ShortcutEventLike,
225 keybindings: ResolvedKeybindingsConfig,
226 command: KeybindingCommand,
227 options?: ShortcutMatchOptions,
228): boolean {
229 return resolveShortcutCommand(event, keybindings, options) === command;
231​
232export function resolveShortcutCommand(
233 event: ShortcutEventLike,
234 keybindings: ResolvedKeybindingsConfig,
235 options?: ShortcutMatchOptions,
236): KeybindingCommand | null {
237 const platform = resolvePlatform(options);
238 const context = resolveContext(options);
239​
240 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
241 const binding = keybindings[index];
242 if (!binding) continue;
243 if (!matchesWhenClause(binding.whenAst, context)) continue;
244 if (!matchesShortcut(event, binding.shortcut, platform)) continue;
245 return binding.command;
246 }
247 return null;
249​
250export function formatShortcutKeyLabel(key: string): string {
251 if (key === " ") return "Space";
252 if (key.length === 1) return key.toUpperCase();
253 if (key === "escape") return "Esc";
254 if (key === "arrowup") return "Up";
255 if (key === "arrowdown") return "Down";
256 if (key === "arrowleft") return "Left";
257 if (key === "arrowright") return "Right";
258 return key.slice(0, 1).toUpperCase() + key.slice(1);
260​
261export function formatShortcutLabel(
262 shortcut: KeybindingShortcut,
263 platform = navigator.platform,
264): string {
265 const keyLabel = formatShortcutKeyLabel(shortcut.key);
266 const useMetaForMod = isMacPlatform(platform);
267 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
268 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
269 const showAlt = shortcut.altKey;
270 const showShift = shortcut.shiftKey;
271​
272 if (useMetaForMod) {
273 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
274 }
275​
276 const parts: string[] = [];
277 if (showCtrl) parts.push("Ctrl");
278 if (showAlt) parts.push("Alt");
279 if (showShift) parts.push("Shift");
280 if (showMeta) parts.push("Meta");
281 parts.push(keyLabel);
282 return parts.join("+");
284​
285export function shortcutLabelForCommand(
286 keybindings: ResolvedKeybindingsConfig,
287 command: KeybindingCommand | null,
288 options?: string | ResolvedShortcutLabelOptions,
289): string | null {
290 if (command === null) return null;
291 const resolvedOptions =
292 typeof options === "string"
293 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
294 : options;
295 const platform = resolvePlatform(resolvedOptions);
296 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
297 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
299​
300export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
301 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
303​
304export function threadJumpIndexFromCommand(command: string): number | null {
305 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
306 return index === -1 ? null : index;
308​
309export function threadTraversalDirectionFromCommand(
310 command: string | null,
311): "previous" | "next" | null {
312 if (command === "thread.previous") return "previous";
313 if (command === "thread.next") return "next";
314 return null;
316​
317export function shouldShowThreadJumpHintsForModifiers(
318 modifiers: ShortcutModifierStateLike,
319 keybindings: ResolvedKeybindingsConfig,
320 options?: ShortcutMatchOptions,
321): boolean {
322 // The embedded terminal owns keystrokes while it has focus: the Ghostty
323 // surface encodes the keydown and can write the pressed key into the shell
324 // before our window-level shortcut handling ever runs, regardless of any
325 // configured `when` clause on the jump command. Advertising jump hints
326 // here would promise a shortcut that instead types into the terminal, so
327 // never show them while the terminal is focused.
328 if (resolveContext(options).terminalFocus) {
329 return false;
330 }
331​
332 const platform = resolvePlatform(options);
333​
334 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
335 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
336 if (!shortcut) continue;
337 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
338 return true;
339 }
340 }
341​
342 return false;
344​
345export function modelPickerJumpCommandForIndex(
346 index: number,
347): ModelPickerJumpKeybindingCommand | null {
348 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
350​
351export function modelPickerJumpIndexFromCommand(command: string): number | null {
352 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
353 command as ModelPickerJumpKeybindingCommand,
354 );
355 return index === -1 ? null : index;
357​
358export function isTerminalToggleShortcut(
359 event: ShortcutEventLike,
360 keybindings: ResolvedKeybindingsConfig,
361 options?: ShortcutMatchOptions,
362): boolean {
363 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
365​
366export function isTerminalSplitShortcut(
367 event: ShortcutEventLike,
368 keybindings: ResolvedKeybindingsConfig,
369 options?: ShortcutMatchOptions,
370): boolean {
371 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
373​
374export function isTerminalSplitVerticalShortcut(
375 event: ShortcutEventLike,
376 keybindings: ResolvedKeybindingsConfig,
377 options?: ShortcutMatchOptions,
378): boolean {
379 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
381​
382export function isTerminalNewShortcut(
383 event: ShortcutEventLike,
384 keybindings: ResolvedKeybindingsConfig,
385 options?: ShortcutMatchOptions,
386): boolean {
387 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
389​
390export function isTerminalCloseShortcut(
391 event: ShortcutEventLike,
392 keybindings: ResolvedKeybindingsConfig,
393 options?: ShortcutMatchOptions,
394): boolean {
395 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
397​
398export function isDiffToggleShortcut(
399 event: ShortcutEventLike,
400 keybindings: ResolvedKeybindingsConfig,
401 options?: ShortcutMatchOptions,
402): boolean {
403 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
405​
406export function isOpenFavoriteEditorShortcut(
407 event: ShortcutEventLike,
408 keybindings: ResolvedKeybindingsConfig,
409 options?: ShortcutMatchOptions,
410): boolean {
411 return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
413​
414/**
415 * Whether the keypress is the rich-text bold chord (Mod+B without extra
416 * modifiers). Tiptap binds the same chord, so app shortcuts captured ahead
417 * of the editor must yield when the rich-text composer is focused.
418 */
419export function isRichTextBoldShortcut(event: ShortcutEventLike): boolean {
420 if (event.type !== undefined && event.type !== "keydown") {
421 return false;
422 }
423 return (
424 event.key.toLowerCase() === "b" &&
425 (event.metaKey || event.ctrlKey) &&
426 !event.altKey &&
427 !event.shiftKey
428 );
430​
431export function isTerminalClearShortcut(
432 event: ShortcutEventLike,
433 platform = navigator.platform,
434): boolean {
435 if (event.type !== undefined && event.type !== "keydown") {
436 return false;
437 }
438​
439 const key = event.key.toLowerCase();
440​
441 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
442 return true;
443 }
444​
445 return (
446 isMacPlatform(platform) &&
447 key === "k" &&
448 event.metaKey &&
449 !event.ctrlKey &&
450 !event.altKey &&
451 !event.shiftKey
452 );
454​
455export function terminalDeleteShortcutData(
456 event: ShortcutEventLike,
457 platform = navigator.platform,
458): string | null {
459 if (event.type !== undefined && event.type !== "keydown") {
460 return null;
461 }
462​
463 if (!isMacPlatform(platform)) {
464 return null;
465 }
466​
467 const key = normalizeEventKey(event.key);
468 if (key !== "backspace") {
469 return null;
470 }
471​
472 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
473 ? TERMINAL_DELETE_TO_LINE_START
474 : null;
476​
477export function terminalNavigationShortcutData(
478 event: ShortcutEventLike,
479 platform = navigator.platform,
480): string | null {
481 if (event.type !== undefined && event.type !== "keydown") {
482 return null;
483 }
484​
485 if (event.shiftKey) return null;
486​
487 const key = normalizeEventKey(event.key);
488 if (key !== "arrowleft" && key !== "arrowright") {
489 return null;
490 }
491​
492 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
493 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
494​
495 if (isMacPlatform(platform)) {
496 if (event.altKey && !event.metaKey && !event.ctrlKey) {
497 return moveWord;
498 }
499 if (event.metaKey && !event.altKey && !event.ctrlKey) {
500 return moveLine;
501 }
502 return null;
503 }
504​
505 if (event.ctrlKey && !event.metaKey && !event.altKey) {
506 return moveWord;
507 }
508​
509 if (event.altKey && !event.metaKey && !event.ctrlKey) {
510 return moveWord;
511 }
512​
513 return null;