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

CaptureShortcutConfig.browser.test.tsx

263 lines10.0 KB

1import {
2 DEFAULT_CLIENT_SETTINGS,
3 type DesktopCaptureConfigPreview,
4 type DesktopSnapShotState,
5} from "@t3tools/contracts";
6import { act } from "react";
7import { createRoot, type Root } from "react-dom/client";
8import { userEvent } from "vite-plus/test/browser";
9import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
10​
11const bridge = vi.hoisted(() => ({
12 previewSnapShotConfig: vi.fn(),
13 applySnapShotConfig: vi.fn(),
14 setSnapShotShortcutSuppressed: vi.fn(),
15}));
16const toast = vi.hoisted(() => vi.fn());
17vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({
18 ...(await original()),
19 getDesktopSnapShotBridge: () => bridge as never,
20}));
21vi.mock(import("../ui/toast"), async (original) => {
22 const actual = await original();
23 return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
24});
25​
26import { CaptureShortcutConfig } from "./CaptureShortcutConfig";
27​
28const preview: DesktopCaptureConfigPreview = {
29 id: "approved-snapshot",
30 path: "/config/niri/config.kdl",
31 resolvedPath: "/config/niri/config.kdl",
32 before: "binds {\n}\n",
33 after: 'binds {\n Ctrl+Shift+2 { spawn "gdbus"; }\n}\n',
34 shortcut: "Ctrl+Shift+2",
35 operation: "install",
36};
37const complete = vi.fn<() => Promise<void>>();
38​
39function deferred<T>() {
40 let resolve!: (value: T) => void;
41 const promise = new Promise<T>((done) => {
42 resolve = done;
43 });
44 return { promise, resolve };
46​
47let root: Root;
48let container: HTMLDivElement;
49​
50async function render(desktop: "niri" | "hyprland" = "niri") {
51 const state: DesktopSnapShotState = {
52 mode: "portal",
53 linuxBackend: desktop,
54 shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
55 shortcutRegistered: false,
56 shortcutActionRegistered: true,
57 shortcutMessage: null,
58 message: null,
59 shortcutConfigPath: preview.path,
60 shortcutBinding: "manual binding",
61 };
62 await act(async () => root.render(<CaptureShortcutConfig state={state} onComplete={complete} />));
64function button(label: string) {
65 return [...container.querySelectorAll("button")].find((element) => element.textContent === label);
67async function click(label: string) {
68 const target = button(label);
69 expect(target, `button ${label}`).toBeDefined();
70 await act(async () => target!.click());
72const recorder = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
73const diff = () => container.querySelector('[aria-label="Shortcut changes"]');
74const alert = () => container.querySelector('[role="alert"]');
75const advanced = () => container.querySelector("details")!;
76async function recordKeys(keys: string) {
77 await act(async () => userEvent.click(recorder()));
78 await act(async () => userEvent.keyboard(keys));
80​
81beforeEach(() => {
82 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
83 Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });
84 bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);
85 bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);
86 bridge.applySnapShotConfig
87 .mockReset()
88 .mockResolvedValue({ backupPath: "/config/backup", warning: null });
89 complete.mockReset().mockResolvedValue(undefined);
90 toast.mockClear();
91 container = document.createElement("div");
92 document.body.append(container);
93 root = createRoot(container);
94});
95afterEach(async () => {
96 await act(async () => root.unmount());
97 container.remove();
98 Reflect.deleteProperty(navigator, "platform");
99 vi.unstubAllGlobals();
100});
101​
102it.each(["niri", "hyprland"] as const)(
103 "shows the fallback before review and requires separate read and write approval on %s",
104 async (desktop) => {
105 await render(desktop);
106 expect(recorder().getAttribute("aria-label")).toBe(
107 "Record snapshot shortcut, currently Ctrl+Shift+2",
108 );
109 expect(advanced().textContent).toContain("manual binding");
110 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
111 await click("Review changes");
112 expect(recorder().getAttribute("aria-label")).toBe(
113 "Record snapshot shortcut, currently Ctrl+Shift+2",
114 );
115 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
116 expect(diff()).not.toBeNull();
117 await click("Save shortcut");
118 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
119 expect(complete).toHaveBeenCalledOnce();
120 expect(toast).toHaveBeenCalledWith(expect.objectContaining({ type: "success" }));
121 },
122);
123​
124it.each(["niri", "hyprland"] as const)(
125 "lets users choose %s keys without opening Advanced, then approve the matching diff",
126 async (desktop) => {
127 await render(desktop);
128 expect(advanced().contains(recorder())).toBe(false);
129 await recordKeys("{Control>}{Alt>}y{/Alt}{/Control}");
130 expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenNthCalledWith(1, true);
131 expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenLastCalledWith(false);
132 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
133 const custom = {
134 ...preview,
135 id: "custom-keys",
136 shortcut: "Ctrl+Alt+Y",
137 after: preview.after.replace("Ctrl+Shift+2", "Ctrl+Alt+Y"),
138 };
139 bridge.previewSnapShotConfig.mockResolvedValue(custom);
140 await click("Review changes");
141 expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
142 operation: "install",
143 chooseFile: false,
144 shortcut: "ctrl+alt+y",
145 });
146 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
147 await click("Save shortcut");
148 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(custom.id);
149 expect(toast).toHaveBeenCalledWith(
150 expect.objectContaining({ description: "Use Ctrl+Alt+Y from another app." }),
151 );
152 },
153);
154​
155it("uses the existing config keys when no replacement was chosen", async () => {
156 bridge.previewSnapShotConfig.mockResolvedValue({ ...preview, shortcut: "Super+F8" });
157 await render();
158 await click("Review changes");
159 expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
160 operation: "install",
161 chooseFile: false,
162 });
163 expect(recorder().getAttribute("aria-label")).toContain("F8");
164});
165​
166it("requires a new diff after changing keys during review", async () => {
167 await render();
168 await click("Review changes");
169 expect(diff()).not.toBeNull();
170 await recordKeys("{Meta>}{F8}{/Meta}");
171 expect(diff()).toBeNull();
172 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
173 const replacement = { ...preview, id: "replacement", shortcut: "Super+F8" };
174 bridge.previewSnapShotConfig.mockResolvedValue(replacement);
175 await click("Review changes");
176 expect(bridge.previewSnapShotConfig).toHaveBeenLastCalledWith({
177 operation: "install",
178 chooseFile: false,
179 shortcut: "meta+f8",
180 });
181 await click("Save shortcut");
182 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(replacement.id);
183});
184​
185it.each(["Escape", "blur"])(
186 "keeps the reviewed diff when recording is cancelled with %s",
187 async (cancel) => {
188 await render();
189 await click("Review changes");
190 await act(async () => userEvent.click(recorder()));
191 expect(button("Save shortcut")?.disabled).toBe(true);
192 if (cancel === "Escape") await act(async () => userEvent.keyboard("{Escape}"));
193 else await act(async () => recorder().blur());
194 expect(button("Save shortcut")?.disabled).toBe(false);
195 expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();
196 await click("Save shortcut");
197 expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
198 },
199);
200​
201it("cancelling a reviewed diff does not write or finish setup", async () => {
202 await render();
203 await click("Review changes");
204 await click("Cancel");
205 expect(recorder().getAttribute("aria-label")).toBe(
206 "Record snapshot shortcut, currently Ctrl+Shift+2",
207 );
208 expect(button("Review changes")).toBeDefined();
209 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
210 expect(complete).not.toHaveBeenCalled();
211});
212​
213it("shows reading feedback until a proposal arrives", async () => {
214 const pending = deferred<DesktopCaptureConfigPreview>();
215 bridge.previewSnapShotConfig.mockReturnValue(pending.promise);
216 await render();
217 await click("Review changes");
218 expect(button("Preparing changes…")?.disabled).toBe(true);
219 await act(async () => pending.resolve(preview));
220 expect(button("Save shortcut")?.disabled).toBe(false);
221});
222​
223it("keeps read failures actionable with technical details in Advanced, then permits retry", async () => {
224 bridge.previewSnapShotConfig.mockRejectedValueOnce(new Error("EACCES: /config/niri/config.kdl"));
225 await render();
226 await click("Review changes");
227 expect(alert()?.textContent).toBe("Couldn't prepare the changes. Check Advanced for help.");
228 expect(advanced().textContent).toContain("EACCES: /config/niri/config.kdl");
229 await click("Review changes");
230 expect(alert()).toBeNull();
231 expect(button("Save shortcut")?.disabled).toBe(false);
232 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
233});
234​
235it("withdraws a stale diff and requires another read instead of retrying its write", async () => {
236 await render();
237 await click("Review changes");
238 bridge.applySnapShotConfig.mockRejectedValue(
239 new Error("Your config changed since this preview."),
240 );
241 await click("Save shortcut");
242 expect(alert()?.textContent).toContain("Review the changes and try again");
243 expect(advanced().textContent).toContain("Your config changed since this preview.");
244 expect(button("Review changes")).toBeDefined();
245 expect(diff()).toBeNull();
246 expect(complete).not.toHaveBeenCalled();
247});
248​
249it("does not finish or claim success when the desktop could not reload", async () => {
250 await render();
251 await click("Review changes");
252 bridge.applySnapShotConfig.mockResolvedValue({
253 backupPath: "/config/backup",
254 warning: "Config saved, but reload failed.",
255 });
256 await click("Save shortcut");
257 expect(container.querySelector('[role="status"]')?.textContent).toBe(
258 "Saved, but the shortcut needs attention. Check Advanced for help.",
259 );
260 expect(advanced().textContent).toContain("Config saved, but reload failed.");
261 expect(complete).not.toHaveBeenCalled();
262 expect(toast).not.toHaveBeenCalled();
263});