Open History to see the last commit
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4
5import type {
6 KeybindingRule,
7 KeybindingsConfig,
8 KeybindingShortcut,
9 KeybindingWhenNode,
10 ResolvedKeybindingRule,
11 ResolvedKeybindingsConfig,
12} from "@t3tools/contracts";
13import { keybindingRuleSchema } from "@t3tools/contracts";
14
15interface KeybindingsLogger {
16 warn(message: string, context?: Record<string, unknown>): void;
17}
18
19type WhenToken =
20 | { type: "identifier"; value: string }
21 | { type: "not" }
22 | { type: "and" }
23 | { type: "or" }
24 | { type: "lparen" }
25 | { type: "rparen" };
26
27export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
28 { key: "mod+j", command: "terminal.toggle" },
29 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
30 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
31 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
32 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
33 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
34 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
35 { key: "mod+o", command: "editor.openFavorite" },
36];
37
38function normalizeKeyToken(token: string): string {
39 if (token === "space") return " ";
40 if (token === "esc") return "escape";
41 return token;
42}
43
44export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
45 const rawTokens = value
46 .toLowerCase()
47 .split("+")
48 .map((token) => token.trim());
49 const tokens = [...rawTokens];
50 let trailingEmptyCount = 0;
51 while (tokens[tokens.length - 1] === "") {
52 trailingEmptyCount += 1;
53 tokens.pop();
54 }
55 if (trailingEmptyCount > 0) {
56 tokens.push("+");
57 }
58 if (tokens.some((token) => token.length === 0)) {
59 return null;
60 }
61 if (tokens.length === 0) return null;
62
63 let key: string | null = null;
64 let metaKey = false;
65 let ctrlKey = false;
66 let shiftKey = false;
67 let altKey = false;
68 let modKey = false;
69
70 for (const token of tokens) {
71 switch (token) {
72 case "cmd":
73 case "meta":
74 metaKey = true;
75 break;
76 case "ctrl":
77 case "control":
78 ctrlKey = true;
79 break;
80 case "shift":
81 shiftKey = true;
82 break;
83 case "alt":
84 case "option":
85 altKey = true;
86 break;
87 case "mod":
88 modKey = true;
89 break;
90 default: {
91 if (key !== null) return null;
92 key = normalizeKeyToken(token);
93 }
94 }
95 }
96
97 if (key === null) return null;
98 return {
99 key,
100 metaKey,
101 ctrlKey,
102 shiftKey,
103 altKey,
104 modKey,
105 };
106}
107
108function tokenizeWhenExpression(expression: string): WhenToken[] | null {
109 const tokens: WhenToken[] = [];
110 let index = 0;
111
112 while (index < expression.length) {
113 const current = expression[index];
114 if (!current) break;
115
116 if (/\s/.test(current)) {
117 index += 1;
118 continue;
119 }
120 if (expression.startsWith("&&", index)) {
121 tokens.push({ type: "and" });
122 index += 2;
123 continue;
124 }
125 if (expression.startsWith("||", index)) {
126 tokens.push({ type: "or" });
127 index += 2;
128 continue;
129 }
130 if (current === "!") {
131 tokens.push({ type: "not" });
132 index += 1;
133 continue;
134 }
135 if (current === "(") {
136 tokens.push({ type: "lparen" });
137 index += 1;
138 continue;
139 }
140 if (current === ")") {
141 tokens.push({ type: "rparen" });
142 index += 1;
143 continue;
144 }
145
146 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
147 if (!identifier) {
148 return null;
149 }
150 tokens.push({ type: "identifier", value: identifier[0] });
151 index += identifier[0].length;
152 }
153
154 return tokens;
155}
156
157export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
158 const tokens = tokenizeWhenExpression(expression);
159 if (!tokens || tokens.length === 0) return null;
160 let index = 0;
161
162 const parsePrimary = (): KeybindingWhenNode | null => {
163 const token = tokens[index];
164 if (!token) return null;
165
166 if (token.type === "identifier") {
167 index += 1;
168 return { type: "identifier", name: token.value };
169 }
170
171 if (token.type === "lparen") {
172 index += 1;
173 const expressionNode = parseOr();
174 const closeToken = tokens[index];
175 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
176 return null;
177 }
178 index += 1;
179 return expressionNode;
180 }
181
182 return null;
183 };
184
185 const parseUnary = (): KeybindingWhenNode | null => {
186 const token = tokens[index];
187 if (token?.type === "not") {
188 index += 1;
189 const node = parseUnary();
190 if (!node) return null;
191 return { type: "not", node };
192 }
193 return parsePrimary();
194 };
195
196 const parseAnd = (): KeybindingWhenNode | null => {
197 let left = parseUnary();
198 if (!left) return null;
199
200 while (tokens[index]?.type === "and") {
201 index += 1;
202 const right = parseUnary();
203 if (!right) return null;
204 left = { type: "and", left, right };
205 }
206
207 return left;
208 };
209
210 const parseOr = (): KeybindingWhenNode | null => {
211 let left = parseAnd();
212 if (!left) return null;
213
214 while (tokens[index]?.type === "or") {
215 index += 1;
216 const right = parseAnd();
217 if (!right) return null;
218 left = { type: "or", left, right };
219 }
220
221 return left;
222 };
223
224 const ast = parseOr();
225 if (!ast || index !== tokens.length) return null;
226 return ast;
227}
228
229export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
230 const key = rule.key.trim();
231 if (key.length === 0) return null;
232 const shortcut = parseKeybindingShortcut(key);
233 if (!shortcut) return null;
234
235 const when = rule.when?.trim();
236 if (when && when.length > 0) {
237 const whenAst = parseKeybindingWhenExpression(when);
238 if (!whenAst) return null;
239 return {
240 command: rule.command,
241 shortcut,
242 whenAst,
243 };
244 }
245
246 return {
247 command: rule.command,
248 shortcut,
249 };
250}
251
252export function compileResolvedKeybindingsConfig(
253 config: KeybindingsConfig,
254): ResolvedKeybindingsConfig {
255 const compiled: ResolvedKeybindingsConfig = [];
256 for (const rule of config) {
257 const resolved = compileResolvedKeybindingRule(rule);
258 if (!resolved) continue;
259 compiled.push(resolved);
260 }
261 return compiled;
262}
263
264function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
265 const resolved: ResolvedKeybindingsConfig = [];
266 for (const rule of DEFAULT_KEYBINDINGS) {
267 const compiled = compileResolvedKeybindingRule(rule);
268 if (!compiled) {
269 throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
270 }
271 resolved.push(compiled);
272 }
273 return resolved;
274}
275
276const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
277
278function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
279 if (custom.length === 0) {
280 return [...DEFAULT_RESOLVED_KEYBINDINGS];
281 }
282
283 const overriddenCommands = new Set(custom.map((binding) => binding.command));
284 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
285 (binding) => !overriddenCommands.has(binding.command),
286 );
287 const merged = [...retainedDefaults, ...custom];
288
289 if (merged.length <= 256) {
290 return merged;
291 }
292
293 // Keep the latest rules when the config exceeds max size; later rules have higher precedence.
294 return merged.slice(-256);
295}
296
297export function loadResolvedKeybindingsConfig(
298 logger: KeybindingsLogger,
299): ResolvedKeybindingsConfig {
300 const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
301 try {
302 const raw = fs.readFileSync(configPath, "utf8");
303 const parsed = JSON.parse(raw) as unknown;
304 if (!Array.isArray(parsed)) {
305 logger.warn("ignoring keybindings config with unsupported format; expected array", {
306 path: configPath,
307 });
308 return [...DEFAULT_RESOLVED_KEYBINDINGS];
309 }
310
311 const sanitized: ResolvedKeybindingsConfig = [];
312 let invalidEntries = 0;
313 for (const entry of parsed) {
314 const result = keybindingRuleSchema.safeParse(entry);
315 if (result.success) {
316 const compiled = compileResolvedKeybindingRule(result.data);
317 if (!compiled) {
318 invalidEntries += 1;
319 continue;
320 }
321 sanitized.push(compiled);
322 continue;
323 }
324 invalidEntries += 1;
325 }
326 if (invalidEntries > 0) {
327 logger.warn("ignoring invalid keybinding entries", {
328 path: configPath,
329 invalidEntries,
330 totalEntries: parsed.length,
331 });
332 }
333 const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
334 const mergedBeforeCapLength =
335 DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
336 .length + sanitized.length;
337 const merged = mergeWithDefaultKeybindings(sanitized);
338 if (mergedBeforeCapLength > 256) {
339 logger.warn("truncating merged keybindings config to max entries", {
340 path: configPath,
341 maxEntries: 256,
342 });
343 }
344 return merged;
345 } catch (error) {
346 if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
347 return [...DEFAULT_RESOLVED_KEYBINDINGS];
348 }
349 logger.warn("ignoring malformed keybindings config", {
350 path: configPath,
351 error: error instanceof Error ? error.message : String(error),
352 });
353 }
354 return [...DEFAULT_RESOLVED_KEYBINDINGS];
355}