Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

447 lines12.1 KB

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;
18​
19type WhenToken =
20 | { type: "identifier"; value: string }
21 | { type: "not" }
22 | { type: "and" }
23 | { type: "or" }
24 | { type: "lparen" }
25 | { type: "rparen" };
26​
27const MAX_WHEN_EXPRESSION_DEPTH = 256;
28​
29export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
30 { key: "mod+j", command: "terminal.toggle" },
31 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
32 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
33 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
34 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
35 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
36 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
37 { key: "mod+o", command: "editor.openFavorite" },
38];
39​
40function normalizeKeyToken(token: string): string {
41 if (token === "space") return " ";
42 if (token === "esc") return "escape";
43 return token;
45​
46export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
47 const rawTokens = value
48 .toLowerCase()
49 .split("+")
50 .map((token) => token.trim());
51 const tokens = [...rawTokens];
52 let trailingEmptyCount = 0;
53 while (tokens[tokens.length - 1] === "") {
54 trailingEmptyCount += 1;
55 tokens.pop();
56 }
57 if (trailingEmptyCount > 0) {
58 tokens.push("+");
59 }
60 if (tokens.some((token) => token.length === 0)) {
61 return null;
62 }
63 if (tokens.length === 0) return null;
64​
65 let key: string | null = null;
66 let metaKey = false;
67 let ctrlKey = false;
68 let shiftKey = false;
69 let altKey = false;
70 let modKey = false;
71​
72 for (const token of tokens) {
73 switch (token) {
74 case "cmd":
75 case "meta":
76 metaKey = true;
77 break;
78 case "ctrl":
79 case "control":
80 ctrlKey = true;
81 break;
82 case "shift":
83 shiftKey = true;
84 break;
85 case "alt":
86 case "option":
87 altKey = true;
88 break;
89 case "mod":
90 modKey = true;
91 break;
92 default: {
93 if (key !== null) return null;
94 key = normalizeKeyToken(token);
95 }
96 }
97 }
98​
99 if (key === null) return null;
100 return {
101 key,
102 metaKey,
103 ctrlKey,
104 shiftKey,
105 altKey,
106 modKey,
107 };
109​
110function tokenizeWhenExpression(expression: string): WhenToken[] | null {
111 const tokens: WhenToken[] = [];
112 let index = 0;
113​
114 while (index < expression.length) {
115 const current = expression[index];
116 if (!current) break;
117​
118 if (/\s/.test(current)) {
119 index += 1;
120 continue;
121 }
122 if (expression.startsWith("&&", index)) {
123 tokens.push({ type: "and" });
124 index += 2;
125 continue;
126 }
127 if (expression.startsWith("||", index)) {
128 tokens.push({ type: "or" });
129 index += 2;
130 continue;
131 }
132 if (current === "!") {
133 tokens.push({ type: "not" });
134 index += 1;
135 continue;
136 }
137 if (current === "(") {
138 tokens.push({ type: "lparen" });
139 index += 1;
140 continue;
141 }
142 if (current === ")") {
143 tokens.push({ type: "rparen" });
144 index += 1;
145 continue;
146 }
147​
148 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
149 if (!identifier) {
150 return null;
151 }
152 tokens.push({ type: "identifier", value: identifier[0] });
153 index += identifier[0].length;
154 }
155​
156 return tokens;
158​
159export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
160 const tokens = tokenizeWhenExpression(expression);
161 if (!tokens || tokens.length === 0) return null;
162 let index = 0;
163​
164 const parsePrimary = (depth: number): KeybindingWhenNode | null => {
165 if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
166 return null;
167 }
168 const token = tokens[index];
169 if (!token) return null;
170​
171 if (token.type === "identifier") {
172 index += 1;
173 return { type: "identifier", name: token.value };
174 }
175​
176 if (token.type === "lparen") {
177 index += 1;
178 const expressionNode = parseOr(depth + 1);
179 const closeToken = tokens[index];
180 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
181 return null;
182 }
183 index += 1;
184 return expressionNode;
185 }
186​
187 return null;
188 };
189​
190 const parseUnary = (depth: number): KeybindingWhenNode | null => {
191 let notCount = 0;
192 while (tokens[index]?.type === "not") {
193 index += 1;
194 notCount += 1;
195 if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
196 return null;
197 }
198 }
199​
200 let node = parsePrimary(depth);
201 if (!node) return null;
202​
203 while (notCount > 0) {
204 node = { type: "not", node };
205 notCount -= 1;
206 }
207​
208 return node;
209 };
210​
211 const parseAnd = (depth: number): KeybindingWhenNode | null => {
212 let left = parseUnary(depth);
213 if (!left) return null;
214​
215 while (tokens[index]?.type === "and") {
216 index += 1;
217 const right = parseUnary(depth);
218 if (!right) return null;
219 left = { type: "and", left, right };
220 }
221​
222 return left;
223 };
224​
225 const parseOr = (depth: number): KeybindingWhenNode | null => {
226 let left = parseAnd(depth);
227 if (!left) return null;
228​
229 while (tokens[index]?.type === "or") {
230 index += 1;
231 const right = parseAnd(depth);
232 if (!right) return null;
233 left = { type: "or", left, right };
234 }
235​
236 return left;
237 };
238​
239 const ast = parseOr(0);
240 if (!ast || index !== tokens.length) return null;
241 return ast;
243​
244export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
245 const key = rule.key.trim();
246 if (key.length === 0) return null;
247 const shortcut = parseKeybindingShortcut(key);
248 if (!shortcut) return null;
249​
250 const when = rule.when?.trim();
251 if (when && when.length > 0) {
252 const whenAst = parseKeybindingWhenExpression(when);
253 if (!whenAst) return null;
254 return {
255 command: rule.command,
256 shortcut,
257 whenAst,
258 };
259 }
260​
261 return {
262 command: rule.command,
263 shortcut,
264 };
266​
267export function compileResolvedKeybindingsConfig(
268 config: KeybindingsConfig,
269): ResolvedKeybindingsConfig {
270 const compiled: ResolvedKeybindingsConfig = [];
271 for (const rule of config) {
272 const resolved = compileResolvedKeybindingRule(rule);
273 if (!resolved) continue;
274 compiled.push(resolved);
275 }
276 return compiled;
278​
279function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
280 const resolved: ResolvedKeybindingsConfig = [];
281 for (const rule of DEFAULT_KEYBINDINGS) {
282 const compiled = compileResolvedKeybindingRule(rule);
283 if (!compiled) {
284 throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
285 }
286 resolved.push(compiled);
287 }
288 return resolved;
290​
291const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
292const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
293const MAX_KEYBINDINGS = 256;
294​
295class KeybindingsConfigParseError extends Error {
296 constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
297 super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
298 }
300​
301function resolveKeybindingsConfigPath(): string {
302 return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
304​
305function loadCustomKeybindingsConfig(
306 logger: KeybindingsLogger,
307 options?: {
308 throwOnUnreadableConfig?: boolean;
309 },
310): KeybindingsConfig {
311 const configPath = resolveKeybindingsConfigPath();
312 try {
313 const raw = fs.readFileSync(configPath, "utf8");
314 const parsed = JSON.parse(raw) as unknown;
315 if (!Array.isArray(parsed)) {
316 if (options?.throwOnUnreadableConfig) {
317 throw new KeybindingsConfigParseError(configPath, "expected JSON array");
318 }
319 logger.warn("ignoring keybindings config with unsupported format; expected array", {
320 path: configPath,
321 });
322 return [];
323 }
324​
325 const sanitized: KeybindingsConfig = [];
326 let invalidEntries = 0;
327 for (const entry of parsed) {
328 const result = keybindingRuleSchema.safeParse(entry);
329 if (result.success) {
330 if (!compileResolvedKeybindingRule(result.data)) {
331 invalidEntries += 1;
332 continue;
333 }
334 sanitized.push(result.data);
335 continue;
336 }
337 invalidEntries += 1;
338 }
339 if (invalidEntries > 0) {
340 logger.warn("ignoring invalid keybinding entries", {
341 path: configPath,
342 invalidEntries,
343 totalEntries: parsed.length,
344 });
345 }
346 return sanitized;
347 } catch (error) {
348 if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
349 return [];
350 }
351 if (options?.throwOnUnreadableConfig) {
352 if (error instanceof KeybindingsConfigParseError) {
353 throw error;
354 }
355 throw new KeybindingsConfigParseError(
356 configPath,
357 error instanceof Error ? error.message : String(error),
358 { cause: error },
359 );
360 }
361 logger.warn("ignoring malformed keybindings config", {
362 path: configPath,
363 error: error instanceof Error ? error.message : String(error),
364 });
365 return [];
366 }
368​
369function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
370 const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
371 try {
372 fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
373 fs.renameSync(tempPath, configPath);
374 } catch (error) {
375 fs.rmSync(tempPath, { force: true });
376 throw error;
377 }
379​
380function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
381 if (custom.length === 0) {
382 return [...DEFAULT_RESOLVED_KEYBINDINGS];
383 }
384​
385 const overriddenCommands = new Set(custom.map((binding) => binding.command));
386 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
387 (binding) => !overriddenCommands.has(binding.command),
388 );
389 const merged = [...retainedDefaults, ...custom];
390​
391 if (merged.length <= MAX_KEYBINDINGS) {
392 return merged;
393 }
394​
395 // Keep the latest rules when the config exceeds max size; later rules have higher precedence.
396 return merged.slice(-MAX_KEYBINDINGS);
398​
399export function loadResolvedKeybindingsConfig(
400 logger: KeybindingsLogger,
401): ResolvedKeybindingsConfig {
402 const customConfig = loadCustomKeybindingsConfig(logger);
403 const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
404 const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
405 const mergedBeforeCapLength =
406 DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
407 .length + compiledCustomConfig.length;
408 const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
409 if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
410 logger.warn("truncating merged keybindings config to max entries", {
411 path: resolveKeybindingsConfigPath(),
412 maxEntries: MAX_KEYBINDINGS,
413 });
414 }
415 return merged;
417​
418export function upsertKeybindingRule(
419 logger: KeybindingsLogger,
420 rawRule: unknown,
421): ResolvedKeybindingsConfig {
422 const rule = keybindingRuleSchema.parse(rawRule);
423 if (!compileResolvedKeybindingRule(rule)) {
424 throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
425 }
426​
427 const configPath = resolveKeybindingsConfigPath();
428 const customConfig = loadCustomKeybindingsConfig(logger, {
429 throwOnUnreadableConfig: true,
430 });
431 const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
432 const cappedConfig =
433 nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
434​
435 if (nextConfig.length > MAX_KEYBINDINGS) {
436 logger.warn("truncating keybindings config to max entries", {
437 path: configPath,
438 maxEntries: MAX_KEYBINDINGS,
439 });
440 }
441​
442 fs.mkdirSync(path.dirname(configPath), { recursive: true });
443 writeConfigAtomically(configPath, cappedConfig);
444​
445 const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
446 return mergeWithDefaultKeybindings(compiledCustomConfig);