The best way to control Claude Code, Codex and more from any computer or phone

main
ts 514 lines 18.5 KB
Raw
1 import { parse, type ParseError } from "jsonc-parser";
2 import { msg } from "gt-react";
3
4 import { m } from "./i18n/messages";
5
6 import {
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
22 type VsCodeRgba = { r: number; g: number; b: number; a: number };
23 type VsCodeRgb = { r: number; g: number; b: number };
24
25 function isRecord(value: unknown): value is Record<string, unknown> {
26 return typeof value === "object" && value !== null && !Array.isArray(value);
27 }
28
29 function decodeGamma(value: number): number {
30 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
31 }
32
33 function 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;
36 }
37
38 function 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)) };
72 }
73
74 function 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 };
96 }
97
98 function 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)}`;
104 }
105
106 // Composite VS Code translucent overlays onto their surfaces; our roles are opaque.
107 function 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 });
114 }
115
116 function 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);
122 }
123
124 function 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);
128 }
129
130 function hexToRgb(value: string): VsCodeRgb {
131 return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
132 }
133
134 export 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);
140 }
141
142 export 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));
149 }
150
151 function 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";
156 }
157
158 export 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(" ");
166 }
167
168 function resolveName(value: Record<string, unknown>): string {
169 for (const candidate of [value.displayName, value.name]) {
170 if (typeof candidate !== "string") continue;
171 const humanized = humanizeThemeName(candidate);
172 if (humanized.length > 0) return humanized.slice(0, 48);
173 }
174 return m(msg("VS Code theme"));
175 }
176
177 export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
178 if (!isRecord(value)) throw new Error(m(msg("Theme files must contain a JSON object.")));
179 const colors = isRecord(value.colors) ? value.colors : {};
180
181 const pick = (...keys: ReadonlyArray<string>): VsCodeRgba | null => {
182 for (const key of keys) {
183 const parsed = parseVsCodeColor(colors[key]);
184 if (parsed) return parsed;
185 }
186 return null;
187 };
188 const solidOver = (base: VsCodeRgb, ...keys: ReadonlyArray<string>): string | null => {
189 const parsed = pick(...keys);
190 return parsed ? flattenOver(parsed, base) : null;
191 };
192
193 const canvasColor = pick("editor.background", "editorPane.background");
194 if (!canvasColor) {
195 throw new Error(
196 m(
197 msg(
198 'That VS Code theme has no "editor.background" color, so there is nothing to build a palette from.',
199 ),
200 ),
201 );
202 }
203 const canvas = { r: canvasColor.r, g: canvasColor.g, b: canvasColor.b };
204 const appearance = resolveAppearance(value, canvas);
205
206 const canvasHex = toHex(canvas);
207 const raisedSurfaceCandidateHex = solidOver(
208 canvas,
209 "editorWidget.background",
210 "dropdown.background",
211 );
212
213 const standsApart = (first: string, second: string) =>
214 contrastRatio(hexToRgb(first), hexToRgb(second)) >= 1.1;
215
216 let accentColor: VsCodeRgba | null = null;
217 let accentHex: string | null = null;
218 for (const key of [
219 "focusBorder",
220 "button.background",
221 "textLink.foreground",
222 "activityBarBadge.background",
223 "progressBar.background",
224 "badge.background",
225 ]) {
226 const candidate = parseVsCodeColor(colors[key]);
227 if (!candidate) continue;
228 const candidateHex = flattenOver(candidate, canvas);
229 if (
230 !standsApart(candidateHex, canvasHex) ||
231 (raisedSurfaceCandidateHex !== null && !standsApart(candidateHex, raisedSurfaceCandidateHex))
232 )
233 continue;
234 accentColor = candidate;
235 accentHex = candidateHex;
236 break;
237 }
238 if (!accentColor || !accentHex) {
239 const standardAccentHex = themeColorToHex(getStandardThemeColors(appearance).accent)!;
240 accentHex =
241 [standardAccentHex, "#ffffff", "#000000"].find(
242 (candidate) =>
243 standsApart(candidate, canvasHex) &&
244 (raisedSurfaceCandidateHex === null || standsApart(candidate, raisedSurfaceCandidateHex)),
245 ) ?? standardAccentHex;
246 accentColor = parseVsCodeColor(accentHex)!;
247 }
248
249 const mutedAccentHex = flattenOver(
250 { r: accentColor.r, g: accentColor.g, b: accentColor.b, a: 0.2 },
251 canvas,
252 );
253 const derived = createVividThemeColors(appearance, canvasHex, mutedAccentHex);
254 const sidebarHex =
255 solidOver(canvas, "sideBar.background", "activityBar.background") ?? derived.sidebar;
256 const sidebar = hexToRgb(sidebarHex);
257 const terminalHex =
258 solidOver(canvas, "terminal.background", "panel.background") ?? derived.terminalBackground;
259 const terminal = hexToRgb(terminalHex);
260
261 const readableOn = (
262 surface: string,
263 fallback: string,
264 ...keys: ReadonlyArray<string>
265 ): string => {
266 const surfaceRgb = hexToRgb(surface);
267 const isReadable = (candidate: string) => contrastRatio(hexToRgb(candidate), surfaceRgb) >= 4.5;
268 const specified = solidOver(surfaceRgb, ...keys);
269 if (specified && isReadable(specified)) return specified;
270 if (isReadable(fallback)) return fallback;
271 return relativeLuminance(surfaceRgb) < 0.179 ? "#ffffff" : "#000000";
272 };
273 // Status colors also fill controls such as destructive buttons, which carry
274 // white text, so a dim one is lightened along its hue rather than replaced
275 // by readableOn's black or white. One hidden in the canvas has no hue to
276 // keep, so the derived color stands in.
277 const readableStatusColor = (fallback: string, ...keys: ReadonlyArray<string>): string => {
278 const specified = solidOver(canvas, ...keys);
279 const base = specified && standsApart(specified, canvasHex) ? specified : fallback;
280 return readableThemeColorOn(base, canvasHex, 4.5);
281 };
282
283 const surfaceRaisedHex = raisedSurfaceCandidateHex ?? derived.surfaceRaised;
284 // Checked tracks use messageAction; resolve it before the unchecked input role.
285 const buttonHex = solidOver(canvas, "button.background");
286 const actionHex =
287 buttonHex && standsApart(buttonHex, canvasHex) && standsApart(buttonHex, surfaceRaisedHex)
288 ? buttonHex
289 : accentHex;
290 const inputCandidates = [
291 derived.input,
292 derived.surfaceRaised,
293 getStandardThemeColors(appearance).input,
294 "#000000",
295 "#ffffff",
296 "#808080",
297 ];
298 let inputHex =
299 inputCandidates.find(
300 (candidate) => standsApart(candidate, canvasHex) && standsApart(candidate, actionHex),
301 ) ?? "#808080";
302 for (const key of ["input.background", "input.border"]) {
303 const candidate = solidOver(canvas, key);
304 if (candidate && standsApart(candidate, canvasHex) && standsApart(candidate, actionHex)) {
305 inputHex = candidate;
306 break;
307 }
308 }
309 const searchMatchBackground =
310 solidOver(canvas, "editor.findMatchHighlightBackground") ?? derived.searchMatchBackground;
311 const searchMatchActiveBackground =
312 solidOver(canvas, "editor.findMatchBackground") ?? derived.searchMatchActiveBackground;
313
314 const overrides: Partial<Record<ThemeColorRole, string>> = {
315 canvas: canvasHex,
316 text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
317 textMuted: readableOn(
318 canvasHex,
319 derived.textMuted,
320 "descriptionForeground",
321 "disabledForeground",
322 ),
323 surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
324 surfaceRaised: surfaceRaisedHex,
325 surfaceOverlay:
326 solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
327 derived.surfaceOverlay,
328 border:
329 solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
330 input: inputHex,
331 placeholder: readableOn(surfaceRaisedHex, derived.placeholder, "input.placeholderForeground"),
332 error: readableStatusColor(derived.error, "editorError.foreground", "errorForeground"),
333 warning: readableStatusColor(derived.warning, "editorWarning.foreground"),
334 accentSurface:
335 solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
336 derived.accentSurface,
337 codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
338 searchMatchBackground,
339 searchMatchForeground: readableOn(
340 searchMatchBackground,
341 derived.searchMatchForeground,
342 "editor.findMatchHighlightForeground",
343 "editor.foreground",
344 "foreground",
345 ),
346 searchMatchActiveBackground,
347 searchMatchActiveForeground: readableOn(
348 searchMatchActiveBackground,
349 derived.searchMatchActiveForeground,
350 "editor.findMatchForeground",
351 "editor.foreground",
352 "foreground",
353 ),
354 sidebar: sidebarHex,
355 sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
356 sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
357 sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
358 sidebarRowActive:
359 solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
360 derived.sidebarRowActive,
361 sidebarRowSelected:
362 solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
363 terminalBackground: terminalHex,
364 terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
365 terminalCursor:
366 solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
367 derived.terminalCursor,
368 terminalSelection:
369 solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
370 derived.terminalSelection,
371 terminalScrollbar:
372 solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
373 };
374 overrides.accent = accentHex;
375 overrides.focus = accentHex;
376 overrides.messageAction = actionHex;
377 overrides.messageActionForeground = readableOn(
378 actionHex,
379 derived.messageActionForeground,
380 "button.foreground",
381 );
382 overrides.accentForeground = readableOn(accentHex, derived.accentForeground, "button.foreground");
383
384 const name = resolveName(value);
385 const generatedId = themeIdFromName(name);
386 return parseThemeFile({
387 version: THEME_FILE_VERSION,
388 ...(isReservedThemeId(generatedId) ? { id: `${generatedId}-vscode` } : {}),
389 name,
390 appearance,
391 colors: { ...derived, ...overrides },
392 });
393 }
394
395 export function pairVsCodeThemes(
396 themes: ReadonlyArray<ThemeDefinition>,
397 options?: {
398 pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
399 },
400 ): ReadonlyArray<ThemeDefinition> {
401 const stripAppearance = (label: string) =>
402 label
403 .replace(/\b(?:light|dark)\b/gi, " ")
404 .replace(/\s+/g, " ")
405 .trim();
406
407 type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
408 const groups = new Map<string, Group>();
409 const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
410 themes.forEach((theme, order) => {
411 const key = stripAppearance(theme.label);
412 if (getThemeModes(theme).length !== 1 || key === theme.label || !/[a-z0-9]/i.test(key)) {
413 passthrough.push({ theme, order });
414 return;
415 }
416 const group = groups.get(key) ?? { light: [], dark: [], order };
417 group[theme.appearance].push(theme);
418 groups.set(key, group);
419 });
420
421 const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
422 for (const [key, group] of groups) {
423 const [light] = group.light;
424 const [dark] = group.dark;
425 // A theme carries one stylesheet for both modes, so conflicting CSS stays as two themes.
426 if (
427 light &&
428 dark &&
429 group.light.length === 1 &&
430 group.dark.length === 1 &&
431 (!light.css || !dark.css || light.css === dark.css)
432 ) {
433 try {
434 paired.push({
435 order: group.order,
436 theme: parseThemeFile({
437 version: THEME_FILE_VERSION,
438 ...(options?.pairedId ? { id: options.pairedId(light, dark) } : {}),
439 name: key,
440 appearance: "light",
441 colors: light.colors,
442 variants: { dark: dark.colors },
443 css: light.css ?? dark.css,
444 }),
445 });
446 continue;
447 } catch {}
448 }
449 for (const theme of [...group.light, ...group.dark]) {
450 paired.push({ theme, order: group.order });
451 }
452 }
453
454 return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
455 }
456
457 export function resolveThemeLabelCollisions(
458 entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
459 ): ReadonlyArray<ThemeDefinition> {
460 const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
461 try {
462 return renameTheme(theme, name.slice(0, 48));
463 } catch {
464 return null;
465 }
466 };
467
468 const counts = new Map<string, number>();
469 for (const entry of entries) {
470 counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
471 }
472 const relabelled = entries.map(({ theme, sourceName }) => {
473 if ((counts.get(theme.id) ?? 0) < 2) return theme;
474 const stem = sourceName?.replace(/\.[^.]+$/, "");
475 const fromFile = stem ? humanizeThemeName(stem) : null;
476 const renamed =
477 fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
478 ? rename(theme, fromFile)
479 : null;
480 return renamed ?? theme;
481 });
482
483 const inputIds = new Set(relabelled.map(({ id }) => id));
484 const seen = new Set<string>();
485 return relabelled.map((theme) => {
486 if (!seen.has(theme.id)) {
487 seen.add(theme.id);
488 return theme;
489 }
490 for (let suffix = 2; suffix < 100; suffix += 1) {
491 const suffixText = String(suffix);
492 const base = [...theme.label];
493 let stem = base.join("").trimEnd();
494 let name = `${stem} ${suffixText}`;
495 let id = themeIdFromName(name);
496 while (
497 name.length > 48 ||
498 id.split("-").at(-1) !== suffixText ||
499 id === themeIdFromName(stem)
500 ) {
501 base.pop();
502 stem = base.join("").trimEnd();
503 name = `${stem} ${suffixText}`;
504 id = themeIdFromName(name);
505 }
506 const candidate = rename(theme, name);
507 if (candidate && !inputIds.has(candidate.id) && !seen.has(candidate.id)) {
508 seen.add(candidate.id);
509 return candidate;
510 }
511 }
512 return theme;
513 });
514 }