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

useProjectScriptSettings.browser.test.tsx

220 lines6.7 KB

1import { act, render } from "../../../test/render";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 EnvironmentId,
5 ProjectId,
6 type ProjectScript,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { AsyncResult } from "effect/reactivity";
11import { describe, expect, it, vi } from "vite-plus/test";
12​
13import type { NewProjectScriptInput } from "../projectScriptEditor";
14​
15const commands = vi.hoisted(() => ({
16 updateSettings: vi.fn(),
17 upsertKeybinding: vi.fn(),
18 removeKeybinding: vi.fn(),
19}));
20​
21vi.mock(import("../../state/session"), async (original) => ({
22 ...(await original()),
23 readEnvironmentScope: () => true,
24}));
25vi.mock(import("../../state/entities"), async (original) => ({
26 ...(await original()),
27 useProjects: () => [],
28}));
29vi.mock(import("../../state/server"), async (original) => {
30 const actual = await original();
31 return {
32 ...actual,
33 serverEnvironment: {
34 ...actual.serverEnvironment,
35 updateSettings: "updateSettings",
36 upsertKeybinding: "upsertKeybinding",
37 removeKeybinding: "removeKeybinding",
38 } as unknown as typeof actual.serverEnvironment,
39 };
40});
41vi.mock(import("../../state/use-atom-command"), async (original) => ({
42 ...(await original()),
43 useAtomCommand: ((command: keyof typeof commands) => commands[command]) as never,
44}));
45​
46import { useProjectScriptSettings } from "./useProjectScriptSettings";
47​
48const environmentId = EnvironmentId.make("remote");
49const lint: ProjectScript = {
50 id: "lint",
51 name: "Lint",
52 command: "vp lint",
53 icon: "lint",
54 runOnWorktreeCreate: false,
55};
56const lintBinding: ResolvedKeybindingsConfig = [
57 {
58 command: "script.lint.run",
59 shortcut: {
60 key: "k",
61 metaKey: false,
62 ctrlKey: false,
63 shiftKey: true,
64 altKey: false,
65 modKey: true,
66 },
67 },
68];
69const input: NewProjectScriptInput = {
70 name: lint.name,
71 command: lint.command,
72 icon: lint.icon,
73 runOnWorktreeCreate: false,
74 waitForSetup: false,
75 runOnSettle: false,
76 previewUrl: null,
77 autoOpenPreview: false,
78};
79​
80type ProjectScriptSettings = ReturnType<typeof useProjectScriptSettings>;
81​
82function Probe(props: {
83 targets: Parameters<typeof useProjectScriptSettings>[0];
84 onResult: (settings: ProjectScriptSettings) => void;
85}) {
86 props.onResult(useProjectScriptSettings(props.targets));
87 return null;
89​
90async function renderSettings(
91 keybindings: ResolvedKeybindingsConfig,
92 scope: "project" | "environment" = "project",
93 scripts: readonly ProjectScript[] = [lint],
94) {
95 let settings: ProjectScriptSettings | undefined;
96 const screen = await render(
97 <Probe
98 targets={[
99 {
100 environmentId,
101 settings: {
102 ...DEFAULT_SERVER_SETTINGS,
103 defaultProjectScripts: scope === "environment" ? scripts : [],
104 },
105 keybindings,
106 ...(scope === "project" ? { project: { id: ProjectId.make("project"), scripts } } : {}),
107 },
108 ]}
109 onResult={(next) => (settings = next)}
110 />,
111 );
112 return {
113 ...screen,
114 get settings() {
115 return settings!;
116 },
117 };
119​
120async function submitInAct(
121 submit: ProjectScriptSettings["submit"],
122 changes: Partial<NewProjectScriptInput>,
123) {
124 let result: Awaited<ReturnType<typeof submit>> | undefined;
125 await act(async () => {
126 result = await submit(lint.id, { ...input, ...changes });
127 });
128 return result!;
130function setup() {
131 vi.clearAllMocks();
132 for (const command of Object.values(commands))
133 command.mockResolvedValue(AsyncResult.success(undefined));
135​
136describe("useProjectScriptSettings", () => {
137 it("retries a creation whose shortcut failed without duplicating the action", async () => {
138 setup();
139 commands.upsertKeybinding.mockResolvedValueOnce(
140 AsyncResult.failure(Cause.fail(new Error("Temporary shortcut failure"))),
141 );
142 const projects = [ProjectId.make("first"), ProjectId.make("second")];
143 let settings: ProjectScriptSettings | undefined;
144 const renderTargets = (firstScripts: readonly ProjectScript[]) => (
145 <Probe
146 targets={projects.map((id, index) => ({
147 environmentId,
148 settings: DEFAULT_SERVER_SETTINGS,
149 keybindings: [],
150 project: { id, scripts: index === 0 ? firstScripts : [] },
151 }))}
152 onResult={(next) => (settings = next)}
153 />
154 );
155 await using screen = await render(renderTargets([]));
156 const draft = { ...input, keybinding: "mod+shift+k" };
157 const onActionCreated = vi.fn<(scriptId: string) => void>();
158​
159 await act(async () => {
160 expect((await settings!.submit(null, draft, onActionCreated))._tag).toBe("Failure");
161 });
162 expect(onActionCreated).toHaveBeenCalledExactlyOnceWith(lint.id);
163 expect(commands.updateSettings).toHaveBeenCalledTimes(1);
164​
165 // The first project now has the action; the second was never written.
166 await screen.rerender(renderTargets([lint]));
167 await act(async () => {
168 expect((await settings!.submit(lint.id, draft, onActionCreated, true))._tag).toBe("Success");
169 });
170 for (const [index, id] of projects.entries()) {
171 expect(commands.updateSettings).toHaveBeenNthCalledWith(index + 2, {
172 environmentId,
173 input: {
174 patch: {
175 projectSettingsOverrides: {
176 [id]: { defaultProjectScripts: [expect.objectContaining({ id: lint.id })] },
177 },
178 },
179 },
180 });
181 }
182 });
183​
184 it.each(["project", "environment"] as const)(
185 "preserves the shortcut for %s action name and command edits",
186 async (scope) => {
187 setup();
188 await using screen = await renderSettings(lintBinding, scope);
189 const { submit } = screen.settings;
190 const changes = { name: "Lint and fix", command: "vp lint --fix" };
191​
192 const result = await submitInAct(submit, changes);
193​
194 expect(result._tag).toBe("Success");
195 const scripts = [expect.objectContaining({ id: lint.id, ...changes })];
196 expect(commands.updateSettings).toHaveBeenCalledExactlyOnceWith({
197 environmentId,
198 input: {
199 patch:
200 scope === "project"
201 ? { projectSettingsOverrides: { project: { defaultProjectScripts: scripts } } }
202 : { defaultProjectScripts: scripts },
203 },
204 });
205 expect(commands.removeKeybinding).not.toHaveBeenCalled();
206 expect(commands.upsertKeybinding).not.toHaveBeenCalled();
207 },
208 );
209​
210 it("refuses to save an edit to an action another window already deleted", async () => {
211 setup();
212 await using screen = await renderSettings([], "project", []);
213​
214 const result = await submitInAct(screen.settings.submit, { keybinding: "mod+shift+k" });
215​
216 expect(result._tag).toBe("Failure");
217 expect(commands.updateSettings).not.toHaveBeenCalled();
218 expect(commands.upsertKeybinding).not.toHaveBeenCalled();
219 });
220});