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

keybindings.ts

535 lines16.0 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 type ShortcutKeyboardLayoutMap,
21 shortcutKeyFromEvent as sharedShortcutKeyFromEvent,
22} from "@t3tools/shared/keybindings";
23import { isElectron } from "./env";
24import { isEditableFocused } from "./lib/editableFocus";
25import { projectScriptIdFromCommand } from "./projectScripts";
26import { getKeyboardLayoutMap } from "./keyboardLayout";
27​
28export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings";
29export function shortcutKeyFromEvent(
30 event: Pick<ShortcutEventLike, "key" | "code" | "shiftKey" | "altKey">,
31 platform: string,
32) {
33 return sharedShortcutKeyFromEvent(
34 event,
35 isMacPlatform(platform) && event.altKey ? getKeyboardLayoutMap() : undefined,
36 );
38​
39export interface ShortcutEventLike extends SharedShortcutEventLike {
40 target?: EventTarget | null;
42​
43export interface ShortcutMatchContext {
44 terminalFocus: boolean;
45 terminalOpen: boolean;
46 previewFocus: boolean;
47 previewOpen: boolean;
48 isWeb: boolean;
49 isDesktop: boolean;
50 editableFocus?: boolean;
51 [key: string]: boolean;
53​
54interface ShortcutMatchOptions {
55 platform?: string;
56 keyboardLayoutMap?: ShortcutKeyboardLayoutMap;
57 context?: Partial<ShortcutMatchContext>;
59​
60interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions {
61 platform?: string;
63​
64const TERMINAL_WORD_BACKWARD = "\u001bb";
65const TERMINAL_WORD_FORWARD = "\u001bf";
66const TERMINAL_LINE_START = "\u0001";
67const TERMINAL_LINE_END = "\u0005";
68const TERMINAL_DELETE_TO_LINE_START = "\u0015";
69function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
70 return options?.platform ?? navigator.platform;
72​
73function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
74 return {
75 terminalFocus: false,
76 terminalOpen: false,
77 previewFocus: false,
78 previewOpen: false,
79 isWeb: !isElectron,
80 isDesktop: isElectron,
81 editableFocus: false,
82 ...options?.context,
83 };
85​
86function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
87 switch (node.type) {
88 case "identifier":
89 if (node.name === "true") return true;
90 if (node.name === "false") return false;
91 return Boolean(context[node.name]);
92 case "not":
93 return !evaluateWhenNode(node.node, context);
94 case "and":
95 return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
96 case "or":
97 return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
98 }
100​
101function matchesWhenClause(
102 whenAst: KeybindingWhenNode | undefined,
103 context: ShortcutMatchContext,
104): boolean {
105 if (!whenAst) return true;
106 return evaluateWhenNode(whenAst, context);
108​
109export function shortcutConflictKey(
110 shortcut: KeybindingShortcut,
111 platform = navigator.platform,
112): string {
113 const useMetaForMod = isMacPlatform(platform);
114 const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
115 const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
116 return [
117 shortcut.key,
118 metaKey ? "meta" : "",
119 ctrlKey ? "ctrl" : "",
120 shortcut.shiftKey ? "shift" : "",
121 shortcut.altKey ? "alt" : "",
122 ].join("|");
124​
125export function shortcutForContext(
126 binding: ResolvedKeybindingRule,
127 context: Partial<ShortcutMatchContext>,
128) {
129 const shortcut = binding.shortcut;
130 // Resolve persisted Mod+Enter against send preference without rewriting saved shortcuts.
131 if (
132 context.composerRequiresModifier &&
133 (binding.command === "composer.sendAlternate" ||
134 binding.command === "composer.sendBackground") &&
135 shortcut.key === "enter" &&
136 shortcut.modKey &&
137 !shortcut.metaKey &&
138 !shortcut.ctrlKey &&
139 !shortcut.altKey &&
140 !shortcut.shiftKey
141 ) {
142 return { ...shortcut, shiftKey: true };
143 }
144 return shortcut;
146​
147export function effectiveShortcutsForCommand(
148 keybindings: ResolvedKeybindingsConfig,
149 command: KeybindingCommand,
150 options?: ShortcutMatchOptions,
151): KeybindingShortcut[] {
152 const platform = resolvePlatform(options);
153 const context = resolveContext(options);
154 const claimedShortcuts = new Set<string>();
155 const effective: KeybindingShortcut[] = [];
156​
157 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
158 const binding = keybindings[index];
159 if (!binding) continue;
160 if (!matchesWhenClause(binding.whenAst, context)) continue;
161​
162 const shortcut = shortcutForContext(binding, context);
163 const conflictKey = shortcutConflictKey(shortcut, platform);
164 if (claimedShortcuts.has(conflictKey)) {
165 continue;
166 }
167​
168 claimedShortcuts.add(conflictKey);
169 if (binding.command === command) {
170 effective.push(shortcut);
171 }
172 }
173​
174 return effective;
176​
177function findEffectiveShortcutForCommand(
178 keybindings: ResolvedKeybindingsConfig,
179 command: KeybindingCommand,
180 options?: ShortcutMatchOptions,
181): KeybindingShortcut | null {
182 return effectiveShortcutsForCommand(keybindings, command, options)[0] ?? null;
184​
185function matchesCommandShortcut(
186 event: ShortcutEventLike,
187 keybindings: ResolvedKeybindingsConfig,
188 command: KeybindingCommand,
189 options?: ShortcutMatchOptions,
190): boolean {
191 return resolveShortcutCommand(event, keybindings, options) === command;
193​
194export function resolveShortcutCommand(
195 event: ShortcutEventLike,
196 keybindings: ResolvedKeybindingsConfig,
197 options?: ShortcutMatchOptions,
198): KeybindingCommand | null {
199 const platform = resolvePlatform(options);
200 const context = resolveContext(options);
201 if (options?.context?.editableFocus === undefined && typeof document !== "undefined") {
202 context.editableFocus = isEditableFocused(event.target ?? document.activeElement);
203 }
204​
205 for (let index = keybindings.length - 1; index >= 0; index -= 1) {
206 const binding = keybindings[index];
207 if (!binding) continue;
208 if (!matchesWhenClause(binding.whenAst, context)) continue;
209 if (
210 !matchesKeybindingShortcut(
211 event,
212 shortcutForContext(binding, context),
213 platform,
214 options?.keyboardLayoutMap ?? getKeyboardLayoutMap(),
215 )
216 )
217 continue;
218 return binding.command;
219 }
220 return null;
222​
223export function resolveChatShortcutCommand(
224 event: ShortcutEventLike,
225 primaryKeybindings: ResolvedKeybindingsConfig,
226 activeKeybindings: ResolvedKeybindingsConfig,
227 options?: ShortcutMatchOptions,
228): KeybindingCommand | null {
229 const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);
230 if (primaryCommand !== null && projectScriptIdFromCommand(primaryCommand) === null) {
231 return primaryCommand;
232 }
233​
234 const activeCommand = resolveShortcutCommand(event, activeKeybindings, options);
235 return activeCommand !== null && projectScriptIdFromCommand(activeCommand) !== null
236 ? activeCommand
237 : null;
239​
240export function formatShortcutKeyLabel(key: string): string {
241 if (key === " ") return "Space";
242 if (key.length === 1) return key.toUpperCase();
243 if (key === "escape") return "Esc";
244 if (key === "arrowup") return "Up";
245 if (key === "arrowdown") return "Down";
246 if (key === "arrowleft") return "Left";
247 if (key === "arrowright") return "Right";
248 if (key === "pageup") return "PageUp";
249 if (key === "pagedown") return "PageDown";
250 return key.slice(0, 1).toUpperCase() + key.slice(1);
252​
253export function formatShortcutLabel(
254 shortcut: KeybindingShortcut,
255 platform = navigator.platform,
256): string {
257 const keyLabel = formatShortcutKeyLabel(shortcut.key);
258 const useMetaForMod = isMacPlatform(platform);
259 const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
260 const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
261 const showAlt = shortcut.altKey;
262 const showShift = shortcut.shiftKey;
263​
264 if (useMetaForMod) {
265 return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
266 }
267​
268 const parts: string[] = [];
269 if (showCtrl) parts.push("Ctrl");
270 if (showAlt) parts.push("Alt");
271 if (showShift) parts.push("Shift");
272 if (showMeta) parts.push("Meta");
273 parts.push(keyLabel);
274 return parts.join("+");
276​
277export function shortcutLabelForCommand(
278 keybindings: ResolvedKeybindingsConfig,
279 command: KeybindingCommand | null,
280 options?: string | ResolvedShortcutLabelOptions,
281): string | null {
282 if (command === null) return null;
283 const resolvedOptions =
284 typeof options === "string"
285 ? ({ platform: options } satisfies ResolvedShortcutLabelOptions)
286 : options;
287 const platform = resolvePlatform(resolvedOptions);
288 const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions);
289 return shortcut ? formatShortcutLabel(shortcut, platform) : null;
291​
292export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null {
293 return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null;
295​
296export function threadJumpIndexFromCommand(command: string): number | null {
297 const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand);
298 return index === -1 ? null : index;
300​
301export function threadTraversalDirectionFromCommand(
302 command: string | null,
303): "previous" | "next" | null {
304 if (command === "thread.previous") return "previous";
305 if (command === "thread.next") return "next";
306 return null;
308​
309export function isThreadNavigationShortcut(
310 event: ShortcutEventLike,
311 keybindings: ResolvedKeybindingsConfig,
312 options?: ShortcutMatchOptions,
313): boolean {
314 const command = resolveShortcutCommand(event, keybindings, options);
315 return (
316 threadTraversalDirectionFromCommand(command) !== null ||
317 threadJumpIndexFromCommand(command ?? "") !== null
318 );
320​
321export function shouldShowThreadJumpHintsForModifiers(
322 modifiers: ShortcutModifierStateLike,
323 keybindings: ResolvedKeybindingsConfig,
324 options?: ShortcutMatchOptions,
325): boolean {
326 // Holding a modifier is routine in a shell (Ctrl+C, Ctrl+R), so don't flash hints over it.
327 if (resolveContext(options).terminalFocus) {
328 return false;
329 }
330​
331 const platform = resolvePlatform(options);
332​
333 for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) {
334 const shortcut = findEffectiveShortcutForCommand(keybindings, command, options);
335 if (!shortcut) continue;
336 if (matchesKeybindingShortcutModifiers(modifiers, shortcut, platform)) {
337 return true;
338 }
339 }
340​
341 return false;
343​
344export function modelPickerJumpCommandForIndex(
345 index: number,
346): ModelPickerJumpKeybindingCommand | null {
347 return MODEL_PICKER_JUMP_KEYBINDING_COMMANDS[index] ?? null;
349​
350export function modelPickerJumpIndexFromCommand(command: string): number | null {
351 const index = MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.indexOf(
352 command as ModelPickerJumpKeybindingCommand,
353 );
354 return index === -1 ? null : index;
356​
357export function isTerminalToggleShortcut(
358 event: ShortcutEventLike,
359 keybindings: ResolvedKeybindingsConfig,
360 options?: ShortcutMatchOptions,
361): boolean {
362 return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
364​
365export function isTerminalSplitShortcut(
366 event: ShortcutEventLike,
367 keybindings: ResolvedKeybindingsConfig,
368 options?: ShortcutMatchOptions,
369): boolean {
370 return matchesCommandShortcut(event, keybindings, "terminal.split", options);
372​
373export function isTerminalSplitVerticalShortcut(
374 event: ShortcutEventLike,
375 keybindings: ResolvedKeybindingsConfig,
376 options?: ShortcutMatchOptions,
377): boolean {
378 return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
380​
381export function isTerminalNewShortcut(
382 event: ShortcutEventLike,
383 keybindings: ResolvedKeybindingsConfig,
384 options?: ShortcutMatchOptions,
385): boolean {
386 return matchesCommandShortcut(event, keybindings, "terminal.new", options);
388​
389export function isTerminalCloseShortcut(
390 event: ShortcutEventLike,
391 keybindings: ResolvedKeybindingsConfig,
392 options?: ShortcutMatchOptions,
393): boolean {
394 return matchesCommandShortcut(event, keybindings, "terminal.close", options);
396​
397export function isDiffToggleShortcut(
398 event: ShortcutEventLike,
399 keybindings: ResolvedKeybindingsConfig,
400 options?: ShortcutMatchOptions,
401): boolean {
402 return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
404​
405export function isSidebarToggleShortcut(
406 event: ShortcutEventLike,
407 keybindings: ResolvedKeybindingsConfig,
408 options?: ShortcutMatchOptions,
409): boolean {
410 // A focused terminal owns Ctrl chords, such as tmux's Ctrl+B prefix; Cmd never reaches it.
411 if (event.ctrlKey && options?.context?.terminalFocus) return false;
412 return matchesCommandShortcut(event, keybindings, "sidebar.toggle", options);
414​
415export function isOpenFavoriteEditorShortcut(
416 event: ShortcutEventLike,
417 keybindings: ResolvedKeybindingsConfig,
418 options?: ShortcutMatchOptions,
419): boolean {
420 return (
421 event.repeat !== true &&
422 matchesCommandShortcut(event, keybindings, "editor.openFavorite", options)
423 );
425​
426/**
427 * Whether the keypress should bold text in the rich-text composer: Mod+B
428 * without extra modifiers, with text selected. Tiptap binds the same chord, so
429 * app shortcuts captured ahead of the editor yield only in that case. With no
430 * selection an app binding on the chord wins (the sidebar toggle by default).
431 */
432export function isRichTextBoldShortcut(
433 event: ShortcutEventLike,
434 selection: Pick<Selection, "isCollapsed"> | null,
435): boolean {
436 if (event.type !== undefined && event.type !== "keydown") {
437 return false;
438 }
439 return (
440 selection !== null &&
441 !selection.isCollapsed &&
442 resolveEventKeys(event).has("b") &&
443 (event.metaKey || event.ctrlKey) &&
444 !event.altKey &&
445 !event.shiftKey
446 );
448​
449/** Mod+B, Mod+I and Mod+E, the mark chords the rich-text composer binds. */
450export function isRichTextFormattingShortcut(event: ShortcutEventLike): boolean {
451 if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return false;
452 const keys = resolveEventKeys(event);
453 return keys.has("b") || keys.has("i") || keys.has("e");
455​
456export function isTerminalClearShortcut(
457 event: ShortcutEventLike,
458 platform = navigator.platform,
459): boolean {
460 if (event.type !== undefined && event.type !== "keydown") {
461 return false;
462 }
463​
464 const key = event.key.toLowerCase();
465​
466 if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
467 return true;
468 }
469​
470 return (
471 isMacPlatform(platform) &&
472 key === "k" &&
473 event.metaKey &&
474 !event.ctrlKey &&
475 !event.altKey &&
476 !event.shiftKey
477 );
479​
480export function terminalDeleteShortcutData(
481 event: ShortcutEventLike,
482 platform = navigator.platform,
483): string | null {
484 if (event.type !== undefined && event.type !== "keydown") {
485 return null;
486 }
487​
488 if (!isMacPlatform(platform)) {
489 return null;
490 }
491​
492 const key = normalizeEventKey(event.key);
493 if (key !== "backspace") {
494 return null;
495 }
496​
497 return event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
498 ? TERMINAL_DELETE_TO_LINE_START
499 : null;
501​
502export function terminalNavigationShortcutData(
503 event: ShortcutEventLike,
504 platform = navigator.platform,
505): string | null {
506 if (event.type !== undefined && event.type !== "keydown") {
507 return null;
508 }
509​
510 if (event.shiftKey) return null;
511​
512 const key = normalizeEventKey(event.key);
513 if (key !== "arrowleft" && key !== "arrowright") {
514 return null;
515 }
516​
517 const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
518 const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
519​
520 if (isMacPlatform(platform)) {
521 if (event.altKey && !event.metaKey && !event.ctrlKey) {
522 return moveWord;
523 }
524 if (event.metaKey && !event.altKey && !event.ctrlKey) {
525 return moveLine;
526 }
527 return null;
528 }
529​
530 if (event.altKey && !event.metaKey && !event.ctrlKey) {
531 return moveWord;
532 }
533​
534 return null;