NGU-Web/src/components/PageShell.tsx
Aidan Dona f1a0b06ac2 Page management, step 3: section types with their own settings; the front page as sections
Migration 083 gives the section types that need more than blocks their
own tables (hero, slides, countdown, stats, paths, featured cards, the
Community blog's slots, pinned posts and feeds) and turns the front page
into Home's sections: the hero, then its bands in order. Any section can
be hidden. The Front page editor, its tables and the Community page's
are gone; /api/front-page and /api/community-blog fold into the page's
sections (sectionData.js). The admin engine reads and writes a child
collection's own side tables and gated nested collections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:34:56 -05:00

359 lines
15 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
PAGE SHELL
Just the chrome that makes pages look alike: a page header, then
sections with a thin accent banner between them and a left-aligned
heading with a blurb and rule. Sections paint no background of
their own: the page's (PageBackdrop.tsx) runs behind all of them.
`sideNav` adds an "On this page" list in the left margin, the
admin editors' own (SectionNav), sticky under the header, listing
the sections with the one being read lit. It sits beside the
sections rather than taking a column from them, so they stay where
they'd be without it; it shows once the margin beside the 72rem
content is wide enough for it and its circle to take in the
longest list a page may have, 10 sections of two-line titles (30
characters, 15 a line): 2xl (96rem, 1536px) screens up. Narrower,
the header's dropdowns list the sections instead.
Whatever goes inside a section is passed as `content`, the shell
doesn't care what it is.
No <main> and no footer here, Layout provides both, so a page
using this shell drops straight into the router's Outlet.
Usage:
<PageShell
title="Community"
intro="One line under the page title."
sections={[
{
id: "local", // matches the nav hash, #local
title: "Local Groups",
blurb: "Optional line under the section heading.",
accent: BRAND, // heading, banner, rule
actions: <SomeButton />, // optional, right of the heading
content: <YourStuff />,
},
]}
/>
═══════════════════════════════════════════════════════════════ */
import { useEffect, useRef, useState, type ReactNode } from "react";
import { documentTitle } from "../lib/site.ts";
import { accentText, ACCENTS, BRAND } from '../lib/color.ts'
import { SectionNav, useActiveSection } from "./admin/SectionNav.tsx";
import "./PageShell.css";
export type ShellSection = {
id: string;
title: string;
blurb?: string;
accent: string;
actions?: ReactNode;
content: ReactNode;
/** It draws its own heading (a band, sections/Bands.tsx): the shell adds none. */
bare?: boolean;
/** Left out of the side nav (the hero, a countdown). */
unlisted?: boolean;
};
type PageShellProps = {
title: ReactNode;
intro?: ReactNode;
sections: ShellSection[];
/** An "On this page" column beside the sections, from lg up. */
sideNav?: boolean;
};
export function Section({ section }: { section: ShellSection }) {
const {
id,
title,
blurb,
accent,
// Optional action bar for this section's heading row, a view
// toggle, a filter, a link. Whatever the section needs; the
// shell just gives it a place to sit.
actions,
content,
bare,
} = section;
// A band brings its own heading, padding and anchor.
if (bare) return <>{content}</>;
return (
<section
id={id}
// Jumped to, it lands clear of the fixed header
// (scroll-padding-top in index.css).
className="py-20"
>
{/* Heading, left aligned, optional actions on the right */}
<div className="max-w-6xl mx-auto px-6 mb-10">
<div className="flex flex-wrap items-end justify-between gap-4">
<div>
<h2 className="text-3xl md:text-4xl font-bold" style={{ color: accentText(accent) }}>
{title}
</h2>
{blurb && <p className="mt-2 text-muted max-w-xl">{blurb}</p>}
</div>
{actions}
</div>
</div>
{content}
</section>
);
}
/* The side nav's circle at rest: half again the list's width (or a
little more than its height, if taller), at most 22rem. */
const circleSize = (box: { width: number; height: number }) =>
Math.min(Math.max(box.width * 1.5, box.height * 1.1), 22 * 16);
/* The height a pill `width` wide (rounded-full: straight sides, round
ends of radius r = width / 2) needs to take in a box reaching
`across` and `down` from its center (or a corner it's centered on):
the corner must sit inside an end's circle, so the straight part
reaches down - sqrt(r^2 - across^2). Equal to the width when a
circle that wide would do; taller when the list is too tall for
one. A box as wide as the pill can't be taken in, so it stops at 95%. */
const coverHeight = (width: number, across: number, down: number) => {
const r = width / 2;
const ratio = Math.min(across / r, 0.95);
return Math.max(width, 2 * (down - r * Math.sqrt(1 - ratio * ratio) + r));
};
/* How far the list sits in from the column's top and left: the
circle centers on that. LIST_TOP puts "On this page" level with
the first section's title: the line (h-2, 8px), the section's
py-20 (80px), then half the difference between the title's 40px
line (md:text-4xl) and the heading's 16px one. Lower still if its
circle needs the room to start CIRCLE_GAP below that first line
rather than over it.
Once the page scrolls, the list sticks just STUCK_TOP under the
header, so its circle rises up behind the header like a sun in the
corner; the sticky offset takes back whatever the list sits lower
than that. */
const LIST_TOP = 8 + 100 + (40 - 16) / 2;
const STUCK_TOP = 16;
const stickAt = (listTop: number) => `calc(var(--header-h, 5rem) + ${STUCK_TOP - listTop}px)`;
const LIST_LEFT = 16;
const CIRCLE_GAP = 8 + 4;
/* Room the circle keeps: from the section's edge at rest, and around
the list it takes in. */
const CIRCLE_EDGE = 16;
const CIRCLE_MARGIN = 12;
/* The circle's color family for a section's accent (PageShell.css):
green and amber their own, teal and deep teal (and any other) teal. */
const circleFamily = (accent?: string) =>
accent === ACCENTS.green ? "green" : accent === ACCENTS.amber ? "amber" : "teal";
/* How far left of the list's center the circle sits, at most: never
left of the "On this page" heading's own center, so a list of short
titles keeps it on the heading. */
const CIRCLE_SHIFT = 24;
export default function PageShell({ title, intro, sections, sideNav = false }: PageShellProps) {
// The list's measured box, so its circle can center on it from a
// layer of its own (below).
// The column's width too: the circle keeps its right edge inside
// it, sliding off the screen's left edge instead when the window
// narrows.
const listRef = useRef<HTMLDivElement>(null);
const columnRef = useRef<HTMLElement>(null);
const [listBox, setListBox] = useState<{ width: number; height: number; heading: number } | null>(null);
const [columnWidth, setColumnWidth] = useState(0);
useEffect(() => {
const list = listRef.current;
const column = columnRef.current;
if (!list || !column) return;
const ro = new ResizeObserver(() => {
const heading = list.querySelector<HTMLElement>("[data-nav-heading]");
setListBox({
width: list.offsetWidth,
height: list.offsetHeight,
// The heading's center, from the list's left.
heading: heading ? heading.offsetLeft + heading.offsetWidth / 2 : 0,
});
setColumnWidth(column.offsetWidth);
});
ro.observe(list);
ro.observe(column);
return () => ro.disconnect();
}, [sideNav]);
const navSections = sideNav
? sections.filter((s) => !s.unlisted).map((s) => ({ id: s.id, label: s.title, accent: s.accent }))
: [];
const active = useActiveSection(navSections);
const activeAccent = sections.find((s) => s.id === active)?.accent;
// The shape at rest: a circle centered on the list (a little left,
// never left of the heading's center), CIRCLE_EDGE clear of the
// section's edge, made a pill as tall as it takes when the list
// is too tall for the circle (10 sections of two-line titles).
// The shape at a given width: its center as near the list's as the
// section's edge allows (it may run off the screen's left edge), and
// the height it then takes.
const restAt = (width: number, box: { width: number; height: number; heading: number }) => {
const center = Math.min(
LIST_LEFT + Math.max(box.width / 2 - CIRCLE_SHIFT, box.heading),
columnWidth - CIRCLE_EDGE - width / 2,
);
const across = Math.max(center - LIST_LEFT, LIST_LEFT + box.width - center) + CIRCLE_MARGIN;
return { width, height: coverHeight(width, across, box.height / 2 + CIRCLE_MARGIN), left: center - width / 2 };
};
const rest = (() => {
if (!listBox) return null;
const circle = restAt(circleSize(listBox), listBox);
if (circle.height <= circle.width) return circle;
// Too tall a list for the circle: the width, up to 22rem, that
// needs the least height.
let best = circle;
for (let width = listBox.width + 2 * CIRCLE_MARGIN; width <= 22 * 16; width += 8) {
const shape = restAt(width, listBox);
if (shape.height < best.height) best = shape;
}
return best;
})();
const listTop = listBox && rest ? Math.max(LIST_TOP, CIRCLE_GAP + rest.height / 2 - listBox.height / 2) : LIST_TOP;
// Stuck: the page has scrolled the list up to its place under the
// header. The circle then becomes the corner sun (below).
// Leaving: the last section is going up past the list, so the list
// goes with it into the footer; the sun, far bigger than its sticky
// layer, would hang over the footer, so it fades out.
const [stuck, setStuck] = useState(false);
const [leaving, setLeaving] = useState(false);
const listHeight = listBox?.height ?? 0;
useEffect(() => {
const column = columnRef.current;
if (!sideNav || !column) return;
let frame = 0;
const measure = () => {
frame = 0;
const header = parseFloat(getComputedStyle(column).getPropertyValue("--header-h")) || 80;
const box = column.getBoundingClientRect();
setStuck(box.top + listTop <= header + STUCK_TOP + 1);
setLeaving(box.bottom <= header + STUCK_TOP + listHeight + CIRCLE_MARGIN);
};
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);
};
}, [sideNav, listTop, listHeight]);
// The circle's box, from its layer's top left (which sticks with
// the list). At rest: `rest` above. Stuck: a sun in the corner,
// centered on the header's bottom left so the header and the
// screen's edge hide three quarters of it, reaching past the list's
// far corner. Never wider than the column (it'd show a cut edge at
// the content): held narrower by the window, it stays centered on
// the header's edge (so below it, it only ever curves inward) and
// becomes a pill, as tall as it takes to take the list in.
const circleBox = (() => {
if (!listBox || !rest) return null;
if (stuck) {
const across = LIST_LEFT + listBox.width + CIRCLE_MARGIN;
const down = STUCK_TOP + listBox.height + CIRCLE_MARGIN;
const width = 2 * Math.min(Math.hypot(across, down), columnWidth - 8);
const height = coverHeight(width, across, down);
return { width, height, left: -width / 2, top: listTop - STUCK_TOP - height / 2 };
}
return { width: rest.width, height: rest.height, left: rest.left, top: listTop + listBox.height / 2 - rest.height / 2 };
})();
// The tab's title as the visitor moves around. The first load's
// comes from the server (pageMeta.js), which also sets the page's
// description and preview for search and link sharing.
useEffect(() => {
if (typeof title === "string") document.title = documentTitle(title);
}, [title]);
// The thin solid banner between sections, the page's full width
// (behind the side nav).
const banner = (accent: string) => <div className="h-2" style={{ background: accent }} />;
const bands = sections.map((section, i) => (
<div key={section.id}>
{banner(section.accent)}
<Section section={section} />
{i === sections.length - 1 && banner(section.accent)}
</div>
));
return (
<>
{/* Page header */}
<div className="pt-24 pb-12 px-6">
<div className="max-w-6xl mx-auto">
<h1 className="text-4xl sm:text-5xl md:text-6xl font-bold [overflow-wrap:anywhere] hyphens-auto" style={{ color: accentText(BRAND) }}>
{title}
</h1>
{intro && <p className="mt-3 text-lg text-muted max-w-2xl">{intro}</p>}
</div>
</div>
{sideNav ? (
<div className="relative">
{/* The margin left of the content (72rem, its text 1.5rem in),
clipping sideways only, so nothing reaches the
content or the screen's edge. clip, not hidden: hidden
would make it a scroll container, and the sticky layers in
it would stop sticking. z-20: in front of everything in the
sections, such as a carousel's arrows (z-10), which as later
siblings would otherwise draw over it; it takes no clicks
itself, only its list does. */}
<aside
ref={columnRef}
className="pointer-events-none absolute inset-y-0 left-0 z-20 hidden overflow-x-clip 2xl:block"
style={{ width: "calc((100% - 72rem) / 2 + 1rem)" }}
>
{/* A solid circle centered on the list, in the light shade
of the section being read (PageShell.css): a sticky layer of
its own, in front of the section lines like the list,
which comes after it and so draws over it. Height 0, so
the list's layer below starts, and sticks, at the same
place. */}
{circleBox ? (
<div aria-hidden="true" className="pointer-events-none sticky z-10 h-0" style={{ top: stickAt(listTop) }}>
<div
className="side-nav-circle absolute rounded-full"
data-family={circleFamily(activeAccent)}
data-leaving={leaving || undefined}
style={{
width: circleBox.width,
height: circleBox.height,
left: circleBox.left,
top: circleBox.top,
}}
/>
</div>
) : null}
{/* The list, in front of the section lines and its circle. */}
<div className="sticky z-10 pl-4 pr-2" style={{ top: stickAt(listTop), paddingTop: listTop }}>
<div ref={listRef} className="pointer-events-auto w-fit max-w-full">
<SectionNav sections={navSections} wrap />
</div>
</div>
</aside>
{bands}
</div>
) : (
bands
)}
</>
);
}