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 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 15:33:14 -05:00
parent eaff23839f
commit 8186aff62f
5 changed files with 402 additions and 67 deletions

View file

@ -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<string | null>(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 (
<>
<span className="truncate">{section.label}</span>
{section.count != null && (
<span className="text-xs text-[#4a6b72]/70">({section.count})</span>
)}
{section.hasError && (
<span aria-label="needs attention" className="h-1.5 w-1.5 shrink-0 rounded-full bg-[#b3261e]" />
)}
</>
);
}
/* The desktop column. Place it in the grid's first track. */
export function SectionNav({ sections }: { sections: EditorSection[] }) {
const active = useActiveSection(sections);
return (
<nav aria-label="Sections" className="sticky top-6 hidden max-h-[calc(100vh-8rem)] overflow-y-auto lg:block">
<p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-[#4a6b72]/70">
On this page
</p>
<ul className="space-y-0.5 border-l border-[#138ba0]/15">
{sections.map((section) => {
const lit = section.id === active;
return (
<li key={section.id}>
<button
type="button"
onClick={() => jump(section.id)}
aria-current={lit ? "location" : undefined}
className={`-ml-px flex w-full items-center gap-1.5 border-l-2 px-3 py-1.5 text-left text-sm transition-colors ${
lit
? "border-[#138ba0] font-semibold text-[#138ba0]"
: "border-transparent text-[#4a6b72] hover:border-[#138ba0]/40 hover:text-[#138ba0]"
}`}
>
<Label section={section} />
</button>
</li>
);
})}
</ul>
</nav>
);
}
/* The phone and tablet bar. Sits above the form, sticks to the top. */
export function SectionJump({ sections }: { sections: EditorSection[] }) {
const active = useActiveSection(sections);
return (
<div className="sticky top-0 z-20 -mx-6 mb-2 border-b border-[#138ba0]/15 bg-[#f6fbfc]/95 px-6 py-2 backdrop-blur lg:hidden">
<label className="flex items-center gap-3 text-sm text-[#4a6b72]">
<span className="shrink-0">Jump to</span>
<select
value={active ?? ""}
onChange={(e) => jump(e.target.value)}
className="w-full rounded-lg border border-[#4a6b72]/25 bg-white px-3 py-1.5 text-sm text-[#26454c] outline-none focus:border-[#138ba0]"
>
{sections.map((section) => (
<option key={section.id} value={section.id}>
{section.label}
{section.count != null ? ` (${section.count})` : ""}
{section.hasError ? ", needs attention" : ""}
</option>
))}
</select>
</label>
</div>
);
}

View file

@ -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<number>, where: (index: number) => number) {
const next = new Set<number>();
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<Set<number>>(() => 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 (
<section className="mt-8">
<div className="flex items-center justify-between">
<h3 className="text-base font-semibold text-[#26454c]">{spec.label}</h3>
<section className={className}>
<div className="flex flex-wrap items-center gap-3">
<h3 className="text-base font-semibold text-[#26454c]">
{spec.label}
{list.length > 0 && (
<span className="ml-2 text-sm font-normal text-[#4a6b72]/80">{list.length}</span>
)}
</h3>
{list.length > 1 && (
<div className="flex gap-3 text-xs text-[#4a6b72]">
<button
type="button"
onClick={() => setOpen(new Set(list.map((_, i) => i)))}
className="hover:text-[#138ba0] hover:underline"
>
Expand all
</button>
<button
type="button"
onClick={() => setOpen(new Set())}
className="hover:text-[#138ba0] hover:underline"
>
Collapse all
</button>
</div>
)}
<button
type="button"
onClick={() => onChange([...list, { ...spec.blank }])}
className="rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] transition-colors hover:bg-[#eef9fb]"
onClick={add}
className="ml-auto rounded-full border border-[#138ba0] px-3 py-1 text-sm font-medium text-[#138ba0] transition-colors hover:bg-[#eef9fb]"
>
{spec.addLabel ?? "Add"}
</button>
@ -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 (
<div
@ -325,14 +411,14 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange })
endDrag();
}}
className={
"rounded-xl border bg-[#f6fbfc] p-4 transition-colors " +
`rounded-xl border bg-[#f6fbfc] ${expanded ? "p-4" : "px-4 py-2.5"} transition-colors ` +
(over
? "border-[#138ba0] ring-2 ring-[#138ba0]/25 "
: "border-[#4a6b72]/20 ") +
(dragging ? "opacity-50" : "")
}
>
<div className="mb-3 flex items-center gap-2">
<div className={`flex items-center gap-2 ${expanded ? "mb-3" : ""}`}>
<span
draggable
onDragStart={(e) => {
@ -353,11 +439,29 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange })
⠿
</span>
<span className="text-sm font-medium text-[#26454c]">
{spec.title ? spec.title(row, options) : `#${index + 1}`}
</span>
<button
type="button"
onClick={() => toggle(index)}
aria-expanded={expanded}
className="flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-medium text-[#26454c] hover:text-[#138ba0]"
>
<span
aria-hidden="true"
className={`inline-block text-xs text-[#4a6b72] transition-transform ${
expanded ? "rotate-90" : ""
}`}
>
▶
</span>
<span className="truncate">
{spec.title ? spec.title(row, options) : `#${index + 1}`}
</span>
{!expanded && hasError(index) && (
<span className="text-xs text-[#b3261e]">needs attention</span>
)}
</button>
<div className="ml-auto flex gap-1">
<div className="ml-auto flex shrink-0 gap-1">
<IconButton
label="Move up"
onClick={() => move(index, -1)}
@ -375,39 +479,44 @@ export function Repeater({ spec, rows, options, errors, errorPrefix, onChange })
<IconButton
label="Remove"
danger
onClick={() => onChange(list.filter((_, i) => i !== index))}
onClick={() => removeAt(index)}
>
✕
</IconButton>
</div>
</div>
<FieldGrid>
{spec.fields.map((field) => (
<Field
key={field.path}
field={field}
row={row}
value={row[field.path]}
options={options}
error={errors?.[`${errorPrefix}${index}.${field.path}`]}
onChange={(value) => update(index, { ...row, [field.path]: value })}
/>
))}
</FieldGrid>
{expanded && (
<>
<FieldGrid>
{spec.fields.map((field) => (
<Field
key={field.path}
field={field}
row={row}
value={row[field.path]}
options={options}
error={errors?.[`${errorPrefix}${index}.${field.path}`]}
onChange={(value) => update(index, { ...row, [field.path]: value })}
/>
))}
</FieldGrid>
{(spec.children ?? []).map((nested) => (
<div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-2">
<Repeater
spec={nested}
rows={row[nested.key]}
options={options}
errors={errors}
errorPrefix={`${errorPrefix}${index}.${nested.key}.`}
onChange={(value) => update(index, { ...row, [nested.key]: value })}
/>
</div>
))}
{(spec.children ?? []).map((nested) => (
<div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4">
<Repeater
spec={nested}
rows={row[nested.key]}
options={options}
errors={errors}
errorPrefix={`${errorPrefix}${index}.${nested.key}.`}
className=""
onChange={(value) => update(index, { ...row, [nested.key]: value })}
/>
</div>
))}
</>
)}
</div>
);
})}