Open History to see the last commit
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
68const theme = (name: string, accent = "#3b82f6", css?: string) => ({
69 version: THEME_FILE_VERSION,
70 name,
71 appearance: "dark",
72 colors: { accent },
73 ...(css ? { css } : {}),
74});
75
76const themeFile = (name: string, accent?: string, css?: string) =>
77 new File([JSON.stringify(theme(name, accent, css))], `${name}.json`, {
78 type: "application/json",
79 });
80
81const DUSK_CSS = ".chat-header { height: 3rem; }";
82
83it.each(["Update existing", "Keep both"])(
84 "keeps batch failures visible after %s",
85 async (choice) => {
86 using _themes = {
87 [Symbol.dispose]() {
88 window.localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
89 invalidateCustomThemes();
90 },
91 };
92 installCustomTheme(parseThemeFile(theme("Dusk")));
93 const onOpenChange = vi.fn();
94 await using _screen = await render(
95 <ThemeImportDialog
96 open
97 onOpenChange={onOpenChange}
98 onImported={() => true}
99 onImportedMany={() => {}}
100 />,
101 );
102 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
103 await userEvent.upload(input, [
104 themeFile("Dawn"),
105 themeFile("Dusk", "#f97316", DUSK_CSS),
106 new File(["{"], "broken.json", { type: "application/json" }),
107 ]);
108
109 await expect.element(page.getByText("Already installed")).toBeVisible();
110 await expect.element(page.getByText(/^broken\.json:/)).toBeVisible();
111 expect(getCustomThemes().map((theme) => theme.label)).toContain("Dawn");
112 await page.getByRole("button", { name: choice }).click();
113 invalidateCustomThemes();
114 const label = choice === "Update existing" ? "Dusk" : "Dusk (1)";
115 expect(getCustomThemes().find((theme) => theme.label === label)).toMatchObject({
116 colors: parseThemeFile(theme("Dusk", "#f97316")).colors,
117 css: DUSK_CSS,
118 });
119 await expect.element(page.getByText(/^broken\.json:/)).toBeVisible();
120 expect(onOpenChange).not.toHaveBeenCalledWith(false);
121 },
122);
123
124function isolateThemes() {
125 const previous = localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
126 localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
127 invalidateCustomThemes();
128 return {
129 [Symbol.dispose]() {
130 if (previous === null) localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
131 else localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, previous);
132 invalidateCustomThemes();
133 },
134 };
135}
136
137it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => {
138 using _themes = isolateThemes();
139 await using _screen = await render(
140 <ThemeImportDialog
141 open
142 onOpenChange={() => {}}
143 onImported={() => true}
144 onImportedMany={() => {}}
145 />,
146 );
147 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
148 await userEvent.upload(
149 input,
150 new File(["x".repeat(1_048_100)], "huge.json", { type: "application/json" }),
151 );
152
153 await expect
154 .element(page.getByText(/^That file is/))
155 .toHaveTextContent(
156 "That file is 1.00 MB. Theme files are only a few KB, so this one was not read (limit 256 KB).",
157 );
158});
159
160it.each(["failed read", "batch install"])(
161 "keeps the oversized replacement warning after a superseded %s",
162 async (earlierImport) => {
163 using _themes = isolateThemes();
164 await using _screen = await render(
165 <ThemeImportDialog
166 open
167 onOpenChange={() => {}}
168 onImported={() => true}
169 onImportedMany={() => {}}
170 />,
171 );
172 const earlierRead = Promise.withResolvers<string>();
173 const readStarted = Promise.withResolvers<void>();
174 const earlierFile = Object.assign(themeFile("Dusk"), {
175 text() {
176 readStarted.resolve();
177 return earlierRead.promise;
178 },
179 });
180 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
181 const files = new DataTransfer();
182 if (earlierImport === "batch install") files.items.add(themeFile("Dawn"));
183 files.items.add(earlierFile);
184 await act(async () => {
185 input.files = files.files;
186 input.dispatchEvent(new Event("change", { bubbles: true }));
187 await readStarted.promise;
188 });
189 await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled();
190 await userEvent.upload(
191 input,
192 new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }),
193 );
194 const warning = page.getByText(/^That file is/);
195 await expect.element(warning).toBeVisible();
196
197 await act(async () => {
198 if (earlierImport === "batch install") {
199 earlierRead.resolve(JSON.stringify(theme("Dusk")));
200 } else {
201 earlierRead.reject(new Error("Could not read Dusk"));
202 }
203 await earlierRead.promise.catch(() => {});
204 });
205
206 expect(getCustomThemes().map((theme) => theme.label)).toEqual([]);
207 expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/);
208 await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled();
209 },
210);
211
212function themeJsonc(name: string, background: string) {
213 return `{
214 // VS Code themes use JSONC even with a .json extension.
215 "name": "${name}",
216 "colors": {
217 "editor.background": "${background}",
218 },
219 "tokenColors": [],
220 }`;
221}
222
223describe("ThemeImportDialog JSONC imports", () => {
224 it.each(["paste", "file"])("imports a VS Code JSONC theme from %s", async (source) => {
225 using _themes = isolateThemes();
226 await using _screen = await render(
227 <ThemeImportDialog
228 open
229 onOpenChange={() => {}}
230 onImported={() => true}
231 onImportedMany={() => {}}
232 />,
233 );
234 const json = themeJsonc("JSONC Night", "#002b36");
235 if (source === "paste") {
236 await page.getByRole("textbox", { name: "Theme JSON" }).fill(json);
237 } else {
238 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
239 await userEvent.upload(input, new File([json], "night.json", { type: "application/json" }));
240 await expect.element(page.getByRole("textbox", { name: "Theme JSON" })).toHaveValue(json);
241 }
242 await page.getByRole("button", { name: "Add theme", exact: true }).click();
243
244 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night"]);
245 expect(themeColorToHex(getCustomThemes()[0]!.colors.canvas)).toBe("#002b36");
246 });
247
248 it("imports each VS Code JSONC theme in a file batch", async () => {
249 using _themes = isolateThemes();
250 await using _screen = await render(
251 <ThemeImportDialog
252 open
253 onOpenChange={() => {}}
254 onImported={() => true}
255 onImportedMany={() => {}}
256 />,
257 );
258 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
259 await userEvent.upload(input, [
260 new File([themeJsonc("JSONC Night", "#002b36")], "night.json", {
261 type: "application/json",
262 }),
263 new File([themeJsonc("JSONC Day", "#fdf6e3")], "day.json", {
264 type: "application/json",
265 }),
266 ]);
267
268 await vi.waitFor(() => {
269 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night", "JSONC Day"]);
270 });
271 expect(getCustomThemes().map((theme) => themeColorToHex(theme.colors.canvas))).toEqual([
272 "#002b36",
273 "#fdf6e3",
274 ]);
275 });
276});
277
278it("does not install a pending community theme after leaving Appearance", async () => {
279 using _themes = isolateThemes();
280 searchOpenVsxThemes.mockReset();
281 searchOpenVsxThemes.mockResolvedValue([extension]);
282 const download = Promise.withResolvers<ReturnType<typeof parseThemeFile>[]>();
283 vi.mocked(importOpenVsxThemeExtension).mockReset();
284 vi.mocked(importOpenVsxThemeExtension).mockReturnValue(download.promise);
285 await using screen = await render(
286 <ThemeImportDialog
287 open
288 onOpenChange={() => {}}
289 onImported={() => true}
290 onImportedMany={() => {}}
291 />,
292 );
293 await userEvent.fill(page.getByLabelText("Search Open VSX themes"), "night");
294 await page.getByRole("button", { name: "Install Nightfall" }).click();
295 await screen.unmount();
296 await act(async () => {
297 download.resolve([
298 {
299 ...parseThemeFile(theme("Nightfall")),
300 collection: { id: extension.collectionId, label: extension.name },
301 },
302 ]);
303 await download.promise;
304 });
305 expect(
306 getCustomThemes(),
307 "expect leaving Appearance to cancel its pending theme installation",
308 ).toEqual([]);
309});