41 lines
2.4 KiB
TypeScript
41 lines
2.4 KiB
TypeScript
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"] as const;
|
|
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
|
|
export type CustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
|
|
|
|
export function parseCustomTheme(input: unknown): CustomTheme {
|
|
if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file.");
|
|
const value = input as Record<string, unknown>;
|
|
if (value.schema !== 1 || 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 1, 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;
|
|
};
|
|
return { schema: 1, id: value.id, name: value.name.trim(), light: colors("light"), dark: colors("dark") };
|
|
}
|
|
|
|
export function customThemes(): CustomTheme[] {
|
|
try {
|
|
const stored = JSON.parse(localStorage.getItem(CUSTOM_THEMES_KEY) || "[]");
|
|
return Array.isArray(stored) ? stored.flatMap(value => { try { return [parseCustomTheme(value)]; } catch { return []; } }) : [];
|
|
} catch { return []; }
|
|
}
|
|
|
|
export function installTheme(theme: CustomTheme): void {
|
|
const list = customThemes().filter(item => item.id !== theme.id);
|
|
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify([...list, parseCustomTheme(theme)]));
|
|
}
|
|
|
|
export function removeTheme(id: string): void {
|
|
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(customThemes().filter(item => item.id !== id)));
|
|
}
|