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

useProjectScriptSettings.browser.test.tsx

210 lines6.3 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) {
94 let settings: ProjectScriptSettings | undefined;
95 const screen = await render(
96 <Probe
97 targets={[
98 {
99 environmentId,
100 settings: {
101 ...DEFAULT_SERVER_SETTINGS,
102 defaultProjectScripts: scope === "environment" ? [lint] : [],
103 },
104 keybindings,
105 ...(scope === "project"
106 ? { project: { id: ProjectId.make("project"), scripts: [lint] } }
107 : {}),
108 },
109 ]}
110 onResult={(next) => (settings = next)}
111 />,
112 );
113 return {
114 ...screen,
115 get settings() {
116 return settings!;
117 },
118 };
120​
121async function submitInAct(
122 submit: ProjectScriptSettings["submit"],
123 changes: Partial<NewProjectScriptInput>,
124) {
125 let result: Awaited<ReturnType<typeof submit>> | undefined;
126 await act(async () => {
127 result = await submit(lint.id, { ...input, ...changes });
128 });
129 return result!;
131function setup() {
132 vi.clearAllMocks();
133 for (const command of Object.values(commands))
134 command.mockResolvedValue(AsyncResult.success(undefined));
136​
137describe("useProjectScriptSettings", () => {
138 it("retries a creation whose shortcut failed without duplicating the action", async () => {
139 setup();
140 commands.upsertKeybinding.mockResolvedValueOnce(
141 AsyncResult.failure(Cause.fail(new Error("Temporary shortcut failure"))),
142 );
143 const projects = [ProjectId.make("first"), ProjectId.make("second")];
144 let settings: ProjectScriptSettings | undefined;
145 const renderTargets = (firstScripts: readonly ProjectScript[]) => (
146 <Probe
147 targets={projects.map((id, index) => ({
148 environmentId,
149 settings: DEFAULT_SERVER_SETTINGS,
150 keybindings: [],
151 project: { id, scripts: index === 0 ? firstScripts : [] },
152 }))}
153 onResult={(next) => (settings = next)}
154 />
155 );
156 await using screen = await render(renderTargets([]));
157 const draft = { ...input, keybinding: "mod+shift+k" };
158 const onActionCreated = vi.fn<(scriptId: string) => void>();
159​
160 await act(async () => {
161 expect((await settings!.submit(null, draft, onActionCreated))._tag).toBe("Failure");
162 });
163 expect(onActionCreated).toHaveBeenCalledExactlyOnceWith(lint.id);
164 expect(commands.updateSettings).toHaveBeenCalledTimes(1);
165​
166 // The first project now has the action; the second was never written.
167 await screen.rerender(renderTargets([lint]));
168 await act(async () => {
169 expect((await settings!.submit(lint.id, draft, onActionCreated, true))._tag).toBe("Success");
170 });
171 for (const [index, id] of projects.entries()) {
172 expect(commands.updateSettings).toHaveBeenNthCalledWith(index + 2, {
173 environmentId,
174 input: {
175 patch: {
176 projectSettingsOverrides: {
177 [id]: { defaultProjectScripts: [expect.objectContaining({ id: lint.id })] },
178 },
179 },
180 },
181 });
182 }
183 });
184​
185 it.each(["project", "environment"] as const)(
186 "preserves the shortcut for %s action name and command edits",
187 async (scope) => {
188 setup();
189 await using screen = await renderSettings(lintBinding, scope);
190 const { submit } = screen.settings;
191 const changes = { name: "Lint and fix", command: "vp lint --fix" };
192​
193 const result = await submitInAct(submit, changes);
194​
195 expect(result._tag).toBe("Success");
196 const scripts = [expect.objectContaining({ id: lint.id, ...changes })];
197 expect(commands.updateSettings).toHaveBeenCalledExactlyOnceWith({
198 environmentId,
199 input: {
200 patch:
201 scope === "project"
202 ? { projectSettingsOverrides: { project: { defaultProjectScripts: scripts } } }
203 : { defaultProjectScripts: scripts },
204 },
205 });
206 expect(commands.removeKeybinding).not.toHaveBeenCalled();
207 expect(commands.upsertKeybinding).not.toHaveBeenCalled();
208 },
209 );
210});