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