Open History to see the last commit
1import {
2 createVividThemeColors,
3 getThemeModes,
4 isReservedThemeId,
5 parseThemeFile,
6 themeColorToHex,
7 themeIdFromName,
8 THEME_FILE_VERSION,
9 type ThemeAppearance,
10 type ThemeColorRole,
11 type ThemeDefinition,
12} from "./themePalette";
13
14/**
15 * Best-effort import of a VS Code color theme (`*-color-theme.json`).
16 *
17 * VS Code themes describe editor chrome, not an app palette: they carry a few
18 * hundred workbench keys, leave most of them unset, and freely use 8-digit
19 * hex with alpha for overlays. So the conversion derives a complete, contrast
20 * -solved palette from the theme's editor background and accent, then layers
21 * the workbench colors it did specify on top. Anything the file omits keeps
22 * the derived value instead of falling back to an unrelated palette.
23 */
24
25type VsCodeRgba = { r: number; g: number; b: number; a: number };
26type VsCodeRgb = { r: number; g: number; b: number };
27
28function isRecord(value: unknown): value is Record<string, unknown> {
29 return typeof value === "object" && value !== null && !Array.isArray(value);
30}
31
32/** sRGB transfer function, and its inverse, shared by the wide-gamut path. */
33function decodeGamma(value: number): number {
34 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
35}
36
37function encodeGamma(value: number): number {
38 const clamped = Math.max(0, Math.min(1, value));
39 return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;
40}
41
42/**
43 * `color(display-p3 r g b / a)` shows up in themes authored for wide-gamut
44 * displays. Out-of-gamut colors clip to the sRGB edge, which is what a browser
45 * on an sRGB screen shows anyway.
46 */
47function parseColorFunction(value: string): VsCodeRgba | null {
48 const match = /^color\(\s*(display-p3|srgb)\s+([^)]+)\)$/i.exec(value);
49 if (!match) return null;
50 const [space, body] = [match[1]!.toLowerCase(), match[2]!];
51 const [channelPart, alphaPart] = body.split("/");
52 const channels = channelPart!
53 .trim()
54 .split(/\s+/)
55 .map((part) => (part.endsWith("%") ? Number.parseFloat(part) / 100 : Number.parseFloat(part)));
56 if (channels.length !== 3 || channels.some((channel) => !Number.isFinite(channel))) return null;
57 const alphaRaw = alphaPart?.trim();
58 const alpha =
59 alphaRaw === undefined
60 ? 1
61 : alphaRaw.endsWith("%")
62 ? Number.parseFloat(alphaRaw) / 100
63 : Number.parseFloat(alphaRaw);
64 if (!Number.isFinite(alpha)) return null;
65
66 const [red, green, blue] = channels as [number, number, number];
67 if (space === "srgb") {
68 return { r: red * 255, g: green * 255, b: blue * 255, a: Math.max(0, Math.min(1, alpha)) };
69 }
70 const [linearRed, linearGreen, linearBlue] = [red, green, blue].map(decodeGamma) as [
71 number,
72 number,
73 number,
74 ];
75 // Display P3 linear -> sRGB linear.
76 const srgb = [
77 1.2249401762805 * linearRed - 0.2249401762805 * linearGreen,
78 -0.042056961239 * linearRed + 1.042056961239 * linearGreen,
79 -0.0196375547643 * linearRed - 0.0786360655012 * linearGreen + 1.0982736202656 * linearBlue,
80 ].map((channel) => encodeGamma(channel) * 255) as [number, number, number];
81 return { r: srgb[0], g: srgb[1], b: srgb[2], a: Math.max(0, Math.min(1, alpha)) };
82}
83
84/** VS Code accepts #RGB, #RGBA, #RRGGBB, and #RRGGBBAA; some themes also use
85 * CSS color() notation for wide-gamut palettes. */
86function parseVsCodeColor(value: unknown): VsCodeRgba | null {
87 if (typeof value !== "string") return null;
88 const trimmed = value.trim();
89 if (trimmed.startsWith("color(")) return parseColorFunction(trimmed);
90 const hex = trimmed.replace(/^#/, "");
91 if (!/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;
92 const expand = (part: string) =>
93 part.length === 1 ? Number.parseInt(part + part, 16) : Number.parseInt(part, 16);
94 if (hex.length <= 4) {
95 return {
96 r: expand(hex[0]!),
97 g: expand(hex[1]!),
98 b: expand(hex[2]!),
99 a: hex.length === 4 ? expand(hex[3]!) / 255 : 1,
100 };
101 }
102 return {
103 r: Number.parseInt(hex.slice(0, 2), 16),
104 g: Number.parseInt(hex.slice(2, 4), 16),
105 b: Number.parseInt(hex.slice(4, 6), 16),
106 a: hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1,
107 };
108}
109
110function toHex(color: VsCodeRgb): string {
111 const channel = (value: number) =>
112 Math.max(0, Math.min(255, Math.round(value)))
113 .toString(16)
114 .padStart(2, "0");
115 return `#${channel(color.r)}${channel(color.g)}${channel(color.b)}`;
116}
117
118/** Overlays are semi-transparent in VS Code; our roles are opaque, so they are
119 * composited onto whatever surface they sit on. */
120function flattenOver(color: VsCodeRgba, base: VsCodeRgb): string {
121 if (color.a >= 1) return toHex(color);
122 return toHex({
123 r: color.r * color.a + base.r * (1 - color.a),
124 g: color.g * color.a + base.g * (1 - color.a),
125 b: color.b * color.a + base.b * (1 - color.a),
126 });
127}
128
129function relativeLuminance(color: VsCodeRgb): number {
130 const channel = (value: number) => {
131 const ratio = value / 255;
132 return ratio <= 0.03928 ? ratio / 12.92 : ((ratio + 0.055) / 1.055) ** 2.4;
133 };
134 return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
135}
136
137function contrastRatio(first: VsCodeRgb, second: VsCodeRgb): number {
138 const a = relativeLuminance(first);
139 const b = relativeLuminance(second);
140 return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
141}
142
143function hexToRgb(value: string): VsCodeRgb {
144 return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
145}
146
147/**
148 * A VS Code theme is recognised by its workbench colors: the keys are dotted
149 * paths (`editor.background`), which our own files never use.
150 */
151export function isVsCodeThemeFile(value: unknown): boolean {
152 if (!isRecord(value)) return false;
153 if (value.version === THEME_FILE_VERSION) return false;
154 const hasWorkbenchColors =
155 isRecord(value.colors) && Object.keys(value.colors).some((key) => key.includes("."));
156 return hasWorkbenchColors || Array.isArray(value.tokenColors);
157}
158
159function resolveAppearance(value: Record<string, unknown>, canvas: VsCodeRgb): ThemeAppearance {
160 const type = typeof value.type === "string" ? value.type.toLowerCase() : null;
161 if (type === "light" || type === "hc-light") return "light";
162 if (type === "dark" || type === "hc-black") return "dark";
163 // Unlabelled themes (and the odd custom `type`) follow the editor surface.
164 return relativeLuminance(canvas) < 0.179 ? "dark" : "light";
165}
166
167/** Extension `name` fields are often package slugs; read them as words. */
168export function humanizeThemeName(raw: string): string {
169 const trimmed = raw.trim();
170 if (/\s/.test(trimmed) || !/[-_.]/.test(trimmed)) return trimmed;
171 return trimmed
172 .split(/[-_.]+/)
173 .filter(Boolean)
174 .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
175 .join(" ");
176}
177
178function resolveName(value: Record<string, unknown>): string {
179 // Judge candidates by their humanized form: a displayName of "---"
180 // humanizes to nothing and must fall through to the name.
181 for (const candidate of [value.displayName, value.name]) {
182 if (typeof candidate !== "string") continue;
183 const humanized = humanizeThemeName(candidate);
184 if (humanized.length > 0) return humanized.slice(0, 48);
185 }
186 return "VS Code theme";
187}
188
189export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
190 if (!isRecord(value)) throw new Error("Theme files must contain a JSON object.");
191 const colors = isRecord(value.colors) ? value.colors : {};
192
193 /** First key that carries a usable color, in priority order. */
194 const pick = (...keys: ReadonlyArray<string>): VsCodeRgba | null => {
195 for (const key of keys) {
196 const parsed = parseVsCodeColor(colors[key]);
197 if (parsed) return parsed;
198 }
199 return null;
200 };
201 const solidOver = (base: VsCodeRgb, ...keys: ReadonlyArray<string>): string | null => {
202 const parsed = pick(...keys);
203 return parsed ? flattenOver(parsed, base) : null;
204 };
205
206 const canvasColor = pick("editor.background", "editorPane.background");
207 if (!canvasColor) {
208 throw new Error(
209 'That VS Code theme has no "editor.background" color, so there is nothing to build a palette from.',
210 );
211 }
212 const canvas = { r: canvasColor.r, g: canvasColor.g, b: canvasColor.b };
213 const appearance = resolveAppearance(value, canvas);
214
215 const accentColor = pick(
216 "focusBorder",
217 "button.background",
218 "textLink.foreground",
219 "activityBarBadge.background",
220 "progressBar.background",
221 "badge.background",
222 );
223 const canvasHex = toHex(canvas);
224 const accentHex = accentColor ? flattenOver(accentColor, canvas) : null;
225
226 // The derived palette is the floor: every role starts contrast-solved, then
227 // the theme's own workbench colors replace what it actually specified. The
228 // floor derives from a muted accent -- the vivid engine carries the accent
229 // hue into every surface, which washes an imported neutral palette (a gray
230 // theme with a blue focusBorder would get blue code and text surfaces).
231 const mutedAccentHex = accentColor
232 ? flattenOver({ r: accentColor.r, g: accentColor.g, b: accentColor.b, a: 0.2 }, canvas)
233 : null;
234 const derived = createVividThemeColors(appearance, canvasHex, mutedAccentHex ?? canvasHex);
235 const sidebarHex =
236 solidOver(canvas, "sideBar.background", "activityBar.background") ?? derived.sidebar;
237 const sidebar = hexToRgb(sidebarHex);
238 const terminalHex =
239 solidOver(canvas, "terminal.background", "panel.background") ?? derived.terminalBackground;
240 const terminal = hexToRgb(terminalHex);
241
242 /** Foregrounds only win when they stay readable on the surface they land on;
243 * a theme tuned for its own chrome can be unreadable on ours. */
244 const readableOn = (
245 surface: string,
246 fallback: string,
247 ...keys: ReadonlyArray<string>
248 ): string => {
249 const surfaceRgb = hexToRgb(surface);
250 const isReadable = (candidate: string) => contrastRatio(hexToRgb(candidate), surfaceRgb) >= 4.5;
251 const specified = solidOver(surfaceRgb, ...keys);
252 if (specified && isReadable(specified)) return specified;
253 // The derived fallback was solved against the derived surface. When the
254 // file replaced that surface (a light sideBar in a dark theme, say), the
255 // fallback has to clear the bar there too, or the text falls back to the
256 // readable end of the greyscale for the surface actually in play.
257 if (isReadable(fallback)) return fallback;
258 return relativeLuminance(surfaceRgb) < 0.179 ? "#ffffff" : "#000000";
259 };
260
261 const overrides: Partial<Record<ThemeColorRole, string>> = {
262 canvas: canvasHex,
263 text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
264 textMuted: readableOn(
265 canvasHex,
266 derived.textMuted,
267 "descriptionForeground",
268 "disabledForeground",
269 ),
270 surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
271 surfaceRaised:
272 solidOver(canvas, "editorWidget.background", "dropdown.background") ?? derived.surfaceRaised,
273 surfaceOverlay:
274 solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
275 derived.surfaceOverlay,
276 border:
277 solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
278 input: solidOver(canvas, "input.border", "dropdown.border") ?? derived.input,
279 placeholder: readableOn(canvasHex, derived.placeholder, "input.placeholderForeground"),
280 error: readableOn(canvasHex, derived.error, "editorError.foreground", "errorForeground"),
281 warning: readableOn(canvasHex, derived.warning, "editorWarning.foreground"),
282 accentSurface:
283 solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
284 derived.accentSurface,
285 codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
286 sidebar: sidebarHex,
287 sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
288 sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
289 sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
290 sidebarRowActive:
291 solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
292 derived.sidebarRowActive,
293 sidebarRowSelected:
294 solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
295 terminalBackground: terminalHex,
296 terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
297 terminalCursor:
298 solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
299 derived.terminalCursor,
300 terminalSelection:
301 solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
302 derived.terminalSelection,
303 terminalScrollbar:
304 solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
305 };
306 if (accentHex) {
307 overrides.accent = accentHex;
308 overrides.focus = accentHex;
309 // The button pair is the closest thing VS Code has to our action color.
310 const actionHex = solidOver(canvas, "button.background") ?? accentHex;
311 overrides.messageAction = actionHex;
312 overrides.messageActionForeground = readableOn(
313 actionHex,
314 derived.messageActionForeground,
315 "button.foreground",
316 );
317 overrides.accentForeground = readableOn(
318 accentHex,
319 derived.accentForeground,
320 "button.foreground",
321 );
322 }
323
324 // Reuse the theme-file parser so ids, names, and color values go through the
325 // same validation as a hand-written file.
326 const name = resolveName(value);
327 const generatedId = themeIdFromName(name);
328 return parseThemeFile({
329 version: THEME_FILE_VERSION,
330 ...(isReservedThemeId(generatedId) ? { id: `${generatedId}-vscode` } : {}),
331 name,
332 appearance,
333 colors: { ...derived, ...overrides },
334 });
335}
336
337/**
338 * Extensions ship a family of themes (GitHub: dark, light, dark-colorblind,
339 * light-colorblind, dark-dimmed, ...). When several are imported together,
340 * a light and a dark file whose names differ only by the appearance word
341 * become one dual-mode theme; everything else stays its own theme.
342 */
343export function pairVsCodeThemes(
344 themes: ReadonlyArray<ThemeDefinition>,
345 options?: {
346 pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
347 },
348): ReadonlyArray<ThemeDefinition> {
349 const stripAppearance = (label: string) =>
350 label
351 .replace(/\b(?:light|dark)\b/gi, " ")
352 .replace(/\s+/g, " ")
353 .trim();
354
355 type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
356 const groups = new Map<string, Group>();
357 const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
358 themes.forEach((theme, order) => {
359 // Only single-appearance themes with an appearance word in the name can
360 // pair, and only when the rest of the name can still identify the pair
361 // ("Dark+" and "Light+" would pair as "+"); anything else is already
362 // what the user asked for.
363 const key = stripAppearance(theme.label);
364 if (getThemeModes(theme).length !== 1 || key === theme.label || !/[a-z0-9]/i.test(key)) {
365 passthrough.push({ theme, order });
366 return;
367 }
368 const group = groups.get(key) ?? { light: [], dark: [], order };
369 group[theme.appearance].push(theme);
370 groups.set(key, group);
371 });
372
373 const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
374 for (const [key, group] of groups) {
375 // Ambiguity (two darks for one light) is not guessed at, and a pair
376 // whose stripped name collides with a built-in id ("Grove Light" +
377 // "Grove Dark" -> the reserved "grove") stays two single themes rather
378 // than failing the whole batch.
379 if (group.light.length === 1 && group.dark.length === 1) {
380 try {
381 paired.push({
382 order: group.order,
383 theme: parseThemeFile({
384 version: THEME_FILE_VERSION,
385 ...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),
386 name: key,
387 appearance: "light",
388 colors: group.light[0]!.colors,
389 variants: { dark: group.dark[0]!.colors },
390 }),
391 });
392 continue;
393 } catch {
394 // Fall through to the individual themes below.
395 }
396 }
397 for (const theme of [...group.light, ...group.dark]) {
398 paired.push({ theme, order: group.order });
399 }
400 }
401
402 return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
403}
404
405/**
406 * Some extensions reuse one display name across every file: Dracula ships
407 * dracula.json and dracula-soft.json that both say "Dracula". When a batch
408 * carries the same id twice, the file names are the only thing that tells
409 * the variants apart, so colliding entries are relabelled from their file
410 * name (and numbered only when even that collides).
411 */
412export function resolveThemeLabelCollisions(
413 entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
414): ReadonlyArray<ThemeDefinition> {
415 // Null when the new name is unusable (reserved id, invalid characters).
416 const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
417 try {
418 return parseThemeFile({
419 version: THEME_FILE_VERSION,
420 name: name.slice(0, 48),
421 appearance: theme.appearance,
422 colors: theme.colors,
423 ...(theme.variants ? { variants: theme.variants } : {}),
424 ...(theme.managed ? { managed: true } : {}),
425 });
426 } catch {
427 return null;
428 }
429 };
430
431 const counts = new Map<string, number>();
432 for (const entry of entries) {
433 counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
434 }
435 const relabelled = entries.map(({ theme, sourceName }) => {
436 if ((counts.get(theme.id) ?? 0) < 2) return theme;
437 const stem = sourceName?.replace(/\.[^.]+$/, "");
438 const fromFile = stem ? humanizeThemeName(stem) : null;
439 const renamed =
440 fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
441 ? rename(theme, fromFile)
442 : null;
443 return renamed ?? theme;
444 });
445
446 const seen = new Set<string>();
447 return relabelled.map((theme) => {
448 if (!seen.has(theme.id)) {
449 seen.add(theme.id);
450 return theme;
451 }
452 for (let suffix = 2; suffix < 100; suffix += 1) {
453 const candidate = rename(theme, `${theme.label} ${suffix}`);
454 if (candidate && !seen.has(candidate.id)) {
455 seen.add(candidate.id);
456 return candidate;
457 }
458 }
459 return theme;
460 });
461}