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

keybindings.ts

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