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

vscodeThemeImport.ts

454 lines17.9 KB

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