The best way to control Claude Code, Codex and more from any computer or phone

main
ts 620 lines 22.4 KB
Raw
1 import {
2 STATIC_KEYBINDING_COMMANDS,
3 type ClientSettings,
4 type KeybindingCommand,
5 type KeybindingShortcut,
6 type KeybindingWhenNode,
7 type ResolvedKeybindingRule,
8 type ResolvedKeybindingsConfig,
9 } from "@t3tools/contracts";
10 import {
11 DEFAULT_RESOLVED_KEYBINDINGS,
12 parseKeybindingShortcut,
13 parseKeybindingWhenExpression,
14 US_SHIFTED_TO_UNSHIFTED_KEYS,
15 } from "@t3tools/shared/keybindings";
16 import { msg } from "gt-react";
17
18 import { m, type MessageResolver } from "../../i18n/messages";
19 import {
20 formatShortcutLabel,
21 shortcutConflictKey,
22 shortcutForContext,
23 shortcutKeyFromEvent,
24 } from "../../keybindings";
25 import { isMacPlatform } from "../../lib/utils";
26 import { METRIC_OPTIONS, WINDOW_OPTIONS } from "../usage/usageShortcuts";
27
28 // Rank every usage command; mixing rank and alphabetical comparisons makes order input-dependent.
29 const usageCommandOrder = new Map<KeybindingCommand, number>(
30 [
31 "usage.open" as const,
32 ...[...METRIC_OPTIONS, ...WINDOW_OPTIONS].map((option) => option.command),
33 ].map((command, index) => [command, index]),
34 );
35
36 const firstUsageCommand = METRIC_OPTIONS[0].command;
37
38 function compareCommands(
39 left: KeybindingCommand,
40 right: KeybindingCommand,
41 key: (command: KeybindingCommand) => string,
42 ): number {
43 const leftRank = usageCommandOrder.get(left);
44 const rightRank = usageCommandOrder.get(right);
45 if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
46 return key(leftRank === undefined ? left : firstUsageCommand).localeCompare(
47 key(rightRank === undefined ? right : firstUsageCommand),
48 );
49 }
50
51 export type KeybindingSource = "Default" | "Custom" | "Project";
52
53 export interface KeybindingRow {
54 readonly id: string;
55 readonly command: KeybindingCommand;
56 readonly key: string;
57 readonly when: string;
58 readonly source: KeybindingSource;
59 readonly isUnassigned: boolean;
60 readonly defaultKey: string | null;
61 readonly defaultWhen: string;
62 readonly binding: ResolvedKeybindingRule;
63 readonly conflicts: ReadonlyArray<string>;
64 readonly previewLabels: ReadonlyArray<string>;
65 }
66
67 export type WhenVariableOption = string;
68 export type KeybindingCommandOption = KeybindingCommand;
69
70 const CORE_WHEN_VARIABLES = [
71 "terminalFocus",
72 "terminalOpen",
73 "previewOpen",
74 "isWeb",
75 "isDesktop",
76 "true",
77 "false",
78 ] as const;
79
80 const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
81 for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
82 collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
83 }
84
85 export const DEFAULT_WHEN_VARIABLE =
86 [...DEFAULT_WHEN_VARIABLES].find(
87 (identifier) => identifier !== "true" && identifier !== "false",
88 ) ?? "terminalFocus";
89 const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
90
91 export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
92 const parts: string[] = [];
93 if (shortcut.modKey) parts.push("mod");
94 if (shortcut.metaKey) parts.push("meta");
95 if (shortcut.ctrlKey) parts.push("ctrl");
96 if (shortcut.altKey) parts.push("alt");
97 if (shortcut.shiftKey) parts.push("shift");
98 parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
99 return parts.join("+");
100 }
101
102 export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
103 if (!node) return "";
104 switch (node.type) {
105 case "identifier":
106 return node.name;
107 case "not":
108 return `!${wrapWhenExpression(node.node)}`;
109 case "and":
110 return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
111 case "or":
112 return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
113 }
114 }
115
116 export function whenNodeRemoveLabel(
117 node: KeybindingWhenNode,
118 depth: number,
119 resolve: MessageResolver = m,
120 ): string {
121 if (depth === 0) return resolve(msg("Clear all conditions"));
122 if (node.type === "identifier" || (node.type === "not" && node.node.type === "identifier")) {
123 return resolve(msg("Remove condition"));
124 }
125 return resolve(msg("Remove group and its conditions"));
126 }
127
128 function wrapWhenExpression(node: KeybindingWhenNode): string {
129 if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
130 return `(${whenAstToExpression(node)})`;
131 }
132
133 export function parseWhenExpressionDraft(
134 expression: string,
135 resolve: MessageResolver = m,
136 ): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
137 const trimmed = expression.trim();
138 if (trimmed.length === 0) return { ok: true, value: undefined };
139
140 const ast = parseKeybindingWhenExpression(trimmed);
141 if (!ast) {
142 return {
143 ok: false,
144 message: resolve(msg("Use variables with !, &&, ||, and parentheses.")),
145 };
146 }
147
148 return { ok: true, value: ast };
149 }
150
151 function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
152 if (String(binding.command).startsWith("script.")) {
153 const source: KeybindingSource = "Project";
154 return source;
155 }
156
157 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
158 const bindingWhen = whenAstToExpression(binding.whenAst);
159 const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
160 (entry) =>
161 entry.command === binding.command &&
162 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
163 whenAstToExpression(entry.whenAst) === bindingWhen,
164 );
165
166 const source: KeybindingSource = isDefault ? "Default" : "Custom";
167 return source;
168 }
169
170 function defaultBindingForBinding(
171 binding: ResolvedKeybindingRule,
172 ): ResolvedKeybindingRule | undefined {
173 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
174 const bindingWhen = whenAstToExpression(binding.whenAst);
175
176 return (
177 DEFAULT_RESOLVED_KEYBINDINGS.find(
178 (entry) =>
179 entry.command === binding.command &&
180 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
181 whenAstToExpression(entry.whenAst) === bindingWhen,
182 ) ??
183 (bindingWhen === "false"
184 ? DEFAULT_RESOLVED_KEYBINDINGS.find(
185 (entry) =>
186 entry.command === binding.command &&
187 shortcutToKeybindingInput(entry.shortcut) === bindingKey,
188 )
189 : undefined) ??
190 DEFAULT_RESOLVED_KEYBINDINGS.find(
191 (entry) =>
192 entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
193 ) ??
194 DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
195 );
196 }
197
198 function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
199 return `${command}\u0000${key}\u0000${when}`;
200 }
201
202 function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
203 if (leftWhen === "false" || rightWhen === "false") return false;
204 return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
205 }
206
207 export function keybindingConflictLabels(
208 rows: ReadonlyArray<KeybindingRow>,
209 input: { readonly rowId: string; readonly key: string; readonly when: string },
210 platform = navigator.platform,
211 resolve: MessageResolver = m,
212 ): ReadonlyArray<string> {
213 if (input.key.trim().length === 0) return [];
214 const shortcut = parseKeybindingShortcut(input.key);
215 if (!shortcut) return [];
216 // Compare resolved chords so mod+k and ctrl+k collide where mod is Ctrl.
217 const conflictKey = shortcutConflictKey(shortcut, platform);
218 const conflicts: Array<string> = [];
219 for (const candidate of rows) {
220 if (
221 candidate.id !== input.rowId &&
222 shortcutConflictKey(candidate.binding.shortcut, platform) === conflictKey &&
223 conflictsWithWhen(candidate.when, input.when)
224 ) {
225 conflicts.push(commandLabel(candidate.command, resolve));
226 }
227 }
228 return [...new Set(conflicts)].toSorted();
229 }
230
231 export interface KeybindingGroup {
232 readonly id: string;
233 readonly title: string;
234 readonly rows: ReadonlyArray<KeybindingRow>;
235 }
236
237 const KEYBINDING_GROUPS = [
238 {
239 id: "navigation",
240 title: msg("Navigation"),
241 prefixes: ["sidebar", "rightPanel", "commandPalette", "filePicker", "projectSearch", "editor"],
242 },
243 { id: "threads", title: msg("Threads"), prefixes: ["thread", "chat", "pullRequest"] },
244 { id: "composer", title: msg("Composer"), prefixes: ["composer", "modelPicker"] },
245 { id: "terminal", title: msg("Terminal"), prefixes: ["terminal"] },
246 { id: "preview", title: msg("Preview & diff"), prefixes: ["preview", "diff"] },
247 {
248 id: "appearance",
249 title: msg("Appearance"),
250 prefixes: ["theme", "appearance", "themeEditor"],
251 },
252 { id: "scripts", title: msg("Project scripts"), prefixes: ["script"] },
253 ] as const;
254 const OTHER_KEYBINDING_GROUP = {
255 id: "other",
256 title: msg("Other", { $context: "keybinding group" }),
257 } as const;
258
259 function keybindingGroupFor(command: KeybindingCommand): { id: string; title: string } {
260 const prefix = String(command).split(".")[0] ?? "";
261 return (
262 KEYBINDING_GROUPS.find((group) => (group.prefixes as ReadonlyArray<string>).includes(prefix)) ??
263 OTHER_KEYBINDING_GROUP
264 );
265 }
266
267 export function groupKeybindingRows(
268 rows: ReadonlyArray<KeybindingRow>,
269 ): ReadonlyArray<KeybindingGroup> {
270 const rowsByGroup = new Map<string, Array<KeybindingRow>>();
271 for (const row of rows) {
272 const group = keybindingGroupFor(row.command);
273 const bucket = rowsByGroup.get(group.id);
274 if (bucket) bucket.push(row);
275 else rowsByGroup.set(group.id, [row]);
276 }
277 return [...KEYBINDING_GROUPS, OTHER_KEYBINDING_GROUP].flatMap((group) => {
278 const groupRows = rowsByGroup.get(group.id);
279 return groupRows ? [{ id: group.id, title: group.title, rows: groupRows }] : [];
280 });
281 }
282
283 export function buildKeybindingRows(
284 keybindings: ResolvedKeybindingsConfig,
285 platform = navigator.platform,
286 sendShortcut: ClientSettings["sendShortcut"] = "enter",
287 resolve: MessageResolver = m,
288 ): ReadonlyArray<KeybindingRow> {
289 // Multiline sending can use either shortcut; settings have no active composer prompt.
290 const modifierModes =
291 sendShortcut === "mod-enter-multiline" ? [false, true] : [sendShortcut === "mod-enter"];
292 const previewLabels = keybindings.map(() => new Set<string>());
293 for (const composerRequiresModifier of modifierModes) {
294 const laterBindings = new Set<string>();
295 for (let index = keybindings.length - 1; index >= 0; index--) {
296 const binding = keybindings[index]!;
297 const when = whenAstToExpression(binding.whenAst);
298 if (when === "false") continue;
299 const shortcut = shortcutForContext(binding, { composerRequiresModifier });
300 const key = shortcutConflictKey(shortcut, platform);
301 const conditionKey = `${key}:${when === "true" ? "" : when}`;
302 // Distinct conditions may still apply in other focus contexts.
303 if (!laterBindings.has(`${key}:`) && !laterBindings.has(conditionKey)) {
304 previewLabels[index]!.add(formatShortcutLabel(shortcut, platform));
305 }
306 laterBindings.add(conditionKey);
307 }
308 }
309 const rowsById = new Map<string, KeybindingRow>();
310 for (const [index, binding] of keybindings.entries()) {
311 const defaultBinding = defaultBindingForBinding(binding);
312 const key = shortcutToKeybindingInput(binding.shortcut);
313 const when = whenAstToExpression(binding.whenAst);
314 const id = keybindingRowId(binding.command, key, when);
315 rowsById.set(id, {
316 id,
317 command: binding.command,
318 key,
319 when,
320 source: sourceForBinding(binding),
321 isUnassigned:
322 when === "false" &&
323 defaultBinding !== undefined &&
324 key === shortcutToKeybindingInput(defaultBinding.shortcut),
325 defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
326 defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
327 binding,
328 conflicts: [],
329 previewLabels: [...previewLabels[index]!],
330 });
331 }
332 const rows = [...rowsById.values()];
333
334 const rowsWithConflicts = rows.map((row) => {
335 const conflicts = keybindingConflictLabels(
336 rows,
337 {
338 rowId: row.id,
339 key: row.key,
340 when: row.when,
341 },
342 platform,
343 resolve,
344 );
345 return conflicts.length > 0
346 ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
347 : row;
348 });
349
350 rowsWithConflicts.sort((left, right) => {
351 const commandCompare = compareCommands(left.command, right.command, (command) => command);
352 if (commandCompare !== 0) return commandCompare;
353 return left.key.localeCompare(right.key);
354 });
355
356 return rowsWithConflicts;
357 }
358
359 export function filterKeybindingRows(
360 rows: ReadonlyArray<KeybindingRow>,
361 query: string,
362 resolve: MessageResolver = m,
363 ): ReadonlyArray<KeybindingRow> {
364 const normalizedQuery = query.trim().toLowerCase();
365 if (normalizedQuery.length === 0) return rows;
366 return rows.filter((row) => {
367 return (
368 row.command.toLowerCase().includes(normalizedQuery) ||
369 commandLabel(row.command, resolve).toLowerCase().includes(normalizedQuery) ||
370 row.key.toLowerCase().includes(normalizedQuery) ||
371 row.when.toLowerCase().includes(normalizedQuery) ||
372 row.source.toLowerCase().includes(normalizedQuery)
373 );
374 });
375 }
376
377 function collectWhenIdentifiersFromNode(
378 node: KeybindingWhenNode | undefined,
379 identifiers: Set<string>,
380 ): void {
381 if (!node) return;
382 switch (node.type) {
383 case "identifier":
384 identifiers.add(node.name);
385 return;
386 case "not":
387 collectWhenIdentifiersFromNode(node.node, identifiers);
388 return;
389 case "and":
390 case "or":
391 collectWhenIdentifiersFromNode(node.left, identifiers);
392 collectWhenIdentifiersFromNode(node.right, identifiers);
393 return;
394 }
395 }
396
397 export function isKnownWhenVariable(identifier: string): boolean {
398 return KNOWN_WHEN_VARIABLES.has(identifier);
399 }
400
401 export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
402 const identifiers = new Set<string>();
403 collectWhenIdentifiersFromNode(node, identifiers);
404 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
405 }
406
407 export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
408 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
409 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
410 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
411 right as (typeof CORE_WHEN_VARIABLES)[number],
412 );
413 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
414 return (
415 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
416 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
417 );
418 }
419 return left.localeCompare(right);
420 });
421 }
422
423 export function buildKeybindingCommandOptions(
424 keybindings: ResolvedKeybindingsConfig,
425 resolve: MessageResolver = m,
426 ): ReadonlyArray<KeybindingCommandOption> {
427 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
428 for (const binding of keybindings) {
429 commands.add(binding.command);
430 }
431 return [...commands].toSorted((left, right) =>
432 compareCommands(left, right, (command) => commandLabel(command, resolve)),
433 );
434 }
435
436 const COMMAND_LABELS: Partial<Record<KeybindingCommand, string>> = {
437 "workspace.focusNext": msg("Focus Next Workspace Area"),
438 "workspace.focusPrevious": msg("Focus Previous Workspace Area"),
439 "composer.sendAlternate": msg("Composer: Opposite Queue or Steer Action"),
440 "composer.sendBackground": msg("Composer: Start in Background"),
441 "composer.sendAndNewThread": msg("Composer: Send and Start New Thread"),
442 "composer.dictation": msg("Composer: Start or Finish Dictation"),
443 "thread.steerQueuedMessage": msg("Queue: Send First Queued Message"),
444 "thread.editQueuedMessage": msg("Queue: Edit Last Queued Message"),
445 "thread.copyReference": msg("Pull Request: Copy Link or Thread"),
446 "sidebar.toggle": msg("Sidebar: Toggle"),
447 "navigation.back": msg("Navigation: Back"),
448 "navigation.forward": msg("Navigation: Forward"),
449 "terminal.toggle": msg("Terminal: Toggle"),
450 "terminal.split": msg("Terminal: Split"),
451 "terminal.splitVertical": msg("Terminal: Split Vertical"),
452 "terminal.new": msg("Terminal: New"),
453 "terminal.close": msg("Terminal: Close"),
454 "rightPanel.toggle": msg("Right Panel: Toggle"),
455 "rightPanel.new": msg("Right Panel: New"),
456 "threadPanel.toggle": msg("Thread Panel: Toggle"),
457 "rightPanel.toggleMaximized": msg("Right Panel: Toggle Maximized"),
458 "rightPanel.close": msg("Right Panel: Close"),
459 "pullRequest.copyNumber": msg("Pull Request: Copy Number"),
460 "diff.toggle": msg("Diff: Toggle"),
461 "preview.toggle": msg("Preview: Toggle"),
462 "preview.refresh": msg("Preview: Refresh"),
463 "preview.zoomIn": msg("Preview: Zoom In"),
464 "preview.zoomOut": msg("Preview: Zoom Out"),
465 "preview.resetZoom": msg("Preview: Reset Zoom"),
466 "commandPalette.toggle": msg("Command Palette: Toggle"),
467 "filePicker.toggle": msg("File Picker: Toggle"),
468 "projectSearch.toggle": msg("Project Search: Toggle"),
469 "usage.open": msg("Usage: Open"),
470 "theme.select": msg("Theme: Select"),
471 "appearance.cycle": msg("Appearance: Cycle"),
472 "themeEditor.toggle": msg("Theme Editor: Toggle"),
473 "composer.stash": msg("Composer: Stash"),
474 "composer.host": msg("Composer: Host"),
475 "composer.cycleHost": msg("Composer: Cycle Host"),
476 "composer.effort": msg("Composer: Effort"),
477 "composer.increaseEffort": msg("Composer: Increase Effort"),
478 "composer.decreaseEffort": msg("Composer: Decrease Effort"),
479 "composer.mode": msg("Composer: Mode"),
480 "composer.workspace": msg("Composer: Workspace"),
481 "composer.previousWorktree": msg("Composer: Previous Worktree"),
482 "composer.branch": msg("Composer: Branch"),
483 "chat.new": msg("Chat: New"),
484 "chat.newLocal": msg("Chat: New Local"),
485 "chat.newWithoutProject": msg("Chat: New Without Project"),
486 "chat.find": msg("Chat: Find"),
487 "editor.openFavorite": msg("Editor: Open Favorite"),
488 "modelPicker.toggle": msg("Model Picker: Toggle"),
489 "modelPicker.previousProvider": msg("Model Picker: Previous Provider"),
490 "modelPicker.nextProvider": msg("Model Picker: Next Provider"),
491 "thread.stop": msg("Thread: Stop"),
492 "thread.previous": msg("Thread: Previous"),
493 "thread.next": msg("Thread: Next"),
494 "thread.settle": msg("Thread: Settle"),
495 "thread.pin": msg("Thread: Pin"),
496 "thread.regenerateTitle": msg("Thread: Regenerate Title"),
497 "thread.undo": msg("Thread: Undo"),
498 };
499
500 // Whole labels: search titles keep the encoded message, which cannot nest another one.
501 const USAGE_COMMAND_LABELS: Record<
502 (typeof METRIC_OPTIONS)[number]["command"] | (typeof WINDOW_OPTIONS)[number]["command"],
503 string
504 > = {
505 "usage.cost": msg("Usage: Cost"),
506 "usage.tokens": msg("Usage: Tokens"),
507 "usage.limits": msg("Usage: Limits"),
508 "usage.period.day": msg("Usage: Period: Past 24h"),
509 "usage.period.week": msg("Usage: Period: 7 days"),
510 "usage.period.month": msg("Usage: Period: 30 days"),
511 "usage.period.quarter": msg("Usage: Period: 90 days"),
512 };
513
514 const LATE_COMMAND_LABELS: Partial<Record<KeybindingCommand, string>> = {
515 "view.reopenClosed": msg("Reopen Closed Tab"),
516 "preview.focusUrl": msg("Preview: Focus URL"),
517 "preview.find": msg("Preview: Find on Page"),
518 };
519
520 export function commandLabel(command: KeybindingCommand, resolve: MessageResolver = m): string {
521 const label = COMMAND_LABELS[command];
522 if (label) return resolve(label);
523 const usageLabel = USAGE_COMMAND_LABELS[command as keyof typeof USAGE_COMMAND_LABELS];
524 if (usageLabel) return resolve(usageLabel);
525 const lateLabel = LATE_COMMAND_LABELS[command];
526 if (lateLabel) return resolve(lateLabel);
527 const raw = String(command);
528 if (raw.startsWith("thread.jump.")) {
529 return resolve(msg("Thread: Jump: {n}", { n: raw.slice("thread.jump.".length) }));
530 }
531 if (raw.startsWith("modelPicker.jump.")) {
532 return resolve(msg("Model Picker: Jump: {n}", { n: raw.slice("modelPicker.jump.".length) }));
533 }
534 if (raw.startsWith("script.") && raw.endsWith(".run")) {
535 return resolve(
536 msg("Run Script: {name}", {
537 name: titleCaseCommandSegment(raw.slice("script.".length, -".run".length)),
538 }),
539 );
540 }
541 return raw.split(".").map(titleCaseCommandSegment).join(": ");
542 }
543
544 function titleCaseCommandSegment(segment: string): string {
545 const words: Array<string> = [];
546 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
547 if (part.length > 0) {
548 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
549 }
550 }
551 return words.join(" ");
552 }
553
554 function recordedLayoutShortcutKey(
555 event: Pick<KeyboardEvent, "key" | "code" | "shiftKey" | "altKey">,
556 ): string {
557 const physicalKey = shortcutKeyFromEvent(event);
558 const layoutKey = event.key.toLowerCase();
559 if (event.altKey || layoutKey.length !== 1) return physicalKey;
560 // Normalize only US shifted glyphs at their US position. Other layouts can
561 // produce the same glyph without Shift or at a different position.
562 const unshiftedKey = event.shiftKey ? US_SHIFTED_TO_UNSHIFTED_KEYS.get(layoutKey) : undefined;
563 return unshiftedKey === physicalKey ? physicalKey : layoutKey;
564 }
565
566 function normalizeShortcutKeyToken(key: string): string | null {
567 const normalized = key.toLowerCase();
568 if (
569 normalized === "meta" ||
570 normalized === "control" ||
571 normalized === "ctrl" ||
572 normalized === "shift" ||
573 normalized === "alt" ||
574 normalized === "option"
575 ) {
576 return null;
577 }
578 if (normalized === " ") return "space";
579 if (normalized === "escape") return "esc";
580 if (normalized === "arrowup") return "arrowup";
581 if (normalized === "arrowdown") return "arrowdown";
582 if (normalized === "arrowleft") return "arrowleft";
583 if (normalized === "arrowright") return "arrowright";
584 if (normalized.length === 1) return normalized;
585 if (/^f\d{1,2}$/.test(normalized)) return normalized;
586 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
587 return normalized;
588 }
589 if (normalized === "delete" || normalized === "home" || normalized === "end") {
590 return normalized;
591 }
592 if (normalized === "pageup" || normalized === "pagedown") return normalized;
593 return null;
594 }
595
596 export function keybindingFromKeyboardEvent(
597 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
598 platform: string,
599 options?: {
600 readonly layoutCharacter?: boolean;
601 },
602 ): string | null {
603 const keyToken = normalizeShortcutKeyToken(
604 options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event),
605 );
606 if (!keyToken) return null;
607
608 const parts: string[] = [];
609 if (isMacPlatform(platform)) {
610 if (event.metaKey) parts.push("mod");
611 if (event.ctrlKey) parts.push("ctrl");
612 } else {
613 if (event.ctrlKey) parts.push("mod");
614 if (event.metaKey) parts.push("meta");
615 }
616 if (event.altKey) parts.push("alt");
617 if (event.shiftKey) parts.push("shift");
618 parts.push(keyToken);
619 return parts.join("+");
620 }