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