feat(theming): wire the three navs and add the admin nav builder

Phases 6-8 of docs/website/THEMING_AND_NAV.md. The public header, the admin
sidebar and the player portal now read their override row, and /admin/navigation
writes them: rename, reorder by drag, hide, and — on the admin sidebar — move a
row into another existing section.

The merge always runs BEFORE the role and shard-feature filters in the layouts,
which are unchanged and remain the boundary. An override is presentation: it
cannot introduce a route, cannot touch a `roles` or `feature` gate, and a stored
`hidden: false` on a gated item shows nobody anything.

The design scoped these phases as client work, but the server had no way to
store a nav row: updateSettings validates and stringifies theme_visual and
brand_assets and lets everything else through, so a nav object would have been
written as "[object Object]" and read as absent for ever. utils/navOverrides.js
mirrors utils/brandAssets.js — strict on write with the offending key named,
forgiving on read. It validates shape only; whether a `to` exists is settled
client-side at merge time, because the base NAV arrays are client constants and
a server-side copy would be a second source of truth that drifts.

The nav editor cannot be hidden — its own toggle is disabled, the write path
drops `hidden` on that one `to`, and AdminLayout strips it again before merging,
which also covers a row edited straight in the database.

Orders are written only when the sequence actually differs from the code's, and
the comparison is restricted to the rows the editing admin can see, so renaming
one item does not pin the position of every other one and a role- or
feature-gated item missing from their palette is not mistaken for a reorder.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-08 00:02:33 -05:00
parent 42a403ad2e
commit 32a3ff104a
19 changed files with 1499 additions and 79 deletions

View File

