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