feat(theming): dropdown sections and added links in the public header

Phase 10 of docs/website/THEMING_AND_NAV.md, asked for before the edge -> main
cutover. An admin can now create dropdown sections in the public header, organise
the coded entries into them, and add links of their own.

This deliberately amends §7, which said the override layer "cannot introduce a
`to` that is not already in the hardcoded NAV array". That stays true of every
CODED entry; an admin may now also add a link, restricted to a same-origin path —
no scheme, no protocol-relative //host. A link carries no gate of its own and
needs none: the page behind it enforces its own access, so an added link
advertises a route and never grants one.

The invariant is kept structurally rather than by vigilance. Coded entries live
in an `items` map whose keys must be routes the base array declares, so that map
cannot invent a route; everything that CAN name an arbitrary path lives in
`links`, which is the one place the path rule is applied — on both the write and
the read path.

nav_public therefore grew a { items, sections, links } wrapper. A bare map still
reads as the items map, and a nav with no sections still stores one, so this
changed nothing for a nav that does not use it. Free to do now because nothing
has shipped; after the cutover it would have needed a migration.

The Public tab gets its own editor. A public section is an entry in the
top-level order that the admin created and can drag among the pills, unlike the
admin sidebar's four coded sections, where only membership moves — that is a tree
rather than a list of groups. Deleting a section returns its entries to the top
level rather than removing them, which is the one destructive act this screen
could otherwise commit.

The dropdown opens on click and never on hover, and its trigger is not a link: a
hover menu is unusable on touch, and a trigger that navigates means tapping to
open takes you somewhere instead. Escape closes and returns focus, an outside
press closes, navigating closes, and Arrow Up/Down walk the items.

pruneNav applies the shard-feature gate inside a section and drops one it leaves
empty, so a dropdown never opens onto nothing.

Also fixes a bug this surfaced in the phase 6-8 code: the save path judged "does
this route still exist?" against the palette — the base array already filtered to
what the editing admin can see — so on the public header a feature-gated row's
override could never be carried through and would have been silently reset.
Membership is now judged against the full coded nav while the rows still come
from the palette.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-08 00:42:19 -05:00
parent 32a3ff104a
commit b517d7b2df
10 changed files with 1335 additions and 51 deletions

View File