@@ -57,20 +57,73 @@ function byOrder(items) {
})
}
// Apply label/hidden/order to one flat list. Returns visible items only, with
// the sort key parked on `__order` for byOrder to consume.
function mergeItems(items, entries) {
// Apply label/hidden/order to one flat list, with the sort key parked on
// `__order` for byOrder to consume.
//
// `keepHidden` is what the admin editor needs and the site must not have: the
// editor has to render a hidden row in its right place so it can be un-hidden,
// while a layout must simply not render it. Same merge either way, so the two
// can never disagree about where an item sits.
function mergeItems(items, entries, keepHidden = false) {
const out = []
for (const item of items) {
const o = entries.get(item.to)
if (o?.hidden) continue
if (o?.hidden && !keepHidden) continue
// Spread the base item first so `to`, `roles`, `feature`, `icon` and `end`
// survive verbatim — the override only ever lands on `label`.
out.push({ ...item, ...(o?.label ? { label: o.label } : {}), __order: o?.order })
out.push({
...item,
...(o?.label ? { label: o.label } : {}),
...(keepHidden ? { defaultLabel: item.label, hidden: o?.hidden === true } : {}),
__order: o?.order,
})
}
return out
}
// The stored overrides, cleaned and keyed, plus the group titles the base nav
// declares. Shared by the merge and the editor so both read a row the same way.
function readOverrides(baseNav, overrides, grouped) {
const groupTitles = new Set(
grouped ? baseNav.map((g) => g.title).filter((t) => typeof t === 'string') : [],
)
const entries = new Map()
if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) return { entries, groupTitles }
// Keyed by `to`, and only for a `to` the base nav actually declares. An
// override for a route that no longer exists is dropped here, so deleting a
// route in code can never leave a dangling override that does something
// unexpected later.
const known = new Set(
grouped ? baseNav.flatMap((g) => g.items.map((i) => i.to)) : baseNav.map((i) => i.to),
)
for (const [to, raw] of Object.entries(overrides)) {
if (!known.has(to)) continue
const entry = cleanEntry(raw, groupTitles)
if (entry && Object.keys(entry).length > 0) entries.set(to, entry)
}
return { entries, groupTitles }
}
// Move items whose override names a different existing section. Groups keep
// their coded order — only membership and within-group order move.
function regroup(baseNav, entries) {
const moved = new Map() // destination title → items pulled in from elsewhere
const kept = baseNav.map((g) => {
const items = []
for (const item of g.items) {
const o = entries.get(item.to)
if (o?.group && o.group !== g.title) {
if (!moved.has(o.group)) moved.set(o.group, [])
moved.get(o.group).push(item)
continue
}
items.push(item)
}
return { ...g, items }
})
return { kept, moved }
}
/**
* @param {Array} baseNav the hardcoded nav — the source of truth for `to`,
* `roles`, `feature`, `icon` and `end`
@@ -86,43 +139,13 @@ export function applyNavOverrides(baseNav, overrides) {
if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) return baseNav
const grouped = isGrouped(baseNav)
const groupTitles = new Set(
grouped ? baseNav.map((g) => g.title).filter((t) => typeof t === 'string') : [],
)
// Keyed by `to`, and only for a `to` the base nav actually declares. An
// override for a route that no longer exists is dropped here, so deleting a
// route in code can never leave a dangling override that does something
// unexpected later.
const known = new Set(
grouped ? baseNav.flatMap((g) => g.items.map((i) => i.to)) : baseNav.map((i) => i.to),
)
const entries = new Map()
for (const [to, raw] of Object.entries(overrides)) {
if (!known.has(to)) continue
const entry = cleanEntry(raw, groupTitles)
if (entry && Object.keys(entry).length > 0) entries.set(to, entry)
}
const { entries } = readOverrides(baseNav, overrides, grouped)
if (entries.size === 0) return baseNav
if (!grouped) return byOrder(mergeItems(baseNav, entries))
// Grouped: an item may also be moved into another *existing* titled section.
// Groups keep their coded order — only membership and within-group order move.
const moved = new Map() // destination title → items pulled in from elsewhere
const kept = baseNav.map((g) => {
const items = []
for (const item of g.items) {
const o = entries.get(item.to)
if (o?.group && o.group !== g.title) {
if (!moved.has(o.group)) moved.set(o.group, [])
moved.get(o.group).push(item)
continue
}
items.push(item)
}
return { ...g, items }
})
const { kept, moved } = regroup(baseNav, entries)
return kept
.map((g) => ({
@@ -135,4 +158,109 @@ export function applyNavOverrides(baseNav, overrides) {
.filter((g) => g.items.length > 0)
}
// ── The admin editor's round trip ────────────────────────────────────────
//
// Two functions, inverse to each other, kept in this file rather than beside the
// editor screen so the thing that *writes* an override and the thing that
// *applies* one can never drift: the rows the admin drags are produced by the
// same merge the site renders, hidden ones included.
/**
* The base nav plus its stored overrides, as editable rows — always in the
* grouped shape, so one editor handles both navs.
*
* Unlike applyNavOverrides this keeps hidden rows (marked `hidden: true`, so
* they can be un-hidden) and keeps empty groups (so something can be moved back
* into one). Each row carries `defaultLabel`, which is what "reset this label"
* restores and what the input shows as its placeholder.
*
* @param {Array} baseNav the hardcoded nav, flat or grouped
* @param {object|null} overrides the parsed settings JSON
* @returns {Array<{title: string|null, items: Array}>}
*/
export function buildNavRows(baseNav, overrides) {
if (!Array.isArray(baseNav) || baseNav.length === 0) return []
const grouped = isGrouped(baseNav)
const { entries } = readOverrides(baseNav, overrides, grouped)
if (!grouped) {
return [{ title: null, items: byOrder(mergeItems(baseNav, entries, true)) }]
}
const { kept, moved } = regroup(baseNav, entries)
return kept.map((g) => ({
...g,
title: g.title ?? null,
items: byOrder(mergeItems([...g.items, ...(moved.get(g.title) || [])], entries, true)),
}))
}
// Did the admin actually move anything? Comparing the edited sequence with the
// coded one is what decides whether orders are written at all: an admin who only
// renamed an item should not pin the position of every other one, or a route
// added in code later would land in an arbitrary place.
//
// The base side is restricted to the rows the editor is actually holding: §8.1
// filters the palette to what this admin can themselves see, and an item that
// their role or a shard feature kept off the screen is not a reorder.
function orderMatchesBase(groups, baseNav) {
const flatten = (gs) => gs.flatMap((g) => g.items.map((i) => `${g.title ?? ''}::${i.to}`))
const base = isGrouped(baseNav)
? baseNav.map((g) => ({ title: g.title ?? null, items: g.items }))
: [{ title: null, items: baseNav }]
const shown = new Set(groups.flatMap((g) => g.items.map((i) => i.to)))
const a = flatten(groups)
const b = flatten(base.map((g) => ({ ...g, items: g.items.filter((i) => shown.has(i.to)) })))
return a.length === b.length && a.every((v, i) => v === b[i])
}
/**
* The rows the admin has been editing, back as an overrides object to store.
* Only differences from the code default are written — a field that matches the
* default is absent, so the row stays a small statement of intent rather than a
* snapshot of the nav.
*
* @param {Array} groups the editor's groups, in their current order
* @param {Array} baseNav the hardcoded nav these rows came from
* @param {object|null} stored the overrides as loaded, so entries for items
* this admin could not see (role- or feature-gated out of their palette) are
* carried through rather than silently dropped on save
* @returns {object} the overrides to store — `{}` when nothing differs
*/
export function buildNavOverrides(groups, baseNav, stored = null) {
if (!Array.isArray(groups) || !Array.isArray(baseNav)) return {}
const grouped = isGrouped(baseNav)
const baseItems = new Map(
(grouped ? baseNav.flatMap((g) => g.items.map((i) => [i, g.title ?? null])) : baseNav.map((i) => [i, null])).map(
([item, title]) => [item.to, { label: item.label, group: title }],
),
)
const out = {}
// Carry through what this admin's palette never showed them. An entry for a
// `to` the base nav no longer declares is NOT carried: dropping it is the
// cleanup, and applyNavOverrides ignores it anyway.
const shown = new Set(groups.flatMap((g) => g.items.map((i) => i.to)))
if (stored && typeof stored === 'object' && !Array.isArray(stored)) {
for (const [to, entry] of Object.entries(stored)) {
if (!shown.has(to) && baseItems.has(to) && entry && typeof entry === 'object') out[to] = entry
}
}
const writeOrder = !orderMatchesBase(groups, baseNav)
for (const group of groups) {
group.items.forEach((row, index) => {
const base = baseItems.get(row.to)
if (!base) return
const entry = {}
const label = typeof row.label === 'string' ? row.label.trim() : ''
if (label && label !== base.label) entry.label = label
if (row.hidden === true) entry.hidden = true
if (grouped && (group.title ?? null) !== base.group && group.title) entry.group = group.title
if (writeOrder) entry.order = index
if (Object.keys(entry).length > 0) out[row.to] = entry
})
}
return out
}
export default applyNavOverrides

