Skip to content

Commit ef6e05e

Browse files
fix(themes): accept VS Code JSONC imports (#25375)
Co-authored-by: maria-rcks <[email protected]>
1 parent c6bde56 commit ef6e05e

4 files changed

Lines changed: 149 additions & 8 deletions

File tree

‎apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
installCustomTheme,
1010
invalidateCustomThemes,
1111
parseThemeFile,
12+
themeColorToHex,
1213
THEME_FILE_VERSION,
1314
} from "../../themePalette";
1415
import type { OpenVsxThemeExtension } from "../../openVsxThemes";
@@ -112,3 +113,82 @@ it.each(["Update existing", "Keep both"])(
112113
expect(onOpenChange).not.toHaveBeenCalledWith(false);
113114
},
114115
);
116+
117+
function isolateThemes() {
118+
const previous = localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
119+
localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
120+
invalidateCustomThemes();
121+
return {
122+
[Symbol.dispose]() {
123+
if (previous === null) localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
124+
else localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, previous);
125+
invalidateCustomThemes();
126+
},
127+
};
128+
}
129+
130+
function themeJsonc(name: string, background: string) {
131+
return `{
132+
// VS Code themes use JSONC even with a .json extension.
133+
"name": "${name}",
134+
"colors": {
135+
"editor.background": "${background}",
136+
},
137+
"tokenColors": [],
138+
}`;
139+
}
140+
141+
describe("ThemeImportDialog JSONC imports", () => {
142+
it.each(["paste", "file"])("imports a VS Code JSONC theme from %s", async (source) => {
143+
using _themes = isolateThemes();
144+
await using _screen = await render(
145+
<ThemeImportDialog
146+
open
147+
onOpenChange={() => {}}
148+
onImported={() => true}
149+
onImportedMany={() => {}}
150+
/>,
151+
);
152+
const json = themeJsonc("JSONC Night", "#002b36");
153+
if (source === "paste") {
154+
await page.getByRole("textbox", { name: "Theme JSON" }).fill(json);
155+
} else {
156+
const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
157+
await userEvent.upload(input, new File([json], "night.json", { type: "application/json" }));
158+
await expect.element(page.getByRole("textbox", { name: "Theme JSON" })).toHaveValue(json);
159+
}
160+
await page.getByRole("button", { name: "Add theme", exact: true }).click();
161+
162+
expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night"]);
163+
expect(themeColorToHex(getCustomThemes()[0]!.colors.canvas)).toBe("#002b36");
164+
});
165+
166+
it("imports each VS Code JSONC theme in a file batch", async () => {
167+
using _themes = isolateThemes();
168+
await using _screen = await render(
169+
<ThemeImportDialog
170+
open
171+
onOpenChange={() => {}}
172+
onImported={() => true}
173+
onImportedMany={() => {}}
174+
/>,
175+
);
176+
const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
177+
await userEvent.upload(input, [
178+
new File([themeJsonc("JSONC Night", "#002b36")], "night.json", {
179+
type: "application/json",
180+
}),
181+
new File([themeJsonc("JSONC Day", "#fdf6e3")], "day.json", {
182+
type: "application/json",
183+
}),
184+
]);
185+
186+
await vi.waitFor(() => {
187+
expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night", "JSONC Day"]);
188+
});
189+
expect(getCustomThemes().map((theme) => themeColorToHex(theme.colors.canvas))).toEqual([
190+
"#002b36",
191+
"#fdf6e3",
192+
]);
193+
});
194+
});

