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

KeybindingsSettings.logic.ts

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