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

KeybindingsSettings.logic.ts

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