View File

@@ -0,0 +1,32 @@
// Parse a JSON-valued settings row, client side.
//
// The counterpart to server/src/utils/settingsJson.js, and deliberately the same
// three lines of judgement: `settings.value` is TEXT, so theme_visual,
// brand_assets and the three nav_* keys all arrive as strings, and a malformed
// or wrong-shaped one must read as **absent** — the surface falls back to its
// BRAND_* env / theme.css / hardcoded NAV default — never as an error and never
// as a half-applied object.
//
// THEMING_AND_NAV.md §4.4 planned this "with its first consumer"; that consumer
// is the public header reading nav_public. `parseLayout` in heroLayout.js keeps
// its own version check because it validates a shape, not just a shape's kind.
/**
* @param {string|null|undefined} str the raw stored value
* @returns {object|null} the parsed object, or null when absent/malformed
*/
export function parseJsonSetting(str) {
if (typeof str !== 'string' || str === '') return null
let parsed
try {
parsed = JSON.parse(str)
} catch {
return null
}
// Only plain objects. A stored `null`, `4`, `"x"` or array is as unusable to
// every consumer of these keys as a syntax error is.
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
return parsed
}
export default parseJsonSetting

View File

@@ -0,0 +1,56 @@
import { useEffect, useState } from 'react'
import { api } from '../api/client.js'
import { parseJsonSetting } from './settingsJson.js'
// The nav overrides for the two authenticated layouts (THEMING_AND_NAV.md §4.2).
//
// `nav_public` rides along in the public settings payload, but `nav_admin` and
// `nav_player` deliberately do not: an anonymous visitor has no use for either,
// and the admin nav's labels describe the shape of the admin surface. Their
// owners read them from GET /api/v1/settings/nav, which any signed-in account
// may call — AdminLayout renders for editors and moderators, who cannot reach
// GET /admin/settings at all.
//
// Failing quiet is the whole posture: a request that errors, a malformed row and
// "not fetched yet" are the same state to the caller, `{}`, which
// applyNavOverrides turns into the coded nav. A sidebar must never blink empty
// because a settings call was slow.
// One module-level copy, so the second layout to mount renders the nav it
// already knows rather than flashing the coded one, and so the nav editor can
// push its save into the sidebar the admin is looking at without a reload.
let cache = {}
const subscribers = new Set()
async function load() {
try {
const data = await api.navSettings()
cache = {
nav_admin: parseJsonSetting(data?.nav_admin),
nav_player: parseJsonSetting(data?.nav_player),
}
subscribers.forEach((fn) => fn(cache))
} catch {
/* the coded nav is the fallback, and it is already on screen */
}
return cache
}
/** Re-read the rows after a save, so the live sidebar catches up at once. */
export function refreshNavOverrides() {
return load()
}
export function useNavOverrides() {
const [overrides, setOverrides] = useState(cache)
useEffect(() => {
subscribers.add(setOverrides)
load()
return () => subscribers.delete(setOverrides)
}, [])
return overrides
}
export default useNavOverrides