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