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

keybindings.ts

535 lines15.4 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_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {
53 BracketLeft: ["["],
54 BracketRight: ["]"],
55 Digit0: ["0"],
56 Digit1: ["1"],
57 Digit2: ["2"],
58 Digit3: ["3"],
59 Digit4: ["4"],
60 Digit5: ["5"],
61 Digit6: ["6"],
62 Digit7: ["7"],
63 Digit8: ["8"],
64 Digit9: ["9"],
65};
66​
67function normalizeEventKey(key: string): string {
68 const normalized = key.toLowerCase();
69 if (normalized === "esc") return "escape";
70 return normalized;
72​
73function resolveEventKeys(event: ShortcutEventLike): Set<string> {
74 const layoutKey = normalizeEventKey(event.key);
75 const keys = new Set([layoutKey]);
76 // The physical-position fallback exists for layouts that type non-Latin
77 // letters (Cyrillic, Greek) and for Option-modified symbols on macOS.
78 // When the layout already produces a Latin letter, match on it alone;
79 // otherwise a remapped physical key triggers shortcuts for two different
80 // letters at once and shadows system shortcuts on non-QWERTY layouts.
81 const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1];
82 if (letterCode && !/^[a-z]$/.test(layoutKey)) {
83 keys.add(letterCode.toLowerCase());
84 }
85 const aliases = event.code ? EVENT_CODE_KEY_ALIASES[event.code] : undefined;
86 if (!aliases) return keys;
87​
88 for (const alias of aliases) {
89 keys.add(alias);
90 }
91 return keys;
93​
94function matchesShortcutModifiers(
95 event: ShortcutModifierStateLike,
96 shortcut: KeybindingShortcut,
97 platform = navigator.platform,
98): boolean {
99 const useMetaForMod = isMacPlatform(platform);
100 const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
101 const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
102 return (
103 event.metaKey === expectedMeta &&
104 event.ctrlKey === expectedCtrl &&
105 event.shiftKey === shortcut.shiftKey &&
106 event.altKey === shortcut.altKey
107 );
109​
110function matchesShortcut(
111 event: ShortcutEventLike,
112 shortcut: KeybindingShortcut,
113 platform = navigator.platform,
114): boolean {
115 if (!matchesShortcutModifiers(event, shortcut, platform)) return false;
116 return resolveEventKeys(event).has(shortcut.key);
118​
119function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
120 return options?.platform ?? navigator.platform;
122​
123function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
124 return {
125 terminalFocus: false,
126 terminalOpen: false,
127 previewFocus: false,
128 previewOpen: false,
129 ...options?.context,
130 };
132​
133function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
134 switch (node.type) {
135 case "identifier":
136 if (node.name === "true") return true;
137 if (node.name === "false") return false;
138 return Boolean(context[node.name]);
139 case "not":
140 return !evaluateWhenNode(node.node, context);
141 case "and":
142 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
143 case "or":
144 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
145 }
147​
148function matchesWhenClause(
149 whenAst: KeybindingWhenNode | undefined,
150 context: ShortcutMatchContext,
151): boolean {
152 if (!whenAst) return true;
153 return evaluateWhenNode(whenAst, context);
155​
156function shortcutConflictKey(shortcut: KeybindingShortcut, platform = navigator.platform): string {
157 const useMetaForMod = isMacPlatform(platform);
158 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
159 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
160​
161 return [
162 shortcut.key,
163 metaKey ? "meta" : "",
164 ctrlKey ? "ctrl" : "",
165 shortcut.shiftKey ? "shift" : "",
166 shortcut.altKey ? "alt" : "",
167 ].join("|");
169​
170function findEffectiveShortcutForCommand(
171 keybindings: ResolvedKeybindingsConfig,
172 command: KeybindingCommand,
173 options?: ShortcutMatchOptions,
174): KeybindingShortcut | null {
175 const platform = resolvePlatform(options);
176 const context = resolveContext(options);
177 const claimedShortcuts = new Set<string>();
178​
179 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
180 const binding = keybindings[index];
181 if (!binding) continue;
182 if (!matchesWhenClause(binding.whenAst, context)) continue;
183​
184 const conflictKey = shortcutConflictKey(binding.shortcut, platform);
185 if (claimedShortcuts.has(conflictKey)) {
186 continue;
187 }
188​
189 claimedShortcuts.add(conflictKey);
190 if (binding.command === command) {
191 return binding.shortcut;
192 }
193 }
194​
195 return null;
197​
198function matchesCommandShortcut(
199 event: ShortcutEventLike,
200 keybindings: ResolvedKeybindingsConfig,
201 command: KeybindingCommand,
202 options?: ShortcutMatchOptions,
203): boolean {
204 return resolveShortcutCommand(event, keybindings, options) === command;
206​
207export function resolveShortcutCommand(
208 event: ShortcutEventLike,
209 keybindings: ResolvedKeybindingsConfig,
210 options?: ShortcutMatchOptions,
211): KeybindingCommand | null {
212 const platform = resolvePlatform(options);
213 const context = resolveContext(options);
214​
215 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
216 const binding = keybindings[index];
217 if (!binding) continue;
218 if (!matchesWhenClause(binding.whenAst, context)) continue;
219 if (!matchesShortcut(event, binding.shortcut, platform)) continue;
220 return binding.command;
221 }
222 return null;
224​
225function formatShortcutKeyLabel(key: string): string {
226 if (key === " ") return "Space";
227 if (key.length === 1) return key.toUpperCase();
228 if (key === "escape") return "Esc";
229 if (key === "arrowup") return "Up";
230 if (key === "arrowdown") return "Down";
231 if (key === "arrowleft") return "Left";
232 if (key === "arrowright") return "Right";
233 return key.slice(0, 1).toUpperCase() + key.slice(1);
235​
236export function formatShortcutLabel(
237 shortcut: KeybindingShortcut,
238 platform = navigator.platform,
239): string {
240 const keyLabel = formatShortcutKeyLabel(shortcut.key);
241 const useMetaForMod = isMacPlatform(platform);
242 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
243 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
244 const showAlt = shortcut.altKey;
245 const showShift = shortcut.shiftKey;
246​
247 if (useMetaForMod) {
248 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
249 }
250​
251 const parts: string[] = [];
252 if (showCtrl) parts.push("Ctrl");
253 if (showAlt) parts.push("Alt");
254 if (showShift) parts.push("Shift");
255 if (showMeta) parts.push("Meta");
256 parts.push(keyLabel);
257 return parts.join("+");
259​
260export function shortcutLabelForCommand(
261 keybindings: ResolvedKeybindingsConfig,
262 command: KeybindingCommand,
263 options?: string | ResolvedShortcutLabelOptions,
264): string | null {
265 const resolvedOptions =
266 typeof options === "string"
267 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
268 : options;
269 const platform = resolvePlatform(resolvedOptions);
270 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
271 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
273​
274export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
275 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
277​
278export function threadJumpIndexFromCommand(command: string): number | null {
279 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
280 return index === -1 ? null : index;
282​
283export function threadTraversalDirectionFromCommand(
284 command: string | null,
285): "previous" | "next" | null {
286 if (command === "thread.previous") return "previous";
287 if (command === "thread.next") return "next";
288 return null;
290​
291export function shouldShowThreadJumpHints(
292 event: ShortcutEventLike,
293 keybindings: ResolvedKeybindingsConfig,
294 options?: ShortcutMatchOptions,
295): boolean {
296 return shouldShowThreadJumpHintsForModifiers(event, keybindings, options);
298​
299export function shouldShowThreadJumpHintsForModifiers(
300 modifiers: ShortcutModifierStateLike,
301 keybindings: ResolvedKeybindingsConfig,
302 options?: ShortcutMatchOptions,
303): boolean {
304 const platform = resolvePlatform(options);
305​
306 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
307 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
308 if (!shortcut) continue;
309 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
310 return true;
311 }
312 }
313​
314 return false;
316​
317export function modelPickerJumpCommandForIndex(
318 index: number,
319): ModelPickerJumpKeybindingCommand | null {
320 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
322​
323export function modelPickerJumpIndexFromCommand(command: string): number | null {
324 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
325 command as ModelPickerJumpKeybindingCommand,
326 );
327 return index === -1 ? null : index;
329​
330export function shouldShowModelPickerJumpHints(
331 event: ShortcutEventLike,
332 keybindings: ResolvedKeybindingsConfig,
333 options?: ShortcutMatchOptions,
334): boolean {
335 return shouldShowModelPickerJumpHintsForModifiers(event, keybindings, options);
337​
338export function shouldShowModelPickerJumpHintsForModifiers(
339 modifiers: ShortcutModifierStateLike,
340 keybindings: ResolvedKeybindingsConfig,
341 options?: ShortcutMatchOptions,
342): boolean {
343 const platform = resolvePlatform(options);
344​
345 for (const command of MODEL_PICKER_JUMP_KEYBINDING_COMMANDS) {
346 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
347 if (!shortcut) continue;
348 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
349 return true;
350 }
351 }
352​
353 return false;
355​
356export function isTerminalToggleShortcut(
357 event: ShortcutEventLike,
358 keybindings: ResolvedKeybindingsConfig,
359 options?: ShortcutMatchOptions,
360): boolean {
361 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
363​
364export function isTerminalSplitShortcut(
365 event: ShortcutEventLike,
366 keybindings: ResolvedKeybindingsConfig,
367 options?: ShortcutMatchOptions,
368): boolean {
369 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
371​
372export function isTerminalSplitVerticalShortcut(
373 event: ShortcutEventLike,
374 keybindings: ResolvedKeybindingsConfig,
375 options?: ShortcutMatchOptions,
376): boolean {
377 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
379​
380export function isTerminalNewShortcut(
381 event: ShortcutEventLike,
382 keybindings: ResolvedKeybindingsConfig,
383 options?: ShortcutMatchOptions,
384): boolean {
385 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
387​
388export function isTerminalCloseShortcut(
389 event: ShortcutEventLike,
390 keybindings: ResolvedKeybindingsConfig,
391 options?: ShortcutMatchOptions,
392): boolean {
393 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
395​
396export function isDiffToggleShortcut(
397 event: ShortcutEventLike,
398 keybindings: ResolvedKeybindingsConfig,
399 options?: ShortcutMatchOptions,
400): boolean {
401 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
403​
404export function isPreviewToggleShortcut(
405 event: ShortcutEventLike,
406 keybindings: ResolvedKeybindingsConfig,
407 options?: ShortcutMatchOptions,
408): boolean {
409 return matchesCommandShortcut(event, keybindings, "preview.toggle", options);
411​
412export function isPreviewRefreshShortcut(
413 event: ShortcutEventLike,
414 keybindings: ResolvedKeybindingsConfig,
415 options?: ShortcutMatchOptions,
416): boolean {
417 return matchesCommandShortcut(event, keybindings, "preview.refresh", options);
419​
420export function isPreviewFocusUrlShortcut(
421 event: ShortcutEventLike,
422 keybindings: ResolvedKeybindingsConfig,
423 options?: ShortcutMatchOptions,
424): boolean {
425 return matchesCommandShortcut(event, keybindings, "preview.focusUrl", options);
427​
428export function isChatNewShortcut(
429 event: ShortcutEventLike,
430 keybindings: ResolvedKeybindingsConfig,
431 options?: ShortcutMatchOptions,
432): boolean {
433 return matchesCommandShortcut(event, keybindings, "chat.new", options);
435​
436export function isChatNewLocalShortcut(
437 event: ShortcutEventLike,
438 keybindings: ResolvedKeybindingsConfig,
439 options?: ShortcutMatchOptions,
440): boolean {
441 return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
443​
444export function isOpenFavoriteEditorShortcut(
445 event: ShortcutEventLike,
446 keybindings: ResolvedKeybindingsConfig,
447 options?: ShortcutMatchOptions,
448): boolean {
449 return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
451​
452export function isTerminalClearShortcut(
453 event: ShortcutEventLike,
454 platform = navigator.platform,
455): boolean {
456 if (event.type !== undefined && event.type !== "keydown") {
457 return false;
458 }
459​
460 const key = event.key.toLowerCase();
461​
462 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
463 return true;
464 }
465​
466 return (
467 isMacPlatform(platform) &&
468 key === "k" &&
469 event.metaKey &&
470 !event.ctrlKey &&
471 !event.altKey &&
472 !event.shiftKey
473 );
475​
476export function terminalDeleteShortcutData(
477 event: ShortcutEventLike,
478 platform = navigator.platform,
479): string | null {
480 if (event.type !== undefined && event.type !== "keydown") {
481 return null;
482 }
483​
484 if (!isMacPlatform(platform)) {
485 return null;
486 }
487​
488 const key = normalizeEventKey(event.key);
489 if (key !== "backspace") {
490 return null;
491 }
492​
493 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
494 ? TERMINAL_DELETE_TO_LINE_START
495 : null;
497​
498export function terminalNavigationShortcutData(
499 event: ShortcutEventLike,
500 platform = navigator.platform,
501): string | null {
502 if (event.type !== undefined && event.type !== "keydown") {
503 return null;
504 }
505​
506 if (event.shiftKey) return null;
507​
508 const key = normalizeEventKey(event.key);
509 if (key !== "arrowleft" && key !== "arrowright") {
510 return null;
511 }
512​
513 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
514 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
515​
516 if (isMacPlatform(platform)) {
517 if (event.altKey && !event.metaKey && !event.ctrlKey) {
518 return moveWord;
519 }
520 if (event.metaKey && !event.altKey && !event.ctrlKey) {
521 return moveLine;
522 }
523 return null;
524 }
525​
526 if (event.ctrlKey && !event.metaKey && !event.altKey) {
527 return moveWord;
528 }
529​
530 if (event.altKey && !event.metaKey && !event.ctrlKey) {
531 return moveWord;
532 }
533​
534 return null;