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