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
18const usageCommandOrder = new Map<KeybindingCommand, number>(
19 [...METRIC_OPTIONS, ...WINDOW_OPTIONS].map((option, index) => [option.command, index]),
20);
21
22function compareUsageCommands(left: KeybindingCommand, right: KeybindingCommand): number | null {
23 const leftIndex = usageCommandOrder.get(left);
24 const rightIndex = usageCommandOrder.get(right);
25 return leftIndex !== undefined && rightIndex !== undefined ? leftIndex - rightIndex : null;
26}
27
28export type KeybindingSource = "Default" | "Custom" | "Project";
29
30export interface KeybindingRow {
31 readonly id: string;
32 readonly command: KeybindingCommand;
33 readonly key: string;
34 readonly when: string;
35 readonly source: KeybindingSource;
36 readonly defaultKey: string | null;
37 readonly defaultWhen: string;
38 readonly binding: ResolvedKeybindingRule;
39 readonly conflicts: ReadonlyArray<string>;
40}
41
42export type WhenVariableOption = string;
43export type KeybindingCommandOption = KeybindingCommand;
44
45const CORE_WHEN_VARIABLES = [
46 "terminalFocus",
47 "terminalOpen",
48 "isWeb",
49 "isDesktop",
50 "true",
51 "false",
52] as const;
53
54const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
55for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
56 collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
57}
58
59export const DEFAULT_WHEN_VARIABLE =
60 [...DEFAULT_WHEN_VARIABLES].find(
61 (identifier) => identifier !== "true" && identifier !== "false",
62 ) ?? "terminalFocus";
63const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
64
65export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
66 const parts: string[] = [];
67 if (shortcut.modKey) parts.push("mod");
68 if (shortcut.metaKey) parts.push("meta");
69 if (shortcut.ctrlKey) parts.push("ctrl");
70 if (shortcut.altKey) parts.push("alt");
71 if (shortcut.shiftKey) parts.push("shift");
72 parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
73 return parts.join("+");
74}
75
76export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
77 if (!node) return "";
78 switch (node.type) {
79 case "identifier":
80 return node.name;
81 case "not":
82 return `!${wrapWhenExpression(node.node)}`;
83 case "and":
84 return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
85 case "or":
86 return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
87 }
88}
89
90export function whenNodeRemoveLabel(node: KeybindingWhenNode, depth: number): string {
91 if (depth === 0) return "Clear all conditions";
92 if (node.type === "identifier" || (node.type === "not" && node.node.type === "identifier")) {
93 return "Remove condition";
94 }
95 return "Remove group and its conditions";
96}
97
98function wrapWhenExpression(node: KeybindingWhenNode): string {
99 if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
100 return `(${whenAstToExpression(node)})`;
101}
102
103export function parseWhenExpressionDraft(
104 expression: string,
105): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
106 const trimmed = expression.trim();
107 if (trimmed.length === 0) return { ok: true, value: undefined };
108
109 const ast = parseKeybindingWhenExpression(trimmed);
110 if (!ast) {
111 return {
112 ok: false,
113 message: "Use variables with !, &&, ||, and parentheses.",
114 };
115 }
116
117 return { ok: true, value: ast };
118}
119
120function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
121 if (String(binding.command).startsWith("script.")) {
122 return "Project";
123 }
124
125 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
126 const bindingWhen = whenAstToExpression(binding.whenAst);
127 const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
128 (entry) =>
129 entry.command === binding.command &&
130 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
131 whenAstToExpression(entry.whenAst) === bindingWhen,
132 );
133
134 return isDefault ? "Default" : "Custom";
135}
136
137function defaultBindingForBinding(
138 binding: ResolvedKeybindingRule,
139): ResolvedKeybindingRule | undefined {
140 const bindingKey = shortcutToKeybindingInput(binding.shortcut);
141 const bindingWhen = whenAstToExpression(binding.whenAst);
142
143 return (
144 DEFAULT_RESOLVED_KEYBINDINGS.find(
145 (entry) =>
146 entry.command === binding.command &&
147 shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
148 whenAstToExpression(entry.whenAst) === bindingWhen,
149 ) ??
150 DEFAULT_RESOLVED_KEYBINDINGS.find(
151 (entry) =>
152 entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
153 ) ??
154 DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
155 );
156}
157
158function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
159 return `${command}\u0000${key}\u0000${when}`;
160}
161
162function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
163 return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
164}
165
166export function keybindingConflictLabels(
167 rows: ReadonlyArray<KeybindingRow>,
168 input: { readonly rowId: string; readonly key: string; readonly when: string },
169): ReadonlyArray<string> {
170 if (input.key.trim().length === 0) return [];
171 const conflicts: Array<string> = [];
172 for (const candidate of rows) {
173 if (
174 candidate.id !== input.rowId &&
175 candidate.key === input.key &&
176 conflictsWithWhen(candidate.when, input.when)
177 ) {
178 conflicts.push(commandLabel(candidate.command));
179 }
180 }
181 return [...new Set(conflicts)].toSorted();
182}
183
184export function buildKeybindingRows(
185 keybindings: ResolvedKeybindingsConfig,
186 query: string,
187): ReadonlyArray<KeybindingRow> {
188 const normalizedQuery = query.trim().toLowerCase();
189 const rows = keybindings.map((binding, index) => {
190 const defaultBinding = defaultBindingForBinding(binding);
191 const key = shortcutToKeybindingInput(binding.shortcut);
192 const when = whenAstToExpression(binding.whenAst);
193 return {
194 id: `${keybindingRowId(binding.command, key, when)}\u0000${index}`,
195 command: binding.command,
196 key,
197 when,
198 source: sourceForBinding(binding),
199 defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
200 defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
201 binding,
202 conflicts: [],
203 } satisfies KeybindingRow;
204 });
205
206 const rowsWithConflicts = rows.map((row) => {
207 const conflicts = keybindingConflictLabels(rows, {
208 rowId: row.id,
209 key: row.key,
210 when: row.when,
211 });
212 return conflicts.length > 0
213 ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
214 : row;
215 });
216
217 rowsWithConflicts.sort((left, right) => {
218 const commandCompare =
219 compareUsageCommands(left.command, right.command) ??
220 left.command.localeCompare(right.command);
221 if (commandCompare !== 0) return commandCompare;
222 return left.key.localeCompare(right.key);
223 });
224
225 if (normalizedQuery.length === 0) {
226 return rowsWithConflicts;
227 }
228
229 return rowsWithConflicts.filter((row) => {
230 return (
231 row.command.toLowerCase().includes(normalizedQuery) ||
232 commandLabel(row.command).toLowerCase().includes(normalizedQuery) ||
233 row.key.toLowerCase().includes(normalizedQuery) ||
234 row.when.toLowerCase().includes(normalizedQuery) ||
235 row.source.toLowerCase().includes(normalizedQuery)
236 );
237 });
238}
239
240function collectWhenIdentifiersFromNode(
241 node: KeybindingWhenNode | undefined,
242 identifiers: Set<string>,
243): void {
244 if (!node) return;
245 switch (node.type) {
246 case "identifier":
247 identifiers.add(node.name);
248 return;
249 case "not":
250 collectWhenIdentifiersFromNode(node.node, identifiers);
251 return;
252 case "and":
253 case "or":
254 collectWhenIdentifiersFromNode(node.left, identifiers);
255 collectWhenIdentifiersFromNode(node.right, identifiers);
256 return;
257 }
258}
259
260export function isKnownWhenVariable(identifier: string): boolean {
261 return KNOWN_WHEN_VARIABLES.has(identifier);
262}
263
264export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
265 const identifiers = new Set<string>();
266 collectWhenIdentifiersFromNode(node, identifiers);
267 return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
268}
269
270export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
271 return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
272 const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
273 const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
274 right as (typeof CORE_WHEN_VARIABLES)[number],
275 );
276 if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
277 return (
278 (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
279 (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
280 );
281 }
282 return left.localeCompare(right);
283 });
284}
285
286export function buildKeybindingCommandOptions(
287 keybindings: ResolvedKeybindingsConfig,
288): ReadonlyArray<KeybindingCommandOption> {
289 const commands = new Set<KeybindingCommand>(STATIC_KEYBINDING_COMMANDS);
290 for (const binding of keybindings) {
291 commands.add(binding.command);
292 }
293 return [...commands].toSorted(
294 (left, right) =>
295 compareUsageCommands(left, right) ?? commandLabel(left).localeCompare(commandLabel(right)),
296 );
297}
298
299export function commandLabel(command: KeybindingCommand): string {
300 if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
301 const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
302 if (usageMetric) return `Usage: ${usageMetric.label}`;
303 const usagePeriod = WINDOW_OPTIONS.find((option) => option.command === command);
304 if (usagePeriod) return `Usage: Period: ${usagePeriod.label}`;
305 const raw = String(command);
306 if (raw.startsWith("script.") && raw.endsWith(".run")) {
307 return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
308 }
309 return raw.split(".").map(titleCaseCommandSegment).join(": ");
310}
311
312function titleCaseCommandSegment(segment: string): string {
313 const words: Array<string> = [];
314 for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
315 if (part.length > 0) {
316 words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
317 }
318 }
319 return words.join(" ");
320}
321
322function normalizeShortcutKeyToken(key: string): string | null {
323 const normalized = key.toLowerCase();
324 if (
325 normalized === "meta" ||
326 normalized === "control" ||
327 normalized === "ctrl" ||
328 normalized === "shift" ||
329 normalized === "alt" ||
330 normalized === "option"
331 ) {
332 return null;
333 }
334 if (normalized === " ") return "space";
335 if (normalized === "escape") return "esc";
336 if (normalized === "arrowup") return "arrowup";
337 if (normalized === "arrowdown") return "arrowdown";
338 if (normalized === "arrowleft") return "arrowleft";
339 if (normalized === "arrowright") return "arrowright";
340 if (normalized.length === 1) return normalized;
341 if (/^f\d{1,2}$/.test(normalized)) return normalized;
342 if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
343 return normalized;
344 }
345 if (normalized === "delete" || normalized === "home" || normalized === "end") {
346 return normalized;
347 }
348 if (normalized === "pageup" || normalized === "pagedown") return normalized;
349 return null;
350}
351
352export function keybindingFromKeyboardEvent(
353 event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
354 platform: string,
355): string | null {
356 const keyToken = normalizeShortcutKeyToken(shortcutKeyFromEvent(event));
357 if (!keyToken) return null;
358
359 const parts: string[] = [];
360 if (isMacPlatform(platform)) {
361 if (event.metaKey) parts.push("mod");
362 if (event.ctrlKey) parts.push("ctrl");
363 } else {
364 if (event.ctrlKey) parts.push("mod");
365 if (event.metaKey) parts.push("meta");
366 }
367 if (event.altKey) parts.push("alt");
368 if (event.shiftKey) parts.push("shift");
369 if (parts.length === 0) {
370 return null;
371 }
372 parts.push(keyToken);
373 return parts.join("+");
374}