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