import { readSection, writeSection } from '../settings/store.ts'; /** The old localStorage key. The customThemes section of the settings file replaces it. */ export const CUSTOM_THEMES_KEY = "runestone.custom-themes"; export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const; export type ThemeColors = Partial>; export const FONT_ROLES = ['ui', 'prose', 'heading', 'mono'] as const; export type ThemeFonts = Partial>; export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeColors; fonts?: ThemeFonts }; export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors }; export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): CustomTheme { if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file."); const value = input as Record; if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id) || typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 2, an ID, and a name."); const colors = (mode: string): ThemeColors => { const source = value[mode]; if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`); const result: ThemeColors = {}; for (const [key, color] of Object.entries(source)) { if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(`Unknown theme color: ${key}`); if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(`Use a hexadecimal color for ${key}.`); result[key as keyof ThemeColors] = color; } if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`); return result; }; if (value.schema === 1) { colors("light"); colors("dark"); } let fonts: ThemeFonts | undefined; if (value.fonts !== undefined) { if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error('Use an object for theme fonts.'); fonts = {}; for (const [role, stack] of Object.entries(value.fonts)) { if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(`Unknown theme font: ${role}`); if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim() || stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(`Use a font family stack for ${role}.`); fonts[role as keyof ThemeFonts] = stack.trim(); } } return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) }; } /** The saved custom themes. Version 1 themes use the palette of `legacyMode`, by default the saved appearance mode. */ export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] { try { const stored = readSection('customThemes'); if (!Array.isArray(stored)) return []; if (!legacyMode) legacyMode = (readSection('appearance') as { mode?: unknown } | undefined)?.mode === 'light' ? 'light' : 'dark'; const mode = legacyMode; return stored.flatMap(value => { try { return [parseCustomTheme(value, mode)]; } catch { return []; } }); } catch { return []; } } /** Throws at once if browser storage refuses the change. The promise reports a failed save. */ export function installTheme(theme: CustomTheme): Promise { const list = customThemes().filter(item => item.id !== theme.id); return writeSection('customThemes', [...list, parseCustomTheme(theme)]); } /** Throws at once if browser storage refuses the change. The promise reports a failed save. */ export function removeTheme(id: string): Promise { return writeSection('customThemes', customThemes().filter(item => item.id !== id)); }