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

KeybindingsSettings.logic.ts

666 lines24.4 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​
392export function filterKeybindingRows(
393 rows: ReadonlyArray<KeybindingRow>,
394 query: string,
395 resolve: MessageResolver = m,
396 platform = navigator.platform,
397): ReadonlyArray<KeybindingRow> {
398 const normalizedQuery = query.trim().toLowerCase();
399 if (normalizedQuery.length === 0) return rows;
400 return rows.filter((row) => {
401 return (
402 row.command.toLowerCase().includes(normalizedQuery) ||
403 commandLabel(row.command, resolve).toLowerCase().includes(normalizedQuery) ||
404 row.key.toLowerCase().includes(normalizedQuery) ||
405 // The row shows the platform label ("Ctrl+K"), not the stored "mod+k".
406 formatShortcutLabel(row.binding.shortcut, platform).toLowerCase().includes(normalizedQuery) ||
407 row.when.toLowerCase().includes(normalizedQuery) ||
408 row.source.toLowerCase().includes(normalizedQuery) ||
409 (row.source !== "Default" &&
410 resolve(KEYBINDING_SOURCE_LABELS[row.source]).toLowerCase().includes(normalizedQuery))
411 );
412 });
414​
415function collectWhenIdentifiersFromNode(
416 node: KeybindingWhenNode | undefined,
417 identifiers: Set<string>,
418): void {
419 if (!node) return;
420 switch (node.type) {
421 case "identifier":
422 identifiers.add(node.name);
423 return;
424 case "not":
425 collectWhenIdentifiersFromNode(node.node, identifiers);
426 return;
427 case "and":
428 case "or":
429 collectWhenIdentifiersFromNode(node.left, identifiers);
430 collectWhenIdentifiersFromNode(node.right, identifiers);
431 return;
432 }
434​
435export function isKnownWhenVariable(identifier: string): boolean {
436 return KNOWN_WHEN_VARIABLES.has(identifier);
438​
439export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
440 const identifiers = new Set<string>();
441 collectWhenIdentifiersFromNode(node, identifiers);
442 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
444​
445export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
446 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
447 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
448 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
449 right as (typeof CORE_WHEN_VARIABLES)[number],
450 );
451 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
452 return (
453 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
454 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
455 );
456 }
457 return left.localeCompare(right);
458 });
460​
461export function buildKeybindingCommandOptions(
462 keybindings: ResolvedKeybindingsConfig,
463 resolve: MessageResolver = m,
464): ReadonlyArray<KeybindingCommandOption> {
465 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
466 for (const binding of keybindings) {
467 commands.add(binding.command);
468 }
469 return [...commands].toSorted((left, right) =>
470 compareCommands(left, right, (command) => commandLabel(command, resolve)),
471 );
473​
474const COMMAND_LABELS: Partial<Record<KeybindingCommand, string>> = {
475 "workspace.focusNext": msg("Focus Next Workspace Area"),
476 "workspace.focusPrevious": msg("Focus Previous Workspace Area"),
477 "composer.sendAlternate": msg("Composer: Opposite Queue or Steer Action"),
478 "composer.sendBackground": msg("Composer: Start in Background"),
479 "composer.sendAndNewThread": msg("Composer: Send and Start New Thread"),
480 "composer.dictation": msg("Composer: Start or Finish Dictation"),
481 "thread.steerQueuedMessage": msg("Queue: Send First Queued Message"),
482 "thread.editQueuedMessage": msg("Queue: Edit Last Queued Message"),
483 "thread.copyReference": msg("Pull Request: Copy Link or Thread"),
484 "sidebar.toggle": msg("Sidebar: Toggle"),
485 "navigation.back": msg("Navigation: Back"),
486 "navigation.forward": msg("Navigation: Forward"),
487 "terminal.toggle": msg("Terminal: Toggle"),
488 "terminal.split": msg("Terminal: Split"),
489 "terminal.splitVertical": msg("Terminal: Split Vertical"),
490 "terminal.new": msg("Terminal: New"),
491 "terminal.close": msg("Terminal: Close"),
492 "terminal.previous": msg("Terminal: Previous"),
493 "terminal.next": msg("Terminal: Next"),
494 "rightPanel.toggle": msg("Right Panel: Toggle"),
495 "rightPanel.new": msg("Right Panel: New"),
496 "threadPanel.toggle": msg("Thread Panel: Toggle"),
497 "rightPanel.toggleMaximized": msg("Right Panel: Toggle Maximized"),
498 "rightPanel.close": msg("Right Panel: Close"),
499 "pullRequest.copyNumber": msg("Pull Request: Copy Number"),
500 "diff.toggle": msg("Diff: Toggle"),
501 "preview.toggle": msg("Preview: Toggle"),
502 "preview.refresh": msg("Preview: Refresh"),
503 "preview.zoomIn": msg("Preview: Zoom In"),
504 "preview.zoomOut": msg("Preview: Zoom Out"),
505 "preview.resetZoom": msg("Preview: Reset Zoom"),
506 "commandPalette.toggle": msg("Command Palette: Toggle"),
507 "filePicker.toggle": msg("File Picker: Toggle"),
508 "projectSearch.toggle": msg("Project Search: Toggle"),
509 "usage.open": msg("Usage: Toggle"),
510 "theme.select": msg("Theme: Select"),
511 "appearance.cycle": msg("Appearance: Cycle"),
512 "themeEditor.toggle": msg("Theme Editor: Toggle"),
513 "composer.stash": msg("Composer: Stash"),
514 "composer.host": msg("Composer: Host"),
515 "composer.cycleHost": msg("Composer: Cycle Host"),
516 "composer.effort": msg("Composer: Effort"),
517 "composer.increaseEffort": msg("Composer: Increase Effort"),
518 "composer.decreaseEffort": msg("Composer: Decrease Effort"),
519 "composer.mode": msg("Composer: Mode"),
520 "composer.workspace": msg("Composer: Workspace"),
521 "composer.previousWorktree": msg("Composer: Previous Worktree"),
522 "composer.branch": msg("Composer: Branch"),
523 "chat.new": msg("Chat: New"),
524 "chat.newLocal": msg("Chat: New Local"),
525 "chat.newWithoutProject": msg("Chat: New Without Project"),
526 "chat.find": msg("Chat: Find"),
527 "editor.openFavorite": msg("Editor: Open Favorite"),
528 "modelPicker.toggle": msg("Model Picker: Toggle"),
529 "modelPicker.previousProvider": msg("Model Picker: Previous Provider"),
530 "modelPicker.nextProvider": msg("Model Picker: Next Provider"),
531 "thread.stop": msg("Thread: Stop"),
532 "thread.previous": msg("Thread: Previous"),
533 "thread.next": msg("Thread: Next"),
534 "thread.settle": msg("Thread: Settle"),
535 "thread.pin": msg("Thread: Pin"),
536 "thread.regenerateTitle": msg("Thread: Regenerate Title"),
537 "thread.undo": msg("Thread: Undo"),
538};
539​
540// Whole labels: search titles keep the encoded message, which cannot nest another one.
541const USAGE_COMMAND_LABELS: Record<
542 (typeof METRIC_OPTIONS)[number]["command"] | (typeof WINDOW_OPTIONS)[number]["command"],
543 string
544> = {
545 "usage.cost": msg("Usage: Cost"),
546 "usage.tokens": msg("Usage: Tokens"),
547 "usage.limits": msg("Usage: Limits"),
548 "usage.period.day": msg("Usage: Period: Past 24h"),
549 "usage.period.week": msg("Usage: Period: 7 days"),
550 "usage.period.month": msg("Usage: Period: 30 days"),
551 "usage.period.quarter": msg("Usage: Period: 90 days"),
552};
553​
554const LATE_COMMAND_LABELS: Partial<Record<KeybindingCommand, string>> = {
555 "view.reopenClosed": msg("Reopen Closed Tab"),
556 "preview.focusUrl": msg("Preview: Focus URL"),
557 "preview.find": msg("Preview: Find on Page"),
558};
559​
560export function commandLabel(command: KeybindingCommand, resolve: MessageResolver = m): string {
561 const label = COMMAND_LABELS[command];
562 if (label) return resolve(label);
563 const usageLabel = USAGE_COMMAND_LABELS[command as keyof typeof USAGE_COMMAND_LABELS];
564 if (usageLabel) return resolve(usageLabel);
565 const lateLabel = LATE_COMMAND_LABELS[command];
566 if (lateLabel) return resolve(lateLabel);
567 const raw = String(command);
568 if (raw.startsWith("thread.jump.")) {
569 return resolve(msg`Thread: Jump: ${{ n: raw.slice("thread.jump.".length) }}`);
570 }
571 if (raw.startsWith("modelPicker.jump.")) {
572 return resolve(msg`Model Picker: Jump: ${{ n: raw.slice("modelPicker.jump.".length) }}`);
573 }
574 if (raw.startsWith("script.") && raw.endsWith(".run")) {
575 return resolve(
576 msg`Run Script: ${{ name: titleCaseCommandSegment(raw.slice("script.".length, -".run".length)) }}`,
577 );
578 }
579 return raw.split(".").map(titleCaseCommandSegment).join(": ");
581​
582function titleCaseCommandSegment(segment: string): string {
583 const words: Array<string> = [];
584 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
585 if (part.length > 0) {
586 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
587 }
588 }
589 return words.join(" ");
591​
592function recordedLayoutShortcutKey(
593 event: Pick<KeyboardEvent, "key" | "code" | "shiftKey" | "altKey">,
594 platform: string,
595): string {
596 const physicalKey = shortcutKeyFromEvent(event, platform);
597 const layoutKey = event.key.toLowerCase();
598 if (layoutKey.length !== 1 || (event.altKey && isMacPlatform(platform))) return physicalKey;
599 // A non-Latin letter (Cyrillic, Greek, ...) stops matching once the user switches to a Latin layout.
600 if (/^\p{L}$/u.test(layoutKey) && !/\p{Script=Latin}/u.test(layoutKey)) {
601 return /^Key[A-Z]$/.test(event.code) ? event.code.slice(3).toLowerCase() : physicalKey;
602 }
603 if (event.altKey) return physicalKey;
604 // Normalize only US shifted glyphs at their US position. Other layouts can
605 // produce the same glyph without Shift or at a different position.
606 const unshiftedKey = event.shiftKey ? US_SHIFTED_TO_UNSHIFTED_KEYS.get(layoutKey) : undefined;
607 return unshiftedKey === physicalKey ? physicalKey : layoutKey;
609​
610function normalizeShortcutKeyToken(key: string): string | null {
611 const normalized = key.toLowerCase();
612 if (
613 normalized === "meta" ||
614 normalized === "control" ||
615 normalized === "ctrl" ||
616 normalized === "shift" ||
617 normalized === "alt" ||
618 normalized === "option"
619 ) {
620 return null;
621 }
622 if (normalized === " ") return "space";
623 if (normalized === "escape") return "esc";
624 if (normalized === "arrowup") return "arrowup";
625 if (normalized === "arrowdown") return "arrowdown";
626 if (normalized === "arrowleft") return "arrowleft";
627 if (normalized === "arrowright") return "arrowright";
628 if (normalized.length === 1) return normalized;
629 if (/^f\d{1,2}$/.test(normalized)) return normalized;
630 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
631 return normalized;
632 }
633 if (normalized === "delete" || normalized === "home" || normalized === "end") {
634 return normalized;
635 }
636 if (normalized === "pageup" || normalized === "pagedown") return normalized;
637 return null;
639​
640export function keybindingFromKeyboardEvent(
641 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
642 platform: string,
643 options?: {
644 readonly layoutCharacter?: boolean;
645 },
646): string | null {
647 const keyToken = normalizeShortcutKeyToken(
648 options?.layoutCharacter
649 ? recordedLayoutShortcutKey(event, platform)
650 : shortcutKeyFromEvent(event, platform),
651 );
652 if (!keyToken) return null;
653​
654 const parts: string[] = [];
655 if (isMacPlatform(platform)) {
656 if (event.metaKey) parts.push("mod");
657 if (event.ctrlKey) parts.push("ctrl");
658 } else {
659 if (event.ctrlKey) parts.push("mod");
660 if (event.metaKey) parts.push("meta");
661 }
662 if (event.altKey) parts.push("alt");
663 if (event.shiftKey) parts.push("shift");
664 parts.push(keyToken);
665 return parts.join("+");