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

vscodeThemeImport.ts

449 lines17.7 KB

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