Open History to see the last commit
1import { assert, describe, expect, it } from "vite-plus/test";
2import { STATIC_KEYBINDING_COMMANDS, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
3import {
4 compileResolvedKeybindingsConfig,
5 mergeWithDefaultKeybindings,
6 parseKeybindingShortcut,
7} from "@t3tools/shared/keybindings";
8
9import { mFallback, type Msg } from "gt-react";
10
11import type { MessageResolver } from "../../i18n/messages";
12import { resolveShortcutCommand } from "../../keybindings";
13
14import {
15 buildKeybindingRows,
16 buildWhenVariableOptions,
17 commandLabel,
18 filterKeybindingRows,
19 groupKeybindingRows,
20 keybindingConflictLabels,
21 keybindingFromKeyboardEvent,
22 parseWhenExpressionDraft,
23 shortcutToKeybindingInput,
24 shortcutToKeybindingParts,
25 unknownWhenVariables,
26 whenAstToExpression,
27} from "./KeybindingsSettings.logic";
28
29describe("KeybindingsSettings.logic", () => {
30 it("finds a shortcut by the label its row shows", () => {
31 const rows = buildKeybindingRows(
32 compileResolvedKeybindingsConfig([
33 { command: "commandPalette.toggle", key: "mod+k" },
34 { command: "chat.new", key: "mod+shift+o" },
35 ]),
36 "Linux x86_64",
37 );
38 expect(
39 filterKeybindingRows(rows, "Ctrl+K", undefined, "Linux x86_64").map((row) => row.command),
40 ).toEqual(["commandPalette.toggle"]);
41 expect(
42 filterKeybindingRows(rows, "ctrl+shift+o", undefined, "Linux x86_64").map(
43 (row) => row.command,
44 ),
45 ).toEqual(["chat.new"]);
46 });
47
48 it("finds a shortcut by its translated source badge", () => {
49 const rows = buildKeybindingRows(
50 compileResolvedKeybindingsConfig([
51 { command: "chat.new", key: "mod+alt+n" },
52 { command: "script.build.run", key: "mod+alt+b" },
53 ]),
54 "Linux x86_64",
55 );
56 const german = { Custom: "Benutzerdefiniert", Project: "Projekt" };
57 const resolve = ((message: string | Msg) => {
58 const source = mFallback(message);
59 return german[source as keyof typeof german] ?? source;
60 }) as MessageResolver;
61 const search = (query: string) =>
62 filterKeybindingRows(rows, query, resolve, "Linux x86_64").map((row) => row.command);
63 expect(search("Benutzerdefiniert")).toEqual(["chat.new"]);
64 expect(search("projekt")).toEqual(["script.build.run"]);
65 expect(search("Custom")).toEqual(["chat.new"]);
66 });
67
68 it("lists back and forward under Navigation", () => {
69 const groups = groupKeybindingRows(
70 buildKeybindingRows(
71 compileResolvedKeybindingsConfig([
72 { command: "navigation.back", key: "mod+[" },
73 { command: "navigation.forward", key: "mod+]" },
74 ]),
75 "MacIntel",
76 ),
77 );
78 expect(groups.map((group) => group.id)).toEqual(["navigation"]);
79 });
80
81 it("keeps sibling row identities when a saved binding moves to the end", () => {
82 const bindings = compileResolvedKeybindingsConfig([
83 { command: "chat.new", key: "mod+n" },
84 { command: "terminal.toggle", key: "mod+j" },
85 { command: "terminal.toggle", key: "mod+k", when: "terminalFocus" },
86 ]);
87 const before = buildKeybindingRows(bindings);
88 const after = buildKeybindingRows([
89 ...bindings.slice(1),
90 ...compileResolvedKeybindingsConfig([{ command: "chat.new", key: "mod+shift+n" }]),
91 ]);
92
93 expect(after.filter((row) => row.command === "terminal.toggle").map((row) => row.id)).toEqual(
94 before.filter((row) => row.command === "terminal.toggle").map((row) => row.id),
95 );
96 expect(after.find((row) => row.command === "chat.new")?.id).not.toBe(
97 before.find((row) => row.command === "chat.new")?.id,
98 );
99 });
100
101 it("resets an edited shortcut to the built-in one its command no longer has", () => {
102 const rows = buildKeybindingRows(
103 mergeWithDefaultKeybindings(
104 compileResolvedKeybindingsConfig([
105 { command: "chat.new", key: "mod+n", when: "!terminalFocus" },
106 { command: "chat.new", key: "f8", when: "!terminalFocus" },
107 ]),
108 ),
109 );
110 expect(
111 rows
112 .filter((row) => row.command === "chat.new")
113 .map(({ key, defaultKey }) => ({ key, defaultKey })),
114 ).toEqual([
115 { key: "f8", defaultKey: "mod+shift+o" },
116 { key: "mod+n", defaultKey: "mod+n" },
117 ]);
118 const unassigned = buildKeybindingRows(
119 mergeWithDefaultKeybindings(
120 compileResolvedKeybindingsConfig([
121 { command: "chat.new", key: "mod+n", when: "!terminalFocus" },
122 { command: "chat.new", key: "mod+shift+o", when: "false" },
123 { command: "chat.new", key: "f8", when: "!terminalFocus" },
124 ]),
125 ),
126 );
127 expect(unassigned.find((row) => row.key === "f8")?.defaultKey).toBe("mod+n");
128 });
129
130 it("gives every built-in command a translatable label", () => {
131 const translated = (() => "translated") as unknown as MessageResolver;
132 expect(
133 STATIC_KEYBINDING_COMMANDS.filter(
134 (command) => commandLabel(command, translated) !== "translated",
135 ),
136 ).toEqual([]);
137 });
138
139 it("shares a stable editor for resolved duplicates but separates commands, shortcuts, and conditions", () => {
140 const bindings = compileResolvedKeybindingsConfig([
141 { command: "terminal.toggle", key: "mod+esc", when: "terminalFocus" },
142 { command: "terminal.toggle", key: "mod+escape", when: "(terminalFocus)" },
143 { command: "terminal.toggle", key: "mod+esc", when: "!terminalFocus" },
144 { command: "terminal.toggle", key: "mod+j", when: "terminalFocus" },
145 { command: "chat.new", key: "mod+esc", when: "terminalFocus" },
146 ]);
147 const rows = buildKeybindingRows(bindings);
148 expect(rows.map(({ command, key, when }) => ({ command, key, when }))).toEqual([
149 { command: "chat.new", key: "mod+esc", when: "terminalFocus" },
150 { command: "terminal.toggle", key: "mod+esc", when: "terminalFocus" },
151 { command: "terminal.toggle", key: "mod+esc", when: "!terminalFocus" },
152 { command: "terminal.toggle", key: "mod+j", when: "terminalFocus" },
153 ]);
154 expect(new Set(rows.map((row) => row.id)).size).toBe(4);
155 expect(rows.find((row) => row.command === "chat.new")?.conflicts).toEqual(["Terminal: Toggle"]);
156 expect(buildKeybindingRows(bindings.slice(1)).map((row) => row.id)).toEqual(
157 rows.map((row) => row.id),
158 );
159 });
160
161 it("marks only bindings shadowed by later unconditional or matching conditions", () => {
162 const bindings = compileResolvedKeybindingsConfig([
163 { command: "sidebar.toggle", key: "mod+b" },
164 { command: "terminal.toggle", key: "meta+b", when: "true" },
165 { command: "chat.new", key: "mod+n", when: "terminalFocus" },
166 { command: "terminal.new", key: "mod+n", when: "(terminalFocus)" },
167 { command: "chat.new", key: "mod+j" },
168 { command: "terminal.toggle", key: "mod+j", when: "terminalFocus" },
169 { command: "chat.new", key: "mod+k", when: "!terminalFocus" },
170 { command: "terminal.toggle", key: "mod+k", when: "terminalFocus" },
171 { command: "chat.new", key: "mod+l", when: "terminalFocus" },
172 { command: "terminal.toggle", key: "mod+l" },
173 ]);
174 const rows = buildKeybindingRows(bindings, "MacIntel");
175 expect(rows.filter((row) => row.previewLabels.length === 0).map((row) => row.binding)).toEqual([
176 bindings[8],
177 bindings[2],
178 bindings[0],
179 ]);
180 expect(rows.filter((row) => row.previewLabels.length > 0)).toHaveLength(7);
181 const sendBindings = compileResolvedKeybindingsConfig([
182 { command: "composer.sendAlternate", key: "mod+enter" },
183 { command: "chat.new", key: "mod+enter" },
184 ]);
185 for (const sendShortcut of ["enter", "mod-enter", "mod-enter-multiline"] as const) {
186 expect(
187 buildKeybindingRows(sendBindings, "MacIntel", sendShortcut).find(
188 (row) => row.command === "composer.sendAlternate",
189 )?.previewLabels.length === 0,
190 ).toBe(sendShortcut === "enter");
191 }
192 for (const command of ["composer.sendAlternate", "composer.sendBackground"] as const) {
193 const binding = compileResolvedKeybindingsConfig([{ command, key: "mod+enter" }]);
194 const labels = (mode: "enter" | "mod-enter" | "mod-enter-multiline") =>
195 buildKeybindingRows(binding, "Win32", mode)[0]?.previewLabels;
196 expect(labels("enter")).toEqual(["Ctrl+Enter"]);
197 expect(labels("mod-enter")).toEqual(["Ctrl+Shift+Enter"]);
198 expect(labels("mod-enter-multiline")).toEqual(["Ctrl+Enter", "Ctrl+Shift+Enter"]);
199 }
200 const shiftedBindings = compileResolvedKeybindingsConfig([
201 { command: "chat.new", key: "mod+shift+enter" },
202 { command: "composer.sendAlternate", key: "mod+enter" },
203 ]);
204 for (const sendShortcut of ["enter", "mod-enter", "mod-enter-multiline"] as const) {
205 expect(
206 buildKeybindingRows(shiftedBindings, "MacIntel", sendShortcut).find(
207 (row) => row.command === "chat.new",
208 )?.previewLabels.length === 0,
209 ).toBe(sendShortcut === "mod-enter");
210 }
211 expect(
212 buildKeybindingRows(bindings, "Win32").find((row) => row.command === "sidebar.toggle")
213 ?.previewLabels.length === 0,
214 ).toBe(false);
215 });
216
217 it("captures platform-specific mod shortcuts", () => {
218 expect(
219 keybindingFromKeyboardEvent(
220 { key: "K", code: "KeyK", metaKey: true, ctrlKey: false, altKey: false, shiftKey: true },
221 "MacIntel",
222 ),
223 ).toBe("mod+shift+k");
224 expect(
225 keybindingFromKeyboardEvent(
226 { key: "K", code: "KeyK", metaKey: false, ctrlKey: true, altKey: false, shiftKey: true },
227 "Win32",
228 ),
229 ).toBe("mod+shift+k");
230 });
231
232 it("waits for a key when only a modifier is pressed", () => {
233 expect(
234 keybindingFromKeyboardEvent(
235 {
236 key: "Meta",
237 code: "MetaLeft",
238 metaKey: true,
239 ctrlKey: false,
240 altKey: false,
241 shiftKey: false,
242 },
243 "MacIntel",
244 ),
245 ).toBeNull();
246 });
247
248 it.each([
249 ["@", "Digit2", "mod+shift+2"],
250 ['"', "Digit2", "mod+shift+2"],
251 ["@", "Quote", "mod+shift+'"],
252 ])("captures %s at %s by physical key", (key, code, expected) => {
253 expect(
254 keybindingFromKeyboardEvent(
255 {
256 key,
257 code,
258 metaKey: true,
259 ctrlKey: false,
260 altKey: false,
261 shiftKey: true,
262 },
263 "MacIntel",
264 ),
265 ).toBe(expected);
266 });
267
268 it("records layout punctuation while preserving physical Alt shortcuts; saved bindings still trigger", () => {
269 for (const { key, code, altKey = false, shiftKey, expected, defaultInput } of [
270 { key: "#", code: "Backslash", shiftKey: false, expected: "#", defaultInput: "\\" },
271 {
272 key: "'",
273 code: "Backslash",
274 shiftKey: true,
275 expected: "shift+'",
276 defaultInput: "shift+\\",
277 },
278 {
279 key: "¡",
280 code: "Digit1",
281 altKey: true,
282 shiftKey: false,
283 expected: "alt+1",
284 defaultInput: "alt+1",
285 },
286 {
287 key: "π",
288 code: "KeyP",
289 altKey: true,
290 shiftKey: false,
291 expected: "alt+p",
292 defaultInput: "alt+p",
293 },
294 // Dvorak Option+L and AZERTY Option+A: not the US glyph at its US key.
295 {
296 key: "¬",
297 code: "KeyP",
298 altKey: true,
299 shiftKey: false,
300 expected: "alt+¬",
301 defaultInput: "alt+¬",
302 },
303 {
304 key: "æ",
305 code: "KeyQ",
306 altKey: true,
307 shiftKey: false,
308 expected: "alt+æ",
309 defaultInput: "alt+æ",
310 },
311 ]) {
312 const pressed = {
313 key,
314 code,
315 metaKey: false,
316 ctrlKey: false,
317 altKey,
318 shiftKey,
319 };
320 expect(keybindingFromKeyboardEvent(pressed, "MacIntel")).toBe(defaultInput);
321 const input = keybindingFromKeyboardEvent(pressed, "MacIntel", { layoutCharacter: true });
322 expect(input).toBe(expected);
323 assert(input);
324 const shortcut = parseKeybindingShortcut(input);
325 assert(shortcut);
326 expect(
327 resolveShortcutCommand(pressed, [{ command: "chat.new", shortcut }], {
328 platform: "MacIntel",
329 }),
330 ).toBe("chat.new");
331 }
332 });
333
334 it("captures Latin layout keys instead of their punctuation position", () => {
335 expect(
336 keybindingFromKeyboardEvent(
337 {
338 key: "m",
339 code: "Semicolon",
340 metaKey: true,
341 ctrlKey: false,
342 altKey: false,
343 shiftKey: false,
344 },
345 "MacIntel",
346 ),
347 ).toBe("mod+m");
348 });
349
350 it("records the physical letter for Cyrillic and Greek layouts, so it works after switching back", () => {
351 const record = (key: string, code: string) =>
352 keybindingFromKeyboardEvent(
353 { key, code, metaKey: false, ctrlKey: true, altKey: false, shiftKey: false },
354 "Linux x86_64",
355 { layoutCharacter: true },
356 );
357 expect(record("л", "KeyK")).toBe("mod+k");
358 expect(record("Л", "KeyK")).toBe("mod+k");
359 expect(record("ν", "KeyN")).toBe("mod+n");
360 expect(record("ö", "Semicolon")).toBe("mod+ö");
361 const shortcut = parseKeybindingShortcut(record("л", "KeyK")!)!;
362 const russianCtrlK = {
363 key: "л",
364 code: "KeyK",
365 metaKey: false,
366 ctrlKey: true,
367 altKey: false,
368 shiftKey: false,
369 };
370 expect(
371 resolveShortcutCommand(russianCtrlK, [{ command: "chat.new", shortcut }], {
372 platform: "Linux x86_64",
373 }),
374 ).toBe("chat.new");
375 });
376
377 it("records the physical letter for non-Latin Alt shortcuts on Linux and Windows", () => {
378 const record = (platform: string) =>
379 keybindingFromKeyboardEvent(
380 { key: "и", code: "KeyB", metaKey: false, ctrlKey: true, altKey: true, shiftKey: false },
381 platform,
382 { layoutCharacter: true },
383 );
384 expect(record("Win32")).toBe("mod+alt+b");
385 const recorded = record("Linux x86_64");
386 expect(recorded).toBe("mod+alt+b");
387 assert(recorded);
388 const shortcut = parseKeybindingShortcut(recorded);
389 assert(shortcut);
390 for (const key of ["b", "и"]) {
391 expect(
392 resolveShortcutCommand(
393 { key, code: "KeyB", metaKey: false, ctrlKey: true, altKey: true, shiftKey: false },
394 [{ command: "chat.new", shortcut }],
395 { platform: "Linux x86_64" },
396 ),
397 ).toBe("chat.new");
398 }
399 });
400
401 it("keeps a literal plus key as its own part", () => {
402 expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod++")!)).toEqual(["mod", "+"]);
403 expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod+shift++")!)).toEqual([
404 "mod",
405 "shift",
406 "+",
407 ]);
408 });
409
410 it("serializes shortcuts and when expressions for upserts", () => {
411 expect(
412 shortcutToKeybindingInput({
413 key: " ",
414 modKey: true,
415 metaKey: false,
416 ctrlKey: false,
417 altKey: true,
418 shiftKey: false,
419 }),
420 ).toBe("mod+alt+space");
421
422 expect(
423 whenAstToExpression({
424 type: "and",
425 left: { type: "identifier", name: "editorFocus" },
426 right: {
427 type: "not",
428 node: { type: "identifier", name: "terminalFocus" },
429 },
430 }),
431 ).toBe("editorFocus && !terminalFocus");
432
433 expect(parseWhenExpressionDraft("editorFocus && (!terminalFocus || modelPickerOpen)")).toEqual({
434 ok: true,
435 value: {
436 type: "and",
437 left: { type: "identifier", name: "editorFocus" },
438 right: {
439 type: "or",
440 left: {
441 type: "not",
442 node: { type: "identifier", name: "terminalFocus" },
443 },
444 right: { type: "identifier", name: "modelPickerOpen" },
445 },
446 },
447 });
448 for (const [expression, condition] of [
449 ["previewOpen && !previewFocus", "previewOpen"],
450 ["composerFocus && turnRunning && composerEmpty", "composerEmpty"],
451 ] as const) {
452 const draft = parseWhenExpressionDraft(expression);
453 assert(draft.ok);
454 expect(unknownWhenVariables(draft.value)).toEqual([]);
455 expect(buildWhenVariableOptions()).toContain(condition);
456 }
457 expect(parseWhenExpressionDraft("editorFocus &&")).toEqual({
458 ok: false,
459 message: "Use variables with !, &&, ||, and parentheses.",
460 });
461
462 expect(parseWhenExpressionDraft("!(terminalFocus || modelPickerOpen)")).toEqual({
463 ok: true,
464 value: {
465 type: "not",
466 node: {
467 type: "or",
468 left: { type: "identifier", name: "terminalFocus" },
469 right: { type: "identifier", name: "modelPickerOpen" },
470 },
471 },
472 });
473 });
474
475 it("reports conflicting shortcuts that share an active when context", () => {
476 const rows = buildKeybindingRows([
477 {
478 command: "chat.new",
479 shortcut: {
480 key: "n",
481 modKey: true,
482 metaKey: false,
483 ctrlKey: false,
484 altKey: false,
485 shiftKey: false,
486 },
487 whenAst: {
488 type: "not",
489 node: { type: "identifier", name: "terminalFocus" },
490 },
491 },
492 {
493 command: "chat.newLocal",
494 shortcut: {
495 key: "n",
496 modKey: true,
497 metaKey: false,
498 ctrlKey: false,
499 altKey: false,
500 shiftKey: false,
501 },
502 whenAst: {
503 type: "not",
504 node: { type: "identifier", name: "terminalFocus" },
505 },
506 },
507 ] satisfies ResolvedKeybindingsConfig);
508
509 expect(rows[0]?.conflicts).toEqual(["Chat: New Local"]);
510 const disabledRows = buildKeybindingRows([
511 rows[0]!.binding,
512 { ...rows[1]!.binding, whenAst: { type: "identifier", name: "false" } },
513 ]);
514 expect(disabledRows.find((row) => row.when === "false")?.previewLabels).toEqual([]);
515 expect(disabledRows.map((row) => row.conflicts)).toEqual([[], []]);
516
517 expect(
518 keybindingConflictLabels(rows, {
519 rowId: rows[0]?.id ?? "",
520 key: "mod+n",
521 when: "",
522 }),
523 ).toEqual(["Chat: New Local"]);
524 });
525
526 it.each([
527 { platform: "Linux x86_64", ctrl: ["Chat: New"], meta: [] },
528 { platform: "Win32", ctrl: ["Chat: New"], meta: [] },
529 { platform: "MacIntel", ctrl: [], meta: ["Chat: New"] },
530 ])("resolves mod to the $platform modifier when reporting conflicts", (expected) => {
531 const rows = buildKeybindingRows(
532 compileResolvedKeybindingsConfig([
533 { command: "chat.new", key: "mod+k" },
534 { command: "chat.newLocal", key: "ctrl+k" },
535 { command: "thread.copyReference", key: "meta+k" },
536 ]),
537 expected.platform,
538 );
539 const conflictsFor = (key: string) => rows.find((row) => row.key === key)?.conflicts;
540
541 expect(conflictsFor("ctrl+k")).toEqual(expected.ctrl);
542 expect(conflictsFor("meta+k")).toEqual(expected.meta);
543 expect(
544 keybindingConflictLabels(rows, { rowId: "new", key: "ctrl+k", when: "" }, expected.platform),
545 ).toEqual(["Chat: New Local", ...expected.ctrl].toSorted());
546 });
547
548 it("treats a true condition like no condition when reporting conflicts", () => {
549 const rows = buildKeybindingRows(
550 compileResolvedKeybindingsConfig([
551 { command: "chat.new", key: "mod+k", when: "true" },
552 { command: "chat.newLocal", key: "mod+k", when: "terminalFocus" },
553 ]),
554 "Linux x86_64",
555 );
556
557 expect(rows.map((row) => row.conflicts)).toEqual([["Chat: New Local"], ["Chat: New"]]);
558 });
559
560 it("keeps mod and ctrl shortcuts apart when their when contexts differ", () => {
561 const rows = buildKeybindingRows(
562 compileResolvedKeybindingsConfig([
563 { command: "chat.new", key: "mod+k", when: "!terminalFocus" },
564 { command: "chat.newLocal", key: "ctrl+k", when: "terminalFocus" },
565 ]),
566 "Linux x86_64",
567 );
568
569 expect(rows.map((row) => row.conflicts)).toEqual([[], []]);
570 });
571});