Open History to see the last commit
1import {
2 createVividThemeColors,
3 getStandardThemeColors,
4 getThemeModes,
5 isReservedThemeId,
6 parseThemeFile,
7 themeColorToHex,
8 themeIdFromName,
9 THEME_FILE_VERSION,
10 type ThemeAppearance,
11 type ThemeColorRole,
12 type ThemeDefinition,
13} from "./themePalette";
14
15type VsCodeRgba = { r: number; g: number; b: number; a: number };
16type VsCodeRgb = { r: number; g: number; b: number };
17
18function isRecord(value: unknown): value is Record<string, unknown> {
19 return typeof value === "object" && value !== null && !Array.isArray(value);
20}
21
22function decodeGamma(value: number): number {
23 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
24}
25
26function encodeGamma(value: number): number {
27 const clamped = Math.max(0, Math.min(1, value));
28 return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;
29}
30
31function parseColorFunction(value: string): VsCodeRgba | null {
32 const match = /^color\(\s*(display-p3|srgb)\s+([^)]+)\)$/i.exec(value);
33 if (!match) return null;
34 const [space, body] = [match[1]!.toLowerCase(), match[2]!];
35 const [channelPart, alphaPart] = body.split("/");
36 const channels = channelPart!
37 .trim()
38 .split(/\s+/)
39 .map((part) => (part.endsWith("%") ? Number.parseFloat(part) / 100 : Number.parseFloat(part)));
40 if (channels.length !== 3 || channels.some((channel) => !Number.isFinite(channel))) return null;
41 const alphaRaw = alphaPart?.trim();
42 const alpha =
43 alphaRaw === undefined
44 ? 1
45 : alphaRaw.endsWith("%")
46 ? Number.parseFloat(alphaRaw) / 100
47 : Number.parseFloat(alphaRaw);
48 if (!Number.isFinite(alpha)) return null;
49
50 const [red, green, blue] = channels as [number, number, number];
51 if (space === "srgb") {
52 return { r: red * 255, g: green * 255, b: blue * 255, a: Math.max(0, Math.min(1, alpha)) };
53 }
54 const [linearRed, linearGreen, linearBlue] = [red, green, blue].map(decodeGamma) as [
55 number,
56 number,
57 number,
58 ];
59 const srgb = [
60 1.2249401762805 * linearRed - 0.2249401762805 * linearGreen,
61 -0.042056961239 * linearRed + 1.042056961239 * linearGreen,
62 -0.0196375547643 * linearRed - 0.0786360655012 * linearGreen + 1.0982736202656 * linearBlue,
63 ].map((channel) => encodeGamma(channel) * 255) as [number, number, number];
64 return { r: srgb[0], g: srgb[1], b: srgb[2], a: Math.max(0, Math.min(1, alpha)) };
65}
66
67function parseVsCodeColor(value: unknown): VsCodeRgba | null {
68 if (typeof value !== "string") return null;
69 const trimmed = value.trim();
70 if (trimmed.startsWith("color(")) return parseColorFunction(trimmed);
71 const hex = trimmed.replace(/^#/, "");
72 if (!/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;
73 const expand = (part: string) =>
74 part.length === 1 ? Number.parseInt(part + part, 16) : Number.parseInt(part, 16);
75 if (hex.length <= 4) {
76 return {
77 r: expand(hex[0]!),
78 g: expand(hex[1]!),
79 b: expand(hex[2]!),
80 a: hex.length === 4 ? expand(hex[3]!) / 255 : 1,
81 };
82 }
83 return {
84 r: Number.parseInt(hex.slice(0, 2), 16),
85 g: Number.parseInt(hex.slice(2, 4), 16),
86 b: Number.parseInt(hex.slice(4, 6), 16),
87 a: hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1,
88 };
89}
90
91function toHex(color: VsCodeRgb): string {
92 const channel = (value: number) =>
93 Math.max(0, Math.min(255, Math.round(value)))
94 .toString(16)
95 .padStart(2, "0");
96 return `#${channel(color.r)}${channel(color.g)}${channel(color.b)}`;
97}
98
99/** Overlays are semi-transparent in VS Code; our roles are opaque, so they are
100 * composited onto whatever surface they sit on. */
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 });
108}
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);
116}
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);
122}
123
124function hexToRgb(value: string): VsCodeRgb {
125 return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
126}
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);
134}
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";
141}
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(" ");
151}
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";
160}
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
255 const surfaceRaisedHex = raisedSurfaceCandidateHex ?? derived.surfaceRaised;
256 // The checked switch track maps to messageAction, so resolve it before
257 // choosing the input role used by the unchecked track.
258 const buttonHex = solidOver(canvas, "button.background");
259 const actionHex =
260 buttonHex && standsApart(buttonHex, canvasHex) && standsApart(buttonHex, surfaceRaisedHex)
261 ? buttonHex
262 : accentHex;
263 const inputCandidates = [
264 derived.input,
265 derived.surfaceRaised,
266 getStandardThemeColors(appearance).input,
267 "#000000",
268 "#ffffff",
269 "#808080",
270 ];
271 let inputHex =
272 inputCandidates.find(
273 (candidate) => standsApart(candidate, canvasHex) && standsApart(candidate, actionHex),
274 ) ?? "#808080";
275 for (const key of ["input.background", "input.border"]) {
276 const candidate = solidOver(canvas, key);
277 if (candidate && standsApart(candidate, canvasHex) && standsApart(candidate, actionHex)) {
278 inputHex = candidate;
279 break;
280 }
281 }
282 const searchMatchBackground =
283 solidOver(canvas, "editor.findMatchHighlightBackground") ?? derived.searchMatchBackground;
284 const searchMatchActiveBackground =
285 solidOver(canvas, "editor.findMatchBackground") ?? derived.searchMatchActiveBackground;
286
287 const overrides: Partial<Record<ThemeColorRole, string>> = {
288 canvas: canvasHex,
289 text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
290 textMuted: readableOn(
291 canvasHex,
292 derived.textMuted,
293 "descriptionForeground",
294 "disabledForeground",
295 ),
296 surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
297 surfaceRaised: surfaceRaisedHex,
298 surfaceOverlay:
299 solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
300 derived.surfaceOverlay,
301 border:
302 solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
303 input: inputHex,
304 placeholder: readableOn(surfaceRaisedHex, derived.placeholder, "input.placeholderForeground"),
305 error: readableOn(canvasHex, derived.error, "editorError.foreground", "errorForeground"),
306 warning: readableOn(canvasHex, derived.warning, "editorWarning.foreground"),
307 accentSurface:
308 solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
309 derived.accentSurface,
310 codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
311 searchMatchBackground,
312 searchMatchForeground: readableOn(
313 searchMatchBackground,
314 derived.searchMatchForeground,
315 "editor.findMatchHighlightForeground",
316 "editor.foreground",
317 "foreground",
318 ),
319 searchMatchActiveBackground,
320 searchMatchActiveForeground: readableOn(
321 searchMatchActiveBackground,
322 derived.searchMatchActiveForeground,
323 "editor.findMatchForeground",
324 "editor.foreground",
325 "foreground",
326 ),
327 sidebar: sidebarHex,
328 sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
329 sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
330 sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
331 sidebarRowActive:
332 solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
333 derived.sidebarRowActive,
334 sidebarRowSelected:
335 solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
336 terminalBackground: terminalHex,
337 terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
338 terminalCursor:
339 solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
340 derived.terminalCursor,
341 terminalSelection:
342 solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
343 derived.terminalSelection,
344 terminalScrollbar:
345 solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
346 };
347 overrides.accent = accentHex;
348 overrides.focus = accentHex;
349 overrides.messageAction = actionHex;
350 overrides.messageActionForeground = readableOn(
351 actionHex,
352 derived.messageActionForeground,
353 "button.foreground",
354 );
355 overrides.accentForeground = readableOn(accentHex, derived.accentForeground, "button.foreground");
356
357 const name = resolveName(value);
358 const generatedId = themeIdFromName(name);
359 return parseThemeFile({
360 version: THEME_FILE_VERSION,
361 ...(isReservedThemeId(generatedId) ? { id: `${generatedId}-vscode` } : {}),
362 name,
363 appearance,
364 colors: { ...derived, ...overrides },
365 });
366}
367
368export function pairVsCodeThemes(
369 themes: ReadonlyArray<ThemeDefinition>,
370 options?: {
371 pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
372 },
373): ReadonlyArray<ThemeDefinition> {
374 const stripAppearance = (label: string) =>
375 label
376 .replace(/\b(?:light|dark)\b/gi, " ")
377 .replace(/\s+/g, " ")
378 .trim();
379
380 type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
381 const groups = new Map<string, Group>();
382 const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
383 themes.forEach((theme, order) => {
384 const key = stripAppearance(theme.label);
385 if (getThemeModes(theme).length !== 1 || key === theme.label || !/[a-z0-9]/i.test(key)) {
386 passthrough.push({ theme, order });
387 return;
388 }
389 const group = groups.get(key) ?? { light: [], dark: [], order };
390 group[theme.appearance].push(theme);
391 groups.set(key, group);
392 });
393
394 const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
395 for (const [key, group] of groups) {
396 if (group.light.length === 1 && group.dark.length === 1) {
397 try {
398 paired.push({
399 order: group.order,
400 theme: parseThemeFile({
401 version: THEME_FILE_VERSION,
402 ...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),
403 name: key,
404 appearance: "light",
405 colors: group.light[0]!.colors,
406 variants: { dark: group.dark[0]!.colors },
407 }),
408 });
409 continue;
410 } catch {}
411 }
412 for (const theme of [...group.light, ...group.dark]) {
413 paired.push({ theme, order: group.order });
414 }
415 }
416
417 return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
418}
419
420/**
421 * Some extensions reuse one display name across every file: Dracula ships
422 * dracula.json and dracula-soft.json that both say "Dracula".
423 */
424export function resolveThemeLabelCollisions(
425 entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
426): ReadonlyArray<ThemeDefinition> {
427 const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
428 try {
429 return parseThemeFile({
430 version: THEME_FILE_VERSION,
431 name: name.slice(0, 48),
432 appearance: theme.appearance,
433 colors: theme.colors,
434 ...(theme.variants ? { variants: theme.variants } : {}),
435 ...(theme.managed ? { managed: true } : {}),
436 });
437 } catch {
438 return null;
439 }
440 };
441
442 const counts = new Map<string, number>();
443 for (const entry of entries) {
444 counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
445 }
446 const relabelled = entries.map(({ theme, sourceName }) => {
447 if ((counts.get(theme.id) ?? 0) < 2) return theme;
448 const stem = sourceName?.replace(/\.[^.]+$/, "");
449 const fromFile = stem ? humanizeThemeName(stem) : null;
450 const renamed =
451 fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
452 ? rename(theme, fromFile)
453 : null;
454 return renamed ?? theme;
455 });
456
457 const seen = new Set<string>();
458 return relabelled.map((theme) => {
459 if (!seen.has(theme.id)) {
460 seen.add(theme.id);
461 return theme;
462 }
463 for (let suffix = 2; suffix < 100; suffix += 1) {
464 const candidate = rename(theme, `${theme.label} ${suffix}`);
465 if (candidate && !seen.has(candidate.id)) {
466 seen.add(candidate.id);
467 return candidate;
468 }
469 }
470 return theme;
471 });
472}