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

keybindings.ts

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