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