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

KeybindingsSettings.logic.test.ts

557 lines17.3 KB

1import { assert, describe, expect, it } from "vite-plus/test";
2import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
3import {
4 compileResolvedKeybindingsConfig,
5 DEFAULT_RESOLVED_KEYBINDINGS,
6 parseKeybindingShortcut,
7} from "@t3tools/shared/keybindings";
8​
9import { resolveShortcutCommand } from "../../keybindings";
10​
11import {
12 buildKeybindingRows,
13 buildKeybindingCommandOptions,
14 buildWhenVariableOptions,
15 commandLabel,
16 filterKeybindingRows,
17 groupKeybindingRows,
18 keybindingConflictLabels,
19 keybindingFromKeyboardEvent,
20 parseWhenExpressionDraft,
21 shortcutToKeybindingInput,
22 unknownWhenVariables,
23 whenAstToExpression,
24 whenNodeRemoveLabel,
25} from "./KeybindingsSettings.logic";
26​
27describe("KeybindingsSettings.logic", () => {
28 it("lists composer, provider, and pull request commands with editable defaults", () => {
29 const rows = buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS);
30 for (const command of [
31 "composer.sendAlternate",
32 "composer.sendBackground",
33 "thread.steerQueuedMessage",
34 "thread.editQueuedMessage",
35 "composer.host",
36 "composer.effort",
37 "composer.mode",
38 "composer.workspace",
39 "composer.branch",
40 "composer.previousWorktree",
41 "modelPicker.previousProvider",
42 "modelPicker.nextProvider",
43 "thread.copyReference",
44 "pullRequest.copyNumber",
45 ]) {
46 expect(rows.find((row) => row.command === command)).toMatchObject({
47 source: "Default",
48 conflicts: [],
49 });
50 }
51 });
52 it("finds the editable shortcut for sending the first queued message", () => {
53 expect(
54 filterKeybindingRows(buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS), "first queued"),
55 ).toContainEqual(
56 expect.objectContaining({
57 command: "thread.steerQueuedMessage",
58 key: "mod+shift+enter",
59 }),
60 );
61 });
62 it("filtering keeps the row objects so unchanged rows skip rendering", () => {
63 const rows = buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS);
64 const filtered = filterKeybindingRows(rows, "terminal");
65 expect(filtered.length).toBeGreaterThan(0);
66 expect(filtered.length).toBeLessThan(rows.length);
67 for (const row of filtered) expect(rows).toContain(row);
68 expect(filterKeybindingRows(rows, " ")).toBe(rows);
69 });
70 it.each(["pu", "pull request", "copy link", "thread id"])(
71 "finds the copy link shortcut with %s",
72 (query) => {
73 const rows = filterKeybindingRows(buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS), query);
74 expect(rows).toContainEqual(
75 expect.objectContaining({ command: "thread.copyReference", key: "mod+shift+c" }),
76 );
77 },
78 );
79 it("groups rows by command area in page order and drops empty groups", () => {
80 const groups = groupKeybindingRows(buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS));
81 expect(groups.map((group) => group.title)).toEqual([
82 "Navigation",
83 "Threads",
84 "Composer",
85 "Terminal",
86 "Preview & diff",
87 "Appearance",
88 "Other",
89 ]);
90 const composer = groups.find((group) => group.id === "composer");
91 expect(composer?.rows.map((row) => row.command)).toEqual(
92 expect.arrayContaining(["composer.host", "modelPicker.toggle"]),
93 );
94 expect(
95 groupKeybindingRows(
96 filterKeybindingRows(buildKeybindingRows(DEFAULT_RESOLVED_KEYBINDINGS), "split"),
97 ),
98 ).toEqual([expect.objectContaining({ id: "terminal" })]);
99 });
100 it("orders Usage bindings and command choices like the page", () => {
101 const expected = [
102 "usage.open",
103 "usage.cost",
104 "usage.tokens",
105 "usage.limits",
106 "usage.period.day",
107 "usage.period.week",
108 "usage.period.month",
109 "usage.period.quarter",
110 ];
111 for (const bindings of [
112 DEFAULT_RESOLVED_KEYBINDINGS,
113 DEFAULT_RESOLVED_KEYBINDINGS.toReversed(),
114 ]) {
115 expect(
116 filterKeybindingRows(buildKeybindingRows(bindings), "usage").map((row) => row.command),
117 ).toEqual(expected);
118 expect(
119 buildKeybindingCommandOptions(bindings).filter((command) => command.startsWith("usage.")),
120 ).toEqual(expected);
121 }
122 });
123​
124 it("keeps sibling row identities when a saved binding moves to the end", () => {
125 const bindings = compileResolvedKeybindingsConfig([
126 { command: "chat.new", key: "mod+n" },
127 { command: "terminal.toggle", key: "mod+j" },
128 { command: "terminal.toggle", key: "mod+k", when: "terminalFocus" },
129 ]);
130 const before = buildKeybindingRows(bindings);
131 const after = buildKeybindingRows([
132 ...bindings.slice(1),
133 ...compileResolvedKeybindingsConfig([{ command: "chat.new", key: "mod+shift+n" }]),
134 ]);
135​
136 expect(after.filter((row) => row.command === "terminal.toggle").map((row) => row.id)).toEqual(
137 before.filter((row) => row.command === "terminal.toggle").map((row) => row.id),
138 );
139 expect(after.find((row) => row.command === "chat.new")?.id).not.toBe(
140 before.find((row) => row.command === "chat.new")?.id,
141 );
142 });
143​
144 it("shares a stable editor for resolved duplicates but separates commands, shortcuts, and conditions", () => {
145 const bindings = compileResolvedKeybindingsConfig([
146 { command: "terminal.toggle", key: "mod+esc", when: "terminalFocus" },
147 { command: "terminal.toggle", key: "mod+escape", when: "(terminalFocus)" },
148 { command: "terminal.toggle", key: "mod+esc", when: "!terminalFocus" },
149 { command: "terminal.toggle", key: "mod+j", when: "terminalFocus" },
150 { command: "chat.new", key: "mod+esc", when: "terminalFocus" },
151 ]);
152 const rows = buildKeybindingRows(bindings);
153 expect(rows.map(({ command, key, when }) => ({ command, key, when }))).toEqual([
154 { command: "chat.new", key: "mod+esc", when: "terminalFocus" },
155 { command: "terminal.toggle", key: "mod+esc", when: "terminalFocus" },
156 { command: "terminal.toggle", key: "mod+esc", when: "!terminalFocus" },
157 { command: "terminal.toggle", key: "mod+j", when: "terminalFocus" },
158 ]);
159 expect(new Set(rows.map((row) => row.id)).size).toBe(4);
160 expect(rows.find((row) => row.command === "chat.new")?.conflicts).toEqual(["Terminal: Toggle"]);
161 expect(buildKeybindingRows(bindings.slice(1)).map((row) => row.id)).toEqual(
162 rows.map((row) => row.id),
163 );
164 });
165​
166 it("builds searchable rows with readable key and when values", () => {
167 const rows = filterKeybindingRows(
168 buildKeybindingRows([
169 {
170 command: "terminal.toggle",
171 shortcut: {
172 key: "j",
173 modKey: true,
174 metaKey: false,
175 ctrlKey: false,
176 altKey: false,
177 shiftKey: false,
178 },
179 whenAst: {
180 type: "not",
181 node: { type: "identifier", name: "terminalFocus" },
182 },
183 },
184 ] satisfies ResolvedKeybindingsConfig),
185 "terminal",
186 );
187​
188 expect(rows).toEqual([
189 expect.objectContaining({
190 command: "terminal.toggle",
191 key: "mod+j",
192 when: "!terminalFocus",
193 defaultKey: "mod+j",
194 defaultWhen: "",
195 source: "Custom",
196 }),
197 ]);
198 });
199​
200 it("captures platform-specific mod shortcuts", () => {
201 expect(
202 keybindingFromKeyboardEvent(
203 { key: "K", code: "KeyK", metaKey: true, ctrlKey: false, altKey: false, shiftKey: true },
204 "MacIntel",
205 ),
206 ).toBe("mod+shift+k");
207 expect(
208 keybindingFromKeyboardEvent(
209 { key: "K", code: "KeyK", metaKey: false, ctrlKey: true, altKey: false, shiftKey: true },
210 "Win32",
211 ),
212 ).toBe("mod+shift+k");
213 });
214​
215 it.each([
216 ["k", "KeyK", "k"],
217 ["Tab", "Tab", "tab"],
218 ["F5", "F5", "f5"],
219 ])("captures %s without a modifier", (key, code, expected) => {
220 const noModifiers = { metaKey: false, ctrlKey: false, altKey: false, shiftKey: false };
221 expect(keybindingFromKeyboardEvent({ key, code, ...noModifiers }, "MacIntel")).toBe(expected);
222 });
223​
224 it("waits for a key when only a modifier is pressed", () => {
225 expect(
226 keybindingFromKeyboardEvent(
227 {
228 key: "Meta",
229 code: "MetaLeft",
230 metaKey: true,
231 ctrlKey: false,
232 altKey: false,
233 shiftKey: false,
234 },
235 "MacIntel",
236 ),
237 ).toBeNull();
238 });
239​
240 it.each([
241 ["@", "Digit2", "mod+shift+2"],
242 ['"', "Digit2", "mod+shift+2"],
243 ["@", "Quote", "mod+shift+'"],
244 ])("captures %s at %s by physical key", (key, code, expected) => {
245 expect(
246 keybindingFromKeyboardEvent(
247 {
248 key,
249 code,
250 metaKey: true,
251 ctrlKey: false,
252 altKey: false,
253 shiftKey: true,
254 },
255 "MacIntel",
256 ),
257 ).toBe(expected);
258 });
259​
260 it("records layout punctuation while preserving physical Alt shortcuts; saved bindings still trigger", () => {
261 for (const { key, code, altKey = false, shiftKey, expected, defaultInput } of [
262 { key: "#", code: "Backslash", shiftKey: false, expected: "#", defaultInput: "\\" },
263 {
264 key: "'",
265 code: "Backslash",
266 shiftKey: true,
267 expected: "shift+'",
268 defaultInput: "shift+\\",
269 },
270 {
271 key: "¡",
272 code: "Digit1",
273 altKey: true,
274 shiftKey: false,
275 expected: "alt+1",
276 defaultInput: "alt+1",
277 },
278 ]) {
279 const pressed = {
280 key,
281 code,
282 metaKey: false,
283 ctrlKey: false,
284 altKey,
285 shiftKey,
286 };
287 expect(keybindingFromKeyboardEvent(pressed, "MacIntel")).toBe(defaultInput);
288 const input = keybindingFromKeyboardEvent(pressed, "MacIntel", { layoutCharacter: true });
289 expect(input).toBe(expected);
290 assert(input);
291 const shortcut = parseKeybindingShortcut(input);
292 assert(shortcut);
293 expect(
294 resolveShortcutCommand(pressed, [{ command: "chat.new", shortcut }], {
295 platform: "MacIntel",
296 }),
297 ).toBe("chat.new");
298 }
299 });
300​
301 it("records an unshifted brace literally and a US shifted brace as Shift+[; both trigger the saved binding", () => {
302 for (const { shiftKey, expected } of [
303 { shiftKey: false, expected: "mod+{" },
304 { shiftKey: true, expected: "mod+shift+[" },
305 ]) {
306 const pressed = {
307 key: "{",
308 code: "BracketLeft",
309 metaKey: true,
310 ctrlKey: false,
311 altKey: false,
312 shiftKey,
313 };
314 const input = keybindingFromKeyboardEvent(pressed, "MacIntel", { layoutCharacter: true });
315 expect(input).toBe(expected);
316 assert(input);
317 const shortcut = parseKeybindingShortcut(input);
318 assert(shortcut);
319 expect(
320 resolveShortcutCommand(pressed, [{ command: "thread.previous", shortcut }], {
321 platform: "MacIntel",
322 }),
323 ).toBe("thread.previous");
324 }
325 });
326​
327 it("captures Latin layout keys instead of their punctuation position", () => {
328 expect(
329 keybindingFromKeyboardEvent(
330 {
331 key: "m",
332 code: "Semicolon",
333 metaKey: true,
334 ctrlKey: false,
335 altKey: false,
336 shiftKey: false,
337 },
338 "MacIntel",
339 ),
340 ).toBe("mod+m");
341 });
342​
343 it("serializes shortcuts and when expressions for upserts", () => {
344 expect(
345 shortcutToKeybindingInput({
346 key: " ",
347 modKey: true,
348 metaKey: false,
349 ctrlKey: false,
350 altKey: true,
351 shiftKey: false,
352 }),
353 ).toBe("mod+alt+space");
354​
355 expect(
356 whenAstToExpression({
357 type: "and",
358 left: { type: "identifier", name: "editorFocus" },
359 right: {
360 type: "not",
361 node: { type: "identifier", name: "terminalFocus" },
362 },
363 }),
364 ).toBe("editorFocus && !terminalFocus");
365​
366 expect(parseWhenExpressionDraft("editorFocus && (!terminalFocus || modelPickerOpen)")).toEqual({
367 ok: true,
368 value: {
369 type: "and",
370 left: { type: "identifier", name: "editorFocus" },
371 right: {
372 type: "or",
373 left: {
374 type: "not",
375 node: { type: "identifier", name: "terminalFocus" },
376 },
377 right: { type: "identifier", name: "modelPickerOpen" },
378 },
379 },
380 });
381 expect(parseWhenExpressionDraft("editorFocus &&")).toEqual({
382 ok: false,
383 message: "Use variables with !, &&, ||, and parentheses.",
384 });
385​
386 expect(parseWhenExpressionDraft("!(terminalFocus || modelPickerOpen)")).toEqual({
387 ok: true,
388 value: {
389 type: "not",
390 node: {
391 type: "or",
392 left: { type: "identifier", name: "terminalFocus" },
393 right: { type: "identifier", name: "modelPickerOpen" },
394 },
395 },
396 });
397 });
398​
399 it("describes the scope of each visual expression removal", () => {
400 const condition = { type: "identifier", name: "terminalFocus" } as const;
401 const negatedCondition = { type: "not", node: condition } as const;
402 const group = { type: "and", left: condition, right: negatedCondition } as const;
403 const negatedGroup = { type: "not", node: group } as const;
404​
405 expect(whenNodeRemoveLabel(group, 0)).toBe("Clear all conditions");
406 expect(whenNodeRemoveLabel(condition, 1)).toBe("Remove condition");
407 expect(whenNodeRemoveLabel(negatedCondition, 1)).toBe("Remove condition");
408 expect(whenNodeRemoveLabel(group, 1)).toBe("Remove group and its conditions");
409 expect(whenNodeRemoveLabel(negatedGroup, 1)).toBe("Remove group and its conditions");
410 });
411​
412 it("formats static and project script command labels", () => {
413 expect(commandLabel("commandPalette.toggle")).toBe("Command Palette: Toggle");
414 expect(commandLabel("themeEditor.toggle")).toBe("Theme Editor: Toggle");
415 expect(commandLabel("view.reopenClosed")).toBe("Reopen Closed Tab");
416 expect(commandLabel("preview.focusUrl")).toBe("Preview: Focus URL");
417 expect(commandLabel("script.setup-db.run")).toBe("Run Script: Setup Db");
418 });
419​
420 it("builds known when variable options from defaults without frontend labels", () => {
421 const options = buildWhenVariableOptions();
422​
423 expect(options).toEqual(
424 expect.arrayContaining([
425 "terminalFocus",
426 "terminalOpen",
427 "isWeb",
428 "isDesktop",
429 "modelPickerOpen",
430 "true",
431 "false",
432 ]),
433 );
434 expect(options).not.toContain("customModeActive");
435 });
436​
437 it("builds command options from all static commands and resolved project bindings", () => {
438 const options = buildKeybindingCommandOptions([
439 {
440 command: "script.setup-db.run",
441 shortcut: {
442 key: "r",
443 modKey: true,
444 metaKey: false,
445 ctrlKey: false,
446 altKey: false,
447 shiftKey: false,
448 },
449 },
450 ] satisfies ResolvedKeybindingsConfig);
451​
452 expect(options).toEqual(
453 expect.arrayContaining([
454 "chat.new",
455 "threadPanel.toggle",
456 "rightPanel.toggleMaximized",
457 "composer.cycleHost",
458 "thread.stop",
459 "usage.open",
460 "script.setup-db.run",
461 ]),
462 );
463 for (const command of ["thread.stop", "composer.cycleHost"]) {
464 expect(DEFAULT_RESOLVED_KEYBINDINGS.some((binding) => binding.command === command)).toBe(
465 false,
466 );
467 }
468 });
469​
470 it("reports unknown when variables without rejecting parseable expressions", () => {
471 const parsed = parseWhenExpressionDraft("!terminalFocus && terminalFoc");
472​
473 expect(parsed.ok).toBe(true);
474 expect(unknownWhenVariables(parsed.ok ? parsed.value : undefined)).toEqual(["terminalFoc"]);
475 });
476​
477 it("marks each default shortcut for multi-binding commands as default", () => {
478 const rows = buildKeybindingRows([
479 {
480 command: "chat.new",
481 shortcut: {
482 key: "n",
483 modKey: true,
484 metaKey: false,
485 ctrlKey: false,
486 altKey: false,
487 shiftKey: false,
488 },
489 whenAst: {
490 type: "not",
491 node: { type: "identifier", name: "terminalFocus" },
492 },
493 },
494 {
495 command: "chat.new",
496 shortcut: {
497 key: "o",
498 modKey: true,
499 metaKey: false,
500 ctrlKey: false,
501 altKey: false,
502 shiftKey: true,
503 },
504 whenAst: {
505 type: "not",
506 node: { type: "identifier", name: "terminalFocus" },
507 },
508 },
509 ] satisfies ResolvedKeybindingsConfig);
510​
511 expect(rows.map((row) => row.source)).toEqual(["Default", "Default"]);
512 });
513​
514 it("reports conflicting shortcuts that share an active when context", () => {
515 const rows = buildKeybindingRows([
516 {
517 command: "chat.new",
518 shortcut: {
519 key: "n",
520 modKey: true,
521 metaKey: false,
522 ctrlKey: false,
523 altKey: false,
524 shiftKey: false,
525 },
526 whenAst: {
527 type: "not",
528 node: { type: "identifier", name: "terminalFocus" },
529 },
530 },
531 {
532 command: "chat.newLocal",
533 shortcut: {
534 key: "n",
535 modKey: true,
536 metaKey: false,
537 ctrlKey: false,
538 altKey: false,
539 shiftKey: false,
540 },
541 whenAst: {
542 type: "not",
543 node: { type: "identifier", name: "terminalFocus" },
544 },
545 },
546 ] satisfies ResolvedKeybindingsConfig);
547​
548 expect(rows[0]?.conflicts).toEqual(["Chat: New Local"]);
549 expect(
550 keybindingConflictLabels(rows, {
551 rowId: rows[0]?.id ?? "",
552 key: "mod+n",
553 when: "",
554 }),
555 ).toEqual(["Chat: New Local"]);
556 });
557});