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

SnapShotSettings.browser.test.tsx

368 lines14.2 KB

1import {
2 DEFAULT_CLIENT_SETTINGS,
3 type ClientSettingsPatch,
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 getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),
13 setSnapShotShortcutSuppressed: vi.fn(),
14 checkSnapShotShortcut: vi.fn(),
15 previewSnapShotConfig: vi.fn(),
16 applySnapShotConfig: vi.fn(),
17 setupSnapShot: vi.fn(),
18 requestSnapShotPermissions: vi.fn(),
19 onMenuAction: vi.fn(),
20 onSnapShotEvent: vi.fn(() => () => undefined),
21}));
22const toast = vi.hoisted(() => vi.fn());
23// Client settings behave like the real store: an update re-renders every reader.
24const settingsStore = vi.hoisted(() => ({
25 current: {} as typeof DEFAULT_CLIENT_SETTINGS,
26 listeners: new Set<() => void>(),
27 update: vi.fn<(patch: ClientSettingsPatch) => Promise<void>>(),
28 set(next: typeof DEFAULT_CLIENT_SETTINGS) {
29 settingsStore.current = next;
30 for (const listener of settingsStore.listeners) listener();
31 },
32}));
33vi.mock(import("@tanstack/react-router"), async (original) => ({
34 ...(await original()),
35 useLocation: ((options?: { select?: (location: unknown) => unknown }) =>
36 options?.select?.({ hash: "", pathname: "/settings/snapshots", state: {} }) ?? "") as never,
37 useNavigate: (() => vi.fn()) as never,
38}));
39vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({
40 ...(await original()),
41 getDesktopSnapShotBridge: () => bridge as never,
42}));
43vi.mock(import("../ui/toast"), async (original) => {
44 const actual = await original();
45 return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
46});
47vi.mock(import("../../hooks/useSettings"), async (original) => {
48 const { useSyncExternalStore } = await import("react");
49 const subscribe = (listener: () => void) => {
50 settingsStore.listeners.add(listener);
51 return () => settingsStore.listeners.delete(listener);
52 };
53 return {
54 ...(await original()),
55 useClientSettings: (() =>
56 useSyncExternalStore(subscribe, () => settingsStore.current)) as never,
57 updateClientSettings: settingsStore.update as never,
58 };
59});
60​
61import { readSnapShotSetupResume } from "../../lib/snapShotSetupResume";
62import { SnapShotSettings } from "./SnapShotSettings";
63​
64let state: DesktopSnapShotState;
65let root: Root;
66let container: HTMLDivElement;
67​
68async function mount() {
69 root = createRoot(container);
70 await act(async () => root.render(<SnapShotSettings />));
71 await vi.waitFor(() => expect(bridge.getSnapShotState).toHaveBeenCalled());
72 await act(async () => {});
74const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');
75const scope = () => dialog() ?? container;
76function button(label: string, within: ParentNode = scope()) {
77 return (
78 [...within.querySelectorAll("button")].find(
79 (element) => element.textContent?.trim() === label,
80 ) ?? null
81 );
83async function click(label: string) {
84 const target = button(label);
85 expect(target, `button ${label}`).not.toBeNull();
86 await act(async () => target!.click());
88const recorder = () => scope().querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
89const toggle = (label: string) =>
90 container.querySelector<HTMLButtonElement>(`[role="switch"][aria-label="${label}"]`)!;
91const stepTitle = () => dialog()?.querySelector("h3")?.textContent;
92​
93beforeEach(() => {
94 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
95 vi.clearAllMocks();
96 localStorage.clear();
97 Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });
98 settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true };
99 state = {
100 mode: "portal",
101 linuxBackend: "hyprland",
102 shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
103 shortcutRegistered: false,
104 shortcutActionRegistered: true,
105 shortcutMessage: null,
106 message: null,
107 hyprlandHelper: { status: "ready", message: "Ready" },
108 };
109 bridge.getSnapShotState.mockImplementation(async () => state);
110 bridge.setSnapShotShortcutSuppressed.mockResolvedValue(undefined);
111 bridge.checkSnapShotShortcut.mockResolvedValue({ available: true, message: null });
112 bridge.requestSnapShotPermissions.mockResolvedValue(undefined);
113 bridge.setupSnapShot.mockReset().mockResolvedValue(undefined);
114 settingsStore.update.mockImplementation(async (patch) => {
115 state = { ...state, shortcut: patch.snapShotShortcut ?? state.shortcut };
116 settingsStore.set({ ...settingsStore.current, ...patch });
117 });
118 container = document.createElement("div");
119 document.body.append(container);
120});
121afterEach(async () => {
122 await act(async () => root.unmount());
123 container.remove();
124 localStorage.clear();
125 Reflect.deleteProperty(navigator, "platform");
126 vi.unstubAllGlobals();
127});
128​
129it.each(["niri", "hyprland"] as const)(
130 "reopens %s setup at Shortcut without reading config or expanding Settings",
131 async (desktop) => {
132 state = { ...state, linuxBackend: desktop };
133 await mount();
134 expect(dialog()).toBeNull();
135 expect(button("Review changes", container)).toBeNull();
136 await click("Change shortcut");
137 expect(stepTitle()).toBe("Choose your shortcut");
138 expect(button("Review changes")).not.toBeNull();
139 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
140 expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
141 await click("Close");
142 expect(dialog()).toBeNull();
143 expect(settingsStore.update).not.toHaveBeenCalled();
144 expect(settingsStore.current.snapShotEnabled).toBe(true);
145 },
146);
147​
148it("returns to Access if the Hyprland helper needs attention before changing keys", async () => {
149 await mount();
150 state = { ...state, hyprlandHelper: { status: "not-installed", message: "Install helper" } };
151 await click("Change shortcut");
152 expect(stepTitle()).toBe("Allow snapshots");
153 expect(button("Install helper")).not.toBeNull();
154 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
155});
156​
157it.each(["direct", "gnome-extension", "kde"] as const)(
158 "keeps %s shortcut recording and saving inline",
159 async (backend) => {
160 state = {
161 ...state,
162 mode: backend === "direct" ? "direct" : "portal",
163 linuxBackend: backend === "direct" ? undefined : backend,
164 shortcutRegistered: true,
165 shortcutLabel: backend === "direct" ? undefined : "Press <Shift><Control>2",
166 shortcutMessage: backend === "direct" ? null : "Desktop shortcut: Press <Shift><Control>2",
167 };
168 await mount();
169 if (backend !== "direct") {
170 expect(recorder().getAttribute("aria-label")).toBe(
171 "Record snapshot shortcut, currently Ctrl+Shift+2",
172 );
173 }
174 await act(async () => userEvent.click(recorder()));
175 await act(async () => userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}"));
176 expect(bridge.checkSnapShotShortcut).toHaveBeenCalledOnce();
177 expect(container.textContent).toContain("Ready to save.");
178 expect(recorder().getAttribute("aria-label")).toBe(
179 "Record snapshot shortcut, currently Ctrl+Alt+Y",
180 );
181 await click("Save");
182 expect(settingsStore.update).toHaveBeenCalledWith({
183 snapShotShortcut: expect.objectContaining({ key: "y", modKey: true, altKey: true }),
184 });
185 expect(dialog()).toBeNull();
186 expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
187 },
188);
189​
190it("turns capture on directly on Windows without opening setup", async () => {
191 settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
192 state = { ...state, mode: "direct", linuxBackend: undefined, windows: true };
193 await mount();
194 await act(async () => toggle("Enable snapshots").click());
195 expect(settingsStore.update).toHaveBeenCalledWith({ snapShotEnabled: true });
196 expect(toggle("Enable snapshots").getAttribute("aria-checked")).toBe("true");
197 expect(dialog()).toBeNull();
198 expect(button("Manage capture")).toBeNull();
199});
200​
201it("keeps the approved desktop shortcut when recording is cancelled in setup", async () => {
202 state = {
203 ...state,
204 linuxBackend: "gnome-extension",
205 gnomeExtension: { status: "enabled", message: "Ready" },
206 shortcutRegistered: true,
207 shortcutLabel: "Press <Control><Alt>8",
208 };
209 await mount();
210 await click("Manage capture");
211 expect(dialog()).not.toBeNull();
212 expect(recorder().getAttribute("aria-label")).toBe(
213 "Record snapshot shortcut, currently Ctrl+Alt+8",
214 );
215 await act(async () => userEvent.click(recorder()));
216 expect(recorder().textContent).toBe("Press shortcut…");
217 await act(async () => userEvent.keyboard("{Escape}"));
218 expect(dialog()).not.toBeNull();
219 expect(recorder().getAttribute("aria-label")).toBe(
220 "Record snapshot shortcut, currently Ctrl+Alt+8",
221 );
222 expect(settingsStore.update).not.toHaveBeenCalled();
223 expect(bridge.checkSnapShotShortcut).not.toHaveBeenCalled();
224});
225​
226function usePortalShortcut(shortcutCanRetry: boolean) {
227 const shortcut = {
228 key: "2",
229 modKey: false,
230 ctrlKey: true,
231 altKey: false,
232 shiftKey: true,
233 metaKey: false,
234 };
235 settingsStore.current = { ...settingsStore.current, snapShotShortcut: shortcut };
236 state = {
237 ...state,
238 linuxBackend: "gnome-extension",
239 gnomeExtension: { status: "enabled", message: "Ready" },
240 shortcut,
241 linuxFeedbackAvailable: true,
242 shortcutRegistered: true,
243 shortcutCanRetry,
244 };
246​
247it("keeps older portal shortcuts editable without offering unsupported permissions", async () => {
248 usePortalShortcut(false);
249 await mount();
250 expect(button("Shortcut permissions")).toBeNull();
251 expect(bridge.setupSnapShot).not.toHaveBeenCalled();
252 await act(async () => userEvent.click(recorder()));
253 expect(recorder().textContent).toBe("Press shortcut…");
254});
255​
256it("shows permission errors once in a toast and allows retrying", async () => {
257 usePortalShortcut(true);
258 bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
259 await mount();
260 await click("Shortcut permissions");
261 expect(toast).toHaveBeenCalledExactlyOnceWith({
262 type: "error",
263 title: "Couldn't open shortcut permissions",
264 description: "The desktop service disconnected.",
265 });
266 expect(container.querySelector('[role="alert"]')).toBeNull();
267 await click("Shortcut permissions");
268 expect(bridge.setupSnapShot).toHaveBeenCalledTimes(2);
269 expect(toast).toHaveBeenCalledTimes(1);
270});
271​
272it("keeps a failed preference unchanged and reports the save error in a toast", async () => {
273 usePortalShortcut(true);
274 settingsStore.update.mockRejectedValueOnce(new Error("The settings file is read-only."));
275 await mount();
276 const flash = () => toggle("Flash captured window");
277 expect(flash().getAttribute("aria-checked")).toBe("true");
278 await act(async () => flash().click());
279 expect(flash().getAttribute("aria-checked")).toBe("true");
280 expect(toast).toHaveBeenCalledExactlyOnceWith({
281 type: "error",
282 title: "Couldn't save capture settings",
283 description: "The settings file is read-only.",
284 });
285 await act(async () => flash().click());
286 expect(flash().getAttribute("aria-checked")).toBe("false");
287 expect(toast).toHaveBeenCalledTimes(1);
288});
289​
290it("keeps setup errors in the wizard and does not toast them after closing it", async () => {
291 usePortalShortcut(true);
292 state = { ...state, shortcutRegistered: false };
293 await mount();
294 await click("Manage capture");
295 expect(stepTitle()).toBe("Choose your shortcut");
296 bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
297 await click("Shortcut permissions");
298 expect(dialog()!.querySelector('[role="alert"]')?.textContent).toContain(
299 "Couldn't finish this step",
300 );
301 expect(dialog()!.querySelector("details")?.textContent).toContain(
302 "The desktop service disconnected.",
303 );
304 expect(toast).not.toHaveBeenCalled();
305 await click("Close");
306 expect(dialog()).toBeNull();
307 expect(toast).not.toHaveBeenCalled();
308});
309​
310function useMacPermissions(granted: boolean) {
311 settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
312 state = {
313 mode: "direct",
314 shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
315 shortcutRegistered: granted,
316 shortcutMessage: null,
317 message: null,
318 macPermissions: { screenRecording: granted, accessibility: granted },
319 };
321​
322it.each([false, true])(
323 "resumes macOS permission setup after restart and clears it on close, completed=%s",
324 async (completed) => {
325 useMacPermissions(false);
326 await mount();
327 await act(async () => toggle("Enable snapshots").click());
328 expect(stepTitle()).toBe("Allow snapshots");
329 bridge.setupSnapShot.mockImplementationOnce(async () => {
330 expect(readSnapShotSetupResume()).toEqual({ wasEnabled: false });
331 });
332 await click("Allow");
333 expect(bridge.setupSnapShot).toHaveBeenCalledWith("allow-screen-recording");
334​
335 // macOS quits the app from its permission prompt; the next launch resumes setup.
336 await act(async () => root.unmount());
337 state = { ...state, shortcutRegistered: true };
338 state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };
339 await mount();
340 expect(stepTitle()).toBe("Allow snapshots");
341 expect(button("Finish later")).not.toBeNull();
342 if (completed) {
343 await click("Test capture and continue");
344 expect(stepTitle()).toBe("Choose your shortcut");
345 await click("Done");
346 } else {
347 await click("Finish later");
348 }
349 expect(dialog()).toBeNull();
350 expect(readSnapShotSetupResume()).toBeNull();
351 },
352);
353​
354it("requires a successful macOS test capture before enabling and allows retry", async () => {
355 useMacPermissions(true);
356 await mount();
357 await act(async () => toggle("Enable snapshots").click());
358 bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));
359 await click("Test capture and continue");
360 expect(dialog()!.querySelector('[role="alert"]')).not.toBeNull();
361 expect(dialog()!.querySelector("details")?.textContent).toContain("Capture was denied");
362 expect(stepTitle()).toBe("Allow snapshots");
363 expect(settingsStore.current.snapShotEnabled).toBe(false);
364 await click("Test capture and continue");
365 expect(stepTitle()).toBe("Choose your shortcut");
366 expect(bridge.setupSnapShot.mock.calls).toEqual([["test-mac-capture"], ["test-mac-capture"]]);
367 expect(settingsStore.current.snapShotEnabled).toBe(true);
368});