Third audit, UI half; side nav on top; request button colors
- Event cards: lazy -640 photo, only nearby slides drawn, a counter past 12 events, past grid paged with Show more - Community map: search over list and grid, 12 per region then Show all, list no longer redrawn on hover - People tiles: one clip check for the list, Show all past 30 - Person pages: 6 events and posts then Show all; excerpts load only the first paragraph - Admin: filter box on long pickers and the QR select, options sent per form, Media thumbnails from the small copy, debounced searches that drop stale answers - Pages show their last data while refreshing after the cache TTL - Side nav stacks above page content (the carousel arrows) - No event request button on National Retreats; request buttons take their section's accent - Version v1.11.1-audit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
11a4555683
commit
222c9e69a2
22 changed files with 686 additions and 259 deletions
|
|
@ -63,12 +63,15 @@ function visible(c, entity, row) {
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Everything the select inputs need, in one request. Small enough
|
/* What the select inputs need, in one request: the lists a form
|
||||||
that paging it would cost more than it saves. */
|
names in ?only=people,events (src/lib/adminSchema.ts, optionsPath),
|
||||||
|
or every list without it. */
|
||||||
entities.get("/options", (c) => {
|
entities.get("/options", (c) => {
|
||||||
const db = c.get("db");
|
const db = c.get("db");
|
||||||
|
const only = c.req.query("only")?.split(",");
|
||||||
const options = {};
|
const options = {};
|
||||||
for (const [key, sql] of Object.entries(OPTION_QUERIES)) {
|
for (const [key, sql] of Object.entries(OPTION_QUERIES)) {
|
||||||
|
if (only && !only.includes(key)) continue;
|
||||||
options[key] = db.prepare(sql).all();
|
options[key] = db.prepare(sql).all();
|
||||||
}
|
}
|
||||||
return c.json({ options }, 200, NO_STORE);
|
return c.json({ options }, 200, NO_STORE);
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@
|
||||||
|
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
|
|
||||||
import { asBool, json, loadBlocks, loadFeaturedCards, marks, paragraphs } from "../shape.js";
|
import { asBool, json, loadBlocks, loadFeaturedCards, marks } from "../shape.js";
|
||||||
import { readFeeds } from "../feeds.js";
|
import { readFeeds } from "../feeds.js";
|
||||||
|
|
||||||
const blog = new Hono();
|
const blog = new Hono();
|
||||||
|
|
@ -64,12 +64,32 @@ function loadAuthors(db, ids) {
|
||||||
return byPost;
|
return byPost;
|
||||||
}
|
}
|
||||||
|
|
||||||
function shapeSummary(row, authors, body) {
|
/* The first paragraph of each post with no excerpt of its own, the
|
||||||
|
card's fallback text, by post id. Only that one row per post: a
|
||||||
|
card doesn't need the rest of the body. */
|
||||||
|
function firstParagraphs(db, rows) {
|
||||||
|
const ids = rows.filter((row) => !row.excerpt).map((row) => row.id);
|
||||||
|
if (ids.length === 0) return new Map();
|
||||||
|
const found = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT owner_id, text FROM (
|
||||||
|
SELECT owner_id, text, ROW_NUMBER() OVER (PARTITION BY owner_id ORDER BY sort_order) AS n
|
||||||
|
FROM content_blocks
|
||||||
|
WHERE owner_kind = 'blog_post' AND slot = 'body' AND type = 'paragraph'
|
||||||
|
AND text IS NOT NULL AND text <> ''
|
||||||
|
AND owner_id IN (${marks(ids.length)})
|
||||||
|
) WHERE n = 1`,
|
||||||
|
)
|
||||||
|
.all(...ids);
|
||||||
|
return new Map(found.map((row) => [row.owner_id, row.text]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function shapeSummary(row, authors, firstParagraph) {
|
||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
title: row.title,
|
title: row.title,
|
||||||
// The card's text: the excerpt, else the body's first paragraph.
|
// The card's text: the excerpt, else the body's first paragraph.
|
||||||
excerpt: row.excerpt || paragraphs(body)[0] || null,
|
excerpt: row.excerpt || firstParagraph || null,
|
||||||
cover_image: row.cover_image,
|
cover_image: row.cover_image,
|
||||||
published_on: row.published_on,
|
published_on: row.published_on,
|
||||||
tags: splitTags(row.tags),
|
tags: splitTags(row.tags),
|
||||||
|
|
@ -94,8 +114,8 @@ export function postsBy(db, personId) {
|
||||||
.all(personId);
|
.all(personId);
|
||||||
const ids = rows.map((row) => row.id);
|
const ids = rows.map((row) => row.id);
|
||||||
const authors = loadAuthors(db, ids);
|
const authors = loadAuthors(db, ids);
|
||||||
const bodies = loadBlocks(db, "blog_post", ids, "body");
|
const first = firstParagraphs(db, rows);
|
||||||
return rows.map((row) => shapeSummary(row, authors.get(row.id) ?? [], bodies.get(row.id) ?? []));
|
return rows.map((row) => shapeSummary(row, authors.get(row.id) ?? [], first.get(row.id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── One post ──────────────────────────────────────────────── */
|
/* ── One post ──────────────────────────────────────────────── */
|
||||||
|
|
@ -164,7 +184,7 @@ blog.get("/community-blog", async (c) => {
|
||||||
const posts = [...pinned, ...newest];
|
const posts = [...pinned, ...newest];
|
||||||
const ids = posts.map((row) => row.id);
|
const ids = posts.map((row) => row.id);
|
||||||
const authors = loadAuthors(db, ids);
|
const authors = loadAuthors(db, ids);
|
||||||
const bodies = loadBlocks(db, "blog_post", ids, "body");
|
const first = firstParagraphs(db, posts);
|
||||||
|
|
||||||
// Theirs: pinned cards, then the feeds' newest.
|
// Theirs: pinned cards, then the feeds' newest.
|
||||||
const cards = loadFeaturedCards(db, "community_page", PAGE_ID);
|
const cards = loadFeaturedCards(db, "community_page", PAGE_ID);
|
||||||
|
|
@ -194,7 +214,7 @@ blog.get("/community-blog", async (c) => {
|
||||||
internal: {
|
internal: {
|
||||||
title: page.internal_title,
|
title: page.internal_title,
|
||||||
posts: posts.map((row) =>
|
posts: posts.map((row) =>
|
||||||
shapeSummary(row, authors.get(row.id) ?? [], bodies.get(row.id) ?? []),
|
shapeSummary(row, authors.get(row.id) ?? [], first.get(row.id)),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
external: {
|
external: {
|
||||||
|
|
|
||||||
53
src/components/OptionFilter.tsx
Normal file
53
src/components/OptionFilter.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
/* ═══════════════════════════════════════════════════════════════
|
||||||
|
OPTION FILTER
|
||||||
|
|
||||||
|
A select over hundreds of records (every person, every event)
|
||||||
|
only matches first letters as you type, so finding one means
|
||||||
|
scrolling. Past FILTER_FROM options, a small box above it narrows
|
||||||
|
the list to the options whose label holds what's typed:
|
||||||
|
|
||||||
|
const [needle, setNeedle] = useState('')
|
||||||
|
const shown = narrow(list, needle, ([, label]) => label, ([id]) => id === value)
|
||||||
|
{list.length > FILTER_FROM && <OptionFilter value={needle} onChange={setNeedle} ... />}
|
||||||
|
|
||||||
|
`keep` holds an option in whatever the box says (the one chosen),
|
||||||
|
so narrowing never blanks the select's value.
|
||||||
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
|
import { MagnifyingGlass } from '@phosphor-icons/react'
|
||||||
|
|
||||||
|
export const FILTER_FROM = 50
|
||||||
|
|
||||||
|
export function narrow<T>(items: T[], needle: string, text: (item: T) => string, keep?: (item: T) => boolean): T[] {
|
||||||
|
const term = needle.trim().toLowerCase()
|
||||||
|
if (!term) return items
|
||||||
|
return items.filter((item) => keep?.(item) || String(text(item) ?? '').toLowerCase().includes(term))
|
||||||
|
}
|
||||||
|
|
||||||
|
type OptionFilterProps = {
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
label: string
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function OptionFilter({ value, onChange, label, className = 'mb-1.5' }: OptionFilterProps) {
|
||||||
|
return (
|
||||||
|
<div className={`relative ${className}`}>
|
||||||
|
<MagnifyingGlass
|
||||||
|
size={16}
|
||||||
|
weight="bold"
|
||||||
|
aria-hidden="true"
|
||||||
|
className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-muted"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
aria-label={label}
|
||||||
|
placeholder="Type to narrow the list"
|
||||||
|
className="w-full border border-muted/25 bg-surface py-1.5 pl-8 pr-3 text-sm text-body outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -294,10 +294,13 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
|
||||||
clipping sideways only, so nothing reaches the
|
clipping sideways only, so nothing reaches the
|
||||||
content or the screen's edge. clip, not hidden: hidden
|
content or the screen's edge. clip, not hidden: hidden
|
||||||
would make it a scroll container, and the sticky layers in
|
would make it a scroll container, and the sticky layers in
|
||||||
it would stop sticking. */}
|
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
|
<aside
|
||||||
ref={columnRef}
|
ref={columnRef}
|
||||||
className="absolute inset-y-0 left-0 hidden overflow-x-clip 2xl:block"
|
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)" }}
|
style={{ width: "calc((100% - 72rem) / 2 + 1rem)" }}
|
||||||
>
|
>
|
||||||
{/* A solid circle centered on the list, in the light shade
|
{/* A solid circle centered on the list, in the light shade
|
||||||
|
|
@ -322,7 +325,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
|
||||||
) : null}
|
) : null}
|
||||||
{/* The list, in front of the section lines and its circle. */}
|
{/* 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 className="sticky z-10 pl-4 pr-2" style={{ top: stickAt(listTop), paddingTop: listTop }}>
|
||||||
<div ref={listRef} className="w-fit max-w-full">
|
<div ref={listRef} className="pointer-events-auto w-fit max-w-full">
|
||||||
<SectionNav sections={navSections} wrap />
|
<SectionNav sections={navSections} wrap />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { ArrowRight, CaretDown, X } from "@phosphor-icons/react";
|
import { ArrowRight, CaretDown, X } from "@phosphor-icons/react";
|
||||||
import {
|
import {
|
||||||
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
useId,
|
useId,
|
||||||
useLayoutEffect,
|
useLayoutEffect,
|
||||||
|
|
@ -153,6 +154,9 @@ export interface PeopleTilesProps
|
||||||
onExpand?: (person: Person | null, group: PeopleGroup | null) => void;
|
onExpand?: (person: Person | null, group: PeopleGroup | null) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A list longer than this shows this many tiles, then "Show all". */
|
||||||
|
const SHOW_FIRST = 30;
|
||||||
|
|
||||||
const SIZE_FEATURES: Record<PeopleTilesSize, { title: boolean; details: boolean }> = {
|
const SIZE_FEATURES: Record<PeopleTilesSize, { title: boolean; details: boolean }> = {
|
||||||
sm: { title: false, details: false },
|
sm: { title: false, details: false },
|
||||||
md: { title: true, details: false },
|
md: { title: true, details: false },
|
||||||
|
|
@ -444,6 +448,21 @@ export function PeopleTilesView({
|
||||||
|
|
||||||
const hasPeople = resolvedGroups.length > 0;
|
const hasPeople = resolvedGroups.length > 0;
|
||||||
|
|
||||||
|
// A long list shows its first SHOW_FIRST tiles until "Show all".
|
||||||
|
const [showAll, setShowAll] = useState(false);
|
||||||
|
const total = resolvedGroups.reduce((sum, group) => sum + group.people.length, 0);
|
||||||
|
const shownGroups = useMemo<PeopleGroup[]>(() => {
|
||||||
|
if (showAll || total <= SHOW_FIRST) return resolvedGroups;
|
||||||
|
let left = SHOW_FIRST;
|
||||||
|
const out: PeopleGroup[] = [];
|
||||||
|
for (const group of resolvedGroups) {
|
||||||
|
if (left <= 0) break;
|
||||||
|
out.push({ ...group, people: group.people.slice(0, left) });
|
||||||
|
left -= group.people.length;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}, [resolvedGroups, showAll, total]);
|
||||||
|
|
||||||
// How much room a row has, and one tile's width and gap there, in
|
// How much room a row has, and one tile's width and gap there, in
|
||||||
// px: the probe carries --pl-w and --pl-gap, so the CSS stays the
|
// px: the probe carries --pl-w and --pl-gap, so the CSS stays the
|
||||||
// one place that sizes tiles.
|
// one place that sizes tiles.
|
||||||
|
|
@ -463,6 +482,34 @@ export function PeopleTilesView({
|
||||||
return () => observer.disconnect();
|
return () => observer.disconnect();
|
||||||
}, [overflow, hasPeople]);
|
}, [overflow, hasPeople]);
|
||||||
|
|
||||||
|
// Which captions are cut off, every tile in one pass: after each
|
||||||
|
// render that can change it (the room, the people, the title line)
|
||||||
|
// and once the web font has arrived, since it changes text widths
|
||||||
|
// without resizing anything.
|
||||||
|
const checkClips = useCallback(() => {
|
||||||
|
const root = rootRef.current;
|
||||||
|
if (!root) return;
|
||||||
|
const next = new Set<string>();
|
||||||
|
for (const caption of root.querySelectorAll<HTMLElement>("[data-clip-key]")) {
|
||||||
|
if (Array.from(caption.children).some((line) => line.scrollHeight > line.clientHeight + 1)) {
|
||||||
|
next.add(caption.dataset.clipKey!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setClipped((current) =>
|
||||||
|
current.size === next.size && [...next].every((key) => current.has(key)) ? current : next,
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useLayoutEffect(checkClips, [checkClips, room, shownGroups, features.title]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let live = true;
|
||||||
|
document.fonts?.ready.then(() => live && checkClips());
|
||||||
|
return () => {
|
||||||
|
live = false;
|
||||||
|
};
|
||||||
|
}, [checkClips]);
|
||||||
|
|
||||||
// A click anywhere outside the list closes the panel.
|
// A click anywhere outside the list closes the panel.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!openKey) return undefined;
|
if (!openKey) return undefined;
|
||||||
|
|
@ -489,23 +536,13 @@ export function PeopleTilesView({
|
||||||
const open = openKey ? findByKey(resolvedGroups, openKey) : null;
|
const open = openKey ? findByKey(resolvedGroups, openKey) : null;
|
||||||
const oneRow =
|
const oneRow =
|
||||||
room !== null && overflow !== "scroll" &&
|
room !== null && overflow !== "scroll" &&
|
||||||
fitsOneRow(resolvedGroups.map((group) => group.people.length), room.width, room.tile, room.gap);
|
fitsOneRow(shownGroups.map((group) => group.people.length), room.width, room.tile, room.gap);
|
||||||
const anchored = overflow !== "scroll";
|
const anchored = overflow !== "scroll";
|
||||||
const closePanel = () => {
|
const closePanel = () => {
|
||||||
setOpenKey(null);
|
setOpenKey(null);
|
||||||
onExpand?.(null, null);
|
onExpand?.(null, null);
|
||||||
};
|
};
|
||||||
|
|
||||||
function markClipped(key: string, isClipped: boolean) {
|
|
||||||
setClipped((current) => {
|
|
||||||
if (current.has(key) === isClipped) return current;
|
|
||||||
const next = new Set(current);
|
|
||||||
if (isClipped) next.add(key);
|
|
||||||
else next.delete(key);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggle(group: PeopleGroup, person: Person, index: number) {
|
function toggle(group: PeopleGroup, person: Person, index: number) {
|
||||||
const key = keyFor(group, person, index);
|
const key = keyFor(group, person, index);
|
||||||
const next = openKey === key ? null : key;
|
const next = openKey === key ? null : key;
|
||||||
|
|
@ -544,7 +581,7 @@ export function PeopleTilesView({
|
||||||
>
|
>
|
||||||
<span ref={probeRef} className="pl__probe" aria-hidden="true" />
|
<span ref={probeRef} className="pl__probe" aria-hidden="true" />
|
||||||
<div className="pl__groups" data-row={oneRow ? "one" : undefined}>
|
<div className="pl__groups" data-row={oneRow ? "one" : undefined}>
|
||||||
{resolvedGroups.map((group) => (
|
{shownGroups.map((group) => (
|
||||||
<section
|
<section
|
||||||
key={group.id}
|
key={group.id}
|
||||||
className="pl__group"
|
className="pl__group"
|
||||||
|
|
@ -598,7 +635,7 @@ export function PeopleTilesView({
|
||||||
isOpen={isOpen}
|
isOpen={isOpen}
|
||||||
panelId={`${baseId}-bio`}
|
panelId={`${baseId}-bio`}
|
||||||
onToggle={() => toggle(group, person, index)}
|
onToggle={() => toggle(group, person, index)}
|
||||||
onClip={(isClipped) => markClipped(key, isClipped)}
|
clipKey={key}
|
||||||
/>
|
/>
|
||||||
{isOpen && anchored && open && (
|
{isOpen && anchored && open && (
|
||||||
<DetailPanel
|
<DetailPanel
|
||||||
|
|
@ -617,6 +654,16 @@ export function PeopleTilesView({
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!showAll && total > SHOW_FIRST && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowAll(true)}
|
||||||
|
className="btn mt-4 border border-brand/40 px-5 py-2 text-sm text-link hover:border-brand"
|
||||||
|
>
|
||||||
|
Show all {total}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
{open && !anchored && (
|
{open && !anchored && (
|
||||||
<DetailPanel
|
<DetailPanel
|
||||||
id={`${baseId}-bio`}
|
id={`${baseId}-bio`}
|
||||||
|
|
@ -636,7 +683,7 @@ function Tile({
|
||||||
isOpen,
|
isOpen,
|
||||||
panelId,
|
panelId,
|
||||||
onToggle,
|
onToggle,
|
||||||
onClip,
|
clipKey,
|
||||||
}: {
|
}: {
|
||||||
person: Person;
|
person: Person;
|
||||||
showTitle: boolean;
|
showTitle: boolean;
|
||||||
|
|
@ -644,36 +691,20 @@ function Tile({
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
panelId: string;
|
panelId: string;
|
||||||
onToggle: () => void;
|
onToggle: () => void;
|
||||||
onClip: (isClipped: boolean) => void;
|
clipKey: string;
|
||||||
}) {
|
}) {
|
||||||
const title = titleOf(person);
|
const title = titleOf(person);
|
||||||
const captionRef = useRef<HTMLSpanElement>(null);
|
|
||||||
|
|
||||||
// Every caption is the same height (two lines of name, two of
|
// Every caption is the same height (two lines of name, two of
|
||||||
// title), so the row stays even; a name or title that needs more
|
// title), so the row stays even; a name or title that needs more
|
||||||
// is cut with an ellipsis. Checked again whenever the tile resizes,
|
// is cut with an ellipsis, and the list (checkClips) gives it the
|
||||||
// which is also when the web font arrives.
|
// down arrow.
|
||||||
useLayoutEffect(() => {
|
|
||||||
const caption = captionRef.current;
|
|
||||||
if (!caption) return undefined;
|
|
||||||
const check = () =>
|
|
||||||
onClip(
|
|
||||||
Array.from(caption.children).some((line) => line.scrollHeight > line.clientHeight + 1),
|
|
||||||
);
|
|
||||||
check();
|
|
||||||
const observer = new ResizeObserver(check);
|
|
||||||
observer.observe(caption);
|
|
||||||
return () => observer.disconnect();
|
|
||||||
// onClip is a fresh closure each render; the name and title are
|
|
||||||
// what can change the answer.
|
|
||||||
}, [person.name, title, showTitle]);
|
|
||||||
|
|
||||||
const content = (
|
const content = (
|
||||||
<span className="pl__frame">
|
<span className="pl__frame">
|
||||||
<span className="pl__photo">
|
<span className="pl__photo">
|
||||||
<Photo src={mediaUrl(person.photo)} name={person.name} />
|
<Photo src={mediaUrl(person.photo)} name={person.name} />
|
||||||
</span>
|
</span>
|
||||||
<span ref={captionRef} className="pl__caption" data-title={showTitle ? "on" : "off"}>
|
<span className="pl__caption" data-clip-key={clipKey} data-title={showTitle ? "on" : "off"}>
|
||||||
<span className="pl__name">{person.name}</span>
|
<span className="pl__name">{person.name}</span>
|
||||||
{showTitle && title && <span className="pl__title">{title}</span>}
|
{showTitle && title && <span className="pl__title">{title}</span>}
|
||||||
</span>
|
</span>
|
||||||
|
|
|
||||||
|
|
@ -2,14 +2,33 @@ import { Link } from "react-router-dom";
|
||||||
import { PaperPlaneTilt } from "@phosphor-icons/react";
|
import { PaperPlaneTilt } from "@phosphor-icons/react";
|
||||||
|
|
||||||
import { requestLink } from "../data/requestTypes.ts";
|
import { requestLink } from "../data/requestTypes.ts";
|
||||||
|
import { BRAND, accentText, withAlpha } from "../lib/color.ts";
|
||||||
|
|
||||||
/* A button to the Request form, opened on one kind of request
|
/* A button to the Request form, opened on one kind of request
|
||||||
(REQUEST_TYPES). Section manifests place it with `request`. */
|
(REQUEST_TYPES), in its section's accent. Section manifests place
|
||||||
export default function RequestLink({ type, label, className = "" }: { type: string; label: string; className?: string }) {
|
it with `request`. */
|
||||||
|
export default function RequestLink({
|
||||||
|
type,
|
||||||
|
label,
|
||||||
|
accent = BRAND,
|
||||||
|
className = "",
|
||||||
|
}: {
|
||||||
|
type: string;
|
||||||
|
label: string;
|
||||||
|
accent?: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
to={requestLink(type)}
|
to={requestLink(type)}
|
||||||
className={`inline-flex items-center gap-2 btn border border-brand/40 px-4 py-2 text-sm text-link transition-colors hover:bg-tint print:hidden ${className}`}
|
className={`inline-flex items-center gap-2 btn border px-4 py-2 text-sm transition-colors hover:bg-[var(--request-hover)] print:hidden ${className}`}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
borderColor: withAlpha(accent, 40),
|
||||||
|
color: accentText(accent),
|
||||||
|
"--request-hover": withAlpha(accent, 10),
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<PaperPlaneTilt aria-hidden="true" weight="bold" className="h-4 w-4" />
|
<PaperPlaneTilt aria-hidden="true" weight="bold" className="h-4 w-4" />
|
||||||
{label}
|
{label}
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"
|
||||||
import { ApiError, get, upload } from "../../lib/api.ts";
|
import { ApiError, get, upload } from "../../lib/api.ts";
|
||||||
import { useAuth } from "../../lib/auth.tsx";
|
import { useAuth } from "../../lib/auth.tsx";
|
||||||
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
||||||
import { formatBytes } from "./MediaLibrary.tsx";
|
import { formatBytes, SEARCH_PAUSE_MS } from "./MediaLibrary.tsx";
|
||||||
|
|
||||||
export type DriveFile = {
|
export type DriveFile = {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -115,21 +115,30 @@ export function useDriveFiles(query: string) {
|
||||||
// Files in the Drive folder that Drive wouldn't share publicly.
|
// Files in the Drive folder that Drive wouldn't share publicly.
|
||||||
const [refused, setRefused] = useState<string[]>([]);
|
const [refused, setRefused] = useState<string[]>([]);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
// Only the newest request may write (a slow earlier search mustn't
|
||||||
|
// replace a later one's list).
|
||||||
|
const latest = useRef(0);
|
||||||
|
|
||||||
const reload = useCallback(() => {
|
const reload = useCallback(() => {
|
||||||
|
const ask = ++latest.current;
|
||||||
const q = query.trim();
|
const q = query.trim();
|
||||||
setError(null);
|
setError(null);
|
||||||
get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
|
get(`/admin/files${q ? `?q=${encodeURIComponent(q)}` : ""}`, { ttl: 0 })
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
|
if (ask !== latest.current) return;
|
||||||
setItems(data.files);
|
setItems(data.files);
|
||||||
setFolders(data.folders ?? []);
|
setFolders(data.folders ?? []);
|
||||||
setReady(data.ready);
|
setReady(data.ready);
|
||||||
setRefused(data.refused ?? []);
|
setRefused(data.refused ?? []);
|
||||||
})
|
})
|
||||||
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
|
.catch((err) => ask === latest.current && setError(err instanceof ApiError ? err.message : "Couldn't load the files."));
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
useEffect(reload, [reload]);
|
// A search waits for a pause in the typing; the first load doesn't.
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(reload, query.trim() ? SEARCH_PAUSE_MS : 0);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [reload]);
|
||||||
return { items, folders, ready, refused, error, reload, setItems };
|
return { items, folders, ready, refused, error, reload, setItems };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,7 @@ import { useLocation } from "react-router-dom";
|
||||||
import { ApiError, get, post, upload } from "../../lib/api.ts";
|
import { ApiError, get, post, upload } from "../../lib/api.ts";
|
||||||
import { useAuth } from "../../lib/auth.tsx";
|
import { useAuth } from "../../lib/auth.tsx";
|
||||||
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
import { canWrite as roleCanWrite } from "../../lib/roles.ts";
|
||||||
|
import { useSmallImage } from "../../lib/useSmallImage.ts";
|
||||||
|
|
||||||
export type MediaItem = {
|
export type MediaItem = {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -138,14 +139,23 @@ export function uploadImage(file: File, keepOriginal: boolean, folder?: string):
|
||||||
return upload("/admin/media", form).then((data) => data.media);
|
return upload("/admin/media", form).then((data) => data.media);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* How long a search waits after the last keystroke. */
|
||||||
|
export const SEARCH_PAUSE_MS = 250;
|
||||||
|
/* The most the library route sends (MAX_LIST, server/src/routes/media.js). */
|
||||||
|
const MEDIA_LIST_MAX = 500;
|
||||||
|
|
||||||
/* `type` narrows to one kind of file: image fields pick images only.
|
/* `type` narrows to one kind of file: image fields pick images only.
|
||||||
Blank lists everything, videos and audio saved from the clip tool
|
Blank lists everything, videos and audio saved from the clip tool
|
||||||
included. */
|
included. */
|
||||||
export function useMediaLibrary(query: string, type?: "image" | "video" | "audio", folder?: string) {
|
export function useMediaLibrary(query: string, type?: "image" | "video" | "audio", folder?: string) {
|
||||||
const [items, setItems] = useState<MediaItem[] | null>(null);
|
const [items, setItems] = useState<MediaItem[] | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
// Only the newest request may write: a slow answer to an earlier
|
||||||
|
// search mustn't replace the list for a later one.
|
||||||
|
const latest = useRef(0);
|
||||||
|
|
||||||
const reload = useCallback(() => {
|
const reload = useCallback(() => {
|
||||||
|
const ask = ++latest.current;
|
||||||
const q = query.trim();
|
const q = query.trim();
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (q) params.set("q", q);
|
if (q) params.set("q", q);
|
||||||
|
|
@ -153,13 +163,17 @@ export function useMediaLibrary(query: string, type?: "image" | "video" | "audio
|
||||||
if (folder) params.set("folder", folder);
|
if (folder) params.set("folder", folder);
|
||||||
setError(null);
|
setError(null);
|
||||||
get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 })
|
get(`/admin/media${params.size ? `?${params}` : ""}`, { ttl: 0 })
|
||||||
.then((data) => setItems(data.media))
|
.then((data) => ask === latest.current && setItems(data.media))
|
||||||
.catch((err) =>
|
.catch((err) =>
|
||||||
setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
|
ask === latest.current && setError(err instanceof ApiError ? err.message : "Couldn't load the library."),
|
||||||
);
|
);
|
||||||
}, [query, type, folder]);
|
}, [query, type, folder]);
|
||||||
|
|
||||||
useEffect(reload, [reload]);
|
// A search waits for a pause in the typing; anything else asks at once.
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(reload, query.trim() ? SEARCH_PAUSE_MS : 0);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [reload]);
|
||||||
|
|
||||||
return { items, error, reload, setItems };
|
return { items, error, reload, setItems };
|
||||||
}
|
}
|
||||||
|
|
@ -263,6 +277,7 @@ export function MediaGrid({
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
{items.map((item) => {
|
{items.map((item) => {
|
||||||
const isSelected = selected === item.url;
|
const isSelected = selected === item.url;
|
||||||
|
|
@ -270,19 +285,15 @@ export function MediaGrid({
|
||||||
<>
|
<>
|
||||||
<div className="aspect-[4/3] overflow-hidden" style={CHECKER}>
|
<div className="aspect-[4/3] overflow-hidden" style={CHECKER}>
|
||||||
{item.content_type.startsWith("video/") ? (
|
{item.content_type.startsWith("video/") ? (
|
||||||
// A still of the first frame; metadata only, not the file.
|
// Nothing loads until it's played: a page of videos
|
||||||
<video src={item.url} preload="metadata" muted className="h-full w-full bg-black object-contain" />
|
// would otherwise fetch every one's opening.
|
||||||
|
<video src={item.url} preload="none" muted className="h-full w-full bg-black object-contain" />
|
||||||
) : item.content_type.startsWith("audio/") ? (
|
) : item.content_type.startsWith("audio/") ? (
|
||||||
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
|
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
|
||||||
<FileAudio weight="bold" className="h-10 w-10 text-link" />
|
<FileAudio weight="bold" className="h-10 w-10 text-link" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<img
|
<Thumb url={item.url} />
|
||||||
src={item.url}
|
|
||||||
alt=""
|
|
||||||
loading="lazy"
|
|
||||||
className="h-full w-full object-contain"
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1.5 truncate text-xs font-medium text-body" title={item.original_name}>
|
<p className="mt-1.5 truncate text-xs font-medium text-body" title={item.original_name}>
|
||||||
|
|
@ -316,9 +327,20 @@ export function MediaGrid({
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
|
{items.length >= MEDIA_LIST_MAX && (
|
||||||
|
<p className="notice mt-4 p-4 text-sm text-body">Newest {MEDIA_LIST_MAX} shown, search to narrow.</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A tile's picture: the 640px copy, the full file if there's none. */
|
||||||
|
function Thumb({ url }: { url: string }) {
|
||||||
|
const img = useSmallImage(url);
|
||||||
|
if (img.failed) return null;
|
||||||
|
return <img src={img.src} onError={img.onError} alt="" loading="lazy" className="h-full w-full object-contain" />;
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Photos sent with requests ───────────────────────────────── */
|
/* ── Photos sent with requests ───────────────────────────────── */
|
||||||
|
|
||||||
const REQUESTS_TAB = "requests";
|
const REQUESTS_TAB = "requests";
|
||||||
|
|
|
||||||
|
|
@ -88,10 +88,11 @@
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
import { ArrowUp, ArrowDown, CaretRight, Copy, Plus, X } from "@phosphor-icons/react";
|
import { ArrowUp, ArrowDown, CaretRight, Copy, Plus, X } from "@phosphor-icons/react";
|
||||||
import { useRef, useState } from "react";
|
import { useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
import { ApiError, post } from "../../lib/api.ts";
|
import { ApiError, post } from "../../lib/api.ts";
|
||||||
import ContentBlocks from "../ContentBlocks.tsx";
|
import ContentBlocks from "../ContentBlocks.tsx";
|
||||||
|
import { FILTER_FROM, OptionFilter, narrow } from "../OptionFilter.tsx";
|
||||||
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
|
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
|
||||||
import { ChooseFileButton } from "./DriveFiles.tsx";
|
import { ChooseFileButton } from "./DriveFiles.tsx";
|
||||||
|
|
||||||
|
|
@ -225,28 +226,35 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
|
||||||
const widget = field.widget ?? "text";
|
const widget = field.widget ?? "text";
|
||||||
const locked = Boolean(field.readOnly);
|
const locked = Boolean(field.readOnly);
|
||||||
|
|
||||||
let list: any = null;
|
// The select's options, rebuilt only when their source changes
|
||||||
let orphaned = false;
|
// (or, with filterBy, the row they're filtered by), not on every
|
||||||
|
// keystroke elsewhere in the form.
|
||||||
if (widget === "select") {
|
const source = field.optionsFrom ? options?.[field.optionsFrom] : field.options;
|
||||||
list = field.optionsFrom
|
const filterRow = field.filterBy ? row : null;
|
||||||
? (options?.[field.optionsFrom] ?? []).map((o) => [o.id, o.label, o])
|
const list: any[] | null = useMemo<any[] | null>(() => {
|
||||||
: (field.options ?? []).map((o) =>
|
if (widget !== "select") return null;
|
||||||
Array.isArray(o) ? [o[0], o[1]] : [o, o],
|
let all = field.optionsFrom
|
||||||
);
|
? (source ?? []).map((o) => [o.id, o.label, o])
|
||||||
if (field.filterBy && row) {
|
: (source ?? []).map((o) => (Array.isArray(o) ? [o[0], o[1]] : [o, o]));
|
||||||
list = list.filter(([, , raw]) => !raw || field.filterBy(raw, row));
|
if (field.filterBy && filterRow) {
|
||||||
|
all = all.filter(([, , raw]) => !raw || field.filterBy(raw, filterRow));
|
||||||
}
|
}
|
||||||
|
return all;
|
||||||
|
}, [widget, field, source, filterRow]);
|
||||||
|
|
||||||
|
// Past FILTER_FROM options, a box above the select narrows them.
|
||||||
|
const [needle, setNeedle] = useState("");
|
||||||
|
const shown: any[] = list ? narrow<any>(list, needle, ([, label]) => label, ([optionId]) => String(optionId) === String(value)) : [];
|
||||||
|
|
||||||
// A stored value with no matching option renders as the blank
|
// A stored value with no matching option renders as the blank
|
||||||
// choice, which reads as "nobody set this" and saves as a
|
// choice, which reads as "nobody set this" and saves as a
|
||||||
// deliberate clear. It usually means the row it pointed at was
|
// deliberate clear. It usually means the row it pointed at was
|
||||||
// deleted, so keep it on screen and say so.
|
// deleted, so keep it on screen and say so.
|
||||||
orphaned =
|
const orphaned =
|
||||||
|
list != null &&
|
||||||
value != null &&
|
value != null &&
|
||||||
value !== "" &&
|
value !== "" &&
|
||||||
!list.some(([optionId]) => String(optionId) === String(value));
|
!list.some(([optionId]) => String(optionId) === String(value));
|
||||||
}
|
|
||||||
|
|
||||||
// A file from the Drive library into this link field (`files`).
|
// A file from the Drive library into this link field (`files`).
|
||||||
const pickFile = (file) => {
|
const pickFile = (file) => {
|
||||||
|
|
@ -297,6 +305,14 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
|
||||||
// A select has no readOnly, so this one really does have
|
// A select has no readOnly, so this one really does have
|
||||||
// to be disabled: there's no way to keep it focusable
|
// to be disabled: there's no way to keep it focusable
|
||||||
// and still refuse a new choice.
|
// and still refuse a new choice.
|
||||||
|
<>
|
||||||
|
{(list?.length ?? 0) > FILTER_FROM && !locked && (
|
||||||
|
<OptionFilter
|
||||||
|
value={needle}
|
||||||
|
onChange={setNeedle}
|
||||||
|
label={`Narrow the ${typeof field.label === "function" ? field.label(row) : field.label} list`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<select
|
<select
|
||||||
{...common}
|
{...common}
|
||||||
disabled={locked}
|
disabled={locked}
|
||||||
|
|
@ -306,12 +322,13 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
|
||||||
>
|
>
|
||||||
<option value="">{field.blankLabel ?? "- Please choose from the list -"}</option>
|
<option value="">{field.blankLabel ?? "- Please choose from the list -"}</option>
|
||||||
{orphaned && <option value={value}>{value} no longer exists</option>}
|
{orphaned && <option value={value}>{value} no longer exists</option>}
|
||||||
{list.map(([id2, label]) => (
|
{shown.map(([id2, label]) => (
|
||||||
<option key={id2} value={id2}>
|
<option key={id2} value={id2}>
|
||||||
{label}
|
{label}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
</>
|
||||||
) : widget === "color" ? (
|
) : widget === "color" ? (
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<input
|
<input
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,23 @@ export const ADMIN_ENTITIES: Record<string, any> = {
|
||||||
site_settings: siteSettings,
|
site_settings: siteSettings,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* The /admin/options request for the option lists `part` of a
|
||||||
|
manifest names (any `optionsFrom` inside it, at any depth), so a
|
||||||
|
form gets only the lists its selects use. An empty request would
|
||||||
|
mean every list, so a part that names none asks for nothing. */
|
||||||
|
export function optionsPath(part: any): string | null {
|
||||||
|
const names = new Set<string>();
|
||||||
|
const seen = new Set<any>();
|
||||||
|
const walk = (value: any) => {
|
||||||
|
if (!value || typeof value !== "object" || seen.has(value)) return;
|
||||||
|
seen.add(value);
|
||||||
|
if (typeof value.optionsFrom === "string") names.add(value.optionsFrom);
|
||||||
|
for (const child of Object.values(value)) walk(child);
|
||||||
|
};
|
||||||
|
walk(part);
|
||||||
|
return names.size ? `/admin/options?only=${[...names].sort().join(",")}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
export function slugify(value) {
|
export function slugify(value) {
|
||||||
return String(value ?? "")
|
return String(value ?? "")
|
||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
|
|
|
||||||
|
|
@ -10,12 +10,17 @@
|
||||||
costs nothing. It resets on page load, which is the right
|
costs nothing. It resets on page load, which is the right
|
||||||
lifetime for content that changes weekly. A failure isn't
|
lifetime for content that changes weekly. A failure isn't
|
||||||
cached, and surfaces as an error rather than empty data.
|
cached, and surfaces as an error rather than empty data.
|
||||||
|
|
||||||
|
The last body each path answered with is kept too (`peek`), so a
|
||||||
|
page opened again after the TTL shows it at once while the fresh
|
||||||
|
request runs, instead of a loading skeleton.
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
|
const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
|
||||||
const DEFAULT_TTL = 60_000;
|
const DEFAULT_TTL = 60_000;
|
||||||
|
|
||||||
const cache = new Map(); // path → { at, promise }
|
const cache = new Map(); // path → { at, promise }
|
||||||
|
const settled = new Map(); // path → the last body it answered with
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
status;
|
status;
|
||||||
|
|
@ -77,18 +82,34 @@ export function get(path, { ttl = DEFAULT_TTL }: { ttl?: number } = {}) {
|
||||||
|
|
||||||
if (hit && Date.now() - hit.at < ttl) return hit.promise;
|
if (hit && Date.now() - hit.at < ttl) return hit.promise;
|
||||||
|
|
||||||
const promise = request(path).catch((err) => {
|
const promise = request(path).then(
|
||||||
|
(body) => {
|
||||||
|
settled.set(path, body);
|
||||||
|
return body;
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
cache.delete(path); // a failure shouldn't be cached
|
cache.delete(path); // a failure shouldn't be cached
|
||||||
throw err;
|
throw err;
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
cache.set(path, { at: Date.now(), promise });
|
cache.set(path, { at: Date.now(), promise });
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The last body `path` answered with, however old, or undefined. */
|
||||||
|
export function peek(path) {
|
||||||
|
return settled.get(path);
|
||||||
|
}
|
||||||
|
|
||||||
export function invalidate(path) {
|
export function invalidate(path) {
|
||||||
if (path) cache.delete(path);
|
if (path) {
|
||||||
else cache.clear();
|
cache.delete(path);
|
||||||
|
settled.delete(path);
|
||||||
|
} else {
|
||||||
|
cache.clear();
|
||||||
|
settled.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Writes ──────────────────────────────────────────────────── */
|
/* ── Writes ──────────────────────────────────────────────────── */
|
||||||
|
|
|
||||||
|
|
@ -65,7 +65,7 @@ export function useSectionManifest(manifest) {
|
||||||
|
|
||||||
actions: Toggle || request ? (
|
actions: Toggle || request ? (
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
{request && <RequestLink type={request.type} label={request.label} />}
|
{request && <RequestLink type={request.type} label={request.label} accent={entry.accent} />}
|
||||||
{Toggle && (
|
{Toggle && (
|
||||||
<Toggle
|
<Toggle
|
||||||
view={view}
|
view={view}
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,10 @@
|
||||||
* · no `fallback`. Rendering plausible-looking content with no
|
* · no `fallback`. Rendering plausible-looking content with no
|
||||||
* sign the server is down is worse than a visible error.
|
* sign the server is down is worse than a visible error.
|
||||||
*
|
*
|
||||||
|
* · a path asked for before starts from its last answer (api.ts,
|
||||||
|
* peek) and isn't `loading` while it refreshes, so a page opened
|
||||||
|
* again after the TTL doesn't flash its skeleton.
|
||||||
|
*
|
||||||
* `notFound` is separated from `error` because they are different
|
* `notFound` is separated from `error` because they are different
|
||||||
* pages: a 404 is a slug that doesn't exist and retrying won't help,
|
* pages: a 404 is a slug that doesn't exist and retrying won't help,
|
||||||
* anything else is worth a Try again button.
|
* anything else is worth a Try again button.
|
||||||
|
|
@ -46,7 +50,7 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { get, invalidate, ApiError } from './api.ts'
|
import { get, invalidate, peek, ApiError } from './api.ts'
|
||||||
|
|
||||||
export type Resource<T> = {
|
export type Resource<T> = {
|
||||||
data: T | null
|
data: T | null
|
||||||
|
|
@ -57,8 +61,9 @@ export type Resource<T> = {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useRecord<T>(path: string | null, key: string): Resource<T> {
|
export function useRecord<T>(path: string | null, key: string): Resource<T> {
|
||||||
const [data, setData] = useState<T | null>(null)
|
const stale = path ? peek(path)?.[key] : undefined
|
||||||
const [loading, setLoading] = useState(true)
|
const [data, setData] = useState<T | null>(stale ?? null)
|
||||||
|
const [loading, setLoading] = useState(stale === undefined)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [notFound, setNotFound] = useState(false)
|
const [notFound, setNotFound] = useState(false)
|
||||||
const [attempt, setAttempt] = useState(0)
|
const [attempt, setAttempt] = useState(0)
|
||||||
|
|
@ -84,7 +89,12 @@ export function useRecord<T>(path: string | null, key: string): Resource<T> {
|
||||||
let live = true
|
let live = true
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
setLoading(true)
|
const last = peek(path as string)?.[key]
|
||||||
|
if (last === undefined) setLoading(true)
|
||||||
|
else {
|
||||||
|
setData(last as T)
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
setError(null)
|
setError(null)
|
||||||
setNotFound(false)
|
setNotFound(false)
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -9,18 +9,30 @@
|
||||||
request is shared and cached, so canceling it would throw away
|
request is shared and cached, so canceling it would throw away
|
||||||
work another component may still want. We just stop writing
|
work another component may still want. We just stop writing
|
||||||
state after unmount.
|
state after unmount.
|
||||||
|
|
||||||
|
A path asked for before starts from its last answer (api.ts,
|
||||||
|
peek) and isn't `loading` while it refreshes, so a page opened
|
||||||
|
again after the TTL doesn't flash its skeleton.
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { get } from "./api.ts";
|
import { get, peek } from "./api.ts";
|
||||||
|
|
||||||
export function useResource(path, { ttl }: { ttl?: number } = {}) {
|
export function useResource(path, { ttl }: { ttl?: number } = {}) {
|
||||||
const [state, setState] = useState<any>({ data: undefined, error: null, loading: true });
|
const [state, setState] = useState<any>(() => {
|
||||||
|
const stale = peek(path);
|
||||||
|
return { data: stale, error: null, loading: stale === undefined };
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let ignore = false;
|
let ignore = false;
|
||||||
|
|
||||||
setState((prev) => ({ ...prev, loading: true, error: null }));
|
const stale = peek(path);
|
||||||
|
setState((prev) =>
|
||||||
|
stale === undefined
|
||||||
|
? { ...prev, loading: true, error: null }
|
||||||
|
: { data: stale, error: null, loading: false },
|
||||||
|
);
|
||||||
|
|
||||||
get(path, { ttl })
|
get(path, { ttl })
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
|
|
|
||||||
|
|
@ -7,4 +7,4 @@
|
||||||
box or a build banner can read the same value later.
|
box or a build banner can read the same value later.
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
export const SITE_VERSION = "NGU-Web.v1.11.0-audit";
|
export const SITE_VERSION = "NGU-Web.v1.11.1-audit";
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,7 @@
|
||||||
in a row.
|
in a row.
|
||||||
═══════════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
|
import { useState, type ReactNode } from 'react'
|
||||||
import { Link, useParams } from 'react-router-dom'
|
import { Link, useParams } from 'react-router-dom'
|
||||||
|
|
||||||
import PageShell, { type ShellSection } from '../components/PageShell.tsx'
|
import PageShell, { type ShellSection } from '../components/PageShell.tsx'
|
||||||
|
|
@ -39,6 +40,9 @@ import { accentText, BRAND } from '../lib/color.ts'
|
||||||
|
|
||||||
const BODY = 'var(--color-muted)'
|
const BODY = 'var(--color-muted)'
|
||||||
|
|
||||||
|
/* Events and posts show this many, then "Show all". */
|
||||||
|
const SHOW_FIRST = 6
|
||||||
|
|
||||||
/* affiliations.role, for a row with no title of its own. */
|
/* affiliations.role, for a row with no title of its own. */
|
||||||
const ROLE_LABEL: Record<string, string> = {
|
const ROLE_LABEL: Record<string, string> = {
|
||||||
lead: 'Lead',
|
lead: 'Lead',
|
||||||
|
|
@ -127,13 +131,17 @@ export default function PersonDetail() {
|
||||||
accent,
|
accent,
|
||||||
content: (
|
content: (
|
||||||
<div className="max-w-6xl mx-auto px-6">
|
<div className="max-w-6xl mx-auto px-6">
|
||||||
|
<Capped items={person.events} accent={accent}>
|
||||||
|
{(events) => (
|
||||||
<ul className="space-y-5">
|
<ul className="space-y-5">
|
||||||
{person.events.map((event) => (
|
{events.map((event) => (
|
||||||
<li key={event.id}>
|
<li key={event.id}>
|
||||||
<EventRow event={event} accent={accent} />
|
<EventRow event={event} accent={accent} />
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
)}
|
||||||
|
</Capped>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|
@ -193,11 +201,15 @@ export default function PersonDetail() {
|
||||||
accent,
|
accent,
|
||||||
content: (
|
content: (
|
||||||
<div className="max-w-6xl mx-auto px-6">
|
<div className="max-w-6xl mx-auto px-6">
|
||||||
|
<Capped items={person.posts} accent={accent}>
|
||||||
|
{(posts) => (
|
||||||
<ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
<ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
{person.posts.map((post) => (
|
{posts.map((post) => (
|
||||||
<PostCard key={post.id} post={post} accent={accent} />
|
<PostCard key={post.id} post={post} accent={accent} />
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
)}
|
||||||
|
</Capped>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
})
|
})
|
||||||
|
|
@ -208,6 +220,35 @@ export default function PersonDetail() {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The first SHOW_FIRST of a list, then a button for the rest. */
|
||||||
|
function Capped<T>({
|
||||||
|
items,
|
||||||
|
accent,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
items: T[]
|
||||||
|
accent: string
|
||||||
|
children: (shown: T[]) => ReactNode
|
||||||
|
}) {
|
||||||
|
const [all, setAll] = useState(false)
|
||||||
|
const more = !all && items.length > SHOW_FIRST
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{children(more ? items.slice(0, SHOW_FIRST) : items)}
|
||||||
|
{more && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setAll(true)}
|
||||||
|
className="btn mt-6 px-5 py-2 text-sm"
|
||||||
|
style={{ border: `1px solid ${accent}`, color: accentText(accent) }}
|
||||||
|
>
|
||||||
|
Show all {items.length}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/* ── The strip of facts under the heading ────────────────────── */
|
/* ── The strip of facts under the heading ────────────────────── */
|
||||||
|
|
||||||
function Facts({ person, accent }: { person: PersonRecord; accent: string }) {
|
function Facts({ person, accent }: { person: PersonRecord; accent: string }) {
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,9 @@ const PROGRAM_START_YEAR = 2000
|
||||||
/* Each preset: the view it draws, its fixed props, its toggle (the
|
/* Each preset: the view it draws, its fixed props, its toggle (the
|
||||||
section's own view picks the first one) and its Request button.
|
section's own view picks the first one) and its Request button.
|
||||||
The keys are the CHECK list on page_sections.preset. */
|
The keys are the CHECK list on page_sections.preset. */
|
||||||
|
/* Event sections in these scopes offer no Request button. */
|
||||||
|
const NO_EVENT_REQUEST_SCOPES = ['national']
|
||||||
|
|
||||||
const PRESETS: Record<string, (section: SitePageSection) => Record<string, any>> = {
|
const PRESETS: Record<string, (section: SitePageSection) => Record<string, any>> = {
|
||||||
community_blog: () => ({
|
community_blog: () => ({
|
||||||
Component: CommunityBlog,
|
Component: CommunityBlog,
|
||||||
|
|
@ -69,7 +72,10 @@ const PRESETS: Record<string, (section: SitePageSection) => Record<string, any>>
|
||||||
}),
|
}),
|
||||||
events: (section) => ({
|
events: (section) => ({
|
||||||
Component: EventListCards,
|
Component: EventListCards,
|
||||||
request: { type: 'event', label: 'Add or update an event' },
|
// NGU's own national retreats aren't the public's to add.
|
||||||
|
request: NO_EVENT_REQUEST_SCOPES.includes(section.scope_id ?? '')
|
||||||
|
? undefined
|
||||||
|
: { type: 'event', label: 'Add or update an event' },
|
||||||
props: { scope: section.scope_id ?? undefined, type: section.event_type ?? undefined },
|
props: { scope: section.scope_id ?? undefined, type: section.event_type ?? undefined },
|
||||||
views: {
|
views: {
|
||||||
options: ['carousel', 'grid'],
|
options: ['carousel', 'grid'],
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,7 @@ import { get, post, patch, del, ApiError } from "../../lib/api.ts";
|
||||||
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
||||||
import { useAdminDetail } from "../../lib/adminTitle.tsx";
|
import { useAdminDetail } from "../../lib/adminTitle.tsx";
|
||||||
import { useWideAdminPage } from "../../lib/adminWidth.tsx";
|
import { useWideAdminPage } from "../../lib/adminWidth.tsx";
|
||||||
import { ADMIN_ENTITIES, slugify } from "../../lib/adminSchema.ts";
|
import { ADMIN_ENTITIES, optionsPath, slugify } from "../../lib/adminSchema.ts";
|
||||||
import { atLeast } from "../../lib/roles.ts";
|
import { atLeast } from "../../lib/roles.ts";
|
||||||
import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx";
|
import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx";
|
||||||
import {
|
import {
|
||||||
|
|
@ -164,7 +164,8 @@ export default function EntityEdit() {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setErrors({});
|
setErrors({});
|
||||||
try {
|
try {
|
||||||
const opts = await get("/admin/options", { ttl: 60_000 });
|
const path = optionsPath(manifest);
|
||||||
|
const opts = path ? await get(path, { ttl: 60_000 }) : { options: {} };
|
||||||
setOptions(opts.options);
|
setOptions(opts.options);
|
||||||
|
|
||||||
if (isNew) {
|
if (isNew) {
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ import { Link, Navigate, useNavigate, useParams, useSearchParams } from "react-r
|
||||||
|
|
||||||
import { get, upload, ApiError } from "../../lib/api.ts";
|
import { get, upload, ApiError } from "../../lib/api.ts";
|
||||||
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
||||||
import { ADMIN_ENTITIES } from "../../lib/adminSchema.ts";
|
import { ADMIN_ENTITIES, optionsPath } from "../../lib/adminSchema.ts";
|
||||||
import { atLeast } from "../../lib/roles.ts";
|
import { atLeast } from "../../lib/roles.ts";
|
||||||
|
|
||||||
export default function EntityList() {
|
export default function EntityList() {
|
||||||
|
|
@ -50,9 +50,10 @@ export default function EntityList() {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
|
const optsPath = optionsPath(manifest.list.filters);
|
||||||
const [list, opts] = await Promise.all([
|
const [list, opts] = await Promise.all([
|
||||||
get(`/admin/${manifest.key}?${params}`, { ttl: 0 }),
|
get(`/admin/${manifest.key}?${params}`, { ttl: 0 }),
|
||||||
get("/admin/options", { ttl: 60_000 }),
|
optsPath ? get(optsPath, { ttl: 60_000 }) : { options: {} },
|
||||||
]);
|
]);
|
||||||
setRows(list.rows);
|
setRows(list.rows);
|
||||||
setTotal(list.total);
|
setTotal(list.total);
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts";
|
||||||
import { seriesLabel } from "../../lib/eventSeries.ts";
|
import { seriesLabel } from "../../lib/eventSeries.ts";
|
||||||
import PlatformIcon from "../../components/PlatformIcon.tsx";
|
import PlatformIcon from "../../components/PlatformIcon.tsx";
|
||||||
import { mediaUrl } from "../../lib/media.ts";
|
import { mediaUrl } from "../../lib/media.ts";
|
||||||
|
import { useSmallImage } from "../../lib/useSmallImage.ts";
|
||||||
import Logo from "../../components/Logo.tsx";
|
import Logo from "../../components/Logo.tsx";
|
||||||
import { accentText, withAlpha, readableOn, BRAND } from '../../lib/color.ts'
|
import { accentText, withAlpha, readableOn, BRAND } from '../../lib/color.ts'
|
||||||
|
|
||||||
|
|
@ -45,16 +46,24 @@ const CARD_BG = "var(--color-surface)"; // sits under every card, photo or not
|
||||||
const CARD_IMAGE_VEIL =
|
const CARD_IMAGE_VEIL =
|
||||||
"linear-gradient(to bottom, color-mix(in srgb, var(--color-surface) 90%, transparent), color-mix(in srgb, var(--color-surface) 78%, transparent))";
|
"linear-gradient(to bottom, color-mix(in srgb, var(--color-surface) 90%, transparent), color-mix(in srgb, var(--color-surface) 78%, transparent))";
|
||||||
|
|
||||||
/* The card's background layers, top first: the veil and photo if it
|
/* The card's photo, behind its veil: an <img> rather than a CSS
|
||||||
has one, then the plain surface. */
|
background, so it loads lazily and takes the 640px copy first
|
||||||
function cardBackground(ev) {
|
(useSmallImage), falling back to the full file. */
|
||||||
const layers: string[] = [];
|
function CardImage({ src }) {
|
||||||
const image = mediaUrl(ev.card_image);
|
const img = useSmallImage(src);
|
||||||
if (image) {
|
if (img.failed) return null;
|
||||||
layers.push(CARD_IMAGE_VEIL, `url(${JSON.stringify(image)}) center / cover no-repeat`);
|
return (
|
||||||
}
|
<>
|
||||||
layers.push(CARD_BG);
|
<img
|
||||||
return layers.join(", ");
|
src={img.src}
|
||||||
|
onError={img.onError}
|
||||||
|
alt=""
|
||||||
|
loading="lazy"
|
||||||
|
className="absolute inset-0 -z-10 h-full w-full object-cover"
|
||||||
|
/>
|
||||||
|
<div aria-hidden="true" className="absolute inset-0 -z-10" style={{ background: CARD_IMAGE_VEIL }} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Grid view ────────────────────────────────────────────────
|
/* ── Grid view ────────────────────────────────────────────────
|
||||||
|
|
@ -71,8 +80,10 @@ const GRID_MAX = `calc(${MAX_COLS} * 38rem)`;
|
||||||
const GRID_TEMPLATE = `repeat(auto-fill, minmax(min(${CARD_MIN}, 100%), 1fr))`;
|
const GRID_TEMPLATE = `repeat(auto-fill, minmax(min(${CARD_MIN}, 100%), 1fr))`;
|
||||||
|
|
||||||
/* Collapsed past-events strip: how much shows, and the downward
|
/* Collapsed past-events strip: how much shows, and the downward
|
||||||
fade applied while it's collapsed. */
|
fade applied while it's collapsed. Collapsed, only a row's worth
|
||||||
|
of cards is drawn; open, PAST_PAGE at a time, newest first. */
|
||||||
const PAST_PEEK = "10rem";
|
const PAST_PEEK = "10rem";
|
||||||
|
const PAST_PAGE = 12;
|
||||||
const PAST_FADE = "linear-gradient(to bottom, black 0%, black 45%, transparent 100%)";
|
const PAST_FADE = "linear-gradient(to bottom, black 0%, black 45%, transparent 100%)";
|
||||||
|
|
||||||
/* ── Carousel sizing ──────────────────────────────────────────
|
/* ── Carousel sizing ──────────────────────────────────────────
|
||||||
|
|
@ -86,6 +97,14 @@ const SLIDE = `calc(${CARD} + ${GAP})`;
|
||||||
const HALF_SLIDE = `calc(${CARD} / 2)`;
|
const HALF_SLIDE = `calc(${CARD} / 2)`;
|
||||||
const FADE_DIST = "18rem";
|
const FADE_DIST = "18rem";
|
||||||
|
|
||||||
|
/* Slides this far either side of the current one are drawn; the
|
||||||
|
rest are empty slots of the same width (past FADE_DIST they're
|
||||||
|
invisible anyway). Two, so the card sliding in during a turn is
|
||||||
|
already there. */
|
||||||
|
const NEAR = 2;
|
||||||
|
/* Above this many events, a "7 / 200" count instead of a dot each. */
|
||||||
|
const MAX_DOTS = 12;
|
||||||
|
|
||||||
const EDGE_FADE = `linear-gradient(to right,
|
const EDGE_FADE = `linear-gradient(to right,
|
||||||
transparent calc(50% - (${HALF_SLIDE} + ${FADE_DIST})),
|
transparent calc(50% - (${HALF_SLIDE} + ${FADE_DIST})),
|
||||||
black calc(50% - ${HALF_SLIDE}),
|
black calc(50% - ${HALF_SLIDE}),
|
||||||
|
|
@ -177,12 +196,12 @@ export function Card({
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`text-ink overflow-hidden shadow-2xl h-full flex flex-col ${
|
className={`relative isolate text-ink overflow-hidden shadow-2xl h-full flex flex-col ${
|
||||||
compact ? "ev-card" : ""
|
compact ? "ev-card" : ""
|
||||||
}`}
|
}`}
|
||||||
style={{
|
style={{
|
||||||
border: `1px solid ${color}`,
|
border: `1px solid ${color}`,
|
||||||
background: cardBackground(ev),
|
background: CARD_BG,
|
||||||
filter: past ? "saturate(0.75)" : "none",
|
filter: past ? "saturate(0.75)" : "none",
|
||||||
pointerEvents: interactive ? "auto" : "none",
|
pointerEvents: interactive ? "auto" : "none",
|
||||||
}}
|
}}
|
||||||
|
|
@ -190,6 +209,7 @@ export function Card({
|
||||||
// past event) keeps its links out of the tab order too.
|
// past event) keeps its links out of the tab order too.
|
||||||
inert={!interactive}
|
inert={!interactive}
|
||||||
>
|
>
|
||||||
|
{ev.card_image && <CardImage src={mediaUrl(ev.card_image)} />}
|
||||||
<div className={`flex-1 flex flex-col ${compact ? "p-6 sm:p-8" : "p-6 sm:p-10"}`}>
|
<div className={`flex-1 flex flex-col ${compact ? "p-6 sm:p-8" : "p-6 sm:p-10"}`}>
|
||||||
{compact ? (
|
{compact ? (
|
||||||
/* ── GRID CARD: layout driven by .ev-grid container queries ── */
|
/* ── GRID CARD: layout driven by .ev-grid container queries ── */
|
||||||
|
|
@ -443,6 +463,7 @@ export default function EventListCards({
|
||||||
|
|
||||||
const [index, setIndex] = useState(0);
|
const [index, setIndex] = useState(0);
|
||||||
const [showPast, setShowPast] = useState(false);
|
const [showPast, setShowPast] = useState(false);
|
||||||
|
const [pastShown, setPastShown] = useState(PAST_PAGE);
|
||||||
const [activeType, setActiveType] = useState("all");
|
const [activeType, setActiveType] = useState("all");
|
||||||
|
|
||||||
/* What this band holds, which is what the chips offer, not the
|
/* What this band holds, which is what the chips offer, not the
|
||||||
|
|
@ -491,7 +512,10 @@ export default function EventListCards({
|
||||||
}, [events]);
|
}, [events]);
|
||||||
|
|
||||||
// Grid view splits the list; the carousel still shows everything.
|
// Grid view splits the list; the carousel still shows everything.
|
||||||
const { upcoming, past: pastEvents } = splitByStatus(events);
|
// The list comes oldest first; the past grid reads newest first.
|
||||||
|
const { upcoming, past } = splitByStatus(events);
|
||||||
|
const pastEvents = past.reverse();
|
||||||
|
const pastDrawn = pastEvents.slice(0, showPast ? pastShown : MAX_COLS);
|
||||||
|
|
||||||
const prev = () => setIndex(i => Math.max(0, i - 1));
|
const prev = () => setIndex(i => Math.max(0, i - 1));
|
||||||
const next = () => setIndex(i => Math.min(events.length - 1, i + 1));
|
const next = () => setIndex(i => Math.min(events.length - 1, i + 1));
|
||||||
|
|
@ -610,7 +634,7 @@ export default function EventListCards({
|
||||||
style={{ gridTemplateColumns: GRID_TEMPLATE }}
|
style={{ gridTemplateColumns: GRID_TEMPLATE }}
|
||||||
aria-hidden={!showPast}
|
aria-hidden={!showPast}
|
||||||
>
|
>
|
||||||
{pastEvents.map(ev => (
|
{pastDrawn.map(ev => (
|
||||||
<Card
|
<Card
|
||||||
key={ev.id}
|
key={ev.id}
|
||||||
ev={ev}
|
ev={ev}
|
||||||
|
|
@ -624,7 +648,16 @@ export default function EventListCards({
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-center mt-6">
|
<div className="flex flex-wrap justify-center gap-3 mt-6">
|
||||||
|
{showPast && pastShown < pastEvents.length && (
|
||||||
|
<button
|
||||||
|
onClick={() => setPastShown(n => n + PAST_PAGE)}
|
||||||
|
className="btn py-2.5 px-6 transition-all duration-200 hover:scale-105"
|
||||||
|
style={{ border: `1px solid ${accent}`, color: accentText(accent) }}
|
||||||
|
>
|
||||||
|
Show more ({pastEvents.length - pastShown})
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowPast(v => !v)}
|
onClick={() => setShowPast(v => !v)}
|
||||||
aria-expanded={showPast}
|
aria-expanded={showPast}
|
||||||
|
|
@ -654,6 +687,9 @@ export default function EventListCards({
|
||||||
>
|
>
|
||||||
{events.map((ev, i) => {
|
{events.map((ev, i) => {
|
||||||
const active = i === index;
|
const active = i === index;
|
||||||
|
if (Math.abs(i - index) > NEAR) {
|
||||||
|
return <div key={ev.id} className="shrink-0" style={{ width: SLIDE }} aria-hidden="true" />;
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={ev.id}
|
key={ev.id}
|
||||||
|
|
@ -716,7 +752,11 @@ export default function EventListCards({
|
||||||
>
|
>
|
||||||
<CaretLeft size={18} weight="bold" aria-hidden="true" />
|
<CaretLeft size={18} weight="bold" aria-hidden="true" />
|
||||||
</button>
|
</button>
|
||||||
{events.map((e, i) => (
|
{events.length > MAX_DOTS ? (
|
||||||
|
<p className="min-w-20 px-3 text-center text-sm font-bold" style={{ color: accentText(accent) }} aria-live="polite">
|
||||||
|
{index + 1} / {events.length}
|
||||||
|
</p>
|
||||||
|
) : events.map((e, i) => (
|
||||||
<button
|
<button
|
||||||
key={e.id}
|
key={e.id}
|
||||||
onClick={() => setIndex(i)}
|
onClick={() => setIndex(i)}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { CaretRight, X } from '@phosphor-icons/react';
|
import { CaretRight, MagnifyingGlass, X } from '@phosphor-icons/react';
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useCommunity } from "../../lib/useCommunity.ts";
|
import { useCommunity } from "../../lib/useCommunity.ts";
|
||||||
import { useOrganization } from "../../lib/useContent.ts";
|
import { useOrganization } from "../../lib/useContent.ts";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
|
|
@ -53,6 +53,9 @@ const FALLBACK_COLOR = "#3b5456";
|
||||||
black, so an uncolored region takes the same fallback as a card. */
|
black, so an uncolored region takes the same fallback as a card. */
|
||||||
const colorOf = (item) => item.color || FALLBACK_COLOR;
|
const colorOf = (item) => item.color || FALLBACK_COLOR;
|
||||||
|
|
||||||
|
/* A region's grid shows this many cards until "Show all". */
|
||||||
|
const GRID_CAP = 12;
|
||||||
|
|
||||||
const US_TITLE = "US Unity Regions";
|
const US_TITLE = "US Unity Regions";
|
||||||
const INTL_TITLE = "International Unity Regions";
|
const INTL_TITLE = "International Unity Regions";
|
||||||
|
|
||||||
|
|
@ -461,6 +464,29 @@ function RegionBlock({
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Narrows the list or grid to groups whose name or place has the text. */
|
||||||
|
function GroupSearch({ query, setQuery }) {
|
||||||
|
return (
|
||||||
|
<label className="mb-4 flex items-center gap-2 border border-muted/25 bg-surface px-3 py-2 focus-within:border-brand">
|
||||||
|
<MagnifyingGlass size={16} weight="bold" className="shrink-0 text-muted" aria-hidden="true" />
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={query}
|
||||||
|
onChange={e => setQuery(e.target.value)}
|
||||||
|
placeholder="Search groups by name or place"
|
||||||
|
aria-label="Search groups"
|
||||||
|
className="min-w-0 flex-1 bg-transparent text-sm text-body outline-none"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const matcher = query => {
|
||||||
|
const q = query.trim().toLowerCase();
|
||||||
|
if (!q) return null;
|
||||||
|
return c => `${c.name ?? ""} ${c.location_label ?? ""}`.toLowerCase().includes(q);
|
||||||
|
};
|
||||||
|
|
||||||
/* ═══════════════════════════════════════════════════════════════
|
/* ═══════════════════════════════════════════════════════════════
|
||||||
GRID VIEW
|
GRID VIEW
|
||||||
One grid per region. Clicking a card's arrow opens a detail
|
One grid per region. Clicking a card's arrow opens a detail
|
||||||
|
|
@ -620,17 +646,25 @@ function GroupDetail({ group, region, onClose }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function GroupGrid({ regions, groups, groupsIn, subtextFor, openId, setOpenId }) {
|
function GroupGrid({ regions, groups, groupsIn, subtextFor, openId, setOpenId }) {
|
||||||
// Only regions that actually have groups get a grid.
|
const [query, setQuery] = useState("");
|
||||||
|
const [expanded, setExpanded] = useState(() => new Set());
|
||||||
|
const match = matcher(query);
|
||||||
|
|
||||||
|
// Only regions that actually have groups (or matches) get a grid.
|
||||||
const populated = regions
|
const populated = regions
|
||||||
.map(region => ({ region, list: groupsIn(region.id) }))
|
.map(region => ({ region, list: match ? groupsIn(region.id).filter(match) : groupsIn(region.id) }))
|
||||||
.filter(({ list }) => list.length > 0);
|
.filter(({ list }) => list.length > 0);
|
||||||
const empty = regions.filter(region => groupsIn(region.id).length === 0);
|
const empty = match ? [] : regions.filter(region => groupsIn(region.id).length === 0);
|
||||||
const openGroup = groups.find(c => c.id === openId) || null;
|
const openGroup = groups.find(c => c.id === openId) || null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto px-8 md:px-12" style={{ maxWidth: CONTENT_MAX }}>
|
<div className="mx-auto px-8 md:px-12" style={{ maxWidth: CONTENT_MAX }}>
|
||||||
|
<GroupSearch query={query} setQuery={setQuery} />
|
||||||
|
{match && populated.length === 0 && <p className="notice text-sm">No groups match that.</p>}
|
||||||
{populated.map(({ region, list }) => {
|
{populated.map(({ region, list }) => {
|
||||||
const subtext = subtextFor(region);
|
const subtext = subtextFor(region);
|
||||||
|
const all = expanded.has(region.id);
|
||||||
|
const shown = all ? list : list.slice(0, GRID_CAP);
|
||||||
return (
|
return (
|
||||||
<section key={region.id} className="mb-12">
|
<section key={region.id} className="mb-12">
|
||||||
<div className="flex items-baseline gap-3 mb-1">
|
<div className="flex items-baseline gap-3 mb-1">
|
||||||
|
|
@ -667,7 +701,7 @@ function GroupGrid({ regions, groups, groupsIn, subtextFor, openId, setOpenId })
|
||||||
gridTemplateColumns: "repeat(auto-fill, minmax(min(22rem, 100%), 1fr))",
|
gridTemplateColumns: "repeat(auto-fill, minmax(min(22rem, 100%), 1fr))",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{list.map(c => (
|
{shown.map(c => (
|
||||||
<GroupCard
|
<GroupCard
|
||||||
key={c.id}
|
key={c.id}
|
||||||
group={c}
|
group={c}
|
||||||
|
|
@ -677,6 +711,16 @@ function GroupGrid({ regions, groups, groupsIn, subtextFor, openId, setOpenId })
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
{!all && list.length > GRID_CAP && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setExpanded(prev => new Set(prev).add(region.id))}
|
||||||
|
className="btn mt-4 py-2 px-5 text-sm"
|
||||||
|
style={{ border: `1px solid ${colorOf(region)}`, color: accentText(colorOf(region)) }}
|
||||||
|
>
|
||||||
|
Show all {list.length}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
@ -743,6 +787,7 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) {
|
||||||
const [selected, setSelected] = useState<any>(null);
|
const [selected, setSelected] = useState<any>(null);
|
||||||
const [hovered, setHovered] = useState<any>(null);
|
const [hovered, setHovered] = useState<any>(null);
|
||||||
const [openId, setOpenId] = useState<any>(null); // no card open on arrival
|
const [openId, setOpenId] = useState<any>(null); // no card open on arrival
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
|
||||||
// The list scrolls itself to whatever the map or legend points at.
|
// The list scrolls itself to whatever the map or legend points at.
|
||||||
const listRef = useRef<any>(null);
|
const listRef = useRef<any>(null);
|
||||||
|
|
@ -765,9 +810,8 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) {
|
||||||
const scrollListTo = el => {
|
const scrollListTo = el => {
|
||||||
const box = listRef.current;
|
const box = listRef.current;
|
||||||
if (!box || !el) return;
|
if (!box || !el) return;
|
||||||
// Only when the list is its own scroll area (lg and up). Below
|
// Only when the list is long enough to scroll in its own box;
|
||||||
// that it's stacked under the map and scrolling it would fight
|
// a short one has nowhere to go.
|
||||||
// the page.
|
|
||||||
if (box.scrollHeight <= box.clientHeight) return;
|
if (box.scrollHeight <= box.clientHeight) return;
|
||||||
box.scrollTo({ top: el.offsetTop - 8, behavior: scrollBehavior() });
|
box.scrollTo({ top: el.offsetTop - 8, behavior: scrollBehavior() });
|
||||||
};
|
};
|
||||||
|
|
@ -792,6 +836,68 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) {
|
||||||
if (region) scrollListTo(regionRefs.current[region.id]);
|
if (region) scrollListTo(regionRefs.current[region.id]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* The list column, built only when what it shows changes: hovering
|
||||||
|
a map tile or legend entry changes `hovered`, which no row reads,
|
||||||
|
so hundreds of groups aren't drawn again for every tile crossed.
|
||||||
|
hoverInList only touches a ref and a state setter, both stable. */
|
||||||
|
const list = useMemo(() => {
|
||||||
|
const match = matcher(query);
|
||||||
|
const block = (region, indent) => {
|
||||||
|
const inRegion = match ? groupsIn(region.id).filter(match) : groupsIn(region.id);
|
||||||
|
if (match && inRegion.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<RegionBlock
|
||||||
|
key={region.id}
|
||||||
|
region={region}
|
||||||
|
groups={inRegion}
|
||||||
|
subtext={subtextFor(region)}
|
||||||
|
indent={indent}
|
||||||
|
regionRefs={regionRefs}
|
||||||
|
groupRefs={groupRefs}
|
||||||
|
selected={selected}
|
||||||
|
setSelected={setSelected}
|
||||||
|
setHovered={hoverInList}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const us = domestic.map(r => block(r, true)).filter(Boolean);
|
||||||
|
const intl = international.map(r => block(r, true)).filter(Boolean);
|
||||||
|
const online = virtual.map(r => block(r, false)).filter(Boolean);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{match && us.length + intl.length + online.length === 0 && (
|
||||||
|
<p className="notice text-sm">No groups match that.</p>
|
||||||
|
)}
|
||||||
|
{us.length > 0 && (
|
||||||
|
<>
|
||||||
|
<h3 className="text-xl font-bold mb-1" style={{ color: FALLBACK_COLOR }}>
|
||||||
|
{US_TITLE}
|
||||||
|
</h3>
|
||||||
|
{us}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{intl.length > 0 && (
|
||||||
|
<>
|
||||||
|
<h3
|
||||||
|
className="text-xl font-display font-bold mt-6 mb-1 pt-4"
|
||||||
|
style={{ color: FALLBACK_COLOR, borderTop: `1px solid ${RULE}` }}
|
||||||
|
>
|
||||||
|
{INTL_TITLE}
|
||||||
|
</h3>
|
||||||
|
{intl}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{online.length > 0 && (
|
||||||
|
<div className="mt-6 pt-4" style={{ borderTop: `1px solid ${RULE}` }}>
|
||||||
|
{online}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}, [domestic, international, virtual, groupsIn, subtextFor, selected, query]);
|
||||||
|
|
||||||
const shell = children => (
|
const shell = children => (
|
||||||
<div className="mx-auto px-8 md:px-12" style={{ maxWidth: CONTENT_MAX }}>
|
<div className="mx-auto px-8 md:px-12" style={{ maxWidth: CONTENT_MAX }}>
|
||||||
{children}
|
{children}
|
||||||
|
|
@ -828,20 +934,6 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) {
|
||||||
const shared = { selected, setSelected, hovered, setHovered: hoverOnMap };
|
const shared = { selected, setSelected, hovered, setHovered: hoverOnMap };
|
||||||
const onMapIds = new Set(regionAreas.map(a => a.region_id));
|
const onMapIds = new Set(regionAreas.map(a => a.region_id));
|
||||||
|
|
||||||
const block = (region, indent) => (
|
|
||||||
<RegionBlock
|
|
||||||
key={region.id}
|
|
||||||
region={region}
|
|
||||||
groups={groupsIn(region.id)}
|
|
||||||
subtext={subtextFor(region)}
|
|
||||||
indent={indent}
|
|
||||||
regionRefs={regionRefs}
|
|
||||||
groupRefs={groupRefs}
|
|
||||||
{...shared}
|
|
||||||
setHovered={hoverInList}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
/* Wider than the section heading above it, the map needs the
|
/* Wider than the section heading above it, the map needs the
|
||||||
room. CONTENT_MAX is the knob; drop it toward 72rem to pull
|
room. CONTENT_MAX is the knob; drop it toward 72rem to pull
|
||||||
|
|
@ -877,26 +969,16 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) {
|
||||||
|
|
||||||
{/* List, h-0 + min-h-full makes this column take its height
|
{/* List, h-0 + min-h-full makes this column take its height
|
||||||
from the map column rather than the other way round, so a
|
from the map column rather than the other way round, so a
|
||||||
long list scrolls instead of stretching the section. */}
|
long list scrolls instead of stretching the section. Below
|
||||||
|
lg, stacked under the map, it's capped at about a screenful
|
||||||
|
instead, so hundreds of groups don't run down the page. */}
|
||||||
|
<div className="flex min-h-0 flex-col lg:h-0 lg:min-h-full">
|
||||||
|
<GroupSearch query={query} setQuery={setQuery} />
|
||||||
<div
|
<div
|
||||||
ref={listRef}
|
ref={listRef}
|
||||||
className="relative lg:h-0 lg:min-h-full overflow-y-auto pr-2"
|
className="relative max-h-[36rem] min-h-0 flex-1 overflow-y-auto pr-2 lg:max-h-none"
|
||||||
>
|
>
|
||||||
<h3 className="text-xl font-bold mb-1" style={{ color: FALLBACK_COLOR }}>
|
{list}
|
||||||
{US_TITLE}
|
|
||||||
</h3>
|
|
||||||
{domestic.map(r => block(r, true))}
|
|
||||||
|
|
||||||
<h3
|
|
||||||
className="text-xl font-display font-bold mt-6 mb-1 pt-4"
|
|
||||||
style={{ color: FALLBACK_COLOR, borderTop: `1px solid ${RULE}` }}
|
|
||||||
>
|
|
||||||
{INTL_TITLE}
|
|
||||||
</h3>
|
|
||||||
{international.map(r => block(r, true))}
|
|
||||||
|
|
||||||
<div className="mt-6 pt-4" style={{ borderTop: `1px solid ${RULE}` }}>
|
|
||||||
{virtual.map(r => block(r, false))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ import { useNavSections } from '../../lib/navSections.ts'
|
||||||
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
|
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
|
||||||
import { siteUrl } from '../../lib/site.ts'
|
import { siteUrl } from '../../lib/site.ts'
|
||||||
import { useDirectory, type Directory } from '../../lib/useContent.ts'
|
import { useDirectory, type Directory } from '../../lib/useContent.ts'
|
||||||
|
import { FILTER_FROM, OptionFilter, narrow } from '../../components/OptionFilter.tsx'
|
||||||
import { accentText, BRAND } from '../../lib/color.ts'
|
import { accentText, BRAND } from '../../lib/color.ts'
|
||||||
|
|
||||||
const MUTED = 'var(--color-muted)'
|
const MUTED = 'var(--color-muted)'
|
||||||
|
|
@ -269,6 +270,16 @@ export default function QrCodeMaker() {
|
||||||
|
|
||||||
const groups = useMemo(() => groupsFor(kind, directory), [kind, directory])
|
const groups = useMemo(() => groupsFor(kind, directory), [kind, directory])
|
||||||
const choices = useMemo(() => groups.flatMap((group) => group.choices), [groups])
|
const choices = useMemo(() => groups.flatMap((group) => group.choices), [groups])
|
||||||
|
// Past FILTER_FROM records, a box above the select narrows them;
|
||||||
|
// the one chosen always stays.
|
||||||
|
const [needle, setNeedle] = useState('')
|
||||||
|
const shownGroups = useMemo(
|
||||||
|
() =>
|
||||||
|
groups
|
||||||
|
.map((group) => ({ ...group, choices: narrow(group.choices, needle, (c) => c.label, (c) => c.path === path) }))
|
||||||
|
.filter((group) => group.choices.length > 0),
|
||||||
|
[groups, needle, path],
|
||||||
|
)
|
||||||
|
|
||||||
// A new kind, or the directory arriving, can leave the current
|
// A new kind, or the directory arriving, can leave the current
|
||||||
// path outside the list; fall back to its first entry.
|
// path outside the list; fall back to its first entry.
|
||||||
|
|
@ -308,7 +319,10 @@ export default function QrCodeMaker() {
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-10 lg:grid-cols-2 lg:items-start">
|
<div className="grid gap-10 lg:grid-cols-2 lg:items-start">
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<Select id="qr-kind" label="What to link to" value={kind} onChange={(v) => setKind(v as Kind)}>
|
<Select id="qr-kind" label="What to link to" value={kind} onChange={(v) => {
|
||||||
|
setKind(v as Kind)
|
||||||
|
setNeedle('')
|
||||||
|
}}>
|
||||||
{KINDS.map(([value, label]) => (
|
{KINDS.map(([value, label]) => (
|
||||||
<option key={value} value={value}>
|
<option key={value} value={value}>
|
||||||
{label}
|
{label}
|
||||||
|
|
@ -343,6 +357,7 @@ export default function QrCodeMaker() {
|
||||||
) : choices.length === 0 ? (
|
) : choices.length === 0 ? (
|
||||||
<p style={{ color: MUTED }}>Nothing published here yet.</p>
|
<p style={{ color: MUTED }}>Nothing published here yet.</p>
|
||||||
) : (
|
) : (
|
||||||
|
<div>
|
||||||
<Select
|
<Select
|
||||||
id="qr-target"
|
id="qr-target"
|
||||||
label={kind === 'pages' ? 'Page' : 'Which one'}
|
label={kind === 'pages' ? 'Page' : 'Which one'}
|
||||||
|
|
@ -352,7 +367,7 @@ export default function QrCodeMaker() {
|
||||||
setSection('')
|
setSection('')
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{groups.map((group, i) =>
|
{shownGroups.map((group, i) =>
|
||||||
group.label ? (
|
group.label ? (
|
||||||
<optgroup key={group.label} label={group.label}>
|
<optgroup key={group.label} label={group.label}>
|
||||||
{group.choices.map((c) => (
|
{group.choices.map((c) => (
|
||||||
|
|
@ -370,6 +385,10 @@ export default function QrCodeMaker() {
|
||||||
),
|
),
|
||||||
)}
|
)}
|
||||||
</Select>
|
</Select>
|
||||||
|
{choices.length > FILTER_FROM && (
|
||||||
|
<OptionFilter value={needle} onChange={setNeedle} label="Narrow the list" className="mt-2" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{sections.length > 0 && (
|
{sections.length > 0 && (
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue