Let superadmins change the whole colour palette

Panel -> Site settings -> Colours: any colour token, with a light and a
dark value (migration 041). The server writes the overrides into each
page's head in the same cascade layers as index.css, so a light-only
change leaves dark mode alone. Values must be #rrggbb (a table CHECK),
and saving refuses a palette that puts any text under 4.5:1 in either
mode, through a new descriptor hook, check(db, id), run inside the
save's transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-28 23:26:35 -05:00
parent a225e84408
commit f1edaaf92a
9 changed files with 258 additions and 4 deletions

135
server/src/theme.js Normal file
View file

@ -0,0 +1,135 @@
/* ═══════════════════════════════════════════════════════════════
THEME
The admin's palette (Panel → Site settings → Colours, table
site_setting_colors) over the site's own colour tokens.
THEME_DEFAULTS must match @theme and the dark block in
src/index.css: the same tokens, the same light and dark values.
A blank override keeps the default.
themeCss() is written into every page's <head> (pageMeta.js).
It goes into the same cascade layers as index.css (theme for
light, base for dark), after it, so an override replaces exactly
the value it names: a light-only change leaves dark mode alone.
checkTheme() runs when Site settings is saved (the descriptor's
`check`, inside the save's transaction), and refuses a palette in
which any text would fall under WCAG AA (4.5:1) in either mode, so
an admin can't make the site unreadable.
═══════════════════════════════════════════════════════════════ */
import { HttpError } from "./admin-crud.js";
// light dark
export const THEME_DEFAULTS = {
ink: ["#073d4a", "#eaf6f8"],
body: ["#26454c", "#cde0e4"],
muted: ["#4a6b72", "#9fb9bf"],
link: ["#0f7183", "#5ccbdc"],
brand: ["#138ba0", "#2aa7bc"],
action: ["#0f7183", "#0f7183"],
"action-hover": ["#0b5c6a", "#0b5c6a"],
surface: ["#ffffff", "#0c1d21"],
tint: ["#eef9fb", "#11292e"],
"tint-soft": ["#f6fbfc", "#0f2428"],
danger: ["#b3261e", "#ff8a80"],
"danger-tint": ["#fdf3f2", "#3b1714"],
};
export const THEME_TOKENS = Object.keys(THEME_DEFAULTS);
const HEX = /^#[0-9a-f]{6}$/i;
const MODES = ["light", "dark"];
function overrides(db) {
const rows = db
.prepare(`SELECT token, light, dark FROM site_setting_colors WHERE settings_id = 'site'`)
.all();
// Checked again here, not only by the table's CHECK: this goes
// straight into a <style> element.
return rows.filter((row) => THEME_DEFAULTS[row.token]);
}
/* { light: { ink: '#…', … }, dark: { … } }, defaults with overrides. */
function palette(db) {
const out = { light: {}, dark: {} };
for (const [token, [light, dark]] of Object.entries(THEME_DEFAULTS)) {
out.light[token] = light;
out.dark[token] = dark;
}
for (const row of overrides(db)) {
MODES.forEach((mode) => {
if (HEX.test(row[mode] ?? "")) out[mode][row.token] = row[mode].toLowerCase();
});
}
return out;
}
export function themeCss(db) {
const rows = overrides(db);
const decls = (mode) =>
rows
.filter((row) => HEX.test(row[mode] ?? ""))
.map((row) => `--color-${row.token}:${row[mode].toLowerCase()}`)
.join(";");
const light = decls("light");
const dark = decls("dark");
if (!light && !dark) return "";
return [
light && `@layer theme{:root{${light}}}`,
dark &&
`@layer base{:root[data-theme="dark"]{${dark}}` +
`@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){${dark}}}}`,
]
.filter(Boolean)
.join("");
}
/* ── Contrast ──────────────────────────────────────────────────── */
function luminance(hex) {
const channel = (i) => {
const c = parseInt(hex.slice(i, i + 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);
}
export function contrast(a, b) {
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
}
const TEXT = ["ink", "body", "muted", "link", "danger"];
const BACKGROUNDS = ["surface", "tint", "tint-soft"];
/* Every pair that has to stay readable: [text, background, minimum]. */
function pairs(colors) {
const list = [];
for (const text of TEXT) {
for (const bg of BACKGROUNDS) list.push([text, colors[text], bg, colors[bg], 4.5]);
}
list.push(["danger", colors.danger, "danger-tint", colors["danger-tint"], 4.5]);
list.push(["white text", "#ffffff", "action", colors.action, 4.5]);
list.push(["white text", "#ffffff", "action-hover", colors["action-hover"], 4.5]);
// Decoration (borders, rules) only needs to be visible.
list.push(["brand", colors.brand, "surface", colors.surface, 3]);
return list;
}
export function checkTheme(db) {
const colors = palette(db);
const problems = [];
for (const mode of MODES) {
for (const [a, aHex, b, bHex, min] of pairs(colors[mode])) {
const ratio = contrast(aHex, bHex);
if (ratio < min) {
problems.push(`${a} on ${b} in ${mode} mode is ${ratio.toFixed(2)}:1, needs ${min}:1`);
}
}
}
if (problems.length) {
throw new HttpError(422, `These colours would be hard to read: ${problems.join("; ")}.`);
}
}