@@ -14,7 +14,8 @@ 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 { buildNavRows, buildNavOverrides, buildPublicNav, buildPublicNavOverrides } from '../../../lib/navOverrides.js'
import PublicNavTree from './PublicNavTree.jsx'
import { parseJsonSetting } from '../../../lib/settingsJson.js'
import { refreshNavOverrides } from '../../../lib/useNavOverrides.js'
import { NAV as PUBLIC_NAV } from '../../../components/SiteHeader.jsx'
@@ -95,9 +96,23 @@ function EyeIcon({ off }) {
)
}
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
/**
* One editable nav row, shared by all three tabs.
*
* The destination control is generic because the two navs that have one mean
* different things by it: the admin sidebar moves rows between the four coded
* sections, the public header between admin-created dropdowns. Both are "pick a
* container", so both get one `<select>` rather than cross-container dragging —
* which is a lot of interaction surface for something an admin does once.
*
* @param {Array<{value: string, label: string}>} [destinations] omit for a nav
* with no containers (the player portal)
* @param {() => void} [onDelete] only an admin-authored link can be deleted;
* a coded row is hidden, never removed
*/
export function Row({ row, id, destinations, destination, onDestination, onChange, onDelete }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id })
const renamed = row.defaultLabel !== undefined && row.label !== row.defaultLabel
const locked = row.to === SELF
return (
@@ -121,10 +136,10 @@ function Row({ row, groupTitles, currentGroup, baseGroup, onChange, onMoveGroup
<input
className="input"
value={row.label}
placeholder={row.defaultLabel}
placeholder={row.defaultLabel || row.to}
maxLength={64}
onChange={(e) => onChange({ ...row, label: e.target.value })}
aria-label={`Label for ${row.defaultLabel}`}
aria-label={`Label for ${row.defaultLabel || row.to}`}
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
@@ -157,28 +172,44 @@ function Row({ row, groupTitles, currentGroup, baseGroup, onChange, onMoveGroup
reset
</button>
)}
{groupTitles.length > 0 && (
{destinations && destinations.length > 0 && (
<select
className="select"
value={currentGroup ?? ''}
onChange={(e) => onMoveGroup(row.to, e.target.value || null)}
aria-label={`Section for ${row.defaultLabel}`}
value={destination ?? ''}
onChange={(e) => onDestination(e.target.value || null)}
aria-label={`Section for ${row.defaultLabel || row.to}`}
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}
{destinations.map((d) => (
<option key={d.value} value={d.value}>
{d.label}
</option>
))}
</select>
)}
{onDelete && (
<button
type="button"
className="sans"
title="Remove this link"
onClick={onDelete}
style={{
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input)',
background: 'transparent',
color: 'var(--muted)',
cursor: 'pointer',
padding: '4px 8px',
fontSize: '0.76rem',
}}
>
×
</button>
)}
{/* A coded row is hidden, never removed — the route still exists. An
admin-authored link is the opposite: there is nothing to fall back to,
so it is deleted instead (the × above). */}
{!onDelete && (
<button
type="button"
className="sans"
@@ -205,6 +236,7 @@ function Row({ row, groupTitles, currentGroup, baseGroup, onChange, onMoveGroup
>
<EyeIcon off={row.hidden} />
</button>
)}
</li>
)
}
@@ -226,6 +258,13 @@ export default function NavEditor() {
// 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.
// The nav as coded, unfiltered. The palette below is what this admin may EDIT;
// this is what still EXISTS, and the two are different questions. Saving needs
// both: an entry for a row their palette filtered out must be carried through
// rather than reset, and only an entry for a route the code no longer declares
// at all should be dropped.
const fullNavs = { nav_public: PUBLIC_NAV, nav_admin: ADMIN_NAV, nav_player: PLAYER_NAV }
const palettes = useMemo(
() => ({
nav_public: PUBLIC_NAV.filter((item) => !item.feature || canSee(shardFeatures, item.feature)),
@@ -246,7 +285,12 @@ export default function NavEditor() {
const next = {}
for (const { key } of TABS) {
const stored = parseJsonSetting(all[key])
next[key] = { stored, hasRow: Boolean(all[key]), groups: buildNavRows(palettes[key], stored) }
// The public header is a tree (sections are entries in the top-level
// order); the other two are the fixed-frame grouped/flat shape.
next[key] =
key === 'nav_public'
? { stored, hasRow: Boolean(all[key]), tree: buildPublicNav(palettes[key], stored, { keepHidden: true }) }
: { stored, hasRow: Boolean(all[key]), groups: buildNavRows(palettes[key], stored) }
}
setState(next)
})
@@ -269,14 +313,23 @@ export default function NavEditor() {
if (error && !state) return <ErrorState message={error} />
const current = state[tab]
const groupTitles = current.groups.map((g) => g.title).filter(Boolean)
const isPublic = tab === 'nav_public'
const groupTitles = isPublic ? [] : 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
(!isPublic && Array.isArray(palettes[tab]) && palettes[tab][0]?.items
? palettes[tab].flatMap((g) => g.items.map((i) => [i.to, g.title ?? null]))
: []),
)
// The admin sidebar can only move a row between the four coded sections, and
// "(no section)" only for a row coded into an untitled one — for anything else
// it is a move an override cannot express (§6.4), so offering it would
// silently do nothing.
const groupDestinations = (baseGroup) => [
...(baseGroup === null ? [{ value: '', label: '(no section)' }] : []),
...groupTitles.map((t) => ({ value: t, label: t })),
]
function mutate(updater) {
setState((s) => ({ ...s, [tab]: { ...s[tab], groups: updater(s[tab].groups) } }))
@@ -284,6 +337,12 @@ export default function NavEditor() {
setSaved('')
}
function setTree(tree) {
setState((s) => ({ ...s, [tab]: { ...s[tab], tree } }))
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)) })))
@@ -327,8 +386,17 @@ export default function NavEditor() {
setBusy(true)
setError('')
try {
const overrides = buildNavOverrides(current.groups, palettes[tab], current.stored)
const empty = Object.keys(overrides).length === 0
const overrides = isPublic
? buildPublicNavOverrides(current.tree, fullNavs[tab], current.stored)
: buildNavOverrides(current.groups, fullNavs[tab], current.stored)
// A wrapper with an empty `items` and no sections/links says nothing
// either, so "empty" is about the whole value, not just its key count.
const empty =
Object.keys(overrides).length === 0 ||
(overrides.items !== undefined &&
Object.keys(overrides.items).length === 0 &&
!overrides.sections?.length &&
!overrides.links?.length)
// 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).
@@ -353,7 +421,12 @@ export default function NavEditor() {
setError('')
try {
await api.admin.resetSetting(tab)
setState((s) => ({ ...s, [tab]: { stored: null, hasRow: false, groups: buildNavRows(palettes[tab], null) } }))
setState((s) => ({
...s,
[tab]: isPublic
? { stored: null, hasRow: false, tree: buildPublicNav(palettes[tab], null, { keepHidden: true }) }
: { stored: null, hasRow: false, groups: buildNavRows(palettes[tab], null) },
}))
setDirty((d) => ({ ...d, [tab]: false }))
setSaved('')
await propagate(tab)
@@ -410,6 +483,12 @@ export default function NavEditor() {
</span>
{/* ── Rows ───────────────────────────────────────────────── */}
{/* The public header gets its own editor: a section there is an entry in
the top-level order that an admin created, not a fixed frame the code
declares, so it is a tree rather than a list of groups. */}
{isPublic ? (
<PublicNavTree tree={current.tree} onChange={setTree} />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
{current.groups.map((group, groupIndex) => (
<div key={group.title ?? `group-${groupIndex}`}>
@@ -420,12 +499,12 @@ export default function NavEditor() {
{group.items.map((row) => (
<Row
key={row.to}
id={row.to}
row={row}
groupTitles={groupTitles}
currentGroup={group.title ?? null}
baseGroup={baseGroups.get(row.to) ?? null}
destinations={groupTitles.length > 0 ? groupDestinations(baseGroups.get(row.to) ?? null) : null}
destination={group.title ?? ''}
onDestination={(value) => onMoveGroup(row.to, value)}
onChange={onRowChange}
onMoveGroup={onMoveGroup}
/>
))}
{group.items.length === 0 && (
@@ -439,6 +518,7 @@ export default function NavEditor() {
</div>
))}
</div>
)}
<div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<button onClick={save} disabled={busy} className="btn btn-primary btn-sq">

View File

@@ -0,0 +1,310 @@
import { 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 Modal from '../../../components/Modal.jsx'
import { Row } from './NavEditor.jsx'
// The Public tab of Admin → Navigation (THEMING_AND_NAV.md §7, Phase 10).
//
// The public header is the one nav an admin can restructure rather than only
// reorder, so it needs its own editor: a **section is itself an entry in the
// top-level order**, which the fixed coded sections of the admin sidebar never
// are. That is the whole reason this is not the grouped editor with a different
// label — there, groups are a fixed frame and only membership moves.
//
// The tree is `[{kind: 'item' | 'link' | 'section', ...}]`, one level deep, and
// comes from the same `buildPublicNav` the header renders, so what an admin
// drags is what visitors get.
const uid = (prefix) => `${prefix}_${Math.random().toString(36).slice(2, 10)}`
// A path on this site, matching what the server will accept. Checked here so the
// admin gets the message while the field is in front of them; the server's 400
// stays the backstop, not the first feedback.
export function badLinkPath(value) {
const v = (value || '').trim()
if (!v) return 'Enter a path.'
if (/^[a-z][a-z0-9+.-]*:/i.test(v) || v.startsWith('//')) {
return 'Links must point somewhere on this site — start with “/”.'
}
if (!v.startsWith('/')) return 'Start the path with “/”, for example /wiki/new-player-guide.'
if (/[\s<>"'\\]/.test(v)) return 'A path cannot contain spaces or quotes.'
if (v.length > 128) return 'That path is too long.'
return null
}
function SectionCard({ section, index, children, onChange, onDelete }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: section.id })
return (
<li
ref={setNodeRef}
style={{
transform: CSS.Transform.toString(transform),
transition,
listStyle: 'none',
border: '1px solid var(--line)',
borderRadius: 'var(--radius-card)',
background: isDragging ? 'var(--blue)' : 'transparent',
padding: 10,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<button
type="button"
className="sans"
aria-label={`Reorder ${section.label}`}
{...attributes}
{...listeners}
style={{ border: 'none', background: 'transparent', color: 'var(--dim)', cursor: '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>
<input
className="input"
value={section.label}
maxLength={64}
placeholder="Section name"
onChange={(e) => onChange({ ...section, label: e.target.value })}
aria-label={`Name for section ${index + 1}`}
style={{ flex: '1 1 auto', minWidth: 120, padding: '5px 8px', fontSize: '0.84rem', fontWeight: 600 }}
/>
<span className="sans dim" style={{ fontSize: '0.7rem' }}>dropdown</span>
<button
type="button"
className="sans"
title="Delete this section — the entries inside move back out, they are not removed"
onClick={onDelete}
style={{
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input)',
background: 'transparent',
color: 'var(--muted)',
cursor: 'pointer',
padding: '4px 8px',
fontSize: '0.76rem',
}}
>
×
</button>
</div>
{children}
</li>
)
}
export default function PublicNavTree({ tree, onChange }) {
const [adding, setAdding] = useState(null) // {label, to, error} while the modal is open
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
)
const sections = tree.filter((n) => n.kind === 'section')
const destinations = [{ value: '', label: 'Top level' }, ...sections.map((s) => ({ value: s.id, label: s.label || 'Section' }))]
const keyOf = (node) => (node.kind === 'item' ? node.to : node.id)
// Every mutation rebuilds the tree; there is no partial in-place editing, which
// keeps "what will be saved" exactly "what is on screen".
const replace = (nextTree) => onChange(nextTree)
const updateNode = (key, next) =>
replace(
tree.map((node) => {
if (keyOf(node) === key) return next
if (node.kind !== 'section') return node
return { ...node, items: node.items.map((child) => (keyOf(child) === key ? next : child)) }
}),
)
// Moving between containers is the dropdown, not a drag. The entry lands at the
// end of its destination, where it is visible and can then be dragged home.
const moveTo = (key, sectionId) => {
let moving = null
const stripped = tree
.map((node) => {
if (node.kind === 'section') {
const items = node.items.filter((child) => {
if (keyOf(child) !== key) return true
moving = child
return false
})
return { ...node, items }
}
if (keyOf(node) === key) {
moving = node
return null
}
return node
})
.filter(Boolean)
if (!moving) return
if (!sectionId) return replace([...stripped, moving])
return replace(
stripped.map((node) => (node.kind === 'section' && node.id === sectionId ? { ...node, items: [...node.items, moving] } : node)),
)
}
const addSection = () => replace([...tree, { kind: 'section', id: uid('sec'), label: 'New section', items: [] }])
// Deleting a section must NOT delete what is inside it: those are coded pages
// and the admin's own links, and losing them to a mis-click would be the one
// destructive act this screen could commit. They move back to the top level.
const deleteSection = (id) => {
const section = tree.find((n) => n.kind === 'section' && n.id === id)
if (!section) return
replace([...tree.filter((n) => keyOf(n) !== id), ...(section.items || [])])
}
const deleteLink = (id) =>
replace(
tree
.filter((n) => keyOf(n) !== id)
.map((n) => (n.kind === 'section' ? { ...n, items: n.items.filter((c) => keyOf(c) !== id) } : n)),
)
const submitLink = () => {
const error = badLinkPath(adding.to)
if (error) return setAdding({ ...adding, error })
const label = adding.label.trim()
if (!label) return setAdding({ ...adding, error: 'Give the link a name.' })
replace([...tree, { kind: 'link', id: uid('lnk'), label, to: adding.to.trim() }])
return setAdding(null)
}
const onDragEnd = (containerId) => (event) => {
const { active, over } = event
if (!over || active.id === over.id) return
if (containerId === null) {
const from = tree.findIndex((n) => keyOf(n) === active.id)
const to = tree.findIndex((n) => keyOf(n) === over.id)
if (from < 0 || to < 0) return
return replace(arrayMove(tree, from, to))
}
return replace(
tree.map((node) => {
if (node.kind !== 'section' || node.id !== containerId) return node
const from = node.items.findIndex((c) => keyOf(c) === active.id)
const to = node.items.findIndex((c) => keyOf(c) === over.id)
if (from < 0 || to < 0) return node
return { ...node, items: arrayMove(node.items, from, to) }
}),
)
}
const renderRow = (node, sectionId) => (
<Row
key={keyOf(node)}
id={keyOf(node)}
row={node}
destinations={destinations}
destination={sectionId ?? ''}
onDestination={(value) => moveTo(keyOf(node), value)}
onChange={(next) => updateNode(keyOf(node), next)}
onDelete={node.kind === 'link' ? () => deleteLink(node.id) : undefined}
/>
)
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd(null)}>
<SortableContext items={tree.map(keyOf)} strategy={verticalListSortingStrategy}>
<ul style={{ display: 'flex', flexDirection: 'column', gap: 6, margin: 0, padding: 0 }}>
{tree.map((node, index) =>
node.kind === 'section' ? (
<SectionCard
key={node.id}
section={node}
index={index}
onChange={(next) => updateNode(node.id, next)}
onDelete={() => deleteSection(node.id)}
>
{/* A nested context, so a drag inside a dropdown reorders that
dropdown rather than escaping into the header. */}
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd(node.id)}>
<SortableContext items={(node.items || []).map(keyOf)} strategy={verticalListSortingStrategy}>
<ul style={{ display: 'flex', flexDirection: 'column', gap: 6, margin: '10px 0 0', padding: '0 0 0 22px' }}>
{(node.items || []).map((child) => renderRow(child, node.id))}
{(node.items || []).length === 0 && (
<li className="sans dim" style={{ fontSize: '0.76rem', listStyle: 'none', padding: '4px 2px' }}>
Empty an empty dropdown is not shown on the site.
</li>
)}
</ul>
</SortableContext>
</DndContext>
</SectionCard>
) : (
renderRow(node, null)
),
)}
</ul>
</SortableContext>
</DndContext>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
<button type="button" className="pill" onClick={addSection}>
+ Add dropdown section
</button>
<button type="button" className="pill" onClick={() => setAdding({ label: '', to: '', error: null })}>
+ Add link
</button>
</div>
{adding && (
<Modal
title="Add a link"
onClose={() => setAdding(null)}
width={480}
footer={
<>
<button className="pill" onClick={() => setAdding(null)}>Cancel</button>
<button className="btn btn-primary btn-sq" onClick={submitLink}>Add link</button>
</>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<label style={{ display: 'block' }}>
<span className="field-label">Name</span>
<input
className="input"
value={adding.label}
maxLength={64}
placeholder="Player Guide"
onChange={(e) => setAdding({ ...adding, label: e.target.value, error: null })}
/>
</label>
<label style={{ display: 'block' }}>
<span className="field-label">Path on this site</span>
<input
className="input"
value={adding.to}
maxLength={128}
placeholder="/wiki/new-player-guide"
onChange={(e) => setAdding({ ...adding, to: e.target.value, error: null })}
/>
</label>
<p className="sans dim" style={{ margin: 0, fontSize: '0.76rem', lineHeight: 1.7 }}>
Links point somewhere on this site a wiki page, a custom page, any section of the site.
They are not gated: the page itself still decides who may open it, so a link to something
restricted behaves exactly as typing its address would.
</p>
{adding.error && <span className="sans" style={{ color: '#d98b84', fontSize: '0.85rem' }}>{adding.error}</span>}
</div>
</Modal>
)}
</div>
)
}