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

ThemeImportDialog.browser.test.tsx

340 lines11.2 KB

1import { StrictMode } from "react";
2import { describe, expect, it, vi } from "vite-plus/test";
3import { page, userEvent } from "vite-plus/test/browser";
4​
5import { act, render } from "../../../test/render";
6import {
7 CUSTOM_THEMES_STORAGE_KEY,
8 getCustomThemes,
9 installCustomTheme,
10 invalidateCustomThemes,
11 parseThemeFile,
12 themeColorToHex,
13 THEME_FILE_VERSION,
14} from "../../themePalette";
15import { importOpenVsxThemeExtension, type OpenVsxThemeExtension } from "../../openVsxThemes";
16import { ThemeImportDialog } from "./ThemeImportDialog";
17​
18const searchOpenVsxThemes = vi.hoisted(() => vi.fn());
19​
20vi.mock("../../openVsxThemes", () => ({
21 searchOpenVsxThemes,
22 importOpenVsxThemeExtension: vi.fn(),
23}));
24​
25const extension: OpenVsxThemeExtension = {
26 id: "acme.nightfall",
27 collectionId: "acme.nightfall",
28 name: "Nightfall",
29 publisher: "acme",
30 description: "A dark theme",
31 downloadCount: 10,
32 iconUrl: null,
33 sourceUrl: null,
34 manifestUrl: "https://example.test/manifest",
35 sha256Url: "https://example.test/sha256",
36 vsixUrl: "https://example.test/vsix",
37 version: "1.0.0",
38 license: "MIT",
39};
40​
41describe("ThemeImportDialog", () => {
42 // StrictMode replays ref attach/detach on mount, which must not end the session.
43 it("searches Open VSX under StrictMode", async () => {
44 searchOpenVsxThemes.mockReset();
45 searchOpenVsxThemes.mockResolvedValue([extension]);
46 await using _screen = await render(
47 <StrictMode>
48 <ThemeImportDialog
49 open
50 onOpenChange={() => {}}
51 onImported={() => true}
52 onImportedMany={() => {}}
53 />
54 </StrictMode>,
55 );
56​
57 // One input event: keystrokes more than the search debounce apart would search a prefix first.
58 await userEvent.fill(page.getByLabelText("Search Open VSX themes"), "night");
59​
60 await expect.element(page.getByRole("heading", { name: "Nightfall" })).toBeVisible();
61 expect(searchOpenVsxThemes).toHaveBeenCalledWith(
62 "night",
63 expect.objectContaining({ sortBy: "downloadCount" }),
64 );
65 });
66​
67 it("clears the search on Escape before closing the dialog", async () => {
68 searchOpenVsxThemes.mockReset();
69 searchOpenVsxThemes.mockResolvedValue([]);
70 const onOpenChange = vi.fn();
71 await using _screen = await render(
72 <ThemeImportDialog
73 open
74 onOpenChange={onOpenChange}
75 onImported={() => true}
76 onImportedMany={() => {}}
77 />,
78 );
79 const search = page.getByRole("searchbox", { name: "Search Open VSX themes" });
80 await expect.element(search).toHaveAttribute("type", "text");
81 await userEvent.fill(search, "nord");
82 await userEvent.keyboard("{Escape}");
83 await expect.element(search).toHaveValue("");
84 search.element().dispatchEvent(
85 new KeyboardEvent("keydown", {
86 bubbles: true,
87 cancelable: true,
88 key: "Escape",
89 repeat: true,
90 }),
91 );
92 expect(onOpenChange).not.toHaveBeenCalled();
93​
94 await userEvent.keyboard("{Escape}");
95 expect(onOpenChange).toHaveBeenCalledWith(false);
96 });
97});
98​
99const theme = (name: string, accent = "#3b82f6", css?: string) => ({
100 version: THEME_FILE_VERSION,
101 name,
102 appearance: "dark",
103 colors: { accent },
104 ...(css ? { css } : {}),
105});
106​
107const themeFile = (name: string, accent?: string, css?: string) =>
108 new File([JSON.stringify(theme(name, accent, css))], `${name}.json`, {
109 type: "application/json",
110 });
111​
112const DUSK_CSS = ".chat-header { height: 3rem; }";
113​
114it.each(["Update existing", "Keep both"])(
115 "keeps batch failures visible after %s",
116 async (choice) => {
117 using _themes = {
118 [Symbol.dispose]() {
119 window.localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
120 invalidateCustomThemes();
121 },
122 };
123 installCustomTheme(parseThemeFile(theme("Dusk")));
124 const onOpenChange = vi.fn();
125 await using _screen = await render(
126 <ThemeImportDialog
127 open
128 onOpenChange={onOpenChange}
129 onImported={() => true}
130 onImportedMany={() => {}}
131 />,
132 );
133 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
134 await userEvent.upload(input, [
135 themeFile("Dawn"),
136 themeFile("Dusk", "#f97316", DUSK_CSS),
137 new File(["{"], "broken.json", { type: "application/json" }),
138 ]);
139​
140 await expect.element(page.getByText("Already installed")).toBeVisible();
141 await expect.element(page.getByText(/^broken\.json:/)).toBeVisible();
142 expect(getCustomThemes().map((theme) => theme.label)).toContain("Dawn");
143 await page.getByRole("button", { name: choice }).click();
144 invalidateCustomThemes();
145 const label = choice === "Update existing" ? "Dusk" : "Dusk (1)";
146 expect(getCustomThemes().find((theme) => theme.label === label)).toMatchObject({
147 colors: parseThemeFile(theme("Dusk", "#f97316")).colors,
148 css: DUSK_CSS,
149 });
150 await expect.element(page.getByText(/^broken\.json:/)).toBeVisible();
151 expect(onOpenChange).not.toHaveBeenCalledWith(false);
152 },
153);
154​
155function isolateThemes() {
156 const previous = localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
157 localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
158 invalidateCustomThemes();
159 return {
160 [Symbol.dispose]() {
161 if (previous === null) localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
162 else localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, previous);
163 invalidateCustomThemes();
164 },
165 };
167​
168it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => {
169 using _themes = isolateThemes();
170 await using _screen = await render(
171 <ThemeImportDialog
172 open
173 onOpenChange={() => {}}
174 onImported={() => true}
175 onImportedMany={() => {}}
176 />,
177 );
178 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
179 await userEvent.upload(
180 input,
181 new File(["x".repeat(1_048_100)], "huge.json", { type: "application/json" }),
182 );
183​
184 await expect
185 .element(page.getByText(/^That file is/))
186 .toHaveTextContent(
187 "That file is 1.00 MB. Theme files are only a few KB, so this one was not read (limit 256 KB).",
188 );
189});
190​
191it.each(["failed read", "batch install"])(
192 "keeps the oversized replacement warning after a superseded %s",
193 async (earlierImport) => {
194 using _themes = isolateThemes();
195 await using _screen = await render(
196 <ThemeImportDialog
197 open
198 onOpenChange={() => {}}
199 onImported={() => true}
200 onImportedMany={() => {}}
201 />,
202 );
203 const earlierRead = Promise.withResolvers<string>();
204 const readStarted = Promise.withResolvers<void>();
205 const earlierFile = Object.assign(themeFile("Dusk"), {
206 text() {
207 readStarted.resolve();
208 return earlierRead.promise;
209 },
210 });
211 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
212 const files = new DataTransfer();
213 if (earlierImport === "batch install") files.items.add(themeFile("Dawn"));
214 files.items.add(earlierFile);
215 await act(async () => {
216 input.files = files.files;
217 input.dispatchEvent(new Event("change", { bubbles: true }));
218 await readStarted.promise;
219 });
220 await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled();
221 await userEvent.upload(
222 input,
223 new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }),
224 );
225 const warning = page.getByText(/^That file is/);
226 await expect.element(warning).toBeVisible();
227​
228 await act(async () => {
229 if (earlierImport === "batch install") {
230 earlierRead.resolve(JSON.stringify(theme("Dusk")));
231 } else {
232 earlierRead.reject(new Error("Could not read Dusk"));
233 }
234 await earlierRead.promise.catch(() => {});
235 });
236​
237 expect(getCustomThemes().map((theme) => theme.label)).toEqual([]);
238 expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/);
239 await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled();
240 },
241);
242​
243function themeJsonc(name: string, background: string) {
244 return `{
245 // VS Code themes use JSONC even with a .json extension.
246 "name": "${name}",
247 "colors": {
248 "editor.background": "${background}",
249 },
250 "tokenColors": [],
251 }`;
253​
254describe("ThemeImportDialog JSONC imports", () => {
255 it.each(["paste", "file"])("imports a VS Code JSONC theme from %s", async (source) => {
256 using _themes = isolateThemes();
257 await using _screen = await render(
258 <ThemeImportDialog
259 open
260 onOpenChange={() => {}}
261 onImported={() => true}
262 onImportedMany={() => {}}
263 />,
264 );
265 const json = themeJsonc("JSONC Night", "#002b36");
266 if (source === "paste") {
267 await page.getByRole("textbox", { name: "Theme JSON" }).fill(json);
268 } else {
269 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
270 await userEvent.upload(input, new File([json], "night.json", { type: "application/json" }));
271 await expect.element(page.getByRole("textbox", { name: "Theme JSON" })).toHaveValue(json);
272 }
273 await page.getByRole("button", { name: "Add theme", exact: true }).click();
274​
275 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night"]);
276 expect(themeColorToHex(getCustomThemes()[0]!.colors.canvas)).toBe("#002b36");
277 });
278​
279 it("imports each VS Code JSONC theme in a file batch", async () => {
280 using _themes = isolateThemes();
281 await using _screen = await render(
282 <ThemeImportDialog
283 open
284 onOpenChange={() => {}}
285 onImported={() => true}
286 onImportedMany={() => {}}
287 />,
288 );
289 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
290 await userEvent.upload(input, [
291 new File([themeJsonc("JSONC Night", "#002b36")], "night.json", {
292 type: "application/json",
293 }),
294 new File([themeJsonc("JSONC Day", "#fdf6e3")], "day.json", {
295 type: "application/json",
296 }),
297 ]);
298​
299 await vi.waitFor(() => {
300 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night", "JSONC Day"]);
301 });
302 expect(getCustomThemes().map((theme) => themeColorToHex(theme.colors.canvas))).toEqual([
303 "#002b36",
304 "#fdf6e3",
305 ]);
306 });
307});
308​
309it("does not install a pending community theme after leaving Appearance", async () => {
310 using _themes = isolateThemes();
311 searchOpenVsxThemes.mockReset();
312 searchOpenVsxThemes.mockResolvedValue([extension]);
313 const download = Promise.withResolvers<ReturnType<typeof parseThemeFile>[]>();
314 vi.mocked(importOpenVsxThemeExtension).mockReset();
315 vi.mocked(importOpenVsxThemeExtension).mockReturnValue(download.promise);
316 await using screen = await render(
317 <ThemeImportDialog
318 open
319 onOpenChange={() => {}}
320 onImported={() => true}
321 onImportedMany={() => {}}
322 />,
323 );
324 await userEvent.fill(page.getByLabelText("Search Open VSX themes"), "night");
325 await page.getByRole("button", { name: "Install Nightfall" }).click();
326 await screen.unmount();
327 await act(async () => {
328 download.resolve([
329 {
330 ...parseThemeFile(theme("Nightfall")),
331 collection: { id: extension.collectionId, label: extension.name },
332 },
333 ]);
334 await download.promise;
335 });
336 expect(
337 getCustomThemes(),
338 "expect leaving Appearance to cancel its pending theme installation",
339 ).toEqual([]);
340});