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

vscodeThemeImport.ts

618 lines23.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";
21import type { ThemeSyntax } from "@t3tools/shared/themePalettes";
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);
29​
30function decodeGamma(value: number): number {
31 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
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;
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)) };
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 };
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)}`;
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 });
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);
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);
130​
131function hexToRgb(value: string): VsCodeRgb {
132 return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
134​
135// Highlights token types and the TextMate scopes that stand for them, tried in order.
136// An unmatched subtype such as `keyword.import` inherits its parent's style.
137const SYNTAX_SCOPES: ReadonlyArray<readonly [string, ...string[]]> = [
138 ["comment", "comment"],
139 ["string", "string"],
140 ["string.escape", "constant.character.escape"],
141 ["string.regex", "string.regexp"],
142 ["number", "constant.numeric"],
143 ["boolean", "constant.language.boolean", "constant.language"],
144 ["constant", "variable.other.constant", "constant"],
145 ["keyword", "keyword.control", "keyword", "storage"],
146 ["keyword.declaration", "storage.type", "storage"],
147 ["keyword.import", "keyword.control.import"],
148 ["operator", "keyword.operator"],
149 ["function", "entity.name.function", "support.function"],
150 ["type", "entity.name.type", "entity.name.class", "support.type"],
151 ["variable", "variable.other.readwrite", "variable"],
152 ["variable.parameter", "variable.parameter"],
153 ["variable.special", "variable.language"],
154 ["property", "variable.other.property", "support.type.property-name"],
155 ["punctuation", "punctuation"],
156 ["tag", "entity.name.tag"],
157 ["attribute", "entity.other.attribute-name"],
158 ["namespace", "entity.name.namespace"],
159 ["title", "markup.heading"],
160 ["emphasis", "markup.italic"],
161 ["emphasis.strong", "markup.bold"],
162 ["link_uri", "markup.underline.link"],
163 ["text.literal", "markup.inline.raw"],
164 ["diff.plus", "markup.inserted"],
165 ["diff.minus", "markup.deleted"],
166];
167​
168function parseTokenColors(
169 tokenColors: unknown,
170 canvas: VsCodeRgb,
171 foreground: string | null,
172): ThemeSyntax | undefined {
173 if (!Array.isArray(tokenColors)) return undefined;
174 const rules = tokenColors.flatMap((rule) => {
175 if (!isRecord(rule) || !isRecord(rule.settings)) return [];
176 const scopes: unknown[] =
177 typeof rule.scope === "string" ? rule.scope.split(",") : [rule.scope].flat();
178 // Highlights tokens carry no parent scopes, so descendant and exclusion selectors never match.
179 const selectors = scopes.flatMap((scope) =>
180 typeof scope === "string" && /^\w[\w.-]*$/.test(scope.trim()) ? [scope.trim()] : [],
181 );
182 return [{ selectors, settings: rule.settings }];
183 });
184 // TextMate precedence: the longest matching selector wins, then the later rule.
185 const lookup = (scope: string, key: "foreground" | "fontStyle") => {
186 let value: unknown;
187 let depth = 0;
188 for (const { selectors, settings } of rules) {
189 if (settings[key] === undefined) continue;
190 for (const selector of selectors) {
191 if (scope !== selector && !scope.startsWith(`${selector}.`)) continue;
192 if (selector.split(".").length < depth) continue;
193 depth = selector.split(".").length;
194 value = settings[key];
195 }
196 }
197 return value;
198 };
199 const syntax: Record<string, ThemeSyntax[string]> = {};
200 for (const [tokenType, ...scopes] of SYNTAX_SCOPES) {
201 for (const scope of scopes) {
202 const color = parseVsCodeColor(lookup(scope, "foreground"));
203 const fontStyle = lookup(scope, "fontStyle");
204 const fontStyles = typeof fontStyle === "string" ? fontStyle.split(/\s+/) : [];
205 const style = {
206 ...(color ? { color: flattenOver(color, canvas) } : {}),
207 ...(fontStyle === "" ? { font_style: "normal" as const, font_weight: 400 as const } : {}),
208 ...(fontStyles.includes("italic") ? { font_style: "italic" as const } : {}),
209 ...(fontStyles.includes("bold") ? { font_weight: 700 as const } : {}),
210 };
211 if (Object.keys(style).length === 0) continue;
212 syntax[tokenType] = style;
213 break;
214 }
215 }
216 if (Object.keys(syntax).length === 0) return undefined;
217 // Unscoped code takes the editor's text color, as it does in VS Code.
218 return foreground ? { ...syntax, foreground: { color: foreground } } : syntax;
220​
221export function isVsCodeThemeFile(value: unknown): boolean {
222 if (!isRecord(value)) return false;
223 if (value.version === THEME_FILE_VERSION) return false;
224 const hasWorkbenchColors =
225 isRecord(value.colors) && Object.keys(value.colors).some((key) => key.includes("."));
226 return hasWorkbenchColors || Array.isArray(value.tokenColors);
228​
229export function parseThemeImport(source: string): ThemeDefinition {
230 const errors: ParseError[] = [];
231 const value: unknown = parse(source, errors, { allowTrailingComma: true });
232 if (errors.length > 0) throw new Error(m(msg("That theme file is not valid JSON.")));
233 return isVsCodeThemeFile(value)
234 ? parseVsCodeThemeFile(value)
235 : parseThemeFile(JSON.parse(source));
237​
238function resolveAppearance(value: Record<string, unknown>, canvas: VsCodeRgb): ThemeAppearance {
239 const type = typeof value.type === "string" ? value.type.toLowerCase() : null;
240 if (type === "light" || type === "hc-light") return "light";
241 if (type === "dark" || type === "hc-black") return "dark";
242 return relativeLuminance(canvas) < 0.179 ? "dark" : "light";
244​
245export function humanizeThemeName(raw: string): string {
246 const trimmed = raw.trim();
247 if (/\s/.test(trimmed) || !/[-_.]/.test(trimmed)) return trimmed;
248 return trimmed
249 .split(/[-_.]+/)
250 .filter(Boolean)
251 .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
252 .join(" ");
254​
255const themeNameGraphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
256export function truncateThemeName(value: string): string {
257 let end = 0;
258 for (const { index, segment } of themeNameGraphemes.segment(value)) {
259 if (index + segment.length > 48) return value.slice(0, end);
260 end = index + segment.length;
261 }
262 return value;
264​
265function resolveName(value: Record<string, unknown>): string {
266 for (const candidate of [value.displayName, value.name]) {
267 if (typeof candidate !== "string") continue;
268 const truncated = truncateThemeName(humanizeThemeName(candidate));
269 if (truncated.length > 0) return truncated;
270 }
271 return m(msg("VS Code theme"));
273​
274export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
275 if (!isRecord(value)) throw new Error(m(msg("Theme files must contain a JSON object.")));
276 const colors = isRecord(value.colors) ? value.colors : {};
277​
278 const pick = (...keys: ReadonlyArray<string>): VsCodeRgba | null => {
279 for (const key of keys) {
280 const parsed = parseVsCodeColor(colors[key]);
281 if (parsed) return parsed;
282 }
283 return null;
284 };
285 const solidOver = (base: VsCodeRgb, ...keys: ReadonlyArray<string>): string | null => {
286 const parsed = pick(...keys);
287 return parsed ? flattenOver(parsed, base) : null;
288 };
289​
290 const canvasColor = pick("editor.background", "editorPane.background");
291 if (!canvasColor) {
292 throw new Error(
293 m(
294 msg(
295 'That VS Code theme has no "editor.background" color, so there is nothing to build a palette from.',
296 ),
297 ),
298 );
299 }
300 const canvas = { r: canvasColor.r, g: canvasColor.g, b: canvasColor.b };
301 const appearance = resolveAppearance(value, canvas);
302​
303 const canvasHex = toHex(canvas);
304 const raisedSurfaceCandidateHex = solidOver(
305 canvas,
306 "editorWidget.background",
307 "dropdown.background",
308 );
309​
310 const standsApart = (first: string, second: string) =>
311 contrastRatio(hexToRgb(first), hexToRgb(second)) >= 1.1;
312​
313 let accentColor: VsCodeRgba | null = null;
314 let accentHex: string | null = null;
315 for (const key of [
316 "focusBorder",
317 "button.background",
318 "textLink.foreground",
319 "activityBarBadge.background",
320 "progressBar.background",
321 "badge.background",
322 ]) {
323 const candidate = parseVsCodeColor(colors[key]);
324 if (!candidate) continue;
325 const candidateHex = flattenOver(candidate, canvas);
326 if (
327 !standsApart(candidateHex, canvasHex) ||
328 (raisedSurfaceCandidateHex !== null && !standsApart(candidateHex, raisedSurfaceCandidateHex))
329 )
330 continue;
331 accentColor = candidate;
332 accentHex = candidateHex;
333 break;
334 }
335 if (!accentColor || !accentHex) {
336 const standardAccentHex = themeColorToHex(getStandardThemeColors(appearance).accent)!;
337 accentHex =
338 [standardAccentHex, "#ffffff", "#000000"].find(
339 (candidate) =>
340 standsApart(candidate, canvasHex) &&
341 (raisedSurfaceCandidateHex === null || standsApart(candidate, raisedSurfaceCandidateHex)),
342 ) ?? standardAccentHex;
343 accentColor = parseVsCodeColor(accentHex)!;
344 }
345​
346 const mutedAccentHex = flattenOver(
347 { r: accentColor.r, g: accentColor.g, b: accentColor.b, a: 0.2 },
348 canvas,
349 );
350 const derived = createVividThemeColors(appearance, canvasHex, mutedAccentHex);
351 const sidebarHex =
352 solidOver(canvas, "sideBar.background", "activityBar.background") ?? derived.sidebar;
353 const sidebar = hexToRgb(sidebarHex);
354 const terminalHex =
355 solidOver(canvas, "terminal.background", "panel.background") ?? derived.terminalBackground;
356 const terminal = hexToRgb(terminalHex);
357​
358 const readableOn = (
359 surface: string,
360 fallback: string,
361 ...keys: ReadonlyArray<string>
362 ): string => {
363 const surfaceRgb = hexToRgb(surface);
364 const isReadable = (candidate: string) => contrastRatio(hexToRgb(candidate), surfaceRgb) >= 4.5;
365 const specified = solidOver(surfaceRgb, ...keys);
366 if (specified && isReadable(specified)) return specified;
367 if (isReadable(fallback)) return fallback;
368 return relativeLuminance(surfaceRgb) < 0.179 ? "#ffffff" : "#000000";
369 };
370 // Status colors also fill controls such as destructive buttons, which carry
371 // white text, so a dim one is lightened along its hue rather than replaced
372 // by readableOn's black or white. One hidden in the canvas has no hue to
373 // keep, so the derived color stands in.
374 const readableStatusColor = (fallback: string, ...keys: ReadonlyArray<string>): string => {
375 const specified = solidOver(canvas, ...keys);
376 const base = specified && standsApart(specified, canvasHex) ? specified : fallback;
377 return readableThemeColorOn(base, canvasHex, 4.5);
378 };
379​
380 const surfaceRaisedHex = raisedSurfaceCandidateHex ?? derived.surfaceRaised;
381 // Checked tracks use messageAction; resolve it before the unchecked input role.
382 const buttonHex = solidOver(canvas, "button.background");
383 const actionHex =
384 buttonHex && standsApart(buttonHex, canvasHex) && standsApart(buttonHex, surfaceRaisedHex)
385 ? buttonHex
386 : accentHex;
387 const inputCandidates = [
388 derived.input,
389 derived.surfaceRaised,
390 getStandardThemeColors(appearance).input,
391 "#000000",
392 "#ffffff",
393 "#808080",
394 ];
395 let inputHex =
396 inputCandidates.find(
397 (candidate) => standsApart(candidate, canvasHex) && standsApart(candidate, actionHex),
398 ) ?? "#808080";
399 for (const key of ["input.background", "input.border"]) {
400 const candidate = solidOver(canvas, key);
401 if (candidate && standsApart(candidate, canvasHex) && standsApart(candidate, actionHex)) {
402 inputHex = candidate;
403 break;
404 }
405 }
406 const searchMatchBackground =
407 solidOver(canvas, "editor.findMatchHighlightBackground") ?? derived.searchMatchBackground;
408 const searchMatchActiveBackground =
409 solidOver(canvas, "editor.findMatchBackground") ?? derived.searchMatchActiveBackground;
410​
411 const overrides: Partial<Record<ThemeColorRole, string>> = {
412 canvas: canvasHex,
413 text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
414 textMuted: readableOn(
415 canvasHex,
416 derived.textMuted,
417 "descriptionForeground",
418 "disabledForeground",
419 ),
420 surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
421 surfaceRaised: surfaceRaisedHex,
422 surfaceOverlay:
423 solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
424 derived.surfaceOverlay,
425 border:
426 solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
427 input: inputHex,
428 placeholder: readableOn(surfaceRaisedHex, derived.placeholder, "input.placeholderForeground"),
429 error: readableStatusColor(derived.error, "editorError.foreground", "errorForeground"),
430 warning: readableStatusColor(derived.warning, "editorWarning.foreground"),
431 accentSurface:
432 solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
433 derived.accentSurface,
434 codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
435 searchMatchBackground,
436 searchMatchForeground: readableOn(
437 searchMatchBackground,
438 derived.searchMatchForeground,
439 "editor.findMatchHighlightForeground",
440 "editor.foreground",
441 "foreground",
442 ),
443 searchMatchActiveBackground,
444 searchMatchActiveForeground: readableOn(
445 searchMatchActiveBackground,
446 derived.searchMatchActiveForeground,
447 "editor.findMatchForeground",
448 "editor.foreground",
449 "foreground",
450 ),
451 sidebar: sidebarHex,
452 sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
453 sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
454 sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
455 sidebarRowActive:
456 solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
457 derived.sidebarRowActive,
458 sidebarRowSelected:
459 solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
460 terminalBackground: terminalHex,
461 terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
462 terminalCursor:
463 solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
464 derived.terminalCursor,
465 terminalSelection:
466 solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
467 derived.terminalSelection,
468 terminalScrollbar:
469 solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
470 };
471 overrides.accent = accentHex;
472 overrides.focus = accentHex;
473 overrides.messageAction = actionHex;
474 overrides.messageActionForeground = readableOn(
475 actionHex,
476 derived.messageActionForeground,
477 "button.foreground",
478 );
479 overrides.accentForeground = readableOn(accentHex, derived.accentForeground, "button.foreground");
480​
481 const name = resolveName(value);
482 const generatedId = themeIdFromName(name);
483 const syntax = parseTokenColors(
484 value.tokenColors,
485 canvas,
486 solidOver(canvas, "editor.foreground", "foreground"),
487 );
488 return parseThemeFile({
489 version: THEME_FILE_VERSION,
490 ...(isReservedThemeId(generatedId) ? { id: `${generatedId}-vscode` } : {}),
491 name,
492 appearance,
493 colors: { ...derived, ...overrides },
494 ...(syntax ? { syntax: { [appearance]: syntax } } : {}),
495 });
497​
498export function pairVsCodeThemes(
499 themes: ReadonlyArray<ThemeDefinition>,
500 options?: {
501 pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
502 },
503): ReadonlyArray<ThemeDefinition> {
504 const stripAppearance = (label: string) =>
505 label
506 .replace(/\b(?:light|dark)\b/gi, " ")
507 .replace(/\s+/g, " ")
508 .trim();
509​
510 type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
511 const groups = new Map<string, Group>();
512 const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
513 themes.forEach((theme, order) => {
514 const key = stripAppearance(theme.label);
515 if (getThemeModes(theme).length !== 1 || key === theme.label || !/[a-z0-9]/i.test(key)) {
516 passthrough.push({ theme, order });
517 return;
518 }
519 const group = groups.get(key) ?? { light: [], dark: [], order };
520 group[theme.appearance].push(theme);
521 groups.set(key, group);
522 });
523​
524 const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
525 for (const [key, group] of groups) {
526 const [light] = group.light;
527 const [dark] = group.dark;
528 // A theme carries one stylesheet for both modes, so conflicting CSS stays as two themes.
529 if (
530 light &&
531 dark &&
532 group.light.length === 1 &&
533 group.dark.length === 1 &&
534 (!light.css || !dark.css || light.css === dark.css)
535 ) {
536 try {
537 paired.push({
538 order: group.order,
539 theme: parseThemeFile({
540 version: THEME_FILE_VERSION,
541 ...(options?.pairedId ? { id: options.pairedId(light, dark) } : {}),
542 name: key,
543 appearance: "light",
544 colors: light.colors,
545 variants: { dark: dark.colors },
546 css: light.css ?? dark.css,
547 syntax: { ...light.syntax, ...dark.syntax },
548 }),
549 });
550 continue;
551 } catch {}
552 }
553 for (const theme of [...group.light, ...group.dark]) {
554 paired.push({ theme, order: group.order });
555 }
556 }
557​
558 return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
560​
561export function numberedThemeName(label: string, suffix: string): string {
562 const suffixId = themeIdFromName(suffix);
563 const base = Array.from(themeNameGraphemes.segment(label), ({ segment }) => segment);
564 while (base.length > 0) {
565 const stem = base.join("").trimEnd();
566 const name = `${stem}${suffix}`;
567 const id = themeIdFromName(name);
568 if (name.length <= 48 && id.split("-").at(-1) === suffixId && id !== themeIdFromName(stem)) {
569 return name;
570 }
571 base.pop();
572 }
573 return suffix.trimStart();
575​
576export function resolveThemeLabelCollisions(
577 entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
578): ReadonlyArray<ThemeDefinition> {
579 const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
580 try {
581 return renameTheme(theme, truncateThemeName(name));
582 } catch {
583 return null;
584 }
585 };
586​
587 const counts = new Map<string, number>();
588 for (const entry of entries) {
589 counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
590 }
591 const relabelled = entries.map(({ theme, sourceName }) => {
592 if ((counts.get(theme.id) ?? 0) < 2) return theme;
593 const stem = sourceName?.replace(/\.[^.]+$/, "");
594 const fromFile = stem ? humanizeThemeName(stem) : null;
595 const renamed =
596 fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
597 ? rename(theme, fromFile)
598 : null;
599 return renamed ?? theme;
600 });
601​
602 const inputIds = new Set(relabelled.map(({ id }) => id));
603 const seen = new Set<string>();
604 return relabelled.map((theme) => {
605 if (!seen.has(theme.id)) {
606 seen.add(theme.id);
607 return theme;
608 }
609 for (let suffix = 2; suffix < 100; suffix += 1) {
610 const candidate = rename(theme, numberedThemeName(theme.label, ` ${suffix}`));
611 if (candidate && !inputIds.has(candidate.id) && !seen.has(candidate.id)) {
612 seen.add(candidate.id);
613 return candidate;
614 }
615 }
616 return theme;
617 });