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 parseKeybindingShortcut,
12 parseKeybindingWhenExpression,
13 US_SHIFTED_TO_UNSHIFTED_KEYS,
14} from "@t3tools/shared/keybindings";
15
16import { shortcutConflictKey, shortcutKeyFromEvent } from "../../keybindings";
17import { isMacPlatform } from "../../lib/utils";
18import { METRIC_OPTIONS, WINDOW_OPTIONS } from "../usage/usageShortcuts";
19
20// Rank every usage command; mixing rank and alphabetical comparisons makes order input-dependent.
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 platform = navigator.platform,
185): ReadonlyArray<string> {
186 if (input.key.trim().length === 0) return [];
187 const shortcut = parseKeybindingShortcut(input.key);
188 if (!shortcut) return [];
189 // Compare resolved chords so mod+k and ctrl+k collide where mod is Ctrl.
190 const conflictKey = shortcutConflictKey(shortcut, platform);
191 const conflicts: Array<string> = [];
192 for (const candidate of rows) {
193 if (
194 candidate.id !== input.rowId &&
195 shortcutConflictKey(candidate.binding.shortcut, platform) === conflictKey &&
196 conflictsWithWhen(candidate.when, input.when)
197 ) {
198 conflicts.push(commandLabel(candidate.command));
199 }
200 }
201 return [...new Set(conflicts)].toSorted();
202}
203
204export interface KeybindingGroup {
205 readonly id: string;
206 readonly title: string;
207 readonly rows: ReadonlyArray<KeybindingRow>;
208}
209
210const KEYBINDING_GROUPS = [
211 {
212 id: "navigation",
213 title: "Navigation",
214 prefixes: ["sidebar", "rightPanel", "commandPalette", "filePicker", "projectSearch", "editor"],
215 },
216 { id: "threads", title: "Threads", prefixes: ["thread", "chat", "pullRequest"] },
217 { id: "composer", title: "Composer", prefixes: ["composer", "modelPicker"] },
218 { id: "terminal", title: "Terminal", prefixes: ["terminal"] },
219 { id: "preview", title: "Preview & diff", prefixes: ["preview", "diff"] },
220 { id: "appearance", title: "Appearance", prefixes: ["theme", "appearance", "themeEditor"] },
221 { id: "scripts", title: "Project scripts", prefixes: ["script"] },
222] as const;
223const OTHER_KEYBINDING_GROUP = { id: "other", title: "Other" } as const;
224
225function keybindingGroupFor(command: KeybindingCommand): { id: string; title: string } {
226 const prefix = String(command).split(".")[0] ?? "";
227 return (
228 KEYBINDING_GROUPS.find((group) => (group.prefixes as ReadonlyArray<string>).includes(prefix)) ??
229 OTHER_KEYBINDING_GROUP
230 );
231}
232
233export function groupKeybindingRows(
234 rows: ReadonlyArray<KeybindingRow>,
235): ReadonlyArray<KeybindingGroup> {
236 const rowsByGroup = new Map<string, Array<KeybindingRow>>();
237 for (const row of rows) {
238 const group = keybindingGroupFor(row.command);
239 const bucket = rowsByGroup.get(group.id);
240 if (bucket) bucket.push(row);
241 else rowsByGroup.set(group.id, [row]);
242 }
243 return [...KEYBINDING_GROUPS, OTHER_KEYBINDING_GROUP].flatMap((group) => {
244 const groupRows = rowsByGroup.get(group.id);
245 return groupRows ? [{ id: group.id, title: group.title, rows: groupRows }] : [];
246 });
247}
248
249export function buildKeybindingRows(
250 keybindings: ResolvedKeybindingsConfig,
251 platform = navigator.platform,
252): ReadonlyArray<KeybindingRow> {
253 const rowsById = new Map<string, KeybindingRow>();
254 for (const binding of keybindings) {
255 const defaultBinding = defaultBindingForBinding(binding);
256 const key = shortcutToKeybindingInput(binding.shortcut);
257 const when = whenAstToExpression(binding.whenAst);
258 const id = keybindingRowId(binding.command, key, when);
259 rowsById.set(id, {
260 id,
261 command: binding.command,
262 key,
263 when,
264 source: sourceForBinding(binding),
265 defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
266 defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
267 binding,
268 conflicts: [],
269 });
270 }
271 const rows = [...rowsById.values()];
272
273 const rowsWithConflicts = rows.map((row) => {
274 const conflicts = keybindingConflictLabels(
275 rows,
276 {
277 rowId: row.id,
278 key: row.key,
279 when: row.when,
280 },
281 platform,
282 );
283 return conflicts.length > 0
284 ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
285 : row;
286 });
287
288 rowsWithConflicts.sort((left, right) => {
289 const commandCompare = compareCommands(left.command, right.command, (command) => command);
290 if (commandCompare !== 0) return commandCompare;
291 return left.key.localeCompare(right.key);
292 });
293
294 return rowsWithConflicts;
295}
296
297export function filterKeybindingRows(
298 rows: ReadonlyArray<KeybindingRow>,
299 query: string,
300): ReadonlyArray<KeybindingRow> {
301 const normalizedQuery = query.trim().toLowerCase();
302 if (normalizedQuery.length === 0) return rows;
303 return rows.filter((row) => {
304 return (
305 row.command.toLowerCase().includes(normalizedQuery) ||
306 commandLabel(row.command).toLowerCase().includes(normalizedQuery) ||
307 row.key.toLowerCase().includes(normalizedQuery) ||
308 row.when.toLowerCase().includes(normalizedQuery) ||
309 row.source.toLowerCase().includes(normalizedQuery)
310 );
311 });
312}
313
314function collectWhenIdentifiersFromNode(
315 node: KeybindingWhenNode | undefined,
316 identifiers: Set<string>,
317): void {
318 if (!node) return;
319 switch (node.type) {
320 case "identifier":
321 identifiers.add(node.name);
322 return;
323 case "not":
324 collectWhenIdentifiersFromNode(node.node, identifiers);
325 return;
326 case "and":
327 case "or":
328 collectWhenIdentifiersFromNode(node.left, identifiers);
329 collectWhenIdentifiersFromNode(node.right, identifiers);
330 return;
331 }
332}
333
334export function isKnownWhenVariable(identifier: string): boolean {
335 return KNOWN_WHEN_VARIABLES.has(identifier);
336}
337
338export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
339 const identifiers = new Set<string>();
340 collectWhenIdentifiersFromNode(node, identifiers);
341 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
342}
343
344export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
345 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
346 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
347 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
348 right as (typeof CORE_WHEN_VARIABLES)[number],
349 );
350 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
351 return (
352 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
353 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
354 );
355 }
356 return left.localeCompare(right);
357 });
358}
359
360export function buildKeybindingCommandOptions(
361 keybindings: ResolvedKeybindingsConfig,
362): ReadonlyArray<KeybindingCommandOption> {
363 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
364 for (const binding of keybindings) {
365 commands.add(binding.command);
366 }
367 return [...commands].toSorted((left, right) => compareCommands(left, right, commandLabel));
368}
369
370export function commandLabel(command: KeybindingCommand): string {
371 if (command === "workspace.focusNext") return "Focus Next Workspace Area";
372 if (command === "workspace.focusPrevious") return "Focus Previous Workspace Area";
373 if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";
374 if (command === "composer.sendBackground") return "Composer: Start in Background";
375 if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
376 if (command === "composer.dictation") return "Composer: Start or Finish Dictation";
377 if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message";
378 if (command === "thread.editQueuedMessage") return "Queue: Edit Last Queued Message";
379 if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread";
380 const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
381 if (usageMetric) return `Usage: ${usageMetric.label}`;
382 const usagePeriod = WINDOW_OPTIONS.find((option) => option.command === command);
383 if (usagePeriod) return `Usage: Period: ${usagePeriod.label}`;
384 if (command === "view.reopenClosed") return "Reopen Closed Tab";
385 if (command === "preview.focusUrl") return "Preview: Focus URL";
386 const raw = String(command);
387 if (raw.startsWith("script.") && raw.endsWith(".run")) {
388 return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
389 }
390 return raw.split(".").map(titleCaseCommandSegment).join(": ");
391}
392
393function titleCaseCommandSegment(segment: string): string {
394 const words: Array<string> = [];
395 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
396 if (part.length > 0) {
397 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
398 }
399 }
400 return words.join(" ");
401}
402
403function recordedLayoutShortcutKey(
404 event: Pick<KeyboardEvent, "key" | "code" | "shiftKey" | "altKey">,
405): string {
406 const physicalKey = shortcutKeyFromEvent(event);
407 const layoutKey = event.key.toLowerCase();
408 if (event.altKey || layoutKey.length !== 1) return physicalKey;
409 // Normalize only US shifted glyphs at their US position. Other layouts can
410 // produce the same glyph without Shift or at a different position.
411 const unshiftedKey = event.shiftKey ? US_SHIFTED_TO_UNSHIFTED_KEYS.get(layoutKey) : undefined;
412 return unshiftedKey === physicalKey ? physicalKey : layoutKey;
413}
414
415function normalizeShortcutKeyToken(key: string): string | null {
416 const normalized = key.toLowerCase();
417 if (
418 normalized === "meta" ||
419 normalized === "control" ||
420 normalized === "ctrl" ||
421 normalized === "shift" ||
422 normalized === "alt" ||
423 normalized === "option"
424 ) {
425 return null;
426 }
427 if (normalized === " ") return "space";
428 if (normalized === "escape") return "esc";
429 if (normalized === "arrowup") return "arrowup";
430 if (normalized === "arrowdown") return "arrowdown";
431 if (normalized === "arrowleft") return "arrowleft";
432 if (normalized === "arrowright") return "arrowright";
433 if (normalized.length === 1) return normalized;
434 if (/^f\d{1,2}$/.test(normalized)) return normalized;
435 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
436 return normalized;
437 }
438 if (normalized === "delete" || normalized === "home" || normalized === "end") {
439 return normalized;
440 }
441 if (normalized === "pageup" || normalized === "pagedown") return normalized;
442 return null;
443}
444
445export function keybindingFromKeyboardEvent(
446 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
447 platform: string,
448 options?: {
449 readonly layoutCharacter?: boolean;
450 },
451): string | null {
452 const keyToken = normalizeShortcutKeyToken(
453 options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event),
454 );
455 if (!keyToken) return null;
456
457 const parts: string[] = [];
458 if (isMacPlatform(platform)) {
459 if (event.metaKey) parts.push("mod");
460 if (event.ctrlKey) parts.push("ctrl");
461 } else {
462 if (event.ctrlKey) parts.push("mod");
463 if (event.metaKey) parts.push("meta");
464 }
465 if (event.altKey) parts.push("alt");
466 if (event.shiftKey) parts.push("shift");
467 parts.push(keyToken);
468 return parts.join("+");
469}