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

keybindings.ts

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