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

keybindings.ts

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