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

keybindings.ts

529 lines15.0 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 "@v12/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 keys = new Set([normalizeEventKey(event.key)]);
75 const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1];
76 if (letterCode) {
77 keys.add(letterCode.toLowerCase());
78 }
79 const aliases = event.code ? EVENT_CODE_KEY_ALIASES[event.code] : undefined;
80 if (!aliases) return keys;
81​
82 for (const alias of aliases) {
83 keys.add(alias);
84 }
85 return keys;
87​
88function matchesShortcutModifiers(
89 event: ShortcutModifierStateLike,
90 shortcut: KeybindingShortcut,
91 platform = navigator.platform,
92): boolean {
93 const useMetaForMod = isMacPlatform(platform);
94 const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
95 const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
96 return (
97 event.metaKey === expectedMeta &&
98 event.ctrlKey === expectedCtrl &&
99 event.shiftKey === shortcut.shiftKey &&
100 event.altKey === shortcut.altKey
101 );
103​
104function matchesShortcut(
105 event: ShortcutEventLike,
106 shortcut: KeybindingShortcut,
107 platform = navigator.platform,
108): boolean {
109 if (!matchesShortcutModifiers(event, shortcut, platform)) return false;
110 return resolveEventKeys(event).has(shortcut.key);
112​
113function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
114 return options?.platform ?? navigator.platform;
116​
117function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
118 return {
119 terminalFocus: false,
120 terminalOpen: false,
121 previewFocus: false,
122 previewOpen: false,
123 ...options?.context,
124 };
126​
127function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
128 switch (node.type) {
129 case "identifier":
130 if (node.name === "true") return true;
131 if (node.name === "false") return false;
132 return Boolean(context[node.name]);
133 case "not":
134 return !evaluateWhenNode(node.node, context);
135 case "and":
136 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
137 case "or":
138 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
139 }
141​
142function matchesWhenClause(
143 whenAst: KeybindingWhenNode | undefined,
144 context: ShortcutMatchContext,
145): boolean {
146 if (!whenAst) return true;
147 return evaluateWhenNode(whenAst, context);
149​
150function shortcutConflictKey(shortcut: KeybindingShortcut, platform = navigator.platform): string {
151 const useMetaForMod = isMacPlatform(platform);
152 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
153 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
154​
155 return [
156 shortcut.key,
157 metaKey ? "meta" : "",
158 ctrlKey ? "ctrl" : "",
159 shortcut.shiftKey ? "shift" : "",
160 shortcut.altKey ? "alt" : "",
161 ].join("|");
163​
164function findEffectiveShortcutForCommand(
165 keybindings: ResolvedKeybindingsConfig,
166 command: KeybindingCommand,
167 options?: ShortcutMatchOptions,
168): KeybindingShortcut | null {
169 const platform = resolvePlatform(options);
170 const context = resolveContext(options);
171 const claimedShortcuts = new Set<string>();
172​
173 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
174 const binding = keybindings[index];
175 if (!binding) continue;
176 if (!matchesWhenClause(binding.whenAst, context)) continue;
177​
178 const conflictKey = shortcutConflictKey(binding.shortcut, platform);
179 if (claimedShortcuts.has(conflictKey)) {
180 continue;
181 }
182​
183 claimedShortcuts.add(conflictKey);
184 if (binding.command === command) {
185 return binding.shortcut;
186 }
187 }
188​
189 return null;
191​
192function matchesCommandShortcut(
193 event: ShortcutEventLike,
194 keybindings: ResolvedKeybindingsConfig,
195 command: KeybindingCommand,
196 options?: ShortcutMatchOptions,
197): boolean {
198 return resolveShortcutCommand(event, keybindings, options) === command;
200​
201export function resolveShortcutCommand(
202 event: ShortcutEventLike,
203 keybindings: ResolvedKeybindingsConfig,
204 options?: ShortcutMatchOptions,
205): KeybindingCommand | null {
206 const platform = resolvePlatform(options);
207 const context = resolveContext(options);
208​
209 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
210 const binding = keybindings[index];
211 if (!binding) continue;
212 if (!matchesWhenClause(binding.whenAst, context)) continue;
213 if (!matchesShortcut(event, binding.shortcut, platform)) continue;
214 return binding.command;
215 }
216 return null;
218​
219function formatShortcutKeyLabel(key: string): string {
220 if (key === " ") return "Space";
221 if (key.length === 1) return key.toUpperCase();
222 if (key === "escape") return "Esc";
223 if (key === "arrowup") return "Up";
224 if (key === "arrowdown") return "Down";
225 if (key === "arrowleft") return "Left";
226 if (key === "arrowright") return "Right";
227 return key.slice(0, 1).toUpperCase() + key.slice(1);
229​
230export function formatShortcutLabel(
231 shortcut: KeybindingShortcut,
232 platform = navigator.platform,
233): string {
234 const keyLabel = formatShortcutKeyLabel(shortcut.key);
235 const useMetaForMod = isMacPlatform(platform);
236 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
237 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
238 const showAlt = shortcut.altKey;
239 const showShift = shortcut.shiftKey;
240​
241 if (useMetaForMod) {
242 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
243 }
244​
245 const parts: string[] = [];
246 if (showCtrl) parts.push("Ctrl");
247 if (showAlt) parts.push("Alt");
248 if (showShift) parts.push("Shift");
249 if (showMeta) parts.push("Meta");
250 parts.push(keyLabel);
251 return parts.join("+");
253​
254export function shortcutLabelForCommand(
255 keybindings: ResolvedKeybindingsConfig,
256 command: KeybindingCommand,
257 options?: string | ResolvedShortcutLabelOptions,
258): string | null {
259 const resolvedOptions =
260 typeof options === "string"
261 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
262 : options;
263 const platform = resolvePlatform(resolvedOptions);
264 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
265 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
267​
268export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
269 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
271​
272export function threadJumpIndexFromCommand(command: string): number | null {
273 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
274 return index === -1 ? null : index;
276​
277export function threadTraversalDirectionFromCommand(
278 command: string | null,
279): "previous" | "next" | null {
280 if (command === "thread.previous") return "previous";
281 if (command === "thread.next") return "next";
282 return null;
284​
285export function shouldShowThreadJumpHints(
286 event: ShortcutEventLike,
287 keybindings: ResolvedKeybindingsConfig,
288 options?: ShortcutMatchOptions,
289): boolean {
290 return shouldShowThreadJumpHintsForModifiers(event, keybindings, options);
292​
293export function shouldShowThreadJumpHintsForModifiers(
294 modifiers: ShortcutModifierStateLike,
295 keybindings: ResolvedKeybindingsConfig,
296 options?: ShortcutMatchOptions,
297): boolean {
298 const platform = resolvePlatform(options);
299​
300 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
301 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
302 if (!shortcut) continue;
303 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
304 return true;
305 }
306 }
307​
308 return false;
310​
311export function modelPickerJumpCommandForIndex(
312 index: number,
313): ModelPickerJumpKeybindingCommand | null {
314 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
316​
317export function modelPickerJumpIndexFromCommand(command: string): number | null {
318 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
319 command as ModelPickerJumpKeybindingCommand,
320 );
321 return index === -1 ? null : index;
323​
324export function shouldShowModelPickerJumpHints(
325 event: ShortcutEventLike,
326 keybindings: ResolvedKeybindingsConfig,
327 options?: ShortcutMatchOptions,
328): boolean {
329 return shouldShowModelPickerJumpHintsForModifiers(event, keybindings, options);
331​
332export function shouldShowModelPickerJumpHintsForModifiers(
333 modifiers: ShortcutModifierStateLike,
334 keybindings: ResolvedKeybindingsConfig,
335 options?: ShortcutMatchOptions,
336): boolean {
337 const platform = resolvePlatform(options);
338​
339 for (const command of MODEL_PICKER_JUMP_KEYBINDING_COMMANDS) {
340 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
341 if (!shortcut) continue;
342 if (matchesShortcutModifiers(modifiers, shortcut, platform)) {
343 return true;
344 }
345 }
346​
347 return false;
349​
350export function isTerminalToggleShortcut(
351 event: ShortcutEventLike,
352 keybindings: ResolvedKeybindingsConfig,
353 options?: ShortcutMatchOptions,
354): boolean {
355 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
357​
358export function isTerminalSplitShortcut(
359 event: ShortcutEventLike,
360 keybindings: ResolvedKeybindingsConfig,
361 options?: ShortcutMatchOptions,
362): boolean {
363 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
365​
366export function isTerminalSplitVerticalShortcut(
367 event: ShortcutEventLike,
368 keybindings: ResolvedKeybindingsConfig,
369 options?: ShortcutMatchOptions,
370): boolean {
371 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
373​
374export function isTerminalNewShortcut(
375 event: ShortcutEventLike,
376 keybindings: ResolvedKeybindingsConfig,
377 options?: ShortcutMatchOptions,
378): boolean {
379 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
381​
382export function isTerminalCloseShortcut(
383 event: ShortcutEventLike,
384 keybindings: ResolvedKeybindingsConfig,
385 options?: ShortcutMatchOptions,
386): boolean {
387 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
389​
390export function isDiffToggleShortcut(
391 event: ShortcutEventLike,
392 keybindings: ResolvedKeybindingsConfig,
393 options?: ShortcutMatchOptions,
394): boolean {
395 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
397​
398export function isPreviewToggleShortcut(
399 event: ShortcutEventLike,
400 keybindings: ResolvedKeybindingsConfig,
401 options?: ShortcutMatchOptions,
402): boolean {
403 return matchesCommandShortcut(event, keybindings, "preview.toggle", options);
405​
406export function isPreviewRefreshShortcut(
407 event: ShortcutEventLike,
408 keybindings: ResolvedKeybindingsConfig,
409 options?: ShortcutMatchOptions,
410): boolean {
411 return matchesCommandShortcut(event, keybindings, "preview.refresh", options);
413​
414export function isPreviewFocusUrlShortcut(
415 event: ShortcutEventLike,
416 keybindings: ResolvedKeybindingsConfig,
417 options?: ShortcutMatchOptions,
418): boolean {
419 return matchesCommandShortcut(event, keybindings, "preview.focusUrl", options);
421​
422export function isChatNewShortcut(
423 event: ShortcutEventLike,
424 keybindings: ResolvedKeybindingsConfig,
425 options?: ShortcutMatchOptions,
426): boolean {
427 return matchesCommandShortcut(event, keybindings, "chat.new", options);
429​
430export function isChatNewLocalShortcut(
431 event: ShortcutEventLike,
432 keybindings: ResolvedKeybindingsConfig,
433 options?: ShortcutMatchOptions,
434): boolean {
435 return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
437​
438export function isOpenFavoriteEditorShortcut(
439 event: ShortcutEventLike,
440 keybindings: ResolvedKeybindingsConfig,
441 options?: ShortcutMatchOptions,
442): boolean {
443 return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
445​
446export function isTerminalClearShortcut(
447 event: ShortcutEventLike,
448 platform = navigator.platform,
449): boolean {
450 if (event.type !== undefined && event.type !== "keydown") {
451 return false;
452 }
453​
454 const key = event.key.toLowerCase();
455​
456 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
457 return true;
458 }
459​
460 return (
461 isMacPlatform(platform) &&
462 key === "k" &&
463 event.metaKey &&
464 !event.ctrlKey &&
465 !event.altKey &&
466 !event.shiftKey
467 );
469​
470export function terminalDeleteShortcutData(
471 event: ShortcutEventLike,
472 platform = navigator.platform,
473): string | null {
474 if (event.type !== undefined && event.type !== "keydown") {
475 return null;
476 }
477​
478 if (!isMacPlatform(platform)) {
479 return null;
480 }
481​
482 const key = normalizeEventKey(event.key);
483 if (key !== "backspace") {
484 return null;
485 }
486​
487 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
488 ? TERMINAL_DELETE_TO_LINE_START
489 : null;
491​
492export function terminalNavigationShortcutData(
493 event: ShortcutEventLike,
494 platform = navigator.platform,
495): string | null {
496 if (event.type !== undefined && event.type !== "keydown") {
497 return null;
498 }
499​
500 if (event.shiftKey) return null;
501​
502 const key = normalizeEventKey(event.key);
503 if (key !== "arrowleft" && key !== "arrowright") {
504 return null;
505 }
506​
507 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
508 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
509​
510 if (isMacPlatform(platform)) {
511 if (event.altKey && !event.metaKey && !event.ctrlKey) {
512 return moveWord;
513 }
514 if (event.metaKey && !event.altKey && !event.ctrlKey) {
515 return moveLine;
516 }
517 return null;
518 }
519​
520 if (event.ctrlKey && !event.metaKey && !event.altKey) {
521 return moveWord;
522 }
523​
524 if (event.altKey && !event.metaKey && !event.ctrlKey) {
525 return moveWord;
526 }
527​
528 return null;