Clean up code found in the audit

- Replace every em-dash in src and server/src with a colon, comma or hyphen
- Give every relative import its file extension (.jsx imports of .tsx fixed)
- Delete old-historyMock.ts, unused exports, unused CSS utilities, the
  unused @ alias and the fallback option nothing passed
- One copy each of initials, capitalize, byName and the server's marks()
- Move the organization, chapter and event hooks from src/data to src/lib
- Schema sync always throws on a mismatch (strict was never turned off)
- Replace the placeholder README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-28 22:02:03 -05:00
parent 4066e9ec61
commit 5274e09571
75 changed files with 282 additions and 688 deletions

View file

@ -2,21 +2,14 @@
API CLIENT
One place that knows how to talk to the server, so components
never call fetch directly and swapping the transport later is a
single-file change.
Two things worth knowing about the design:
never call fetch directly.
The cache is a module-level Map of in-flight and settled
promises. Two components asking for /events during the same
render pass share one request, and a remount inside the TTL
costs nothing. It resets on page load, which is the right
lifetime for content that changes weekly.
Every reader can pass a `fallback`. If the request fails, that
value is used instead. This is what keeps the Figma preview
working: pass the old static module as the fallback and the
preview renders real content with no server in sight.
lifetime for content that changes weekly. A failure isn't
cached, and surfaces as an error rather than empty data.
═══════════════════════════════════════════════════════════════ */
const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
@ -68,20 +61,15 @@ async function request(path, options: RequestInit = {}) {
/* ── Reads ─────────────────────────────────────────────────────
get("/events") → cached for 60s
get("/events", { ttl: 0 }) → always fresh
get("/events", { fallback }) → fallback on any failure
───────────────────────────────────────────────────────────── */
export function get(path, { ttl = DEFAULT_TTL, fallback }: { ttl?: number; fallback?: any } = {}) {
export function get(path, { ttl = DEFAULT_TTL }: { ttl?: number } = {}) {
const hit = cache.get(path);
if (hit && Date.now() - hit.at < ttl) return hit.promise;
const promise = request(path).catch((err) => {
cache.delete(path); // a failure shouldn't be cached
if (fallback !== undefined) {
console.warn(`api: ${path} failed, using fallback`, err);
return fallback;
}
throw err;
});

View file

@ -9,7 +9,7 @@
RequireAuth guards routes. Worth being clear about what that
does and doesn't do: it hides the interface, not the data. The
protection is the 401 from /api/admin — this only stops someone
protection is the 401 from /api/admin, this only stops someone
staring at an empty table.
═══════════════════════════════════════════════════════════════ */
@ -71,7 +71,7 @@ export function useAuth() {
return value;
}
/* Signals a session that ended while the page was open — the
/* Signals a session that ended while the page was open, the
admin pages call this when a request comes back 401. */
export function isUnauthorized(error) {
return error instanceof ApiError && error.status === 401;

142
src/lib/chapters.ts Normal file
View file

@ -0,0 +1,142 @@
/* ═══════════════════════════════════════════════════════════════
LOCAL CHAPTER DATA
The chapter map's view of the organization list. Regions and
chapters are the same table and the same endpoint; this hook
reshapes them into what a map needs, slices per tile, counts
per tile, chapters grouped by region.
Its return shape is unchanged from the version that called
/regions and /chapters, so LocalChapters didn't have to move.
Two things live elsewhere:
the tile grid src/data/mapGrid.ts. Where a state sits never
changes, so it isn't worth a round trip.
the fetch src/lib/organizations.ts. One endpoint for
every kind, so a section listing regions and
a section listing partners read alike.
═══════════════════════════════════════════════════════════════ */
import { useMemo } from "react";
import {
areasSentence,
byName,
useOrganizations,
} from "./organizations.ts";
import {
areaForChapter,
buildAreaSlices,
countChaptersByArea,
} from "../data/mapGrid.ts";
export function useCommunity() {
const regionsQuery = useOrganizations("region");
const chaptersQuery = useOrganizations("chapter");
const rawRegions = regionsQuery.organizations;
const rawChapters = chaptersQuery.organizations;
return useMemo(() => {
/* ── Regions ───────────────────────────────────────────────
scope and map_note are lifted out of `details` so the rest
of the app doesn't have to know they're kind-specific. */
const regions = rawRegions.map((org) => ({
...org,
scope: org.details?.scope ?? null,
map_note: org.details?.map_note ?? null,
areas: org.details?.areas ?? [],
}));
// Flat, because buildAreaSlices takes it that way.
const regionAreas = regions.flatMap((region) =>
region.areas.map((area) => ({ ...area, region_id: region.id })),
);
/* ── Chapters, each tagged with the tile it lights up ──────
The database stores a real address; which square that maps
to is a rendering question, answered here once rather than
at every call site. */
const chapters = rawChapters.map((org) => ({
...org,
region_id: org.details?.region_id ?? null,
region_name: org.details?.region_name ?? null,
region_color: org.details?.region_color ?? null,
meets: org.details?.meets ?? null,
started: org.details?.started ?? null,
area_code: areaForChapter(org),
}));
const regionById = Object.fromEntries(regions.map((r) => [r.id, r]));
/* { WA: [{ regionId, name, color, share, edge, note }], ... }
California comes back as two half slices rather than a
primary and a remainder, so the SVG never does arithmetic. */
const slices = buildAreaSlices(regionAreas, regions);
const chapterCounts = countChaptersByArea(chapters);
const chaptersByRegion = new Map();
for (const chapter of chapters) {
if (!chapter.region_id) continue;
const list = chaptersByRegion.get(chapter.region_id);
if (list) list.push(chapter);
else chaptersByRegion.set(chapter.region_id, [chapter]);
}
const chaptersIn = (regionId) => chaptersByRegion.get(regionId) ?? [];
/* Sorted by name to match how the page has always shown them,
rather than by the sort_order the API returns. */
const domestic = regions.filter((r) => r.scope === "domestic").sort(byName);
const international = regions
.filter((r) => r.scope === "international")
.sort(byName);
const virtual = regions.filter((r) => r.scope === "virtual");
const areasLabelFor = (regionId) =>
areasSentence(regionById[regionId]?.areas ?? []);
const subtextFor = (region) => {
const label = areasLabelFor(region.id);
if (label && region.map_note) return `${label} · ${region.map_note}`;
return label || region.map_note || "";
};
const regionsForArea = (areaCode) =>
(slices[areaCode] ?? [])
.map((slice) => regionById[slice.regionId])
.filter(Boolean);
return {
loading: regionsQuery.loading || chaptersQuery.loading,
error: regionsQuery.error ?? chaptersQuery.error,
regions,
regionAreas,
regionById,
domestic,
international,
virtual,
chapters,
chaptersIn,
slices,
chapterCounts,
regionsForArea,
areasLabelFor,
subtextFor,
};
}, [
rawRegions,
rawChapters,
regionsQuery.loading,
regionsQuery.error,
chaptersQuery.loading,
chaptersQuery.error,
]);
}

92
src/lib/eventData.ts Normal file
View file

@ -0,0 +1,92 @@
/* ═══════════════════════════════════════════════════════════════
EVENT DATA
One request, filtered per band. The Retreats page has three
bands of events, and all three call this hook, the cache in
api.ts keys on the path, so they share a single fetch and each
narrows the result to what it shows.
useEvents({ scope: "national" }) one band
useEvents({ host: "northwest" }) one host's events
useEvents({ status: "upcoming" }) a home page strip
useEvents({ type: "workshop" }) one kind, wherever it is
useEvents({ type: ["class", "workshop"] })
useEvents() everything
`scope` and `type` are different questions and stack rather
than overlap: the scope is whose gathering an event is, the type
is what kind of gathering it is. A regional class matches both
{ scope: "regional" } and { type: "class" }.
The event_scopes rows come back alongside, for anything that
offers a scope filter.
No fallback. An empty list on a failed request would read as
"nothing scheduled" when the truth is "the server is down", so
the error comes back and each caller says so.
Filtering here rather than in the query keeps the endpoint to
one cached response. At a few dozen events that's the right
trade; if the list ever runs to hundreds, move the filters into
the URL and let each become its own cache entry.
═══════════════════════════════════════════════════════════════ */
import { useMemo } from "react";
import { useResource } from "./useResource.ts";
/* One shared empty list, so a memo keyed on `scopes` doesn't
restart on every render before the data arrives. */
const NO_SCOPES: any[] = [];
export function useEvents({ scope, host, status, type }: any = {}) {
const { data, error, loading } = useResource("/events");
const all = data?.events;
const scopes = data?.scopes ?? NO_SCOPES;
/* An array prop is a new identity on every render, which would
restart the memo each time. Joining it gives the dependency
list something stable to compare. */
const typeKey = Array.isArray(type) ? type.join(",") : (type ?? "");
const events = useMemo(() => {
let list = all ?? [];
if (scope) list = list.filter(e => e.scope_id === scope);
// `host` is an organization or a person slug, and an event can
// have several of either, co-hosting puts one event on both
// hosts' lists, which is the point.
if (host) list = list.filter(e => e.hosts?.some(h => h.id === host));
if (status) list = list.filter(e => e.status === status);
if (typeKey) {
const wanted = new Set(typeKey.split(","));
list = list.filter(e => wanted.has(e.event_type));
}
return list;
}, [all, scope, host, status, typeKey]);
return { events, scopes, loading, error };
}
/* Past and upcoming, split. `status` arrives already resolved, the
explicit value when there is one, otherwise derived from ends_on,
so nothing here needs to know which of the two it got. */
export function splitByStatus(events: any[] = []) {
const upcoming: any[] = [];
const past: any[] = [];
for (const event of events) {
(event.status === "past" ? past : upcoming).push(event);
}
return { upcoming, past };
}
/* Which of the declared types a list actually contains, in
EVENT_TYPES order rather than whatever order the rows arrived
in. A section with one type has nothing to filter, which is what
lets the chip bar hide itself. */
export function typesPresent(events: any[] = [], declared: any[] = []) {
const seen = new Set(events.map(e => e.event_type));
return declared.filter(entry => seen.has(entry.id));
}

View file

@ -14,7 +14,7 @@
Dates are 'YYYY-MM-DD' and are handled as UTC midnights so that
stepping a day never lands on a DST gap. They are calendar dates,
not instants — nothing here converts timezones.
not instants, nothing here converts timezones.
═══════════════════════════════════════════════════════════════ */
export type SeriesFrequency = 'weekly' | 'monthly_date' | 'monthly_weekday'
@ -76,7 +76,7 @@ const daysInMonth = (year: number, month: number) =>
new Date(Date.UTC(year, month + 1, 0)).getUTCDate()
/* 1st–4th, or 5 for a date in the month's fifth week, which the
schedule treats as "last" — every month has a last Tuesday, not
schedule treats as "last", every month has a last Tuesday, not
every month has a fifth. */
const weekOfMonth = (date: Date) => Math.ceil(date.getUTCDate() / 7)

View file

@ -19,6 +19,8 @@
means the site offers a filter the database will refuse to store.
═══════════════════════════════════════════════════════════════ */
import { capitalize } from './text.ts'
export type EventType = 'retreat' | 'class' | 'workshop' | 'meeting' | 'other'
export const EVENT_TYPES: { id: EventType; label: string; plural: string }[] = [
@ -29,14 +31,10 @@ export const EVENT_TYPES: { id: EventType; label: string; plural: string }[] = [
{ id: 'other', label: 'Other', plural: 'Other' },
]
export const EVENT_TYPE_IDS: EventType[] = EVENT_TYPES.map((entry) => entry.id)
const BY_ID = new Map<string, { label: string; plural: string }>(
EVENT_TYPES.map((entry) => [entry.id as string, entry]),
)
const capitalize = (word: string) =>
word ? word.charAt(0).toUpperCase() + word.slice(1) : ''
/* A value the CHECK has gained since this file was written renders
as itself rather than vanishing, the same rule EventDetail's
@ -44,5 +42,3 @@ const capitalize = (word: string) =>
export const eventTypeLabel = (id?: string | null): string =>
(id ? BY_ID.get(id)?.label : null) ?? capitalize(id ?? '')
export const eventTypePlural = (id?: string | null): string =>
(id ? BY_ID.get(id)?.plural : null) ?? capitalize(id ?? '')

View file

@ -2,7 +2,7 @@
PUBLIC HREFS
One place that turns a record into a URL. The API deliberately
never sends paths — it sends `{ kind, id }` and, for an
never sends paths, it sends `{ kind, id }` and, for an
organization, the `org_kind` that decides which of the three
routes a slug belongs to. Deciding that in each component is how
/regions/x and /chapters/x end up both existing for the same
@ -20,7 +20,7 @@
Every builder takes an id the caller believed it had. When it
doesn't, the old behaviour was to interpolate the string
"undefined" into a path, render a link to it, mount a page and
fetch /api/organizations/undefined — four steps between the
fetch /api/organizations/undefined, four steps between the
mistake and any sign of it, none of which name the component
that made it.
@ -35,7 +35,7 @@ export type RefKind = 'event' | 'organization' | 'team' | 'award' | 'person'
/* A region, a chapter and a partner read as different things to a
visitor even though they are one table, so they get one route
each. 'national' is NGU itself — one record, no listing to sit
each. 'national' is NGU itself, one record, no listing to sit
under, so it falls through to the generic path. */
const ORG_BASE: Record<string, string> = {
region: '/regions',
@ -49,7 +49,7 @@ const ORG_BASE: Record<string, string> = {
* /events/:id, not /retreats/:id. The listing page is called
* Retreats because that's what NGU calls the gatherings it hosts,
* but the records are `events`, the API route is /api/events, and
* plenty of them — partner events, conferences — aren't retreats
* plenty of them, partner events, conferences, aren't retreats
* at all. Naming the record route after one page's editorial
* framing would have been wrong the first time a non-retreat got
* its own page.
@ -73,7 +73,7 @@ function checkId(id: unknown, what: string): string {
if (DEV) {
// console.error rather than warn: this is always a bug, and the
// stack is the whole point — it names the component that passed
// stack is the whole point, it names the component that passed
// nothing.
console.error(
`hrefs: ${what}() was given ${JSON.stringify(id)}. ` +
@ -93,7 +93,7 @@ function checkId(id: unknown, what: string): string {
* have to agree about what counts as an id.
*
* It lives here rather than next to the hook that calls it because
* it is a path, and paths are this file's job — and because a
* it is a path, and paths are this file's job, and because a
* component that interpolates a missing route param produces the
* literal string "undefined", which the server cannot tell apart
* from a slug somebody genuinely typed. It answers 404 either way,
@ -122,8 +122,8 @@ export function orgHref(id?: string | null, kind?: string | null): string {
return `${ORG_BASE[kind ?? ''] ?? '/organizations'}/${checkId(id, 'orgHref')}`
}
/* For anything holding a polymorphic reference — timeline entries,
content blocks — where the kind arrives as data rather than being
/* For anything holding a polymorphic reference, timeline entries,
content blocks, where the kind arrives as data rather than being
known at the call site.
Returns null for a kind with no page AND for a reference with no
@ -153,12 +153,6 @@ export function refHref(
}
/* What to call the kind in a breadcrumb or a back link. */
export const ORG_KIND_LABEL: Record<string, string> = {
national: 'Next Generation of Unity',
region: 'Region',
chapter: 'Chapter',
partner: 'Partner organization',
}
/* Where "back" goes from a record page. A chapter belongs to
/community, a retreat to /retreats. */

View file

@ -24,10 +24,6 @@
const ABSOLUTE = /^(https?:|\/|data:)/
/* An uploaded file ('/uploads/…'), a path anywhere on the site, or
a full URL: something to use as it is rather than resolve. */
export const isAbsoluteMedia = (file?: string | null) => Boolean(file && ABSOLUTE.test(file))
function inDir(dir: string) {
return (file?: string | null): string | null => {
if (!file) return null

91
src/lib/organizations.ts Normal file
View file

@ -0,0 +1,91 @@
/* ═══════════════════════════════════════════════════════════════
ORGANIZATIONS
Regions, chapters, partners and NGU itself are one table and one
endpoint. Anything that lists organizations reads them the same
way and filters by kind:
const { organizations } = useOrganizations("region");
const { organizations } = useOrganizations("partner");
const { organizations } = useOrganizations(); // all
Every organization has the same card surface, name, colour,
logo, description, links. What differs by kind sits under
`details`, so a list component can render the common parts
without knowing what it's holding:
region { scope, map_note, areas[], chapters[] }
chapter { region_id, region_name, region_color, meets, started }
partner {}
Each kind is a separate request path, so the cache in api.ts
keys them apart and two sections asking for regions share one
fetch.
═══════════════════════════════════════════════════════════════ */
import { useResource } from "./useResource.ts";
export function useOrganizations(kind) {
const path = kind
? `/organizations?kind=${encodeURIComponent(kind)}`
: "/organizations";
const { data, error, loading } = useResource(path);
return {
organizations: data?.organizations ?? [],
loading,
error,
};
}
/* ── Where an organization's page lives ────────────────────────
One place to change when routes move. Kinds with no page of
their own return null, and a list should render no link rather
than a dead one.
───────────────────────────────────────────────────────────── */
const PATHS = {
region: "/regions",
chapter: "/chapters",
partner: "/partners",
};
export function orgPath(org) {
const base = PATHS[org?.kind];
return base ? `${base}/${org.id}` : null;
}
/* ── "AK, ID, MT, OR, UT (Salt Lake City area), WA" ────────────
The areas a region covers, annotated where it holds only part
of one. Canada is a band on the map rather than somewhere you'd
list, so it's left out of the sentence.
The note comes straight off the row. The old statesLabel had to
work out whether this region was the primary or the secondary of
a split before it knew which note applied; there's no such thing
any more.
───────────────────────────────────────────────────────────── */
export function areasSentence(areas: any[] = []) {
return areas
.filter((area) => area.area_code !== "CANADA")
.map((area) => (area.note ? `${area.area_code} (${area.note})` : area.area_code))
.sort()
.join(", ");
}
/* Initials for a card with no logo. "NGU Lynnwood" → "NL", dropping
the org prefix so every card doesn't read "NG". */
export const byName = (a, b) => a.name.localeCompare(b.name);
export function initialsFor(name = "") {
return name
.replace(/^NGU\s+/i, "")
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((word) => word[0].toUpperCase())
.join("");
}

View file

@ -24,7 +24,7 @@ import { useState } from "react";
}
Sections fetch their own data. The page never does, which is why
there's no loading or error state here — each view handles its
there's no loading or error state here, each view handles its
own, and one section failing doesn't blank the page.
Every Component receives `accent` so its empty and error notices

View file

@ -40,8 +40,6 @@ export const siteUrl = (path: string): string => new URL(path, SITE_ORIGIN).href
const PAGES: Record<string, PageText> = { ...siteConfiguration.pages, ...fromServer.pages }
/** The static pages site.json knows, for the admin's page list. */
export const SITE_PAGE_PATHS: string[] = Object.keys(siteConfiguration.pages)
/** A static page's title and intro, from site.json's "pages". */
export function sitePage(path: string): PageText {
const page = PAGES[path]

View file

@ -21,3 +21,6 @@ export function preview(text: string | null | undefined, max: number): string {
const clean = lastSpace > max / 2 ? cut.slice(0, lastSpace) : cut
return `${clean.replace(/[\s.,;:!?]+$/, '')}…`
}
export const capitalize = (word: string) =>
word ? word.charAt(0).toUpperCase() + word.slice(1) : ''

View file

@ -11,14 +11,14 @@
* date are read back from `events` at query time. Editing the event
* therefore edits the timeline, and there is no second copy to drift.
*
* Hand-authored entries — "bylaws rewritten", "the gathering becomes
* annual" — carry no ref and supply their own title and blurb. An entry
* Hand-authored entries, "bylaws rewritten", "the gathering becomes
* annual", carry no ref and supply their own title and blurb. An entry
* may also do both: reference an event but override its title, for when
* the timeline wants to say something the event card doesn't.
*
* ── What the server resolves, and what it doesn't ──────────────────────
* The server resolves *data*: title, date, logo filename, the members of
* a referenced team. It does not resolve *routes* or *asset paths* —
* a referenced team. It does not resolve *routes* or *asset paths*,
* those are presentation, and live in `timelineRefs.ts` so React Router
* and the public/ layout stay the frontend's business.
*/
@ -41,7 +41,7 @@ export type RefKind = 'event' | 'organization' | 'award' | 'person' | 'team'
export type TimelineRef = {
kind: RefKind
/** The row's TEXT primary key — an event id, org slug, team slug. */
/** The row's TEXT primary key, an event id, org slug, team slug. */
id: string
/** Only on organizations: history.js copies v_timeline.org_kind. */
orgKind?: OrgKind
@ -59,7 +59,7 @@ export type TimelineLogo = {
export type PersonRef = {
id: string
name: string
/** people.photo — filename only. */
/** people.photo, filename only. */
photo?: string
/** Their affiliation title at the time, if it's worth printing. */
title?: string
@ -78,7 +78,7 @@ export type TimelineItem = {
id: string
/** "2014" | "2014-06" | "2014-06-12" */
date: string
/** How much of `date` is trustworthy. Authoritative — a backfilled row
/** How much of `date` is trustworthy. Authoritative, a backfilled row
* may hold a full date while only the year is actually known. */
precision: DatePrecision
kind: TimelineKind
@ -127,7 +127,7 @@ export type GroupedYear = {
featured: boolean
count: number
featuredItems: TimelineItem[]
/** Year-precision items — known to be this year, month unknown. */
/** Year-precision items, known to be this year, month unknown. */
undated: TimelineItem[]
months: GroupedMonth[]
}
@ -238,7 +238,7 @@ export type GroupOptions = {
programStartYear?: number
/**
* Repeat featured items inside their month node as well as in the
* featured block. Off by default — in a sparse year it just prints the
* featured block. Off by default, in a sparse year it just prints the
* same line twice. A month left with nothing but featured items drops
* out entirely.
*/

View file

@ -4,7 +4,7 @@
Turns a timeline item into a destination and an image. Both were
answered locally here before, which is how the timeline came to
link events at /event/:id while the router only knew about
/retreats/:id — two files holding the same opinion, one of them
/retreats/:id, two files holding the same opinion, one of them
wrong, neither aware of the other.
Now this file knows about timeline items and nothing else. Where
@ -13,9 +13,9 @@
── The shape this reads, from history.js ──
item.href explicit link_url override, may be off-site
item.ref { kind, id, orgKind? } — orgKind only on
item.ref { kind, id, orgKind? }, orgKind only on
organizations, because only they have it
item.logo { file, kind } — v_timeline COALESCEs the
item.logo { file, kind }, v_timeline COALESCEs the
filename across five tables, so the kind is
what says which directory it came from
item.team { id, name, orgId? } on a team ref
@ -23,7 +23,7 @@
Every one of those is optional. An entry is a standalone
milestone until proven otherwise, and the two accessors below
return null rather than assuming a shape that isn't there —
return null rather than assuming a shape that isn't there,
which is the other half of the /organizations/undefined bug:
reaching into a ref that wasn't sent yields undefined, and
undefined interpolates into a path perfectly happily.
@ -44,7 +44,7 @@ import type { TimelineItem } from './timeline.ts'
* Otherwise the reference decides, and refHref returns null for a
* kind with no page yet ('person', until /people/:id exists) as
* well as for a ref that didn't resolve. Null means the entry
* renders as a plain <div> — right for a milestone, and right for
* renders as a plain <div>, right for a milestone, and right for
* a reference that's missing an id, which used to render as a link
* to a 404.
*/
@ -67,7 +67,7 @@ export function logoSrc(item: TimelineItem): string | null {
}
/**
* A roster member's photo. Same rule as everywhere else — the API
* A roster member's photo. Same rule as everywhere else, the API
* sends a bare filename.
*/
export function photoSrc(photo?: string | null): string | null {

View file

@ -1,11 +1,11 @@
/**
* The four detail endpoints, typed.
*
* Adding a fifth is a type and a one-line hook — useRecord owns
* Adding a fifth is a type and a one-line hook, useRecord owns
* the fetching, the caching and the 404.
*
* An id that is missing — or the literal string "undefined", which
* is what a template literal makes of a missing route param — never
* An id that is missing, or the literal string "undefined", which
* is what a template literal makes of a missing route param, never
* reaches the network. detailPath returns null and the hook reports
* notFound, which is what the visitor should see anyway, and
* hrefs.ts has already logged the component that produced it.
@ -145,8 +145,6 @@ export type EventListItem = Omit<EventRecord, 'blocks' | 'people' | 'awards'>
/** An event_scopes row, as GET /events sends it beside the list. */
export type EventScope = { id: string; name: string; sort_order: number }
export type EventsResponse = { scopes: EventScope[]; events: EventListItem[] }
export const useEvent = (id?: string): Resource<EventRecord> =>
useRecord<EventRecord>(detailPath('/events', id), 'event')
@ -251,14 +249,12 @@ export type OrganizationListItem = Omit<OrganizationRecord, 'teams' | 'awards' |
sort_order: number
}
export type OrganizationsResponse = { organizations: OrganizationListItem[] }
export const useOrganization = (id?: string): Resource<OrganizationRecord> =>
useRecord<OrganizationRecord>(detailPath('/organizations', id), 'organization')
/* ── Teams ───────────────────────────────────────────────────── */
/** No members here on purpose — PeopleTiles fetches
/** No members here on purpose, PeopleTiles fetches
* /teams/:id/people itself. See the note in content.js. */
export type TeamRecord = {
id: string

View file

@ -14,20 +14,16 @@
* callers, so aborting on unmount would cancel someone else's
* request. The `live` flag drops the result instead.
*
* No `fallback` on purpose. Handing this the mock data would render a
* plausible-looking history with no indication the server is down, and
* the wrong history is worse than a visible error — the same reason
* `fallback: EMPTY` came out elsewhere.
*
* `undated` is the number of published entries the API left out because
* nothing gave them a date. Not rendered publicly — a visitor can't act
* on it — but returned so it's reachable if you want a warning in the
* nothing gave them a date. Not rendered publicly, a visitor can't act
* on it, but returned so it's reachable if you want a warning in the
* admin later.
*/
import { useCallback, useEffect, useState } from 'react'
import { get, invalidate, ApiError } from './api.ts'
import type { TimelineItem } from './timeline'
import type { TimelineItem } from './timeline.ts'
const PATH = '/history'

View file

@ -1,10 +1,10 @@
/**
* useRecord — one record from one endpoint, on the useHistory
* useRecord, one record from one endpoint, on the useHistory
* pattern.
*
* Named for what it returns, and deliberately not useResource:
* src/lib/useResource.ts is a different hook — it hands back the
* whole response body and takes an options object — and a .ts file
* src/lib/useResource.ts is a different hook, it hands back the
* whole response body and takes an options object, and a .ts file
* of the same name would sit one extension away from it. An import
* whose target goes missing then resolves to the other file without
* a word, and every detail page renders the wrapper object instead
@ -43,7 +43,7 @@
* A null `path` means there is nothing to ask for, and the hook
* reports notFound rather than loading forever. Callers build the
* path with detailPath() from hrefs.ts, which returns null for an
* id that could never be real — "undefined" chief among them.
* id that could never be real, "undefined" chief among them.
*/
import { useCallback, useEffect, useState } from 'react'

View file

@ -3,13 +3,7 @@
The read hook every page uses:
const { data, error, loading } = useResource("/events", {
fallback: { events: EVENTS }, // the old static module
});
Deliberately small. If the site ever needs mutation, refetch on
focus, or pagination, that's the point to reach for TanStack
Query rather than growing this file.
const { data, error, loading } = useResource("/events");
Note the `ignore` flag rather than an AbortController: the
request is shared and cached, so cancelling it would throw away
@ -20,22 +14,15 @@
import { useEffect, useState } from "react";
import { get } from "./api.ts";
export function useResource(path, { ttl, fallback }: { ttl?: number; fallback?: any } = {}) {
// Seed with the fallback so the first paint has content when one
// is available, rather than flashing a spinner and then the same
// data a moment later.
const [state, setState] = useState<any>(() => ({
data: fallback,
error: null,
loading: true,
}));
export function useResource(path, { ttl }: { ttl?: number } = {}) {
const [state, setState] = useState<any>({ data: undefined, error: null, loading: true });
useEffect(() => {
let ignore = false;
setState((prev) => ({ ...prev, loading: true, error: null }));
get(path, { ttl, fallback })
get(path, { ttl })
.then((data) => {
if (!ignore) setState({ data, error: null, loading: false });
})
@ -46,7 +33,7 @@ export function useResource(path, { ttl, fallback }: { ttl?: number; fallback?:
return () => {
ignore = true;
};
}, [path, ttl]); // fallback is intentionally not a dependency
}, [path, ttl]);
return state;
}

View file

@ -1,5 +1,5 @@
/* ═══════════════════════════════════════════════════════════════
SITE VERSION — src/lib/version.ts
SITE VERSION: src/lib/version.ts
One string, bumped by hand when the working directory name
changes. The admin footer is the only thing reading it today;