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

@ -66,7 +66,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere.
- **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names.
- **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface.
- **Colours are tokens, not hex.** Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's colour). Data colours (accents, event and region colours) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`.
- **Colours are tokens, not hex.** Admins can override any token (Panel → Site settings → Colours); the defaults live in three places that must agree: `src/index.css`, `THEME_DEFAULTS` in `server/src/theme.js`, `THEME_COLORS` in `src/lib/adminSchema/siteSettings.ts`. Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's colour). Data colours (accents, event and region colours) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`.
- **No em-dashes** (U+2014) anywhere: UI text, help text, comments, docs, commit messages. Use a colon, comma or parentheses. An empty table cell shows `-`.
- **Admin editor text:** blank select options read `Default: …` (what blank means), examples in help text start with `eg.`, and record ids are called "URL ID". Cut-off preview text uses `preview()` from `src/lib/text.ts`, which ends it with an ellipsis. See `docs/updating-data-in-code.md`.
@ -74,6 +74,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema.js` (server) and `src/lib/adminSchema/` (client, one file per entity, registered in `adminSchema.ts`) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code.
- Child collections are deleted and reinserted wholesale. Unsafe for entities referenced by foreign keys elsewhere.
- `reindex: false` prevents cross-entity sort order collisions.
- `check: (db, id) => void` runs after a save has written everything, inside its transaction; throwing an `HttpError` refuses the save (Site settings uses it for the colour contrast check, `server/src/theme.js`).
- The `OMIT` sentinel distinguishes unsent fields from deliberate clears.
- `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree.
- `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift.

View file

@ -274,7 +274,7 @@ The numbers band's "Number Source" dropdown works the same way:
| History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. |
| Chapter map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). |
| Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. |
| The site's colours, light and dark | `src/index.css` (`@theme` tokens and the dark overrides under them) | Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are the `@theme` tokens and dark block in `src/index.css`, and must stay the same in `THEME_DEFAULTS` (`server/src/theme.js`) and `THEME_COLORS` (`src/lib/adminSchema/siteSettings.ts`). Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. |
| Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. |
| Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | |

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

View file

@ -125,6 +125,14 @@ const inputLocked =
/* ── Dotted paths ────────────────────────────────────────────── */
/* What an empty colour field shows in its swatch and placeholder:
the field's own default (a value, or one worked out from the row),
else the brand teal. */
function colorPlaceholder(field, row): string {
const own = typeof field.placeholder === "function" ? field.placeholder(row) : field.placeholder;
return own || "#138ba0";
}
export function getPath(object, path) {
// An entity with no slug has no heading path either, and a missing
// path should read as "no value" rather than throwing on .split.
@ -274,7 +282,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
<div className="flex gap-2">
<input
type="color"
value={/^#[0-9a-f]{6}$/i.test(value ?? "") ? value : "#138ba0"}
value={/^#[0-9a-f]{6}$/i.test(value ?? "") ? value : colorPlaceholder(field, row)}
disabled={locked}
onChange={(e) => onChange(e.target.value)}
className="h-9 w-12 shrink-0 rounded border border-muted/25 bg-surface disabled:opacity-50"
@ -282,7 +290,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
<input
{...common}
readOnly={locked}
placeholder="#138ba0"
placeholder={colorPlaceholder(field, row)}
className={locked ? inputLocked : common.className}
/>
</div>

View file

@ -8,6 +8,29 @@ const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).m
([path, page]) => [path, `${page.title} (${path})`],
);
/* The palette an admin can change: token, label, light default, dark
default. Keep in step with THEME_DEFAULTS in server/src/theme.js
and the tokens in src/index.css. */
const THEME_COLORS: [string, string, string, string][] = [
["ink", "Headings", "#073d4a", "#eaf6f8"],
["body", "Body text", "#26454c", "#cde0e4"],
["muted", "Secondary text and quiet borders", "#4a6b72", "#9fb9bf"],
["link", "Links and teal text", "#0f7183", "#5ccbdc"],
["brand", "Brand teal (borders, rules, rings)", "#138ba0", "#2aa7bc"],
["action", "Buttons (under white text)", "#0f7183", "#0f7183"],
["action-hover", "Buttons, hovered", "#0b5c6a", "#0b5c6a"],
["surface", "Page and card background", "#ffffff", "#0c1d21"],
["tint", "Tinted sections and panels", "#eef9fb", "#11292e"],
["tint-soft", "Faint panels and hovered rows", "#f6fbfc", "#0f2428"],
["danger", "Errors and warnings", "#b3261e", "#ff8a80"],
["danger-tint", "Error panel background", "#fdf3f2", "#3b1714"],
];
const defaultHelp = (row, column: 2 | 3) => {
const entry = THEME_COLORS.find(([token]) => token === row?.token);
return entry ? `Default: ${entry[column]}` : undefined;
};
export const siteSettings = {
key: "site_settings",
label: "Site settings",
@ -93,6 +116,37 @@ export const siteSettings = {
],
children: [
{
key: "colors",
label: "Colours",
note: "Change any of the site's colours, for light mode, dark mode or both; a blank keeps the default. Saving refuses a palette that would make text hard to read (under 4.5:1). Changes show on the next page load.",
addLabel: "Change a colour",
title: (row) => THEME_COLORS.find(([token]) => token === row.token)?.[1] ?? "New colour",
blank: { token: "", light: "", dark: "" },
fields: [
{
path: "token",
label: "Colour",
widget: "select",
options: THEME_COLORS.map(([token, label]) => [token, label]),
required: true,
},
{
path: "light",
label: "Light mode",
widget: "color",
placeholder: (row) => THEME_COLORS.find(([token]) => token === row?.token)?.[2],
help: (row) => defaultHelp(row, 2),
},
{
path: "dark",
label: "Dark mode",
widget: "color",
placeholder: (row) => THEME_COLORS.find(([token]) => token === row?.token)?.[3],
help: (row) => defaultHelp(row, 3),
},
],
},
{
key: "pages",
label: "Page titles and intros",