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

projectScriptEditor.permissions.browser.test.tsx

308 lines10.8 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthSettingsWriteScope,
4 EnvironmentId,
5 type AuthEnvironmentScope,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import { AsyncResult } from "effect/reactivity";
9import { act } from "react";
10import { createRoot, type Root } from "react-dom/client";
11import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12import { userEvent } from "vite-plus/test/browser";
13​
14const permissions = vi.hoisted(() => ({
15 canWriteSettings: false,
16 canEditProject: true,
17 listeners: new Set<() => void>(),
18}));
19​
20vi.mock(import("~/state/session"), async (original) => {
21 const { useSyncExternalStore } = await import("react");
22 const read = (scope: AuthEnvironmentScope) =>
23 scope === AuthOrchestrationOperateScope
24 ? permissions.canEditProject
25 : permissions.canWriteSettings;
26 return {
27 ...(await original()),
28 readEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) => read(scope),
29 useEnvironmentScope: (_id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
30 useSyncExternalStore(
31 (listener) => {
32 permissions.listeners.add(listener);
33 return () => permissions.listeners.delete(listener);
34 },
35 () => read(scope),
36 ),
37 };
38});
39​
40/** A grant change that React has already rendered, unlike a bare assignment. */
41const publish = () => act(async () => permissions.listeners.forEach((listener) => listener()));
42import {
43 ProjectScriptEditorDialog,
44 type NewProjectScriptInput,
45 type ProjectScriptEditorRequest,
46} from "./projectScriptEditor";
47​
48const request: ProjectScriptEditorRequest = {
49 scriptId: "test",
50 initial: {
51 name: "Test",
52 command: "vp test",
53 icon: "test",
54 runOnWorktreeCreate: false,
55 waitForSetup: false,
56 runOnSettle: false,
57 keybinding: "mod+k",
58 previewUrl: null,
59 autoOpenPreview: false,
60 },
61};
62​
63describe("ProjectScriptEditorDialog", () => {
64 let root: Root;
65​
66 beforeEach(() => {
67 root = createRoot(document.createElement("div"));
68 permissions.canWriteSettings = false;
69 permissions.canEditProject = true;
70 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 });
72​
73 afterEach(async () => {
74 await act(async () => root.unmount());
75 vi.restoreAllMocks();
76 vi.unstubAllGlobals();
77 });
78​
79 async function openEditor(
80 onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined)),
81 editorRequest = request,
82 actions = { onDelete: vi.fn(), onClose: vi.fn() },
83 editScope:
84 | typeof AuthOrchestrationOperateScope
85 | typeof AuthSettingsWriteScope = AuthOrchestrationOperateScope,
86 ) {
87 await act(async () =>
88 root.render(
89 <ProjectScriptEditorDialog
90 environmentId={EnvironmentId.make("script-editor-test")}
91 editScope={editScope}
92 request={editorRequest}
93 scripts={[]}
94 onSubmit={onSubmit}
95 onDelete={actions.onDelete}
96 onClose={actions.onClose}
97 />,
98 ),
99 );
100 }
101​
102 const submit = () => act(async () => document.querySelector("form")!.requestSubmit());
103 async function click(label: string) {
104 const button = await vi.waitFor(() => {
105 const match = [...document.querySelectorAll("button")].find(
106 (element) => element.textContent === label,
107 );
108 expect(match, label).toBeDefined();
109 return match!;
110 });
111 await act(async () => button.click());
112 }
113 const confirmation = () => document.querySelector('[role="alertdialog"]');
114 async function pressInShortcutField(keys: string) {
115 document.querySelector<HTMLInputElement>("#script-keybinding")!.focus();
116 await userEvent.keyboard(keys);
117 }
118​
119 it.each([null, "test"])(
120 "saves a settings action without task access (id: %s)",
121 async (scriptId) => {
122 permissions.canEditProject = false;
123 permissions.canWriteSettings = true;
124 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
125 await openEditor(onSubmit, { ...request, scriptId }, undefined, AuthSettingsWriteScope);
126 permissions.canWriteSettings = false;
127 await submit();
128 expect(onSubmit).not.toHaveBeenCalled();
129 permissions.canWriteSettings = true;
130 await submit();
131 expect(onSubmit).toHaveBeenCalledExactlyOnceWith(
132 scriptId,
133 expect.objectContaining({ command: "vp test" }),
134 );
135 },
136 );
137​
138 it("rechecks settings access before deleting a settings action", async () => {
139 permissions.canEditProject = false;
140 permissions.canWriteSettings = true;
141 const actions = { onDelete: vi.fn(), onClose: vi.fn() };
142 await openEditor(undefined, request, actions, AuthSettingsWriteScope);
143 await click("Delete");
144 permissions.canWriteSettings = false;
145 await click("Delete action");
146 expect(actions.onDelete).not.toHaveBeenCalled();
147 await vi.waitFor(() => expect(confirmation()).toBeNull());
148 permissions.canWriteSettings = true;
149 await publish();
150 await click("Delete");
151 await click("Delete action");
152 expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
153 });
154​
155 it("clears an old shortcut when adding an action with no shortcut", async () => {
156 permissions.canWriteSettings = true;
157 let persistedKeybinding: string | null = "mod+k";
158 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
159 if (input.keybinding !== undefined) persistedKeybinding = input.keybinding;
160 return AsyncResult.success(undefined);
161 });
162 await openEditor(onSubmit, {
163 scriptId: null,
164 initial: { ...request.initial, keybinding: null },
165 });
166​
167 await submit();
168​
169 expect(persistedKeybinding).toBeNull();
170 expect(onSubmit).toHaveBeenCalledWith(null, expect.objectContaining({ keybinding: null }));
171 });
172​
173 it.each([false, true])(
174 "re-adds a deleted action while preserving its shortcut without settings access (revoked: %s)",
175 async (revokeBeforeSubmit) => {
176 permissions.canWriteSettings = revokeBeforeSubmit;
177 const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
178 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
179 if (input.keybinding !== undefined && !permissions.canWriteSettings) {
180 return AsyncResult.failure(
181 Cause.fail(new Error("This connection cannot change keyboard shortcuts.")),
182 );
183 }
184 persisted.name = input.name;
185 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
186 return AsyncResult.success(undefined);
187 });
188 await openEditor(onSubmit, {
189 scriptId: null,
190 initial: { ...request.initial, keybinding: null },
191 });
192​
193 permissions.canWriteSettings = false;
194 await submit();
195​
196 expect(persisted).toEqual({ name: "Test", keybinding: "mod+k" });
197 expect(onSubmit).toHaveBeenCalledOnce();
198 },
199 );
200​
201 it.each([false, true])(
202 "requires settings access to override a retained shortcut when re-adding an action (revoked: %s)",
203 async (revokeBeforeSubmit) => {
204 permissions.canWriteSettings = true;
205 vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
206 const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
207 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
208 persisted.name = input.name;
209 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
210 return AsyncResult.success(undefined);
211 });
212 await openEditor(onSubmit, {
213 scriptId: null,
214 initial: { ...request.initial, keybinding: null },
215 });
216 await pressInShortcutField("{Control>}j{/Control}");
217 if (revokeBeforeSubmit) permissions.canWriteSettings = false;
218 await submit();
219​
220 expect(persisted).toEqual(
221 revokeBeforeSubmit
222 ? { name: null, keybinding: "mod+k" }
223 : { name: "Test", keybinding: "mod+j" },
224 );
225 },
226 );
227​
228 it.each([false, true])(
229 "preserves a concurrent shortcut change when saving only the script (settings access: %s)",
230 async (canWriteSettings) => {
231 permissions.canWriteSettings = canWriteSettings;
232 const persisted = { name: request.initial.name, keybinding: request.initial.keybinding };
233 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
234 persisted.name = input.name;
235 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
236 return AsyncResult.success(undefined);
237 });
238 await openEditor(onSubmit);
239​
240 persisted.keybinding = "mod+j";
241 const name = document.querySelector<HTMLInputElement>("#script-name")!;
242 await userEvent.clear(name);
243 await userEvent.type(name, "Renamed");
244 await submit();
245​
246 expect(persisted).toEqual({ name: "Renamed", keybinding: "mod+j" });
247 expect(onSubmit).toHaveBeenCalledOnce();
248 },
249 );
250​
251 it.each([false, true])(
252 "enforces settings access when submitting an explicit shortcut clear (revoked: %s)",
253 async (revokeBeforeSubmit) => {
254 permissions.canWriteSettings = true;
255 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
256 await openEditor(onSubmit);
257 await pressInShortcutField("{Backspace}");
258 if (revokeBeforeSubmit) permissions.canWriteSettings = false;
259 await submit();
260​
261 if (revokeBeforeSubmit) {
262 expect(onSubmit).not.toHaveBeenCalled();
263 } else {
264 expect(onSubmit).toHaveBeenCalledWith(
265 "test",
266 expect.objectContaining({ keybinding: null }),
267 );
268 }
269 },
270 );
271​
272 it.each([false, true])(
273 "requires project access to save even with settings access (revoked: %s)",
274 async (revokeBeforeSubmit) => {
275 permissions.canEditProject = revokeBeforeSubmit;
276 permissions.canWriteSettings = true;
277 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
278 await openEditor(onSubmit);
279​
280 permissions.canEditProject = false;
281 await submit();
282 expect(onSubmit).not.toHaveBeenCalled();
283​
284 permissions.canEditProject = true;
285 await submit();
286 expect(onSubmit).toHaveBeenCalledOnce();
287 },
288 );
289​
290 it("rechecks project access before deleting from an already open confirmation", async () => {
291 const actions = { onDelete: vi.fn(), onClose: vi.fn() };
292 await openEditor(undefined, request, actions);
293 await click("Delete");
294​
295 permissions.canEditProject = false;
296 await click("Delete action");
297 expect(actions.onDelete).not.toHaveBeenCalled();
298 expect(actions.onClose).not.toHaveBeenCalled();
299 await vi.waitFor(() => expect(confirmation()).toBeNull());
300​
301 permissions.canEditProject = true;
302 await publish();
303 await click("Delete");
304 await click("Delete action");
305 expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
306 expect(actions.onClose).toHaveBeenCalledOnce();
307 });
308});