Open History to see the last commit
1import {
2 STATIC_KEYBINDING_COMMANDS,
3 type KeybindingCommand,
4 type KeybindingShortcut,
5 type KeybindingWhenNode,
6 type ResolvedKeybindingRule,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import {
10 DEFAULT_RESOLVED_KEYBINDINGS,
11 parseKeybindingWhenExpression,
12 US_SHIFTED_TO_UNSHIFTED_KEYS,
13} from "@t3tools/shared/keybindings";
14
15import { shortcutKeyFromEvent } from "../../keybindings";
16import { isMacPlatform } from "../../lib/utils";
17import { METRIC_OPTIONS, WINDOW_OPTIONS } from "../usage/usageShortcuts";
18
19// Every usage.* command needs a rank. An unranked one falls back to the
20// alphabetical compare, which makes the comparator inconsistent and the order
21// depend on the input order.
22const usageCommandOrder = new Map<KeybindingCommand, number>(
23 [
24 "usage.open" as const,
25 ...[...METRIC_OPTIONS, ...WINDOW_OPTIONS].map((option) => option.command),
26 ].map((command, index) => [command, index]),
27);
28
29const firstUsageCommand = METRIC_OPTIONS[0].command;
30
31function compareCommands(
32 left: KeybindingCommand,
33 right: KeybindingCommand,
34 key: (command: KeybindingCommand) => string,
35): number {
36 const leftRank = usageCommandOrder.get(left);
37 const rightRank = usageCommandOrder.get(right);
38 if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
39 return key(leftRank === undefined ? left : firstUsageCommand).localeCompare(
40 key(rightRank === undefined ? right : firstUsageCommand),
41 );
42}
43
44export type KeybindingSource = "Default" | "Custom" | "Project";
45
46export interface KeybindingRow {
47 readonly id: string;
48 readonly command: KeybindingCommand;
49 readonly key: string;
50 readonly when: string;
51 readonly source: KeybindingSource;
52 readonly defaultKey: string | null;
53 readonly defaultWhen: string;
54 readonly binding: ResolvedKeybindingRule;
55 readonly conflicts: ReadonlyArray<string>;
56}
57
58export type WhenVariableOption = string;
59export type KeybindingCommandOption = KeybindingCommand;
60
61const CORE_WHEN_VARIABLES = [
62 "terminalFocus",
63 "terminalOpen",
64 "isWeb",
65 "isDesktop",
66 "true",
67 "false",
68] as const;
69
70const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
71for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
72 collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
73}
74
75export const DEFAULT_WHEN_VARIABLE =
76 [...DEFAULT_WHEN_VARIABLES].find(
77 (identifier) => identifier !== "true" && identifier !== "false",
78 ) ?? "terminalFocus";
79const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
80
81export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
82 const parts: string[] = [];
83 if (shortcut.modKey) parts.push("mod");
84 if (shortcut.metaKey) parts.push("meta");
85 if (shortcut.ctrlKey) parts.push("ctrl");
86 if (shortcut.altKey) parts.push("alt");
87 if (shortcut.shiftKey) parts.push("shift");
88 parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
89 return parts.join("+");
90}
91
92export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
93 if (!node) return "";
94 switch (node.type) {
95 case "identifier":
96 return node.name;
97 case "not":
98 return `!${wrapWhenExpression(node.node)}`;
99 case "and":
100 return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
101 case "or":
102 return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
103 }
104}
105
106export function whenNodeRemoveLabel(node: KeybindingWhenNode, depth: number): string {
107 if (depth === 0) return "Clear all conditions";
108 if (node.type === "identifier" || (node.type === "not" && node.node.type === "identifier")) {
109 return "Remove condition";
110 }
111 return "Remove group and its conditions";
112}
113
114function wrapWhenExpression(node: KeybindingWhenNode): string {
115 if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
116 return `(${whenAstToExpression(node)})`;
117}
118
119export function parseWhenExpressionDraft(
120 expression: string,
121): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
122 const trimmed = expression.trim();
123 if (trimmed.length === 0) return { ok: true, value: undefined };
124
125 const ast = parseKeybindingWhenExpression(trimmed);
126 if (!ast) {
127 return {
128 ok: false,
129 message: "Use variables with !, &&, ||, and parentheses.",
130 };
131 }
132
133 return { ok: true, value: ast };
134}
135
136function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
137 if (String(binding.command).startsWith("script.")) {
138 return "Project";
139 }
140
141 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
142 const bindingWhen = whenAstToExpression(binding.whenAst);
143 const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
144 (entry) =>
145 entry.command === binding.command &&
146 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
147 whenAstToExpression(entry.whenAst) === bindingWhen,
148 );
149
150 return isDefault ? "Default" : "Custom";
151}
152
153function defaultBindingForBinding(
154 binding: ResolvedKeybindingRule,
155): ResolvedKeybindingRule | undefined {
156 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
157 const bindingWhen = whenAstToExpression(binding.whenAst);
158
159 return (
160 DEFAULT_RESOLVED_KEYBINDINGS.find(
161 (entry) =>
162 entry.command === binding.command &&
163 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
164 whenAstToExpression(entry.whenAst) === bindingWhen,
165 ) ??
166 DEFAULT_RESOLVED_KEYBINDINGS.find(
167 (entry) =>
168 entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
169 ) ??
170 DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
171 );
172}
173
174function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
175 return `${command}\u0000${key}\u0000${when}`;
176}
177
178function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
179 return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
180}
181
182export function keybindingConflictLabels(
183 rows: ReadonlyArray<KeybindingRow>,
184 input: { readonly rowId: string; readonly key: string; readonly when: string },
185): ReadonlyArray<string> {
186 if (input.key.trim().length === 0) return [];
187 const conflicts: Array<string> = [];
188 for (const candidate of rows) {
189 if (
190 candidate.id !== input.rowId &&
191 candidate.key === input.key &&
192 conflictsWithWhen(candidate.when, input.when)
193 ) {
194 conflicts.push(commandLabel(candidate.command));
195 }
196 }
197 return [...new Set(conflicts)].toSorted();
198}
199
200export interface KeybindingGroup {
201 readonly id: string;
202 readonly title: string;
203 readonly rows: ReadonlyArray<KeybindingRow>;
204}
205
206const KEYBINDING_GROUPS = [
207 {
208 id: "navigation",
209 title: "Navigation",
210 prefixes: ["sidebar", "rightPanel", "commandPalette", "filePicker", "projectSearch", "editor"],
211 },
212 { id: "threads", title: "Threads", prefixes: ["thread", "chat", "pullRequest"] },
213 { id: "composer", title: "Composer", prefixes: ["composer", "modelPicker"] },
214 { id: "terminal", title: "Terminal", prefixes: ["terminal"] },
215 { id: "preview", title: "Preview & diff", prefixes: ["preview", "diff"] },
216 { id: "appearance", title: "Appearance", prefixes: ["theme", "appearance", "themeEditor"] },
217 { id: "scripts", title: "Project scripts", prefixes: ["script"] },
218] as const;
219const OTHER_KEYBINDING_GROUP = { id: "other", title: "Other" } as const;
220
221function keybindingGroupFor(command: KeybindingCommand): { id: string; title: string } {
222 const prefix = String(command).split(".")[0] ?? "";
223 return (
224 KEYBINDING_GROUPS.find((group) => (group.prefixes as ReadonlyArray<string>).includes(prefix)) ??
225 OTHER_KEYBINDING_GROUP
226 );
227}
228
229export function groupKeybindingRows(
230 rows: ReadonlyArray<KeybindingRow>,
231): ReadonlyArray<KeybindingGroup> {
232 const rowsByGroup = new Map<string, Array<KeybindingRow>>();
233 for (const row of rows) {
234 const group = keybindingGroupFor(row.command);
235 const bucket = rowsByGroup.get(group.id);
236 if (bucket) bucket.push(row);
237 else rowsByGroup.set(group.id, [row]);
238 }
239 return [...KEYBINDING_GROUPS, OTHER_KEYBINDING_GROUP].flatMap((group) => {
240 const groupRows = rowsByGroup.get(group.id);
241 return groupRows ? [{ id: group.id, title: group.title, rows: groupRows }] : [];
242 });
243}
244
245export function buildKeybindingRows(
246 keybindings: ResolvedKeybindingsConfig,
247): ReadonlyArray<KeybindingRow> {
248 const rowsById = new Map<string, KeybindingRow>();
249 for (const binding of keybindings) {
250 const defaultBinding = defaultBindingForBinding(binding);
251 const key = shortcutToKeybindingInput(binding.shortcut);
252 const when = whenAstToExpression(binding.whenAst);
253 const id = keybindingRowId(binding.command, key, when);
254 rowsById.set(id, {
255 id,
256 command: binding.command,
257 key,
258 when,
259 source: sourceForBinding(binding),
260 defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
261 defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
262 binding,
263 conflicts: [],
264 });
265 }
266 const rows = [...rowsById.values()];
267
268 const rowsWithConflicts = rows.map((row) => {
269 const conflicts = keybindingConflictLabels(rows, {
270 rowId: row.id,
271 key: row.key,
272 when: row.when,
273 });
274 return conflicts.length > 0
275 ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
276 : row;
277 });
278
279 rowsWithConflicts.sort((left, right) => {
280 const commandCompare = compareCommands(left.command, right.command, (command) => command);
281 if (commandCompare !== 0) return commandCompare;
282 return left.key.localeCompare(right.key);
283 });
284
285 return rowsWithConflicts;
286}
287
288// Filtering keeps the row objects so rows that stay visible while the query
289// changes receive the same props and skip rendering.
290export function filterKeybindingRows(
291 rows: ReadonlyArray<KeybindingRow>,
292 query: string,
293): ReadonlyArray<KeybindingRow> {
294 const normalizedQuery = query.trim().toLowerCase();
295 if (normalizedQuery.length === 0) return rows;
296 return rows.filter((row) => {
297 return (
298 row.command.toLowerCase().includes(normalizedQuery) ||
299 commandLabel(row.command).toLowerCase().includes(normalizedQuery) ||
300 row.key.toLowerCase().includes(normalizedQuery) ||
301 row.when.toLowerCase().includes(normalizedQuery) ||
302 row.source.toLowerCase().includes(normalizedQuery)
303 );
304 });
305}
306
307function collectWhenIdentifiersFromNode(
308 node: KeybindingWhenNode | undefined,
309 identifiers: Set<string>,
310): void {
311 if (!node) return;
312 switch (node.type) {
313 case "identifier":
314 identifiers.add(node.name);
315 return;
316 case "not":
317 collectWhenIdentifiersFromNode(node.node, identifiers);
318 return;
319 case "and":
320 case "or":
321 collectWhenIdentifiersFromNode(node.left, identifiers);
322 collectWhenIdentifiersFromNode(node.right, identifiers);
323 return;
324 }
325}
326
327export function isKnownWhenVariable(identifier: string): boolean {
328 return KNOWN_WHEN_VARIABLES.has(identifier);
329}
330
331export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
332 const identifiers = new Set<string>();
333 collectWhenIdentifiersFromNode(node, identifiers);
334 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
335}
336
337export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
338 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
339 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
340 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
341 right as (typeof CORE_WHEN_VARIABLES)[number],
342 );
343 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
344 return (
345 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
346 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
347 );
348 }
349 return left.localeCompare(right);
350 });
351}
352
353export function buildKeybindingCommandOptions(
354 keybindings: ResolvedKeybindingsConfig,
355): ReadonlyArray<KeybindingCommandOption> {
356 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
357 for (const binding of keybindings) {
358 commands.add(binding.command);
359 }
360 return [...commands].toSorted((left, right) => compareCommands(left, right, commandLabel));
361}
362
363export function commandLabel(command: KeybindingCommand): string {
364 if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";
365 if (command === "composer.sendBackground") return "Composer: Start in Background";
366 if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
367 if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message as Steer";
368 if (command === "thread.editQueuedMessage") return "Queue: Edit Last Queued Message";
369 if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
370 const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
371 if (usageMetric) return `Usage: ${usageMetric.label}`;
372 const usagePeriod = WINDOW_OPTIONS.find((option) => option.command === command);
373 if (usagePeriod) return `Usage: Period: ${usagePeriod.label}`;
374 if (command === "view.reopenClosed") return "Reopen Closed Tab";
375 if (command === "preview.focusUrl") return "Preview: Focus URL";
376 const raw = String(command);
377 if (raw.startsWith("script.") && raw.endsWith(".run")) {
378 return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
379 }
380 return raw.split(".").map(titleCaseCommandSegment).join(": ");
381}
382
383function titleCaseCommandSegment(segment: string): string {
384 const words: Array<string> = [];
385 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
386 if (part.length > 0) {
387 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
388 }
389 }
390 return words.join(" ");
391}
392
393function recordedLayoutShortcutKey(
394 event: Pick<KeyboardEvent, "key" | "code" | "shiftKey" | "altKey">,
395): string {
396 const physicalKey = shortcutKeyFromEvent(event);
397 const layoutKey = event.key.toLowerCase();
398 if (event.altKey || layoutKey.length !== 1) return physicalKey;
399 // Normalize only US shifted glyphs at their US position. Other layouts can
400 // produce the same glyph without Shift or at a different position.
401 const unshiftedKey = event.shiftKey ? US_SHIFTED_TO_UNSHIFTED_KEYS.get(layoutKey) : undefined;
402 return unshiftedKey === physicalKey ? physicalKey : layoutKey;
403}
404
405function normalizeShortcutKeyToken(key: string): string | null {
406 const normalized = key.toLowerCase();
407 if (
408 normalized === "meta" ||
409 normalized === "control" ||
410 normalized === "ctrl" ||
411 normalized === "shift" ||
412 normalized === "alt" ||
413 normalized === "option"
414 ) {
415 return null;
416 }
417 if (normalized === " ") return "space";
418 if (normalized === "escape") return "esc";
419 if (normalized === "arrowup") return "arrowup";
420 if (normalized === "arrowdown") return "arrowdown";
421 if (normalized === "arrowleft") return "arrowleft";
422 if (normalized === "arrowright") return "arrowright";
423 if (normalized.length === 1) return normalized;
424 if (/^f\d{1,2}$/.test(normalized)) return normalized;
425 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
426 return normalized;
427 }
428 if (normalized === "delete" || normalized === "home" || normalized === "end") {
429 return normalized;
430 }
431 if (normalized === "pageup" || normalized === "pagedown") return normalized;
432 return null;
433}
434
435export function keybindingFromKeyboardEvent(
436 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
437 platform: string,
438 options?: {
439 readonly layoutCharacter?: boolean;
440 },
441): string | null {
442 const keyToken = normalizeShortcutKeyToken(
443 options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event),
444 );
445 if (!keyToken) return null;
446
447 const parts: string[] = [];
448 if (isMacPlatform(platform)) {
449 if (event.metaKey) parts.push("mod");
450 if (event.ctrlKey) parts.push("ctrl");
451 } else {
452 if (event.ctrlKey) parts.push("mod");
453 if (event.metaKey) parts.push("meta");
454 }
455 if (event.altKey) parts.push("alt");
456 if (event.shiftKey) parts.push("shift");
457 parts.push(keyToken);
458 return parts.join("+");
459}