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

View file

@ -316,6 +316,7 @@ export function createRow(db, entity, payload) {
writeExtensions(db, entity, newId, payload, values);
writeChildren(db, entity, newId, payload, values);
entity.check?.(db, newId);
}),
);
@ -365,6 +366,9 @@ export function updateRow(db, entity, rawId, payload) {
writeExtensions(db, entity, id, payload, merged);
writeChildren(db, entity, id, payload, merged);
// The descriptor's own rule over the saved result, children
// included. Throwing rolls the whole save back.
entity.check?.(db, id);
}),
);

View file

@ -15,6 +15,9 @@
children ordered collections, replaced wholesale on save
singleton the one id this entity ever has; the engine
refuses create and delete (see front_page)
check (db, id) => void, run after a save has written
everything, inside its transaction: throw an
HttpError to refuse it (site settings' colours)
Replacing children wholesale is only safe because nothing has a
foreign key INTO these tables. That is the dividing line, and
@ -35,6 +38,8 @@
what the other side owns rather than blanking it.
═══════════════════════════════════════════════════════════════ */
import { THEME_TOKENS, checkTheme } from "./theme.js";
/* ── Column helpers ──────────────────────────────────────────── */
const text = (name, opts = {}) => ({ name, type: "text", ...opts });
@ -945,7 +950,21 @@ const siteSettings = {
order: "sort_order",
columns: [text("path", { required: true }), text("title"), text("description")],
},
{
key: "colors",
table: "site_setting_colors",
owner: { column: "settings_id" },
order: "sort_order",
columns: [
enumeration("token", THEME_TOKENS, { required: true }),
text("light"),
text("dark"),
],
},
],
// Refuses a palette that would make text hard to read (theme.js).
check: checkTheme,
};
export const ENTITIES = {

View file

@ -0,0 +1,28 @@
-- ═══════════════════════════════════════════════════════════════
-- 041 SITE COLOURS
--
-- The admin's palette (Panel → Site settings → Colours): one row per
-- colour token that differs from the site's own (src/index.css), with
-- a light and a dark value. Blank keeps that mode's default. The
-- server writes them into every page (server/src/theme.js) and
-- refuses a save that would make text hard to read.
--
-- token one of the tokens in THEME_DEFAULTS (theme.js), which
-- the admin's dropdown offers
-- light '#rrggbb', or null for the default
-- dark '#rrggbb', or null for the default
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_setting_colors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
token TEXT NOT NULL CHECK (token IN (
'ink', 'body', 'muted', 'link', 'brand', 'action', 'action-hover',
'surface', 'tint', 'tint-soft', 'danger', 'danger-tint')),
light TEXT CONSTRAINT "A colour must be written #rrggbb, eg. #0f7183."
CHECK (light IS NULL OR (length(light) = 7 AND light GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')),
dark TEXT CONSTRAINT "A dark colour must be written #rrggbb, eg. #5ccbdc."
CHECK (dark IS NULL OR (length(dark) = 7 AND dark GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')),
UNIQUE (settings_id, token)
) STRICT;

View file

@ -42,6 +42,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadBlocks, paragraphs } from "./shape.js";
import { themeCss } from "./theme.js";
const here = path.dirname(fileURLToPath(import.meta.url));
@ -103,6 +104,9 @@ export function siteFor(db) {
index: row.indexing ? row.indexing === "on" : base.robots?.index !== false,
},
privacyEmail: row.privacy_email || base.privacyEmail || "",
// The admin's colours (theme.js): only #rrggbb values and fixed
// text, so safe inside <style>.
themeCss: themeCss(db),
pages,
};
}
@ -442,6 +446,7 @@ export function renderPage(html, meta) {
// Read by src/lib/site.ts before the app's module runs (a plain
// script in the head runs during parsing; modules wait).
`<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,
site.themeCss && `<style id="site-colors">${site.themeCss}</style>`,
].filter(Boolean);
// A blocked site (Site settings indexing off, or site.json's

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("; ")}.`);
}
}