From 8186aff62fae940e09d581396f6d64383fa02f84 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 27 Sep 2026 15:33:14 -0500 Subject: [PATCH] Add a section nav to the admin editor and fold repeater rows Every record editor gets a sticky "On this page" column listing its field groups and collections (with row counts), lighting the one in view and marking any with a save error. Below lg it becomes a sticky "Jump to" menu. Editor pages widen to fit it through a small layout context; other admin pages keep their width. Each collection now sits in its own card, and repeater rows fold to their title line. Rows start folded, with Expand all and Collapse all; a new row, or one the server rejected, opens itself. Co-Authored-By: Claude Opus 5.5 --- src/components/admin/SectionNav.tsx | 141 +++++++++++++++++++++ src/components/admin/fields.tsx | 187 ++++++++++++++++++++++------ src/lib/adminWidth.tsx | 26 ++++ src/pages/admin/AdminLayout.tsx | 11 +- src/pages/admin/EntityEdit.tsx | 104 ++++++++++++---- 5 files changed, 402 insertions(+), 67 deletions(-) create mode 100644 src/components/admin/SectionNav.tsx create mode 100644 src/lib/adminWidth.tsx diff --git a/src/components/admin/SectionNav.tsx b/src/components/admin/SectionNav.tsx new file mode 100644 index 0000000..9ef994a --- /dev/null +++ b/src/components/admin/SectionNav.tsx @@ -0,0 +1,141 @@ +/* ═══════════════════════════════════════════════════════════════ + EDITOR SECTION NAV + + The record editor's table of contents. On a wide screen it's a + sticky column left of the form; below lg it's a slim sticky bar + with a "Jump to" menu. Both list the same sections, which + EntityEdit derives from the manifest (field groups, then child + collections with their row counts), so every editor gets one + without declaring anything. + + The lit entry is the last section whose top has scrolled past + the line ACTIVE_LINE px below the viewport's top: the one you're + reading, not merely the one peeking in at the bottom. A section + with a save error carries a red dot, so a rejected save points + at where to look. + ═══════════════════════════════════════════════════════════════ */ + +import { useEffect, useState } from "react"; + +export type EditorSection = { + id: string; + label: string; + count?: number; + hasError?: boolean; +}; + +const ACTIVE_LINE = 140; + +function useActiveSection(sections: EditorSection[]) { + const [active, setActive] = useState(sections[0]?.id ?? null); + const ids = sections.map((section) => section.id).join("|"); + + useEffect(() => { + let frame = 0; + const measure = () => { + frame = 0; + let current: string | null = null; + for (const id of ids.split("|")) { + const el = document.getElementById(id); + if (el && el.getBoundingClientRect().top <= ACTIVE_LINE) current = id; + } + // At the very bottom the last short section may never reach + // the line; it's the one being read. + if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4) { + current = ids.split("|").pop() ?? current; + } + setActive(current ?? ids.split("|")[0] ?? null); + }; + const onScroll = () => { + if (!frame) frame = requestAnimationFrame(measure); + }; + measure(); + window.addEventListener("scroll", onScroll, { passive: true }); + window.addEventListener("resize", onScroll); + return () => { + window.removeEventListener("scroll", onScroll); + window.removeEventListener("resize", onScroll); + if (frame) cancelAnimationFrame(frame); + }; + }, [ids]); + + return active; +} + +function jump(id: string) { + document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" }); +} + +function Label({ section }: { section: EditorSection }) { + return ( + <> + {section.label} + {section.count != null && ( + ({section.count}) + )} + {section.hasError && ( + + )} + + ); +} + +/* The desktop column. Place it in the grid's first track. */ +export function SectionNav({ sections }: { sections: EditorSection[] }) { + const active = useActiveSection(sections); + + return ( + + ); +} + +/* The phone and tablet bar. Sits above the form, sticks to the top. */ +export function SectionJump({ sections }: { sections: EditorSection[] }) { + const active = useActiveSection(sections); + + return ( +
+ +
+ ); +} diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 8f395d7..f397f22 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -7,7 +7,15 @@ Ordering is array position (the server writes sort_order from the index), so moving a row is a splice, not a number to - hand-edit. Rows can be dragged by the handle or moved with the + hand-edit. + + Rows fold to their title line. They start folded, so a long + collection (the front page's slides and paths) reads as a list + rather than a wall of fields; a row just added starts open, and + one the server rejected opens itself so the error can't hide. + Which rows are open is a set of indices, remapped by every move, + insert and removal here, so it survives a save (which replaces + every row object but keeps their order). Rows can be dragged by the handle or moved with the arrow buttons; the arrows are the keyboard path and stay whether or not a pointer is in use. @@ -246,9 +254,42 @@ export function FieldGrid({ children }) { /* ── Repeater ────────────────────────────────────────────────── */ -export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) { +/* Where each old index ends up after a change to the list, or -1 + when that row is gone. Used to carry the open set across it. */ +function remapOpen(open: Set, where: (index: number) => number) { + const next = new Set(); + for (const index of open) { + const moved = where(index); + if (moved >= 0) next.add(moved); + } + return next; +} + +export function Repeater({ + spec, + rows, + options, + errors, + errorPrefix, + onChange, + className = "mt-8", +}: any) { const list = rows ?? []; + const [open, setOpen] = useState>(() => new Set()); + const hasError = (index) => + Object.keys(errors ?? {}).some( + (key) => errors[key] && key.startsWith(`${errorPrefix}${index}.`), + ); + const isOpen = (index) => open.has(index) || hasError(index); + const toggle = (index) => + setOpen((prev) => { + const next = new Set(prev); + if (next.has(index)) next.delete(index); + else next.add(index); + return next; + }); + // Which row is in flight, and which one it's currently over. // Both are per-Repeater, which is what keeps a drag inside a // nested collection from being accepted by the outer one. @@ -264,6 +305,9 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) if (target < 0 || target >= list.length) return; const next = [...list]; [next[index], next[target]] = [next[target], next[index]]; + setOpen((prev) => + remapOpen(prev, (i) => (i === index ? target : i === target ? index : i)), + ); onChange(next); }; @@ -272,22 +316,63 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) const next = [...list]; const [moved] = next.splice(from, 1); next.splice(to, 0, moved); + setOpen((prev) => + remapOpen(prev, (i) => { + if (i === from) return to; + if (from < to && i > from && i <= to) return i - 1; + if (from > to && i >= to && i < from) return i + 1; + return i; + }), + ); onChange(next); }; + const add = () => { + setOpen((prev) => new Set(prev).add(list.length)); + onChange([...list, { ...spec.blank }]); + }; + + const removeAt = (index) => { + setOpen((prev) => remapOpen(prev, (i) => (i === index ? -1 : i > index ? i - 1 : i))); + onChange(list.filter((_, i) => i !== index)); + }; + const endDrag = () => { setDragIndex(null); setOverIndex(null); }; return ( -
-
-

{spec.label}

+
+
+

+ {spec.label} + {list.length > 0 && ( + {list.length} + )} +

+ {list.length > 1 && ( +
+ + +
+ )} @@ -301,6 +386,7 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) {list.map((row, index) => { const dragging = dragIndex === index; const over = overIndex === index && dragIndex !== null && !dragging; + const expanded = isOpen(index); return (
-
+
{ @@ -353,11 +439,29 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) ⠿ - - {spec.title ? spec.title(row, options) : `#${index + 1}`} - + -
+
move(index, -1)} @@ -375,39 +479,44 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange }) onChange(list.filter((_, i) => i !== index))} + onClick={() => removeAt(index)} > ✕
- - {spec.fields.map((field) => ( - update(index, { ...row, [field.path]: value })} - /> - ))} - + {expanded && ( + <> + + {spec.fields.map((field) => ( + update(index, { ...row, [field.path]: value })} + /> + ))} + - {(spec.children ?? []).map((nested) => ( -
- update(index, { ...row, [nested.key]: value })} - /> -
- ))} + {(spec.children ?? []).map((nested) => ( +
+ update(index, { ...row, [nested.key]: value })} + /> +
+ ))} + + )}
); })} diff --git a/src/lib/adminWidth.tsx b/src/lib/adminWidth.tsx new file mode 100644 index 0000000..3a3e2fe --- /dev/null +++ b/src/lib/adminWidth.tsx @@ -0,0 +1,26 @@ +/* ═══════════════════════════════════════════════════════════════ + ADMIN PAGE WIDTH + + The admin column is max-w-5xl. The record editor wants more: its + section nav sits to the left of a form that keeps that width. + Like the title (adminTitle.tsx), the page asks and the layout + decides, so AdminLayout stays the one place that sets
's + width. + + Clears on unmount, so leaving the editor puts the list pages + back to their usual width. + ═══════════════════════════════════════════════════════════════ */ + +import { createContext, useContext, useEffect } from "react"; + +export const AdminWidthContext = createContext<((wide: boolean) => void) | null>(null); + +export function useWideAdminPage() { + const setWide = useContext(AdminWidthContext); + + useEffect(() => { + if (!setWide) return undefined; + setWide(true); + return () => setWide(false); + }, [setWide]); +} diff --git a/src/pages/admin/AdminLayout.tsx b/src/pages/admin/AdminLayout.tsx index 7bd1932..a3b5d2d 100644 --- a/src/pages/admin/AdminLayout.tsx +++ b/src/pages/admin/AdminLayout.tsx @@ -20,6 +20,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { Link, NavLink, Outlet, useLocation, useNavigate } from "react-router-dom"; import { useAuth } from "../../lib/auth.tsx"; import { AdminTitleContext } from "../../lib/adminTitle.tsx"; +import { AdminWidthContext } from "../../lib/adminWidth.tsx"; import { SITE_VERSION } from "../../lib/version.ts"; import { ROLE_LABELS, isSuper } from "../../lib/roles.ts"; import nguLogo from "../../assets/NGU_Logo.svg"; @@ -60,6 +61,10 @@ export default function AdminLayout() { const stableSet = useCallback((value) => setDetail(value), []); const titleContext = useMemo(() => ({ setDetail: stableSet }), [stableSet]); + // Whether the page below asked for extra room (the record editor, + // for its section nav). setWide is a state setter, so it's stable. + const [wide, setWide] = useState(false); + useEffect(() => { // Sections only exist in the CMS. Home and Panel already say // what they are in the area title; "Panel | NGU Admin Panel" @@ -159,9 +164,11 @@ export default function AdminLayout() { {/* flex-1 rather than a fixed height: the footer sits at the bottom of a short page and below the content of a long one, without ever floating over it. */} -
+
- + + +
diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx index 5511ce8..7cf4fc4 100644 --- a/src/pages/admin/EntityEdit.tsx +++ b/src/pages/admin/EntityEdit.tsx @@ -33,6 +33,12 @@ None of this is protection. The server refuses the request; this only decides whether to draw a button that would be refused. + The page is laid out as sections: the URL ID, each field group, + then each child collection in a card of its own. SectionNav lists + them (a sticky column on wide screens, a "Jump to" bar below lg), + derived here from the manifest, so no descriptor declares a nav. + The editor asks the layout for extra width to fit it. + slugFrom may name one field or several. Most ids are unique because the name is: two organizations aren't both called Northwest. Team ids are the exception: teams.id is a global @@ -46,9 +52,21 @@ import { useNavigate, useParams } from "react-router-dom"; import { get, post, patch, del, ApiError } from "../../lib/api.ts"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { useAdminDetail } from "../../lib/adminTitle.tsx"; +import { useWideAdminPage } from "../../lib/adminWidth.tsx"; import { ADMIN_ENTITIES, slugify } from "../../lib/adminSchema.ts"; import { atLeast } from "../../lib/roles.ts"; import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx"; +import { + SectionJump, + SectionNav, + type EditorSection, +} from "../../components/admin/SectionNav.tsx"; + +/* One card per section. scroll-mt clears the sticky "Jump to" bar + below lg, and leaves a little air above the card on desktop. */ +const CARD = "mt-6 scroll-mt-16 rounded-2xl border border-[#138ba0]/20 bg-white p-5 lg:scroll-mt-6"; + +const sectionId = (name) => `section-${slugify(name)}`; /* A foreign key refusing to budge is the most common way a save or delete fails here, and SQLite's own wording explains nothing to @@ -66,6 +84,8 @@ export default function EntityEdit() { const navigate = useNavigate(); const { user } = useAuth(); + useWideAdminPage(); + const isNew = id === "new"; const canWrite = atLeast(user, "editor"); const canDelete = atLeast(user, "admin"); @@ -302,6 +322,32 @@ export default function EntityEdit() { const visible = (when) => !when || getPath(form, when.path) === when.value; + const groups = manifest.groups.filter((group) => visible(group.when)); + const shownChildren = children.filter((child) => visible(child.when)); + const childHasError = (key) => + Object.keys(errors).some((path) => errors[path] && path.startsWith(`${key}.`)); + + // A singleton's only header box is "Last saved", and a new + // auto-id record has no box at all: neither is worth a nav entry. + const idSection = !singleton && (!autoId || !isNew); + + const sections: EditorSection[] = [ + ...(idSection + ? [{ id: "section-url-id", label: manifest.idLabel, hasError: Boolean(errors.id) }] + : []), + ...groups.map((group) => ({ + id: sectionId(group.legend), + label: group.legend, + hasError: group.fields.some((field) => errors[field.path]), + })), + ...shownChildren.map((child) => ({ + id: sectionId(`${child.key}-list`), + label: child.label, + count: (form[child.key] ?? []).length, + hasError: childHasError(child.key), + })), + ]; + return (
{!singleton && ( @@ -318,18 +364,29 @@ export default function EntityEdit() { {isNew ? `New ${manifest.singular}` : heading} +
+ +
+ +
+
+ +
+ +
+ {/* Slug. An auto-id entity has nothing to ask for on create, and nothing editable afterwards, so it gets a plain line rather than a disabled box pretending to be a field. */} {singleton ? ( updatedAt && ( -
+

Last saved {updatedAt}

) ) : autoId ? ( !isNew && ( -
+

{manifest.idLabel} #{form.id} {form.updated_at && <> · last saved {form.updated_at}} @@ -337,7 +394,7 @@ export default function EntityEdit() {

) ) : ( -
+
visible(group.when)).map((group) => ( -
+ {groups.map((group) => ( +

{group.legend}

{group.note &&

{group.note}

}
@@ -393,25 +447,23 @@ export default function EntityEdit() {
))} - {/* Child collections. Awards own none, so the panel would be - an empty white box; skip it rather than render it. */} - {children.some((child) => visible(child.when)) && ( -
- {children - .filter((child) => visible(child.when)) - .map((child) => ( - setForm((prev) => ({ ...prev, [child.key]: rows }))} - /> - ))} + {/* Child collections, a card each, so the front page's slides, + stats and paths read as separate things. */} + {shownChildren.map((child) => ( +
+ setForm((prev) => ({ ...prev, [child.key]: rows }))} + />
- )} + ))} +
+
{/* Sticky action bar */}