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

vscodeThemeImport.ts

476 lines17.4 KB

1import {
2 createVividThemeColors,
3 getStandardThemeColors,
4 getThemeModes,
5 isReservedThemeId,
6 parseThemeFile,
7 readableThemeColorOn,
8 themeColorToHex,
9 themeIdFromName,
10 THEME_FILE_VERSION,
11 type ThemeAppearance,
12 type ThemeColorRole,
13 type ThemeDefinition,
14} from "./themePalette";
15​
16type VsCodeRgba = { r: number; g: number; b: number; a: number };
17type VsCodeRgb = { r: number; g: number; b: number };
18​
19function isRecord(value: unknown): value is Record<string, unknown> {
20 return typeof value === "object" && value !== null && !Array.isArray(value);
22​
23function decodeGamma(value: number): number {
24 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
26​
27function encodeGamma(value: number): number {
28 const clamped = Math.max(0, Math.min(1, value));
29 return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;
31​
32function parseColorFunction(value: string): VsCodeRgba | null {
33 const match = /^color\(\s*(display-p3|srgb)\s+([^)]+)\)$/i.exec(value);
34 if (!match) return null;
35 const [space, body] = [match[1]!.toLowerCase(), match[2]!];
36 const [channelPart, alphaPart] = body.split("/");
37 const channels = channelPart!
38 .trim()
39 .split(/\s+/)
40 .map((part) => (part.endsWith("%") ? Number.parseFloat(part) / 100 : Number.parseFloat(part)));
41 if (channels.length !== 3 || channels.some((channel) => !Number.isFinite(channel))) return null;
42 const alphaRaw = alphaPart?.trim();
43 const alpha =
44 alphaRaw === undefined
45 ? 1
46 : alphaRaw.endsWith("%")
47 ? Number.parseFloat(alphaRaw) / 100
48 : Number.parseFloat(alphaRaw);
49 if (!Number.isFinite(alpha)) return null;
50​
51 const [red, green, blue] = channels as [number, number, number];
52 if (space === "srgb") {
53 return { r: red * 255, g: green * 255, b: blue * 255, a: Math.max(0, Math.min(1, alpha)) };
54 }
55 const [linearRed, linearGreen, linearBlue] = [red, green, blue].map(decodeGamma) as [
56 number,
57 number,
58 number,
59 ];
60 const srgb = [
61 1.2249401762805 * linearRed - 0.2249401762805 * linearGreen,
62 -0.042056961239 * linearRed + 1.042056961239 * linearGreen,
63 -0.0196375547643 * linearRed - 0.0786360655012 * linearGreen + 1.0982736202656 * linearBlue,
64 ].map((channel) => encodeGamma(channel) * 255) as [number, number, number];
65 return { r: srgb[0], g: srgb[1], b: srgb[2], a: Math.max(0, Math.min(1, alpha)) };
67​
68function parseVsCodeColor(value: unknown): VsCodeRgba | null {
69 if (typeof value !== "string") return null;
70 const trimmed = value.trim();
71 if (trimmed.startsWith("color(")) return parseColorFunction(trimmed);
72 const hex = trimmed.replace(/^#/, "");
73 if (!/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;
74 const expand = (part: string) =>
75 part.length === 1 ? Number.parseInt(part + part, 16) : Number.parseInt(part, 16);
76 if (hex.length <= 4) {
77 return {
78 r: expand(hex[0]!),
79 g: expand(hex[1]!),
80 b: expand(hex[2]!),
81 a: hex.length === 4 ? expand(hex[3]!) / 255 : 1,
82 };
83 }
84 return {
85 r: Number.parseInt(hex.slice(0, 2), 16),
86 g: Number.parseInt(hex.slice(2, 4), 16),
87 b: Number.parseInt(hex.slice(4, 6), 16),
88 a: hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1,
89 };
91​
92function toHex(color: VsCodeRgb): string {
93 const channel = (value: number) =>
94 Math.max(0, Math.min(255, Math.round(value)))
95 .toString(16)
96 .padStart(2, "0");
97 return `#${channel(color.r)}${channel(color.g)}${channel(color.b)}`;
99​
100// Composite VS Code translucent overlays onto their surfaces; our roles are opaque.
101function flattenOver(color: VsCodeRgba, base: VsCodeRgb): string {
102 if (color.a >= 1) return toHex(color);
103 return toHex({
104 r: color.r * color.a + base.r * (1 - color.a),
105 g: color.g * color.a + base.g * (1 - color.a),
106 b: color.b * color.a + base.b * (1 - color.a),
107 });
109​
110function relativeLuminance(color: VsCodeRgb): number {
111 const channel = (value: number) => {
112 const ratio = value / 255;
113 return ratio <= 0.03928 ? ratio / 12.92 : ((ratio + 0.055) / 1.055) ** 2.4;
114 };
115 return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
117​
118function contrastRatio(first: VsCodeRgb, second: VsCodeRgb): number {
119 const a = relativeLuminance(first);
120 const b = relativeLuminance(second);
121 return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
123​
124function hexToRgb(value: string): VsCodeRgb {
125 return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
127​
128export function isVsCodeThemeFile(value: unknown): boolean {
129 if (!isRecord(value)) return false;
130 if (value.version === THEME_FILE_VERSION) return false;
131 const hasWorkbenchColors =
132 isRecord(value.colors) && Object.keys(value.colors).some((key) => key.includes("."));
133 return hasWorkbenchColors || Array.isArray(value.tokenColors);
135​
136function resolveAppearance(value: Record<string, unknown>, canvas: VsCodeRgb): ThemeAppearance {
137 const type = typeof value.type === "string" ? value.type.toLowerCase() : null;
138 if (type === "light" || type === "hc-light") return "light";
139 if (type === "dark" || type === "hc-black") return "dark";
140 return relativeLuminance(canvas) < 0.179 ? "dark" : "light";
142​
143export function humanizeThemeName(raw: string): string {
144 const trimmed = raw.trim();
145 if (/\s/.test(trimmed) || !/[-_.]/.test(trimmed)) return trimmed;
146 return trimmed
147 .split(/[-_.]+/)
148 .filter(Boolean)
149 .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
150 .join(" ");
152​
153function resolveName(value: Record<string, unknown>): string {
154 for (const candidate of [value.displayName, value.name]) {
155 if (typeof candidate !== "string") continue;
156 const humanized = humanizeThemeName(candidate);
157 if (humanized.length > 0) return humanized.slice(0, 48);
158 }
159 return "VS Code theme";
161​
162export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
163 if (!isRecord(value)) throw new Error("Theme files must contain a JSON object.");
164 const colors = isRecord(value.colors) ? value.colors : {};
165​
166 const pick = (...keys: ReadonlyArray<string>): VsCodeRgba | null => {
167 for (const key of keys) {
168 const parsed = parseVsCodeColor(colors[key]);
169 if (parsed) return parsed;
170 }
171 return null;
172 };
173 const solidOver = (base: VsCodeRgb, ...keys: ReadonlyArray<string>): string | null => {
174 const parsed = pick(...keys);
175 return parsed ? flattenOver(parsed, base) : null;
176 };
177​
178 const canvasColor = pick("editor.background", "editorPane.background");
179 if (!canvasColor) {
180 throw new Error(
181 'That VS Code theme has no "editor.background" color, so there is nothing to build a palette from.',
182 );
183 }
184 const canvas = { r: canvasColor.r, g: canvasColor.g, b: canvasColor.b };
185 const appearance = resolveAppearance(value, canvas);
186​
187 const canvasHex = toHex(canvas);
188 const raisedSurfaceCandidateHex = solidOver(
189 canvas,
190 "editorWidget.background",
191 "dropdown.background",
192 );
193​
194 const standsApart = (first: string, second: string) =>
195 contrastRatio(hexToRgb(first), hexToRgb(second)) >= 1.1;
196​
197 let accentColor: VsCodeRgba | null = null;
198 let accentHex: string | null = null;
199 for (const key of [
200 "focusBorder",
201 "button.background",
202 "textLink.foreground",
203 "activityBarBadge.background",
204 "progressBar.background",
205 "badge.background",
206 ]) {
207 const candidate = parseVsCodeColor(colors[key]);
208 if (!candidate) continue;
209 const candidateHex = flattenOver(candidate, canvas);
210 if (
211 !standsApart(candidateHex, canvasHex) ||
212 (raisedSurfaceCandidateHex !== null && !standsApart(candidateHex, raisedSurfaceCandidateHex))
213 )
214 continue;
215 accentColor = candidate;
216 accentHex = candidateHex;
217 break;
218 }
219 if (!accentColor || !accentHex) {
220 const standardAccentHex = themeColorToHex(getStandardThemeColors(appearance).accent)!;
221 accentHex =
222 [standardAccentHex, "#ffffff", "#000000"].find(
223 (candidate) =>
224 standsApart(candidate, canvasHex) &&
225 (raisedSurfaceCandidateHex === null || standsApart(candidate, raisedSurfaceCandidateHex)),
226 ) ?? standardAccentHex;
227 accentColor = parseVsCodeColor(accentHex)!;
228 }
229​
230 const mutedAccentHex = flattenOver(
231 { r: accentColor.r, g: accentColor.g, b: accentColor.b, a: 0.2 },
232 canvas,
233 );
234 const derived = createVividThemeColors(appearance, canvasHex, mutedAccentHex);
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 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 if (isReadable(fallback)) return fallback;
252 return relativeLuminance(surfaceRgb) < 0.179 ? "#ffffff" : "#000000";
253 };
254 // Status colors also fill controls such as destructive buttons, which carry
255 // white text, so a dim one is lightened along its hue rather than replaced
256 // by readableOn's black or white. One hidden in the canvas has no hue to
257 // keep, so the derived color stands in.
258 const readableStatusColor = (fallback: string, ...keys: ReadonlyArray<string>): string => {
259 const specified = solidOver(canvas, ...keys);
260 const base = specified && standsApart(specified, canvasHex) ? specified : fallback;
261 return readableThemeColorOn(base, canvasHex, 4.5);
262 };
263​
264 const surfaceRaisedHex = raisedSurfaceCandidateHex ?? derived.surfaceRaised;
265 // Checked tracks use messageAction; resolve it before the unchecked input role.
266 const buttonHex = solidOver(canvas, "button.background");
267 const actionHex =
268 buttonHex && standsApart(buttonHex, canvasHex) && standsApart(buttonHex, surfaceRaisedHex)
269 ? buttonHex
270 : accentHex;
271 const inputCandidates = [
272 derived.input,
273 derived.surfaceRaised,
274 getStandardThemeColors(appearance).input,
275 "#000000",
276 "#ffffff",
277 "#808080",
278 ];
279 let inputHex =
280 inputCandidates.find(
281 (candidate) => standsApart(candidate, canvasHex) && standsApart(candidate, actionHex),
282 ) ?? "#808080";
283 for (const key of ["input.background", "input.border"]) {
284 const candidate = solidOver(canvas, key);
285 if (candidate && standsApart(candidate, canvasHex) && standsApart(candidate, actionHex)) {
286 inputHex = candidate;
287 break;
288 }
289 }
290 const searchMatchBackground =
291 solidOver(canvas, "editor.findMatchHighlightBackground") ?? derived.searchMatchBackground;
292 const searchMatchActiveBackground =
293 solidOver(canvas, "editor.findMatchBackground") ?? derived.searchMatchActiveBackground;
294​
295 const overrides: Partial<Record<ThemeColorRole, string>> = {
296 canvas: canvasHex,
297 text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
298 textMuted: readableOn(
299 canvasHex,
300 derived.textMuted,
301 "descriptionForeground",
302 "disabledForeground",
303 ),
304 surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
305 surfaceRaised: surfaceRaisedHex,
306 surfaceOverlay:
307 solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
308 derived.surfaceOverlay,
309 border:
310 solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
311 input: inputHex,
312 placeholder: readableOn(surfaceRaisedHex, derived.placeholder, "input.placeholderForeground"),
313 error: readableStatusColor(derived.error, "editorError.foreground", "errorForeground"),
314 warning: readableStatusColor(derived.warning, "editorWarning.foreground"),
315 accentSurface:
316 solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
317 derived.accentSurface,
318 codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
319 searchMatchBackground,
320 searchMatchForeground: readableOn(
321 searchMatchBackground,
322 derived.searchMatchForeground,
323 "editor.findMatchHighlightForeground",
324 "editor.foreground",
325 "foreground",
326 ),
327 searchMatchActiveBackground,
328 searchMatchActiveForeground: readableOn(
329 searchMatchActiveBackground,
330 derived.searchMatchActiveForeground,
331 "editor.findMatchForeground",
332 "editor.foreground",
333 "foreground",
334 ),
335 sidebar: sidebarHex,
336 sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
337 sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
338 sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
339 sidebarRowActive:
340 solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
341 derived.sidebarRowActive,
342 sidebarRowSelected:
343 solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
344 terminalBackground: terminalHex,
345 terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
346 terminalCursor:
347 solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
348 derived.terminalCursor,
349 terminalSelection:
350 solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
351 derived.terminalSelection,
352 terminalScrollbar:
353 solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
354 };
355 overrides.accent = accentHex;
356 overrides.focus = accentHex;
357 overrides.messageAction = actionHex;
358 overrides.messageActionForeground = readableOn(
359 actionHex,
360 derived.messageActionForeground,
361 "button.foreground",
362 );
363 overrides.accentForeground = readableOn(accentHex, derived.accentForeground, "button.foreground");
364​
365 const name = resolveName(value);
366 const generatedId = themeIdFromName(name);
367 return parseThemeFile({
368 version: THEME_FILE_VERSION,
369 ...(isReservedThemeId(generatedId) ? { id: `${generatedId}-vscode` } : {}),
370 name,
371 appearance,
372 colors: { ...derived, ...overrides },
373 });
375​
376export function pairVsCodeThemes(
377 themes: ReadonlyArray<ThemeDefinition>,
378 options?: {
379 pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
380 },
381): ReadonlyArray<ThemeDefinition> {
382 const stripAppearance = (label: string) =>
383 label
384 .replace(/\b(?:light|dark)\b/gi, " ")
385 .replace(/\s+/g, " ")
386 .trim();
387​
388 type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
389 const groups = new Map<string, Group>();
390 const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
391 themes.forEach((theme, order) => {
392 const key = stripAppearance(theme.label);
393 if (getThemeModes(theme).length !== 1 || key === theme.label || !/[a-z0-9]/i.test(key)) {
394 passthrough.push({ theme, order });
395 return;
396 }
397 const group = groups.get(key) ?? { light: [], dark: [], order };
398 group[theme.appearance].push(theme);
399 groups.set(key, group);
400 });
401​
402 const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
403 for (const [key, group] of groups) {
404 if (group.light.length === 1 && group.dark.length === 1) {
405 try {
406 paired.push({
407 order: group.order,
408 theme: parseThemeFile({
409 version: THEME_FILE_VERSION,
410 ...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),
411 name: key,
412 appearance: "light",
413 colors: group.light[0]!.colors,
414 variants: { dark: group.dark[0]!.colors },
415 }),
416 });
417 continue;
418 } catch {}
419 }
420 for (const theme of [...group.light, ...group.dark]) {
421 paired.push({ theme, order: group.order });
422 }
423 }
424​
425 return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
427​
428export function resolveThemeLabelCollisions(
429 entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
430): ReadonlyArray<ThemeDefinition> {
431 const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
432 try {
433 return parseThemeFile({
434 version: THEME_FILE_VERSION,
435 name: name.slice(0, 48),
436 appearance: theme.appearance,
437 colors: theme.colors,
438 ...(theme.variants ? { variants: theme.variants } : {}),
439 ...(theme.managed ? { managed: true } : {}),
440 });
441 } catch {
442 return null;
443 }
444 };
445​
446 const counts = new Map<string, number>();
447 for (const entry of entries) {
448 counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
449 }
450 const relabelled = entries.map(({ theme, sourceName }) => {
451 if ((counts.get(theme.id) ?? 0) < 2) return theme;
452 const stem = sourceName?.replace(/\.[^.]+$/, "");
453 const fromFile = stem ? humanizeThemeName(stem) : null;
454 const renamed =
455 fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
456 ? rename(theme, fromFile)
457 : null;
458 return renamed ?? theme;
459 });
460​
461 const seen = new Set<string>();
462 return relabelled.map((theme) => {
463 if (!seen.has(theme.id)) {
464 seen.add(theme.id);
465 return theme;
466 }
467 for (let suffix = 2; suffix < 100; suffix += 1) {
468 const candidate = rename(theme, `${theme.label} ${suffix}`);
469 if (candidate && !seen.has(candidate.id)) {
470 seen.add(candidate.id);
471 return candidate;
472 }
473 }
474 return theme;
475 });