‎apps/web/src/components/settings/ThemeImportDialog.tsx‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@ import {
1414
} from "../../themePalette";
1515
import {
1616
humanizeThemeName,
17-
isVsCodeThemeFile,
1817
pairVsCodeThemes,
19-
parseVsCodeThemeFile,
18+
parseThemeImport,
2019
resolveThemeLabelCollisions,
2120
} from "../../vscodeThemeImport";
2221
import { Alert } from "../ui/alert";
@@ -256,10 +255,9 @@ function ThemeImportBody({
256255
continue;
257256
}
258257
try {
259-
const value: unknown = JSON.parse(await file.text());
260258
parsed.push({
261259
sourceName: file.name,
262-
theme: isVsCodeThemeFile(value) ? parseVsCodeThemeFile(value) : parseThemeFile(value),
260+
theme: parseThemeImport(await file.text()),
263261
});
264262
} catch (cause) {
265263
failures.push(
@@ -397,10 +395,7 @@ function ThemeImportBody({
397395
return;
398396
}
399397
try {
400-
const parsed: unknown = JSON.parse(json);
401-
const theme = isVsCodeThemeFile(parsed)
402-
? parseVsCodeThemeFile(parsed)
403-
: parseThemeFile(parsed);
398+
const theme = parseThemeImport(json);
404399
if (getCustomThemes().some((existing) => existing.id === theme.id)) {
405400
setError(null);
406401
setConflicts([theme]);

‎apps/web/src/vscodeThemeImport.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@ import { describe, expect, it } from "vite-plus/test";
22

33
import {
44
getThemeColorsForMode,
5+
parseThemeFile,
56
themeColorToHex,
67
THEME_FILE_VERSION,
78
toCanonicalThemeColor,
89
} from "./themePalette";
910
import {
1011
isVsCodeThemeFile,
1112
pairVsCodeThemes,
13+
parseThemeImport,
1214
parseVsCodeThemeFile,
1315
resolveThemeLabelCollisions,
1416
} from "./vscodeThemeImport";
@@ -63,6 +65,59 @@ const VSCODE_DARK = {
6365
tokenColors: [],
6466
};
6567

68+
describe("theme import text", () => {
69+
it("preserves conversion of ordinary VS Code JSON", () => {
70+
expect(parseThemeImport(JSON.stringify(VSCODE_DARK))).toEqual(
71+
parseVsCodeThemeFile(VSCODE_DARK),
72+
);
73+
});
74+
75+
it.each([
76+
'{ // line comment\n "name": "Test", "colors": { "editor.background": "#002b36" } }',
77+
'{ /* block comment */ "name": "Test", "colors": { "editor.background": "#002b36" } }',
78+
'{ "name": "Test", "colors": { "editor.background": "#002b36", }, "tokenColors": [ { "scope": ["comment",], "settings": {}, }, ], }',
79+
])("imports VS Code JSONC without changing conversion: %s", (source) => {
80+
const theme = parseThemeImport(source);
81+
expect(theme.label).toBe("Test");
82+
expect(theme.appearance).toBe("dark");
83+
expect(asHex(theme.colors.canvas)).toBe("#002b36");
84+
});
85+
86+
it.each([
87+
"",
88+
'{ "name": "Test", "colors": { "editor.background": "#002b36" }',
89+
'{ "name": "Test" "colors": { "editor.background": "#002b36" } }',
90+
'{ "name": "Test", "colors": { "editor.background": "#002b36" } } /* unterminated',
91+
'{ "name": "Test", "colors": { "editor.background": "#002b36" } } extra',
92+
])("rejects malformed input rather than using parser recovery: %s", (source) => {
93+
expect(() => parseThemeImport(source)).toThrow("That theme file is not valid JSON.");
94+
});
95+
96+
it("preserves native T3 theme parsing and strict JSON syntax", () => {
97+
const nativeTheme = {
98+
version: THEME_FILE_VERSION,
99+
name: "Native theme",
100+
appearance: "dark",
101+
colors: { canvas: "#002b36" },
102+
};
103+
const source = JSON.stringify(nativeTheme);
104+
expect(parseThemeImport(source)).toEqual(parseThemeFile(nativeTheme));
105+
expect(() => parseThemeImport(source.replace("{", "{ /* native theme */"))).toThrow();
106+
expect(() => parseThemeImport(source.slice(0, -1) + ",}")).toThrow();
107+
});
108+
109+
it("still validates theme structure after parsing JSONC", () => {
110+
expect(() =>
111+
parseThemeImport('{ /* not a theme */ "colors": { "editor.foreground": "#fff" } }'),
112+
).toThrow('no "editor.background"');
113+
expect(() =>
114+
parseThemeImport(
115+
'{ "version": 1, "name": "Bad native", "appearance": "dark", "colors": { "unknown": "#fff" } }',
116+
),
117+
).toThrow('"unknown" is not a supported theme color role.');
118+
});
119+
});
120+
66121
describe("VS Code theme import", () => {
67122
it("recognises workbench themes and rejects our own files", () => {
68123
expect(isVsCodeThemeFile(VSCODE_DARK)).toBe(true);

‎apps/web/src/vscodeThemeImport.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { parse, type ParseError } from "jsonc-parser";
2+
13
import {
24
createVividThemeColors,
35
getStandardThemeColors,
@@ -133,6 +135,15 @@ export function isVsCodeThemeFile(value: unknown): boolean {
133135
return hasWorkbenchColors || Array.isArray(value.tokenColors);
134136
}
135137

138+
export function parseThemeImport(source: string): ThemeDefinition {
139+
const errors: ParseError[] = [];
140+
const value: unknown = parse(source, errors, { allowTrailingComma: true });
141+
if (errors.length > 0) throw new Error("That theme file is not valid JSON.");
142+
return isVsCodeThemeFile(value)
143+
? parseVsCodeThemeFile(value)
144+
: parseThemeFile(JSON.parse(source));
145+
}
146+
136147
function resolveAppearance(value: Record<string, unknown>, canvas: VsCodeRgb): ThemeAppearance {
137148
const type = typeof value.type === "string" ? value.type.toLowerCase() : null;
138149
if (type === "light" || type === "hc-light") return "light";

0 commit comments

Comments
 (0)