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

@@ -0,0 +1,465 @@
import { useEffect, useMemo, useState } from 'react'
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import {
SortableContext,
arrayMove,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Loading, ErrorState } from '../../../components/PageState.jsx'
import { api } from '../../../api/client.js'
import { useAuth } from '../../../contexts/AuthContext.jsx'
import { useSite } from '../../../contexts/SiteContext.jsx'
import { useShardFeatures, canSee } from '../../../lib/useShardFeatures.js'
import { buildNavRows, buildNavOverrides } from '../../../lib/navOverrides.js'
import { parseJsonSetting } from '../../../lib/settingsJson.js'
import { refreshNavOverrides } from '../../../lib/useNavOverrides.js'
import { NAV as PUBLIC_NAV } from '../../../components/SiteHeader.jsx'
import { NAV as ADMIN_NAV, navItemVisibleTo } from '../AdminLayout.jsx'
import { NAV as PLAYER_NAV } from '../../player/PlayerPortalLayout.jsx'
// Admin · Navigation — phases 6-8 of docs/website/THEMING_AND_NAV.md.
//
// The three navs stay declared in code, each in the component that renders it;
// this screen writes an override *layer* over them (§7). It can relabel,
// reorder, hide and — on the admin sidebar — move a row into another existing
// section, and nothing else. It cannot introduce a route and it cannot touch a
// `roles` or `feature` gate, so the filters in the layouts still decide who sees
// what, and they run after the merge.
//
// Three things shape the screen:
//
// • The palette is filtered to the editing admin's OWN visible rows (§8.1) —
// the base array run through their role and this shard's feature gates. An
// admin cannot drag in, and so can never accidentally advertise, something
// they cannot see themselves. An override on a row they cannot see is
// carried through their save untouched rather than quietly reset.
// • The rows come from the same merge the site renders (buildNavRows), hidden
// ones included, so the editor cannot show an order the nav does not use.
// • Saving writes a settings row; "reset" DELETES it. Absence of the row is
// what selects the coded default, so reset cannot store a copy of it — and a
// save whose result is empty deletes the row for the same reason (§4.1).
// The nav editor's own row. Hiding it would remove the only screen that can
// un-hide it, so its eye toggle is disabled here and the server drops `hidden`
// on it as well (server/src/utils/navOverrides.js) — a hand-written row cannot
// do what the UI refuses.
const SELF = '/admin/navigation'
const TABS = [
{ key: 'nav_public', label: 'Public site', hint: 'The header on every public page.' },
{ key: 'nav_admin', label: 'Admin', hint: 'This sidebar. Rows can also move between sections.' },
{ key: 'nav_player', label: 'Player portal', hint: 'The sidebar a signed-in player sees.' },
]
function DragHandle({ attributes, listeners, disabled }) {
return (
<button
type="button"
className="sans"
aria-label="Reorder"
disabled={disabled}
{...attributes}
{...listeners}
style={{
border: 'none',
background: 'transparent',
color: 'var(--dim)',
cursor: disabled ? 'default' : 'grab',
padding: '2px 4px',
touchAction: 'none',
}}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false">
<circle cx="9" cy="6" r="1.6" />
<circle cx="15" cy="6" r="1.6" />
<circle cx="9" cy="12" r="1.6" />
<circle cx="15" cy="12" r="1.6" />
<circle cx="9" cy="18" r="1.6" />
<circle cx="15" cy="18" r="1.6" />
</svg>
</button>
)
}
function EyeIcon({ off }) {
return (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" />
<circle cx="12" cy="12" r="3" />
{off && <path d="M3 3l18 18" />}
</svg>
)
}
function Row({ row, groupTitles, currentGroup, baseGroup, onChange, onMoveGroup }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.to })
const renamed = row.label !== row.defaultLabel
const locked = row.to === SELF
return (
<li
ref={setNodeRef}
style={{
transform: CSS.Transform.toString(transform),
transition,
display: 'flex',
alignItems: 'center',
gap: 8,
padding: '7px 10px',
borderRadius: 'var(--radius-input)',
border: '1px solid var(--line)',
background: isDragging ? 'var(--blue)' : 'var(--panel-flat)',
opacity: row.hidden ? 0.55 : 1,
listStyle: 'none',
}}
>
<DragHandle attributes={attributes} listeners={listeners} />
<input
className="input"
value={row.label}
placeholder={row.defaultLabel}
maxLength={64}
onChange={(e) => onChange({ ...row, label: e.target.value })}
aria-label={`Label for ${row.defaultLabel}`}
style={{ flex: '1 1 auto', minWidth: 120, padding: '5px 8px', fontSize: '0.84rem' }}
/>
{/* The route, for orientation — it is what the override is keyed by. Fixed
and truncating rather than flexible: /admin/moderation/appeals would
otherwise wrap and squeeze the label input it sits beside. */}
<code
className="sans dim"
title={row.to}
style={{
flex: '0 0 auto',
width: 130,
fontSize: '0.7rem',
opacity: 0.75,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
textAlign: 'right',
}}
>
{row.to}
</code>
{renamed && (
<button
type="button"
className="sans"
title="Use the coded label again"
onClick={() => onChange({ ...row, label: row.defaultLabel })}
style={{ border: 'none', background: 'transparent', color: 'var(--accent)', fontSize: '0.72rem', cursor: 'pointer', padding: 0 }}
>
reset
</button>
)}
{groupTitles.length > 0 && (
<select
className="select"
value={currentGroup ?? ''}
onChange={(e) => onMoveGroup(row.to, e.target.value || null)}
aria-label={`Section for ${row.defaultLabel}`}
style={{ flex: '0 0 auto', width: 130, padding: '4px 6px', fontSize: '0.76rem' }}
>
{/* "(no section)" is offered only to a row that is coded into one of
the untitled groups (Dashboard, Account) — for anything else it is
a move that cannot be stored: an override names an existing titled
section or nothing at all (§6.4), so picking it would silently do
nothing. Such a row can still move OUT and back, which clears the
override rather than storing a null group. */}
{baseGroup === null && <option value="">(no section)</option>}
{groupTitles.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
)}
<button
type="button"
className="sans"
disabled={locked}
title={
locked
? 'This screen is the only way back — it cannot be hidden'
: row.hidden
? 'Currently hidden. Show it again'
: 'Hide from this nav'
}
aria-pressed={row.hidden}
onClick={() => onChange({ ...row, hidden: !row.hidden })}
style={{
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input)',
background: 'transparent',
color: locked ? 'var(--dim)' : row.hidden ? 'var(--accent)' : 'var(--muted)',
cursor: locked ? 'not-allowed' : 'pointer',
padding: '4px 6px',
display: 'flex',
opacity: locked ? 0.5 : 1,
}}
>
<EyeIcon off={row.hidden} />
</button>
</li>
)
}
export default function NavEditor() {
const { user } = useAuth()
const { refresh: refreshSite } = useSite()
const shardFeatures = useShardFeatures()
const [tab, setTab] = useState('nav_public')
// Per nav: the editable groups, the overrides as loaded (so a row this admin
// cannot see survives their save), and whether a settings row exists at all.
const [state, setState] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [saved, setSaved] = useState('')
const [dirty, setDirty] = useState({})
// The palette: each base nav, filtered to what THIS admin can see (§8.1). The
// public nav's gates are the shard-feature ones; the admin nav's are roles.
// The player portal has no gates at all.
const palettes = useMemo(
() => ({
nav_public: PUBLIC_NAV.filter((item) => !item.feature || canSee(shardFeatures, item.feature)),
nav_admin: ADMIN_NAV.map((g) => ({ ...g, items: g.items.filter((i) => navItemVisibleTo(i, user?.role)) })).filter(
(g) => g.items.length > 0,
),
nav_player: PLAYER_NAV,
}),
[shardFeatures, user?.role],
)
useEffect(() => {
let active = true
api.admin
.getSettings()
.then((all) => {
if (!active) return
const next = {}
for (const { key } of TABS) {
const stored = parseJsonSetting(all[key])
next[key] = { stored, hasRow: Boolean(all[key]), groups: buildNavRows(palettes[key], stored) }
}
setState(next)
})
.catch(() => active && setError('Could not load the navigation settings.'))
.finally(() => active && setLoading(false))
return () => {
active = false
}
// Loaded once; the palettes settle before the fetch resolves in practice, and
// re-running on a feature flip would discard the admin's unsaved edits.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
)
if (loading) return <Loading />
if (error && !state) return <ErrorState message={error} />
const current = state[tab]
const groupTitles = current.groups.map((g) => g.title).filter(Boolean)
// Where each row is declared in code, so the section dropdown can offer only
// the destinations an override is able to express.
const baseGroups = new Map(
(Array.isArray(palettes[tab]) && palettes[tab][0]?.items
? palettes[tab].flatMap((g) => g.items.map((i) => [i.to, g.title ?? null]))
: []),
)
function mutate(updater) {
setState((s) => ({ ...s, [tab]: { ...s[tab], groups: updater(s[tab].groups) } }))
setDirty((d) => ({ ...d, [tab]: true }))
setSaved('')
}
const onRowChange = (next) =>
mutate((groups) => groups.map((g) => ({ ...g, items: g.items.map((i) => (i.to === next.to ? next : i)) })))
// Sections change by dropdown, not by dragging: a drag that could land in
// another list is a lot of interaction surface for something an admin does
// once, and this keeps every drag a simple reorder. The row goes to the end of
// its new section, where it is visible and can then be dragged into place.
const onMoveGroup = (to, title) =>
mutate((groups) => {
const moving = groups.flatMap((g) => g.items).find((i) => i.to === to)
if (!moving) return groups
return groups.map((g) => {
if ((g.title ?? null) === title) return { ...g, items: [...g.items.filter((i) => i.to !== to), moving] }
return { ...g, items: g.items.filter((i) => i.to !== to) }
})
})
const onDragEnd = (groupIndex) => (event) => {
const { active, over } = event
if (!over || active.id === over.id) return
mutate((groups) =>
groups.map((g, i) => {
if (i !== groupIndex) return g
const from = g.items.findIndex((it) => it.to === active.id)
const to = g.items.findIndex((it) => it.to === over.id)
if (from < 0 || to < 0) return g
return { ...g, items: arrayMove(g.items, from, to) }
}),
)
}
// Push a save into whatever is rendering that nav right now, so the admin sees
// what they just did: the header re-reads the public settings, the two
// authenticated sidebars re-read /settings/nav.
async function propagate(key) {
if (key === 'nav_public') await refreshSite()
else await refreshNavOverrides()
}
async function save() {
setBusy(true)
setError('')
try {
const overrides = buildNavOverrides(current.groups, palettes[tab], current.stored)
const empty = Object.keys(overrides).length === 0
// Nothing differs from the code default, so there is nothing to store —
// and a row that says nothing would still read as "this nav was
// customised". Delete it instead (§2, §4.1).
if (empty) await api.admin.resetSetting(tab)
else await api.admin.updateSettings({ [tab]: overrides })
setState((s) => ({
...s,
[tab]: { ...s[tab], stored: empty ? null : overrides, hasRow: !empty },
}))
setDirty((d) => ({ ...d, [tab]: false }))
setSaved(tab)
await propagate(tab)
} catch (err) {
setError(err.message || 'Could not save this navigation.')
} finally {
setBusy(false)
}
}
async function resetNav() {
setBusy(true)
setError('')
try {
await api.admin.resetSetting(tab)
setState((s) => ({ ...s, [tab]: { stored: null, hasRow: false, groups: buildNavRows(palettes[tab], null) } }))
setDirty((d) => ({ ...d, [tab]: false }))
setSaved('')
await propagate(tab)
} catch (err) {
setError(err.message || 'Could not reset this navigation.')
} finally {
setBusy(false)
}
}
const activeTab = TABS.find((t) => t.key === tab)
return (
<section style={{ maxWidth: 860, display: 'flex', flexDirection: 'column', gap: 22 }}>
<p className="sans dim" style={{ margin: 0, fontSize: '0.82rem', lineHeight: 1.7 }}>
Rename, reorder and hide the entries in each navigation. The pages themselves are unchanged this
only decides what is advertised, and it can never show anyone a link their role or this shard&rsquo;s
visibility settings would hide.
</p>
{/* ── Tabs ───────────────────────────────────────────────── */}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{TABS.map((t) => (
<button
key={t.key}
type="button"
className="sans"
onClick={() => {
setTab(t.key)
setSaved('')
}}
aria-pressed={tab === t.key}
style={{
padding: '8px 14px',
borderRadius: 'var(--radius-input)',
border: `1px solid ${tab === t.key ? 'var(--accent)' : 'var(--line)'}`,
background: tab === t.key ? 'var(--blue)' : 'transparent',
color: tab === t.key ? 'var(--ink)' : 'var(--muted)',
cursor: 'pointer',
fontSize: '0.86rem',
}}
>
{t.label}
{dirty[t.key] && <span style={{ color: 'var(--accent)' }}> </span>}
</button>
))}
</div>
<span className="sans dim" style={{ fontSize: '0.76rem' }}>
{activeTab.hint}{' '}
{current.hasRow
? 'This nav has saved overrides.'
: 'This nav has never been customised, so it renders exactly as coded.'}
</span>
{/* ── Rows ───────────────────────────────────────────────── */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
{current.groups.map((group, groupIndex) => (
<div key={group.title ?? `group-${groupIndex}`}>
{group.title && <span className="field-label">{group.title}</span>}
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd(groupIndex)}>
<SortableContext items={group.items.map((i) => i.to)} strategy={verticalListSortingStrategy}>
<ul style={{ display: 'flex', flexDirection: 'column', gap: 6, margin: '8px 0 0', padding: 0 }}>
{group.items.map((row) => (
<Row
key={row.to}
row={row}
groupTitles={groupTitles}
currentGroup={group.title ?? null}
baseGroup={baseGroups.get(row.to) ?? null}
onChange={onRowChange}
onMoveGroup={onMoveGroup}
/>
))}
{group.items.length === 0 && (
<li className="sans dim" style={{ fontSize: '0.76rem', listStyle: 'none', padding: '6px 2px' }}>
Empty this section is not rendered until something is moved into it.
</li>
)}
</ul>
</SortableContext>
</DndContext>
</div>
))}
</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 navigation'}
</button>
<button
onClick={resetNav}
disabled={busy || !current.hasRow}
className="pill"
title={current.hasRow ? 'Delete the saved overrides for this nav' : 'Nothing to reset'}
>
Reset to default
</button>
{saved === tab && <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 }}>
Only entries you can see yourself are listed. Anything hidden from you by your role or by Shard
Visibility keeps whatever it was already set to.
</p>
</section>
)
}