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

KeybindingsSettings.logic.ts

640 lines23.3 KB

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