feat(theming): server-resolved theme engine and admin appearance UI

Phases 3-4 of docs/website/THEMING_AND_NAV.md. Three presets, the curated font
shortlist, and /admin/appearance to drive them.

The design put the presets in theme.css as [data-theme] blocks. That does not
work: SiteContext writes --accent as an inline style on <html>, which beats any
attribute-selector block, so a preset's accent would have been painted over by
BRAND_ACCENT_COLOR while getPublic().brand.accent -- the value the Android app
themes itself from -- reported the other one.

Presets now live in server/src/config/themePresets.js. themeResolve.js layers
:root <- preset <- custom per field into a token map, getPublic() returns it as
`theme`, and the client writes it onto <html>. One authority for the merge, and
brand.accent is by construction the accent the site paints. theme.css's :root is
untouched, so an instance with no row gets no theme block and renders as today.

Also: presets carry the full 15-token palette (eight would have left Fantasy
with blue-grey borders); the option catalog is served from
GET /settings/theme/options so the form cannot offer what the server rejects;
validation is strict on write and forgiving on read; and the Discord bot now
fetches the effective accent instead of its boot-time env copy.

Fixes a Phase 0 bug in passing: settings/nav.controller.js imported the logger
factory rather than calling it, so a DB fault would have thrown a TypeError
inside the catch instead of returning 500.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-07 19:16:23 -05:00
parent 0a2ccafff6
commit 3d6b2e23a7
26 changed files with 2113 additions and 28 deletions

View File

