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

keybindings.ts

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