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

vscodeThemeImport.ts

524 lines19.0 KB

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