@@ -41,6 +41,7 @@ import PagesAdmin from './routes/admin/views/PagesAdmin.jsx'
import PageBuilder from './routes/admin/views/PageBuilder.jsx'
import WikiAdmin from './routes/admin/views/WikiAdmin.jsx'
import HeroEditor from './routes/admin/views/HeroEditor.jsx'
import AppearanceAdmin from './routes/admin/views/AppearanceAdmin.jsx'
import SettingsAdmin from './routes/admin/views/SettingsAdmin.jsx'
import ActivityAdmin from './routes/admin/views/ActivityAdmin.jsx'
import BotActivityAdmin from './routes/admin/views/BotActivityAdmin.jsx'
@@ -139,6 +140,17 @@ export default function App() {
<Route path="pages/:id" element={<PageBuilder />} />
<Route path="wiki" element={<WikiAdmin />} />
<Route path="hero" element={<HeroEditor />} />
{/* Theme editing writes an admin-only settings key; the route sits
behind the same RoleGate as the sidebar entry that reaches it,
and PUT/DELETE /admin/settings is admin-only server-side too. */}
<Route
path="appearance"
element={
<RoleGate roles={['admin']}>
<AppearanceAdmin />
</RoleGate>
}
/>
<Route path="settings" element={<SettingsAdmin />} />
<Route
path="moderation"

View File

@@ -97,6 +97,14 @@ export const api = {
generateRecoveryCodes: (currentPassword) =>
req('/auth/me/account/recovery-codes/generate', { method: 'POST', body: { currentPassword } }),
// ----- settings (any authenticated account) -----
// Nav overrides for the layouts the caller's own role renders, and the theme
// catalog the appearance form is built from. A fifth group, not part of
// /admin, because AdminLayout renders for editors and moderators too — see
// docs/website/THEMING_AND_NAV.md §4.2.
navSettings: () => req('/settings/nav'),
themeOptions: () => req('/settings/theme/options'),
// ----- public -----
publicSettings: () => req('/public/settings'),
status: () => req('/public/status'),
@@ -280,6 +288,10 @@ export const api = {
deleteWikiCategory: (id) => req(`/admin/wiki/categories/${id}`, { method: 'DELETE' }),
getSettings: () => req('/admin/settings'),
updateSettings: (obj) => req('/admin/settings', { method: 'PUT', body: obj }),
// Reset one setting to its default by deleting the row — the theming/nav
// keys and the hero draft only (the server holds the allowlist). Idempotent,
// so the caller need not know whether a row exists.
resetSetting: (key) => req(`/admin/settings/${encodeURIComponent(key)}`, { method: 'DELETE' }),
activity: (limit = 50) => req(`/admin/activity?limit=${limit}`),
botActivity: () => req('/admin/bot-activity'),
unbanIp: (ip) => req('/admin/bot-activity/unban', { method: 'POST', body: { ip } }),

View File

@@ -1,5 +1,6 @@
import { createContext, useContext, useEffect, useState, useCallback, useMemo } from 'react'
import { createContext, useContext, useEffect, useRef, useState, useCallback, useMemo } from 'react'
import { api } from '../api/client.js'
import { applyThemeTokens } from '../lib/themeVars.js'
const SiteContext = createContext(null)
@@ -25,11 +26,28 @@ export function SiteProvider({ children }) {
const brand = useMemo(() => settings.brand || {}, [settings])
// Apply the admin's theme. The whole effective token set is resolved
// server-side, so this only writes it and takes back what it wrote before —
// see lib/themeVars.js for why the removal half matters. No theme block means
// the admin never themed this instance, and the shipped :root stands.
const appliedTokens = useRef([])
useEffect(() => {
appliedTokens.current = applyThemeTokens(document.documentElement.style, settings.theme, appliedTokens.current)
}, [settings.theme])
// Apply the instance accent color to the CSS variable the theme is built on,
// so branding flows to every `var(--accent)` at runtime (no rebuild).
// so branding flows to every `var(--accent)` at runtime (no rebuild). This is
// the *effective* accent — the admin theme overrides BRAND_ACCENT_COLOR
// server-side (docs/website/THEMING_AND_NAV.md §4.5) — so it agrees with the
// theme block rather than fighting it.
//
// Deliberately ordered after the theme effect and re-run on any theme change:
// resetting a theme removes --accent from the token map, and this has to be
// the write that lands last or an instance with a custom BRAND_ACCENT_COLOR
// would drop to the stylesheet's default accent until the next reload.
useEffect(() => {
if (brand.accent) document.documentElement.style.setProperty('--accent', brand.accent)
}, [brand.accent])
}, [brand.accent, settings.theme])
// Memoized so consumers don't re-render on every provider render (brand is a
// fresh object each render, which would otherwise churn the context value).

View File

@@ -0,0 +1,47 @@
// Apply the server-resolved theme to the document as CSS custom properties.
//
// The effective token set is resolved server-side and arrives on
// `settings.theme` (see server/src/utils/themeResolve.js). The client's only
// job is to write it onto <html> — and, crucially, to take back what it wrote
// last time, which is the part with actual logic and the reason this lives in
// its own testable module.
//
// Why removal matters: an admin who resets the theme, or switches from a preset
// that sets --bg to one that does not, gets a payload that no longer mentions
// that variable. Inline properties are not cleared by writing a smaller object
// over them, so without an explicit removeProperty the old value would stick
// until a reload. That would make "Reset to defaults" look broken.
//
// Everything written here is a value the server validated against a closed set
// (hex color, curated font stack, bounded px length, listed shadow). The client
// deliberately does not re-validate — it would be a second, drifting authority.
// It does refuse anything that is not a `--custom-property`, which is the one
// check that costs nothing and stops a token map from reaching an ordinary CSS
// property.
const CUSTOM_PROPERTY = /^--[a-zA-Z0-9-_]+$/
/**
* @param {CSSStyleDeclaration} style usually document.documentElement.style
* @param {Record<string, string>|null|undefined} tokens the new theme, or
* null/absent for "no admin theme" — which clears everything previously set
* @param {string[]} [applied] the keys this function wrote last time
* @returns {string[]} the keys now applied, to pass back on the next call
*/
export function applyThemeTokens(style, tokens, applied = []) {
const next = []
if (tokens && typeof tokens === 'object') {
for (const [name, value] of Object.entries(tokens)) {
if (!CUSTOM_PROPERTY.test(name) || typeof value !== 'string' || value === '') continue
style.setProperty(name, value)
next.push(name)
}
}
// Take back only what we set ourselves. Anything else on the element's inline
// style belongs to someone else (SiteContext's own --accent line, a future
// feature) and is not ours to clear.
for (const name of applied) {
if (!next.includes(name)) style.removeProperty(name)
}
return next
}

View File

@@ -38,6 +38,7 @@ const IconBot = () => <Icon><rect x="4" y="8" width="16" height="11" rx="2" /><p
const IconPulse = () => <Icon><path d="M3 12h3l2 6 4-14 2 8h7" /></Icon>
const IconUser = () => <Icon><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></Icon>
const IconShard = () => <Icon><path d="M12 2l7 6-7 14-7-14z" /><path d="M5 8h14" /></Icon>
const IconPalette = () => <Icon><path d="M12 3a9 9 0 1 0 0 18 2 2 0 0 0 1.6-3.2 2 2 0 0 1 1.6-3.2H18a3 3 0 0 0 3-3 9 9 0 0 0-9-8.6z" /><circle cx="7.5" cy="11.5" r="1" /><circle cx="10.5" cy="7.5" r="1" /><circle cx="15" cy="8.5" r="1" /></Icon>
// Nav is grouped into collapsible categories. A group with no `title` renders
// its items ungrouped (Dashboard at top, Account at bottom). Each item's `roles`
@@ -74,6 +75,7 @@ const NAV = [
{ to: '/admin/users', label: 'Users', icon: IconUsers, roles: ['admin'] },
{ to: '/admin/invites', label: 'Invites', icon: IconUsers, roles: ['admin'] },
{ to: '/admin/settings', label: 'Settings', icon: IconGear, roles: ['admin'] },
{ to: '/admin/appearance', label: 'Appearance', icon: IconPalette, roles: ['admin'] },
{ to: '/admin/hero', label: 'Hero Editor', icon: IconHero, roles: ['admin'] },
{ to: '/admin/auth-providers', label: 'Authentication', icon: IconKey, roles: ['admin'] },
{ to: '/admin/discord-bot', label: 'Discord Bot', icon: IconBot, roles: ['admin'] },
@@ -104,6 +106,7 @@ const TITLES = {
'/admin/shard-ops': 'In-Game Ops',
'/admin/houses': 'House Registry',
'/admin/settings': 'Site Settings',
'/admin/appearance': 'Appearance',
'/admin/activity': 'Activity Log',
'/admin/bot-activity': 'Web Bot Activity',
'/admin/discord-bot': 'Discord Bot',

View File

@@ -0,0 +1,354 @@
import { useEffect, useMemo, useState } from 'react'
import { Loading, ErrorState } from '../../../components/PageState.jsx'
import { api } from '../../../api/client.js'
import { useSite } from '../../../contexts/SiteContext.jsx'
// Admin · Appearance — the theme half of docs/website/THEMING_AND_NAV.md
// (phases 3-4). Brand asset uploads and the nav builder are phases 5 and 7 and
// get their own screens.
//
// Two things shape this form:
//
// • Every control is a closed set. The presets, the font shortlist and the
// shadow depths all come from GET /settings/theme/options, which is derived
// from the same server config the save is validated against — so the form
// can never offer a value the server would reject. Nothing here is free
// text except the color inputs, which are <input type="color"> and so are
// hex by construction.
// • Saving means writing a settings row; resetting means DELETING it. Absence
// of the row is what selects the shipped default, so "reset" cannot write a
// copy of the defaults — see §2.
// Human labels for the eight editable colors and four radii. The field names
// and the CSS variables they drive both come from the server
// (colorFields / radiusFields); this only decorates them, and a field with no
// label here still renders under its raw name rather than vanishing.
const COLOR_LABELS = {
bg: 'Background',
bgDeep: 'Background (deep)',
panelA: 'Panel (top)',
panelB: 'Panel (bottom)',
accent: 'Accent',
accentBright: 'Accent (bright)',
ink: 'Ink / headings',
text: 'Body text',
}
const RADIUS_LABELS = {
radiusPill: 'Pills & buttons',
radiusPanel: 'Flat panels',
radiusCard: 'Cards & panels',
radiusInput: 'Inputs & notes',
}
const FONT_LABELS = {
serif: 'Body serif',
display: 'Display / headings',
sans: 'Interface sans',
}
// Strip empty groups so a theme the admin cleared back out is stored as a bare
// preset rather than as `{colors:{}, fonts:{}, structure:{}}`. Never null a
// field out to "clear" it — remove it (§6.1).
function compactCustom(custom) {
const out = {}
for (const [group, fields] of Object.entries(custom)) {
const kept = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== '' && v != null))
if (Object.keys(kept).length) out[group] = kept
}
return Object.keys(out).length ? out : null
}
export default function AppearanceAdmin() {
const { refresh: refreshSite } = useSite()
const [options, setOptions] = useState(null)
const [preset, setPreset] = useState('runic-gateway')
const [custom, setCustom] = useState({ colors: {}, fonts: {}, structure: {} })
// Whether a theme_visual row exists at all. Drives the "reset" button and the
// "this instance is using the shipped theme" note — an admin needs to be able
// to tell "never themed" from "themed to look like the default".
const [stored, setStored] = useState(false)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [saved, setSaved] = useState(false)
useEffect(() => {
let active = true
Promise.all([api.themeOptions(), api.admin.getSettings()])
.then(([opts, all]) => {
if (!active) return
setOptions(opts)
// The stored value is a JSON string (settings.value is TEXT). Malformed
// reads as absent, exactly as the server treats it — the form then shows
// the shipped default rather than an error.
let parsed = null
try {
const raw = all.theme_visual
parsed = raw ? JSON.parse(raw) : null
} catch {
parsed = null
}
setStored(Boolean(all.theme_visual))
if (parsed && typeof parsed === 'object') {
setPreset(parsed.preset || 'runic-gateway')
setCustom({
colors: parsed.custom?.colors || {},
fonts: parsed.custom?.fonts || {},
structure: parsed.custom?.structure || {},
})
}
})
.catch(() => active && setError('Could not load the appearance settings.'))
.finally(() => active && setLoading(false))
return () => {
active = false
}
}, [])
// What an unset field currently resolves to: the selected preset's palette,
// or the shipped theme when the preset is Custom (which has no base). Lets a
// color picker open on the value the admin is actually looking at.
const baseTokens = useMemo(() => {
if (!options) return {}
return options.presets.find((p) => p.id === preset)?.tokens || options.shippedTokens
}, [options, preset])
if (loading) return <Loading />
if (error && !options) return <ErrorState message={error} />
const setField = (group, field) => (value) => {
setCustom((c) => ({ ...c, [group]: { ...c[group], [field]: value } }))
setSaved(false)
}
const clearField = (group, field) => () => {
setCustom((c) => {
const next = { ...c[group] }
delete next[field]
return { ...c, [group]: next }
})
setSaved(false)
}
async function save() {
setBusy(true)
setError('')
try {
await api.admin.updateSettings({ theme_visual: { preset, custom: compactCustom(custom) } })
setStored(true)
setSaved(true)
// Repull the public settings so the surrounding admin UI re-themes itself
// immediately — the admin sees the change they just made.
await refreshSite()
} catch (err) {
setError(err.message || 'Could not save the theme.')
} finally {
setBusy(false)
}
}
async function resetAll() {
setBusy(true)
setError('')
try {
await api.admin.resetSetting('theme_visual')
setPreset('runic-gateway')
setCustom({ colors: {}, fonts: {}, structure: {} })
setStored(false)
setSaved(false)
await refreshSite()
} catch (err) {
setError(err.message || 'Could not reset the theme.')
} finally {
setBusy(false)
}
}
return (
<section style={{ maxWidth: 720, display: 'flex', flexDirection: 'column', gap: 26 }}>
<p className="sans dim" style={{ margin: 0, fontSize: '0.82rem', lineHeight: 1.7 }}>
Colors, fonts and corner radius for the public site, this admin panel and the player portal.
{' '}
{stored ? (
<>This instance has a saved theme. <strong style={{ color: 'var(--muted)' }}>Reset to default</strong> deletes it and returns to the shipped look.</>
) : (
<>This instance has never been themed, so it uses the shipped look and its <code>BRAND_*</code> accent.</>
)}
</p>
{/* ── Preset ─────────────────────────────────────────────── */}
<div>
<span className="field-label">Preset</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginTop: 8 }}>
{options.presets.map((p) => (
<button
key={p.id}
type="button"
onClick={() => {
setPreset(p.id)
setSaved(false)
}}
className="sans"
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
padding: '10px 14px',
borderRadius: 'var(--radius-input)',
border: `1px solid ${preset === p.id ? 'var(--accent)' : 'var(--line)'}`,
background: preset === p.id ? 'var(--blue)' : 'transparent',
color: preset === p.id ? 'var(--ink)' : 'var(--muted)',
cursor: 'pointer',
fontSize: '0.86rem',
}}
aria-pressed={preset === p.id}
>
{p.tokens ? (
<span style={{ display: 'flex', borderRadius: 4, overflow: 'hidden', border: '1px solid var(--line)' }}>
{['--bg', '--panel-a', '--accent', '--ink'].map((t) => (
<span key={t} style={{ width: 11, height: 18, background: p.tokens[t] }} />
))}
</span>
) : (
<span style={{ width: 44, height: 18, borderRadius: 4, border: '1px dashed var(--line)' }} />
)}
{p.label}
</button>
))}
</div>
<span className="sans dim" style={{ display: 'block', marginTop: 8, fontSize: '0.76rem' }}>
{preset === 'custom'
? 'Custom starts from the shipped theme — only the fields you set below change.'
: 'A preset sets the whole palette. Anything you set below overrides it, field by field.'}
</span>
</div>
{/* ── Colors ─────────────────────────────────────────────── */}
<div>
<span className="field-label">Colors</span>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))', gap: 12, marginTop: 8 }}>
{options.colorFields.map(({ name, token }) => {
const set = custom.colors[name] !== undefined
return (
<div key={name} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{/* <input type="color"> has no empty state, so an unset field
shows what it currently resolves to rather than black. */}
<input
type="color"
value={custom.colors[name] || baseTokens[token] || '#000000'}
onChange={(e) => setField('colors', name)(e.target.value)}
aria-label={COLOR_LABELS[name] || name}
style={{ width: 34, height: 30, padding: 0, border: '1px solid var(--line)', borderRadius: 6, background: 'transparent', cursor: 'pointer' }}
/>
<span className="sans" style={{ flex: 1, fontSize: '0.82rem', color: set ? 'var(--ink)' : 'var(--dim)' }}>
{COLOR_LABELS[name] || name}
</span>
{set && (
<button type="button" onClick={clearField('colors', name)} className="sans" title="Follow the preset again" style={linkBtn}>
clear
</button>
)}
</div>
)
})}
</div>
<span className="sans dim" style={{ display: 'block', marginTop: 8, fontSize: '0.76rem' }}>
A color you have not set follows the preset. Live and maintenance status colors are never themed green has to keep meaning live.
</span>
</div>
{/* ── Fonts ──────────────────────────────────────────────── */}
<div>
<span className="field-label">Fonts</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8 }}>
{Object.keys(options.fonts).map((role) => (
<label key={role} style={{ display: 'block' }}>
<span className="sans dim" style={{ display: 'block', fontSize: '0.76rem', marginBottom: 4 }}>
{FONT_LABELS[role] || role}
</span>
<select
className="select"
value={custom.fonts[role] || ''}
onChange={(e) => (e.target.value ? setField('fonts', role)(e.target.value) : clearField('fonts', role)())}
>
<option value="">Follow the preset</option>
{options.fonts[role].map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</label>
))}
</div>
</div>
{/* ── Structure ──────────────────────────────────────────── */}
<div>
<span className="field-label">Corners &amp; depth</span>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))', gap: 12, marginTop: 8 }}>
{options.radiusFields.map(({ name, token }) => (
<label key={name} style={{ display: 'block' }}>
<span className="sans dim" style={{ display: 'block', fontSize: '0.76rem', marginBottom: 4 }}>
{RADIUS_LABELS[name] || name}
</span>
<input
className="input"
type="number"
min="0"
max={options.radiusMaxPx}
placeholder={(baseTokens[token] || '').replace('px', '')}
value={(custom.structure[name] || '').replace('px', '')}
onChange={(e) =>
e.target.value === ''
? clearField('structure', name)()
: setField('structure', name)(`${Math.min(Math.max(parseInt(e.target.value, 10) || 0, 0), options.radiusMaxPx)}px`)
}
/>
</label>
))}
</div>
<label style={{ display: 'block', marginTop: 12 }}>
<span className="sans dim" style={{ display: 'block', fontSize: '0.76rem', marginBottom: 4 }}>
Card shadow
</span>
<select
className="select"
value={custom.structure.shadowDepth || ''}
onChange={(e) => (e.target.value ? setField('structure', 'shadowDepth')(e.target.value) : clearField('structure', 'shadowDepth')())}
>
<option value="">Follow the preset</option>
{options.shadows.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</label>
</div>
<div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<button onClick={save} disabled={busy} className="btn btn-primary btn-sq">
{busy ? 'Saving…' : 'Save theme'}
</button>
<button onClick={resetAll} disabled={busy || !stored} className="pill" title={stored ? 'Delete the saved theme' : 'Nothing to reset'}>
Reset to default
</button>
{saved && <span className="sans" style={{ color: '#7fd0a4', fontSize: '0.85rem' }}>Saved.</span>}
{error && <span className="sans" style={{ color: '#d98b84', fontSize: '0.85rem' }}>{error}</span>}
</div>
<p className="sans dim" style={{ margin: 0, fontSize: '0.76rem', lineHeight: 1.7 }}>
The accent reaches the mobile app and the Discord bot too both theme themselves from this
sites public branding.
</p>
</section>
)
}
const linkBtn = {
border: 'none',
background: 'transparent',
color: 'var(--accent)',
fontSize: '0.72rem',
cursor: 'pointer',
padding: 0,
}