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

keybindings.ts

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