Files
RuneStone/src/lib/theme/customThemes.ts
T
Knotty Wyvern 5d5ba9e1f7 Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder.
WebView storage can be lost, and the host cannot read it. The file has
a schema number, a revision number, and one value for each section:
general, appearance, customThemes, customThemesLegacy, and language.
- settings_read gives all sections, the revision, and a one-time
  notice.
- settings_write replaces one section, writes the file atomically, and
  sends settings-changed to all windows. The limit is 8 MiB.
- settings_migrate writes the first file only when no file exists.
- The host moves a damaged file to settings.corrupt-<seconds>.json,
  starts from the defaults, and reports this one time.

Each window loads the sections before its first render. One store in
src/lib/settings/store.ts replaces the storage listeners. When no file
exists, the window normalizes the old localStorage values and migrates
them. The old keys stay in place for one release. The window layout
and the open tabs stay in localStorage on purpose. The browser preview
keeps all preferences in localStorage.

Keep tab transfer offers in host memory, not in localStorage, because
an offer can hold unsaved text. A window takes an offer once. The host
checks the workspace root and a 120 second expiry. When the receiver
accepts the tab, the host sends tab-transfer-accepted to the source
window only. A refused offer stays open, and the source tab stays open.
A new window and a drop on the tab ribbon use one check.

The smoke harness serves the new commands from one shared state for
each browser context. Tests read saved values from the mock settings
file. Rust, unit, and smoke tests cover the changes.
2026-10-27 23:56:00 -07:00

65 lines
4.4 KiB
TypeScript

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<Record<typeof COLOR_TOKENS[number], string>>;
export const FONT_ROLES = ['ui', 'prose', 'heading', 'mono'] as const;
export type ThemeFonts = Partial<Record<typeof FONT_ROLES[number], string>>;
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<string, unknown>;
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<void> {
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<void> {
return writeSection('customThemes', customThemes().filter(item => item.id !== id));
}