Open History to see the last commit
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4import { assert, afterEach, describe, expect, it, vi } from "vitest";
5
6import {
7 compileResolvedKeybindingRule,
8 parseKeybindingShortcut,
9 upsertKeybindingRule,
10} from "./keybindings";
11
12describe("server keybindings", () => {
13 const tempDirs: string[] = [];
14 const logger = {
15 warn: vi.fn(),
16 };
17
18 function makeTempDir(prefix: string): string {
19 const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
20 tempDirs.push(dir);
21 return dir;
22 }
23
24 afterEach(() => {
25 vi.restoreAllMocks();
26 logger.warn.mockReset();
27 for (const dir of tempDirs.splice(0, tempDirs.length)) {
28 fs.rmSync(dir, { recursive: true, force: true });
29 }
30 });
31
32 it("parses shortcuts including plus key", () => {
33 assert.deepEqual(parseKeybindingShortcut("mod+j"), {
34 key: "j",
35 metaKey: false,
36 ctrlKey: false,
37 shiftKey: false,
38 altKey: false,
39 modKey: true,
40 });
41 assert.deepEqual(parseKeybindingShortcut("mod++"), {
42 key: "+",
43 metaKey: false,
44 ctrlKey: false,
45 shiftKey: false,
46 altKey: false,
47 modKey: true,
48 });
49 });
50
51 it("compiles valid rule with parsed when AST", () => {
52 const compiled = compileResolvedKeybindingRule({
53 key: "mod+d",
54 command: "terminal.split",
55 when: "terminalOpen && !terminalFocus",
56 });
57
58 assert.deepEqual(compiled, {
59 command: "terminal.split",
60 shortcut: {
61 key: "d",
62 metaKey: false,
63 ctrlKey: false,
64 shiftKey: false,
65 altKey: false,
66 modKey: true,
67 },
68 whenAst: {
69 type: "and",
70 left: { type: "identifier", name: "terminalOpen" },
71 right: {
72 type: "not",
73 node: { type: "identifier", name: "terminalFocus" },
74 },
75 },
76 });
77 });
78
79 it("rejects invalid rules", () => {
80 assert.isNull(
81 compileResolvedKeybindingRule({
82 key: "mod+shift+d+o",
83 command: "terminal.new",
84 }),
85 );
86
87 assert.isNull(
88 compileResolvedKeybindingRule({
89 key: "mod+d",
90 command: "terminal.split",
91 when: "terminalFocus && (",
92 }),
93 );
94
95 assert.isNull(
96 compileResolvedKeybindingRule({
97 key: "mod+d",
98 command: "terminal.split",
99 when: `${"!".repeat(300)}terminalFocus`,
100 }),
101 );
102 });
103
104 it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
105 const fakeHome = makeTempDir("t3code-keybindings-upsert-");
106 const configDir = path.join(fakeHome, ".t3");
107 fs.mkdirSync(configDir, { recursive: true });
108 const configPath = path.join(configDir, "keybindings.json");
109 fs.writeFileSync(
110 configPath,
111 JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
112 "utf8",
113 );
114 vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
115
116 const resolved = upsertKeybindingRule(logger, {
117 key: "mod+shift+r",
118 command: "script.run-tests.run",
119 });
120 const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
121 key: string;
122 command: string;
123 }>;
124
125 expect(persisted).toEqual([
126 { key: "mod+j", command: "terminal.toggle" },
127 { key: "mod+shift+r", command: "script.run-tests.run" },
128 ]);
129 expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
130 });
131
132 it("replaces existing custom keybinding for the same command", () => {
133 const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
134 const configDir = path.join(fakeHome, ".t3");
135 fs.mkdirSync(configDir, { recursive: true });
136 const configPath = path.join(configDir, "keybindings.json");
137 fs.writeFileSync(
138 configPath,
139 JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
140 "utf8",
141 );
142 vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
143
144 upsertKeybindingRule(logger, {
145 key: "mod+shift+r",
146 command: "script.run-tests.run",
147 });
148
149 const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
150 key: string;
151 command: string;
152 }>;
153 expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
154 });
155
156 it("refuses to overwrite malformed keybindings config", () => {
157 const fakeHome = makeTempDir("t3code-keybindings-malformed-");
158 const configDir = path.join(fakeHome, ".t3");
159 fs.mkdirSync(configDir, { recursive: true });
160 const configPath = path.join(configDir, "keybindings.json");
161 fs.writeFileSync(configPath, "{ not-json", "utf8");
162 vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
163
164 expect(() =>
165 upsertKeybindingRule(logger, {
166 key: "mod+shift+r",
167 command: "script.run-tests.run",
168 }),
169 ).toThrow(/Unable to parse keybindings config/);
170
171 expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
172 });
173
174 it("reports non-array config parse errors without duplicate prefix", () => {
175 const fakeHome = makeTempDir("t3code-keybindings-non-array-");
176 const configDir = path.join(fakeHome, ".t3");
177 fs.mkdirSync(configDir, { recursive: true });
178 const configPath = path.join(configDir, "keybindings.json");
179 fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
180 vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
181
182 expect(() =>
183 upsertKeybindingRule(logger, {
184 key: "mod+shift+r",
185 command: "script.run-tests.run",
186 }),
187 ).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
188
189 expect(() =>
190 upsertKeybindingRule(logger, {
191 key: "mod+shift+r",
192 command: "script.run-tests.run",
193 }),
194 ).not.toThrow(
195 new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
196 );
197 });
198
199 it("cleans up temp files when atomic keybinding write fails", () => {
200 const fakeHome = makeTempDir("t3code-keybindings-atomic-");
201 const configDir = path.join(fakeHome, ".t3");
202 fs.mkdirSync(configDir, { recursive: true });
203 const configPath = path.join(configDir, "keybindings.json");
204 fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
205 vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
206 vi.spyOn(fs, "renameSync").mockImplementation(() => {
207 throw new Error("rename failed");
208 });
209
210 expect(() =>
211 upsertKeybindingRule(logger, {
212 key: "mod+shift+r",
213 command: "script.run-tests.run",
214 }),
215 ).toThrow(/rename failed/);
216
217 expect(fs.readFileSync(configPath, "utf8")).toBe(
218 JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
219 );
220 const tempFiles = fs
221 .readdirSync(configDir)
222 .filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
223 expect(tempFiles).toEqual([]);
224 });
225});