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

vscodeThemeImport.ts

482 lines17.6 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/** Overlays are semi-transparent in VS Code; our roles are opaque, so they are
101 * composited onto whatever surface they sit on. */
102function flattenOver(color: VsCodeRgba, base: VsCodeRgb): string {
103 if (color.a >= 1) return toHex(color);
104 return toHex({
105 r: color.r * color.a + base.r * (1 - color.a),
106 g: color.g * color.a + base.g * (1 - color.a),
107 b: color.b * color.a + base.b * (1 - color.a),
108 });
110​
111function relativeLuminance(color: VsCodeRgb): number {
112 const channel = (value: number) => {
113 const ratio = value / 255;
114 return ratio <= 0.03928 ? ratio / 12.92 : ((ratio + 0.055) / 1.055) ** 2.4;
115 };
116 return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
118​
119function contrastRatio(first: VsCodeRgb, second: VsCodeRgb): number {
120 const a = relativeLuminance(first);
121 const b = relativeLuminance(second);
122 return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
124​
125function hexToRgb(value: string): VsCodeRgb {
126 return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
128​
129export function isVsCodeThemeFile(value: unknown): boolean {
130 if (!isRecord(value)) return false;
131 if (value.version === THEME_FILE_VERSION) return false;
132 const hasWorkbenchColors =
133 isRecord(value.colors) && Object.keys(value.colors).some((key) => key.includes("."));
134 return hasWorkbenchColors || Array.isArray(value.tokenColors);
136​
137function resolveAppearance(value: Record<string, unknown>, canvas: VsCodeRgb): ThemeAppearance {
138 const type = typeof value.type === "string" ? value.type.toLowerCase() : null;
139 if (type === "light" || type === "hc-light") return "light";
140 if (type === "dark" || type === "hc-black") return "dark";
141 return relativeLuminance(canvas) < 0.179 ? "dark" : "light";
143​
144export function humanizeThemeName(raw: string): string {
145 const trimmed = raw.trim();
146 if (/\s/.test(trimmed) || !/[-_.]/.test(trimmed)) return trimmed;
147 return trimmed
148 .split(/[-_.]+/)
149 .filter(Boolean)
150 .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
151 .join(" ");
153​
154function resolveName(value: Record<string, unknown>): string {
155 for (const candidate of [value.displayName, value.name]) {
156 if (typeof candidate !== "string") continue;
157 const humanized = humanizeThemeName(candidate);
158 if (humanized.length > 0) return humanized.slice(0, 48);
159 }
160 return "VS Code theme";
162​
163export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
164 if (!isRecord(value)) throw new Error("Theme files must contain a JSON object.");
165 const colors = isRecord(value.colors) ? value.colors : {};
166​
167 const pick = (...keys: ReadonlyArray<string>): VsCodeRgba | null => {
168 for (const key of keys) {
169 const parsed = parseVsCodeColor(colors[key]);
170 if (parsed) return parsed;
171 }
172 return null;
173 };
174 const solidOver = (base: VsCodeRgb, ...keys: ReadonlyArray<string>): string | null => {
175 const parsed = pick(...keys);
176 return parsed ? flattenOver(parsed, base) : null;
177 };
178​
179 const canvasColor = pick("editor.background", "editorPane.background");
180 if (!canvasColor) {
181 throw new Error(
182 'That VS Code theme has no "editor.background" color, so there is nothing to build a palette from.',
183 );
184 }
185 const canvas = { r: canvasColor.r, g: canvasColor.g, b: canvasColor.b };
186 const appearance = resolveAppearance(value, canvas);
187​
188 const canvasHex = toHex(canvas);
189 const raisedSurfaceCandidateHex = solidOver(
190 canvas,
191 "editorWidget.background",
192 "dropdown.background",
193 );
194​
195 const standsApart = (first: string, second: string) =>
196 contrastRatio(hexToRgb(first), hexToRgb(second)) >= 1.1;
197​
198 let accentColor: VsCodeRgba | null = null;
199 let accentHex: string | null = null;
200 for (const key of [
201 "focusBorder",
202 "button.background",
203 "textLink.foreground",
204 "activityBarBadge.background",
205 "progressBar.background",
206 "badge.background",
207 ]) {
208 const candidate = parseVsCodeColor(colors[key]);
209 if (!candidate) continue;
210 const candidateHex = flattenOver(candidate, canvas);
211 if (
212 !standsApart(candidateHex, canvasHex) ||
213 (raisedSurfaceCandidateHex !== null && !standsApart(candidateHex, raisedSurfaceCandidateHex))
214 )
215 continue;
216 accentColor = candidate;
217 accentHex = candidateHex;
218 break;
219 }
220 if (!accentColor || !accentHex) {
221 const standardAccentHex = themeColorToHex(getStandardThemeColors(appearance).accent)!;
222 accentHex =
223 [standardAccentHex, "#ffffff", "#000000"].find(
224 (candidate) =>
225 standsApart(candidate, canvasHex) &&
226 (raisedSurfaceCandidateHex === null || standsApart(candidate, raisedSurfaceCandidateHex)),
227 ) ?? standardAccentHex;
228 accentColor = parseVsCodeColor(accentHex)!;
229 }
230​
231 const mutedAccentHex = flattenOver(
232 { r: accentColor.r, g: accentColor.g, b: accentColor.b, a: 0.2 },
233 canvas,
234 );
235 const derived = createVividThemeColors(appearance, canvasHex, mutedAccentHex);
236 const sidebarHex =
237 solidOver(canvas, "sideBar.background", "activityBar.background") ?? derived.sidebar;
238 const sidebar = hexToRgb(sidebarHex);
239 const terminalHex =
240 solidOver(canvas, "terminal.background", "panel.background") ?? derived.terminalBackground;
241 const terminal = hexToRgb(terminalHex);
242​
243 const readableOn = (
244 surface: string,
245 fallback: string,
246 ...keys: ReadonlyArray<string>
247 ): string => {
248 const surfaceRgb = hexToRgb(surface);
249 const isReadable = (candidate: string) => contrastRatio(hexToRgb(candidate), surfaceRgb) >= 4.5;
250 const specified = solidOver(surfaceRgb, ...keys);
251 if (specified && isReadable(specified)) return specified;
252 if (isReadable(fallback)) return fallback;
253 return relativeLuminance(surfaceRgb) < 0.179 ? "#ffffff" : "#000000";
254 };
255 // Status colors also fill controls such as destructive buttons, which carry
256 // white text, so a dim one is lightened along its hue rather than replaced
257 // by readableOn's black or white. One hidden in the canvas has no hue to
258 // keep, so the derived color stands in.
259 const readableStatusColor = (fallback: string, ...keys: ReadonlyArray<string>): string => {
260 const specified = solidOver(canvas, ...keys);
261 const base = specified && standsApart(specified, canvasHex) ? specified : fallback;
262 return readableThemeColorOn(base, canvasHex, 4.5);
263 };
264​
265 const surfaceRaisedHex = raisedSurfaceCandidateHex ?? derived.surfaceRaised;
266 // The checked switch track maps to messageAction, so resolve it before
267 // choosing the input role used by the unchecked track.
268 const buttonHex = solidOver(canvas, "button.background");
269 const actionHex =
270 buttonHex && standsApart(buttonHex, canvasHex) && standsApart(buttonHex, surfaceRaisedHex)
271 ? buttonHex
272 : accentHex;
273 const inputCandidates = [
274 derived.input,
275 derived.surfaceRaised,
276 getStandardThemeColors(appearance).input,
277 "#000000",
278 "#ffffff",
279 "#808080",
280 ];
281 let inputHex =
282 inputCandidates.find(
283 (candidate) => standsApart(candidate, canvasHex) && standsApart(candidate, actionHex),
284 ) ?? "#808080";
285 for (const key of ["input.background", "input.border"]) {
286 const candidate = solidOver(canvas, key);
287 if (candidate && standsApart(candidate, canvasHex) && standsApart(candidate, actionHex)) {
288 inputHex = candidate;
289 break;
290 }
291 }
292 const searchMatchBackground =
293 solidOver(canvas, "editor.findMatchHighlightBackground") ?? derived.searchMatchBackground;
294 const searchMatchActiveBackground =
295 solidOver(canvas, "editor.findMatchBackground") ?? derived.searchMatchActiveBackground;
296​
297 const overrides: Partial<Record<ThemeColorRole, string>> = {
298 canvas: canvasHex,
299 text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
300 textMuted: readableOn(
301 canvasHex,
302 derived.textMuted,
303 "descriptionForeground",
304 "disabledForeground",
305 ),
306 surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
307 surfaceRaised: surfaceRaisedHex,
308 surfaceOverlay:
309 solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
310 derived.surfaceOverlay,
311 border:
312 solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
313 input: inputHex,
314 placeholder: readableOn(surfaceRaisedHex, derived.placeholder, "input.placeholderForeground"),
315 error: readableStatusColor(derived.error, "editorError.foreground", "errorForeground"),
316 warning: readableStatusColor(derived.warning, "editorWarning.foreground"),
317 accentSurface:
318 solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
319 derived.accentSurface,
320 codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
321 searchMatchBackground,
322 searchMatchForeground: readableOn(
323 searchMatchBackground,
324 derived.searchMatchForeground,
325 "editor.findMatchHighlightForeground",
326 "editor.foreground",
327 "foreground",
328 ),
329 searchMatchActiveBackground,
330 searchMatchActiveForeground: readableOn(
331 searchMatchActiveBackground,
332 derived.searchMatchActiveForeground,
333 "editor.findMatchForeground",
334 "editor.foreground",
335 "foreground",
336 ),
337 sidebar: sidebarHex,
338 sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
339 sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
340 sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
341 sidebarRowActive:
342 solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
343 derived.sidebarRowActive,
344 sidebarRowSelected:
345 solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
346 terminalBackground: terminalHex,
347 terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
348 terminalCursor:
349 solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
350 derived.terminalCursor,
351 terminalSelection:
352 solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
353 derived.terminalSelection,
354 terminalScrollbar:
355 solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
356 };
357 overrides.accent = accentHex;
358 overrides.focus = accentHex;
359 overrides.messageAction = actionHex;
360 overrides.messageActionForeground = readableOn(
361 actionHex,
362 derived.messageActionForeground,
363 "button.foreground",
364 );
365 overrides.accentForeground = readableOn(accentHex, derived.accentForeground, "button.foreground");
366​
367 const name = resolveName(value);
368 const generatedId = themeIdFromName(name);
369 return parseThemeFile({
370 version: THEME_FILE_VERSION,
371 ...(isReservedThemeId(generatedId) ? { id: `${generatedId}-vscode` } : {}),
372 name,
373 appearance,
374 colors: { ...derived, ...overrides },
375 });
377​
378export function pairVsCodeThemes(
379 themes: ReadonlyArray<ThemeDefinition>,
380 options?: {
381 pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
382 },
383): ReadonlyArray<ThemeDefinition> {
384 const stripAppearance = (label: string) =>
385 label
386 .replace(/\b(?:light|dark)\b/gi, " ")
387 .replace(/\s+/g, " ")
388 .trim();
389​
390 type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
391 const groups = new Map<string, Group>();
392 const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
393 themes.forEach((theme, order) => {
394 const key = stripAppearance(theme.label);
395 if (getThemeModes(theme).length !== 1 || key === theme.label || !/[a-z0-9]/i.test(key)) {
396 passthrough.push({ theme, order });
397 return;
398 }
399 const group = groups.get(key) ?? { light: [], dark: [], order };
400 group[theme.appearance].push(theme);
401 groups.set(key, group);
402 });
403​
404 const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
405 for (const [key, group] of groups) {
406 if (group.light.length === 1 && group.dark.length === 1) {
407 try {
408 paired.push({
409 order: group.order,
410 theme: parseThemeFile({
411 version: THEME_FILE_VERSION,
412 ...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),
413 name: key,
414 appearance: "light",
415 colors: group.light[0]!.colors,
416 variants: { dark: group.dark[0]!.colors },
417 }),
418 });
419 continue;
420 } catch {}
421 }
422 for (const theme of [...group.light, ...group.dark]) {
423 paired.push({ theme, order: group.order });
424 }
425 }
426​
427 return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
429​
430/**
431 * Some extensions reuse one display name across every file: Dracula ships
432 * dracula.json and dracula-soft.json that both say "Dracula".
433 */
434export function resolveThemeLabelCollisions(
435 entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
436): ReadonlyArray<ThemeDefinition> {
437 const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
438 try {
439 return parseThemeFile({
440 version: THEME_FILE_VERSION,
441 name: name.slice(0, 48),
442 appearance: theme.appearance,
443 colors: theme.colors,
444 ...(theme.variants ? { variants: theme.variants } : {}),
445 ...(theme.managed ? { managed: true } : {}),
446 });
447 } catch {
448 return null;
449 }
450 };
451​
452 const counts = new Map<string, number>();
453 for (const entry of entries) {
454 counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
455 }
456 const relabelled = entries.map(({ theme, sourceName }) => {
457 if ((counts.get(theme.id) ?? 0) < 2) return theme;
458 const stem = sourceName?.replace(/\.[^.]+$/, "");
459 const fromFile = stem ? humanizeThemeName(stem) : null;
460 const renamed =
461 fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
462 ? rename(theme, fromFile)
463 : null;
464 return renamed ?? theme;
465 });
466​
467 const seen = new Set<string>();
468 return relabelled.map((theme) => {
469 if (!seen.has(theme.id)) {
470 seen.add(theme.id);
471 return theme;
472 }
473 for (let suffix = 2; suffix < 100; suffix += 1) {
474 const candidate = rename(theme, `${theme.label} ${suffix}`);
475 if (candidate && !seen.has(candidate.id)) {
476 seen.add(candidate.id);
477 return candidate;
478 }
479 }
480 return theme;
481 });