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

keybindings.ts

480 lines14.3 KB

1import {
2 type KeybindingCommand,
3 type KeybindingShortcut,
4 type KeybindingWhenNode,
5 type ResolvedKeybindingRule,
6 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
7 type ResolvedKeybindingsConfig,
8 THREAD_JUMP_KEYBINDING_COMMANDS,
9 type ModelPickerJumpKeybindingCommand,
10 type ThreadJumpKeybindingCommand,
11} from "@t3tools/contracts";
12import {
13 isMacPlatform,
14 matchesKeybindingShortcut,
15 matchesKeybindingShortcutModifiers,
16 normalizeEventKey,
17 resolveEventKeys,
18 type ShortcutEventLike as SharedShortcutEventLike,
19 type ShortcutModifierStateLike,
20} from "@t3tools/shared/keybindings";
21import { isElectron } from "./env";
22import { isEditableFocused } from "./lib/editableFocus";
23import { projectScriptIdFromCommand } from "./projectScripts";
24​
25export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings";
26export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings";
27​
28export interface ShortcutEventLike extends SharedShortcutEventLike {
29 target?: EventTarget | null;
31​
32export interface ShortcutMatchContext {
33 terminalFocus: boolean;
34 terminalOpen: boolean;
35 previewFocus: boolean;
36 previewOpen: boolean;
37 isWeb: boolean;
38 isDesktop: boolean;
39 editableFocus?: boolean;
40 [key: string]: boolean;
42​
43interface ShortcutMatchOptions {
44 platform?: string;
45 context?: Partial<ShortcutMatchContext>;
47​
48interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
49 platform?: string;
51​
52const TERMINAL_WORD_BACKWARD = "\u001bb";
53const TERMINAL_WORD_FORWARD = "\u001bf";
54const TERMINAL_LINE_START = "\u0001";
55const TERMINAL_LINE_END = "\u0005";
56const TERMINAL_DELETE_TO_LINE_START = "\u0015";
57function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
58 return options?.platform ?? navigator.platform;
60​
61function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
62 return {
63 terminalFocus: false,
64 terminalOpen: false,
65 previewFocus: false,
66 previewOpen: false,
67 isWeb: !isElectron,
68 isDesktop: isElectron,
69 editableFocus: false,
70 ...options?.context,
71 };
73​
74function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
75 switch (node.type) {
76 case "identifier":
77 if (node.name === "true") return true;
78 if (node.name === "false") return false;
79 return Boolean(context[node.name]);
80 case "not":
81 return !evaluateWhenNode(node.node, context);
82 case "and":
83 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
84 case "or":
85 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
86 }
88​
89function matchesWhenClause(
90 whenAst: KeybindingWhenNode | undefined,
91 context: ShortcutMatchContext,
92): boolean {
93 if (!whenAst) return true;
94 return evaluateWhenNode(whenAst, context);
96​
97export function shortcutConflictKey(
98 shortcut: KeybindingShortcut,
99 platform = navigator.platform,
100): string {
101 const useMetaForMod = isMacPlatform(platform);
102 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
103 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
104 return [
105 shortcut.key,
106 metaKey ? "meta" : "",
107 ctrlKey ? "ctrl" : "",
108 shortcut.shiftKey ? "shift" : "",
109 shortcut.altKey ? "alt" : "",
110 ].join("|");
112​
113function shortcutForContext(binding: ResolvedKeybindingRule, context: ShortcutMatchContext) {
114 const shortcut = binding.shortcut;
115 // Resolve persisted Mod+Enter against send preference without rewriting saved shortcuts.
116 if (
117 context.composerRequiresModifier &&
118 binding.command === "composer.sendAlternate" &&
119 shortcut.key === "enter" &&
120 shortcut.modKey &&
121 !shortcut.metaKey &&
122 !shortcut.ctrlKey &&
123 !shortcut.altKey &&
124 !shortcut.shiftKey
125 ) {
126 return { ...shortcut, shiftKey: true };
127 }
128 return shortcut;
130​
131export function effectiveShortcutsForCommand(
132 keybindings: ResolvedKeybindingsConfig,
133 command: KeybindingCommand,
134 options?: ShortcutMatchOptions,
135): KeybindingShortcut[] {
136 const platform = resolvePlatform(options);
137 const context = resolveContext(options);
138 const claimedShortcuts = new Set<string>();
139 const effective: KeybindingShortcut[] = [];
140​
141 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
142 const binding = keybindings[index];
143 if (!binding) continue;
144 if (!matchesWhenClause(binding.whenAst, context)) continue;
145​
146 const shortcut = shortcutForContext(binding, context);
147 const conflictKey = shortcutConflictKey(shortcut, platform);
148 if (claimedShortcuts.has(conflictKey)) {
149 continue;
150 }
151​
152 claimedShortcuts.add(conflictKey);
153 if (binding.command === command) {
154 effective.push(shortcut);
155 }
156 }
157​
158 return effective;
160​
161function findEffectiveShortcutForCommand(
162 keybindings: ResolvedKeybindingsConfig,
163 command: KeybindingCommand,
164 options?: ShortcutMatchOptions,
165): KeybindingShortcut | null {
166 return effectiveShortcutsForCommand(keybindings, command, options)[0] ?? null;
168​
169function matchesCommandShortcut(
170 event: ShortcutEventLike,
171 keybindings: ResolvedKeybindingsConfig,
172 command: KeybindingCommand,
173 options?: ShortcutMatchOptions,
174): boolean {
175 return resolveShortcutCommand(event, keybindings, options) === command;
177​
178export function resolveShortcutCommand(
179 event: ShortcutEventLike,
180 keybindings: ResolvedKeybindingsConfig,
181 options?: ShortcutMatchOptions,
182): KeybindingCommand | null {
183 const platform = resolvePlatform(options);
184 const context = resolveContext(options);
185 if (options?.context?.editableFocus === undefined && typeof document !== "undefined") {
186 context.editableFocus = isEditableFocused(event.target ?? document.activeElement);
187 }
188​
189 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
190 const binding = keybindings[index];
191 if (!binding) continue;
192 if (!matchesWhenClause(binding.whenAst, context)) continue;
193 if (!matchesKeybindingShortcut(event, shortcutForContext(binding, context), platform)) continue;
194 return binding.command;
195 }
196 return null;
198​
199export function resolveChatShortcutCommand(
200 event: ShortcutEventLike,
201 primaryKeybindings: ResolvedKeybindingsConfig,
202 activeKeybindings: ResolvedKeybindingsConfig,
203 options?: ShortcutMatchOptions,
204): KeybindingCommand | null {
205 const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);
206 if (primaryCommand !== null && projectScriptIdFromCommand(primaryCommand) === null) {
207 return primaryCommand;
208 }
209​
210 const activeCommand = resolveShortcutCommand(event, activeKeybindings, options);
211 return activeCommand !== null && projectScriptIdFromCommand(activeCommand) !== null
212 ? activeCommand
213 : null;
215​
216export function formatShortcutKeyLabel(key: string): string {
217 if (key === " ") return "Space";
218 if (key.length === 1) return key.toUpperCase();
219 if (key === "escape") return "Esc";
220 if (key === "arrowup") return "Up";
221 if (key === "arrowdown") return "Down";
222 if (key === "arrowleft") return "Left";
223 if (key === "arrowright") return "Right";
224 return key.slice(0, 1).toUpperCase() + key.slice(1);
226​
227export function formatShortcutLabel(
228 shortcut: KeybindingShortcut,
229 platform = navigator.platform,
230): string {
231 const keyLabel = formatShortcutKeyLabel(shortcut.key);
232 const useMetaForMod = isMacPlatform(platform);
233 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
234 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
235 const showAlt = shortcut.altKey;
236 const showShift = shortcut.shiftKey;
237​
238 if (useMetaForMod) {
239 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
240 }
241​
242 const parts: string[] = [];
243 if (showCtrl) parts.push("Ctrl");
244 if (showAlt) parts.push("Alt");
245 if (showShift) parts.push("Shift");
246 if (showMeta) parts.push("Meta");
247 parts.push(keyLabel);
248 return parts.join("+");
250​
251export function shortcutLabelForCommand(
252 keybindings: ResolvedKeybindingsConfig,
253 command: KeybindingCommand | null,
254 options?: string | ResolvedShortcutLabelOptions,
255): string | null {
256 if (command === null) return null;
257 const resolvedOptions =
258 typeof options === "string"
259 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
260 : options;
261 const platform = resolvePlatform(resolvedOptions);
262 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
263 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
265​
266export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
267 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
269​
270export function threadJumpIndexFromCommand(command: string): number | null {
271 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
272 return index === -1 ? null : index;
274​
275export function threadTraversalDirectionFromCommand(
276 command: string | null,
277): "previous" | "next" | null {
278 if (command === "thread.previous") return "previous";
279 if (command === "thread.next") return "next";
280 return null;
282​
283export function shouldShowThreadJumpHintsForModifiers(
284 modifiers: ShortcutModifierStateLike,
285 keybindings: ResolvedKeybindingsConfig,
286 options?: ShortcutMatchOptions,
287): boolean {
288 // Ghostty can write keys to the shell before window shortcuts run, regardless of the when clause.
289 if (resolveContext(options).terminalFocus) {
290 return false;
291 }
292​
293 const platform = resolvePlatform(options);
294​
295 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
296 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
297 if (!shortcut) continue;
298 if (matchesKeybindingShortcutModifiers(modifiers, shortcut, platform)) {
299 return true;
300 }
301 }
302​
303 return false;
305​
306export function modelPickerJumpCommandForIndex(
307 index: number,
308): ModelPickerJumpKeybindingCommand | null {
309 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
311​
312export function modelPickerJumpIndexFromCommand(command: string): number | null {
313 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
314 command as ModelPickerJumpKeybindingCommand,
315 );
316 return index === -1 ? null : index;
318​
319export function isTerminalToggleShortcut(
320 event: ShortcutEventLike,
321 keybindings: ResolvedKeybindingsConfig,
322 options?: ShortcutMatchOptions,
323): boolean {
324 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
326​
327export function isTerminalSplitShortcut(
328 event: ShortcutEventLike,
329 keybindings: ResolvedKeybindingsConfig,
330 options?: ShortcutMatchOptions,
331): boolean {
332 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
334​
335export function isTerminalSplitVerticalShortcut(
336 event: ShortcutEventLike,
337 keybindings: ResolvedKeybindingsConfig,
338 options?: ShortcutMatchOptions,
339): boolean {
340 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
342​
343export function isTerminalNewShortcut(
344 event: ShortcutEventLike,
345 keybindings: ResolvedKeybindingsConfig,
346 options?: ShortcutMatchOptions,
347): boolean {
348 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
350​
351export function isTerminalCloseShortcut(
352 event: ShortcutEventLike,
353 keybindings: ResolvedKeybindingsConfig,
354 options?: ShortcutMatchOptions,
355): boolean {
356 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
358​
359export function isDiffToggleShortcut(
360 event: ShortcutEventLike,
361 keybindings: ResolvedKeybindingsConfig,
362 options?: ShortcutMatchOptions,
363): boolean {
364 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
366​
367export function isOpenFavoriteEditorShortcut(
368 event: ShortcutEventLike,
369 keybindings: ResolvedKeybindingsConfig,
370 options?: ShortcutMatchOptions,
371): boolean {
372 return (
373 event.repeat !== true &&
374 matchesCommandShortcut(event, keybindings, "editor.openFavorite", options)
375 );
377​
378/**
379 * Whether the keypress should bold text in the rich-text composer: Mod+B
380 * without extra modifiers, with text selected. Tiptap binds the same chord, so
381 * app shortcuts captured ahead of the editor yield only in that case. With no
382 * selection the chord stays with the app (the sidebar toggle by default).
383 */
384export function isRichTextBoldShortcut(
385 event: ShortcutEventLike,
386 selection: Pick<Selection, "isCollapsed"> | null,
387): boolean {
388 if (event.type !== undefined && event.type !== "keydown") {
389 return false;
390 }
391 return (
392 selection !== null &&
393 !selection.isCollapsed &&
394 resolveEventKeys(event).has("b") &&
395 (event.metaKey || event.ctrlKey) &&
396 !event.altKey &&
397 !event.shiftKey
398 );
400​
401export function isTerminalClearShortcut(
402 event: ShortcutEventLike,
403 platform = navigator.platform,
404): boolean {
405 if (event.type !== undefined && event.type !== "keydown") {
406 return false;
407 }
408​
409 const key = event.key.toLowerCase();
410​
411 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
412 return true;
413 }
414​
415 return (
416 isMacPlatform(platform) &&
417 key === "k" &&
418 event.metaKey &&
419 !event.ctrlKey &&
420 !event.altKey &&
421 !event.shiftKey
422 );
424​
425export function terminalDeleteShortcutData(
426 event: ShortcutEventLike,
427 platform = navigator.platform,
428): string | null {
429 if (event.type !== undefined && event.type !== "keydown") {
430 return null;
431 }
432​
433 if (!isMacPlatform(platform)) {
434 return null;
435 }
436​
437 const key = normalizeEventKey(event.key);
438 if (key !== "backspace") {
439 return null;
440 }
441​
442 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
443 ? TERMINAL_DELETE_TO_LINE_START
444 : null;
446​
447export function terminalNavigationShortcutData(
448 event: ShortcutEventLike,
449 platform = navigator.platform,
450): string | null {
451 if (event.type !== undefined && event.type !== "keydown") {
452 return null;
453 }
454​
455 if (event.shiftKey) return null;
456​
457 const key = normalizeEventKey(event.key);
458 if (key !== "arrowleft" && key !== "arrowright") {
459 return null;
460 }
461​
462 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
463 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
464​
465 if (isMacPlatform(platform)) {
466 if (event.altKey && !event.metaKey && !event.ctrlKey) {
467 return moveWord;
468 }
469 if (event.metaKey && !event.altKey && !event.ctrlKey) {
470 return moveLine;
471 }
472 return null;
473 }
474​
475 if (event.altKey && !event.metaKey && !event.ctrlKey) {
476 return moveWord;
477 }
478​
479 return null;