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

keybindings.ts

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