From de17da7dc8ec38e1db0b9eab9a40a587aa9e7f74 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sat, 3 Oct 2026 16:10:57 -0500 Subject: [PATCH 01/94] Accessibility: reader view and full palette swaps; version v1.12.1-accessibility - Reading mode is now a reader view (ReaderView.tsx): the page renders hidden and its headings, paragraphs, links and described pictures are written out in one column, with no header, backdrop or footer. - Color blind modes swap all three color families (teal, green, amber); palette hexes in components and CSS are now var(--pal--) so the modes reach them. - CLAUDE.md and docs/updating-data-in-code.md describe both. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/updating-data-in-code.md | 2 +- src/components/AccessibilityPanel.tsx | 38 +---- src/components/Banner.tsx | 2 +- src/components/Footer.tsx | 6 +- src/components/Layout.tsx | 67 +++++--- src/components/PageBackdrop.css | 24 +-- src/components/PageShell.css | 18 +-- src/components/PrivacyNotice.tsx | 2 +- src/components/ReaderView.tsx | 217 ++++++++++++++++++++++++++ src/components/VideoPlayer.tsx | 2 +- src/components/admin/SectionNav.tsx | 7 +- src/index.css | 202 ++++++++++++++---------- src/lib/color.ts | 54 +++++-- src/lib/readingMode.ts | 15 ++ src/lib/version.ts | 2 +- src/pages/Privacy.tsx | 21 ++- src/pages/sections/home/HeroStage.tsx | 14 +- src/pages/sections/home/StatsBand.tsx | 4 +- 19 files changed, 507 insertions(+), 192 deletions(-) create mode 100644 src/components/ReaderView.tsx create mode 100644 src/lib/readingMode.ts diff --git a/CLAUDE.md b/CLAUDE.md index d462ebd..f4630a0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -71,7 +71,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere. - **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names. - **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface. -- **Colors are tokens, not hex.** Admins can override any token (Panel → Site settings → Colors). The defaults are `server/src/themeDefaults.js` plus the same values as CSS in `src/index.css`; the build fails if they differ (`themeDefaultsCheck` in `vite.config.ts`), and migration 041's CHECK lists the token names. Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's color). Data colors (accents, event and region colors) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`. +- **Colors are tokens, not hex.** Admins can override any token (Panel → Site settings → Colors). The defaults are `server/src/themeDefaults.js` plus the same values as CSS in `src/index.css`; the build fails if they differ (`themeDefaultsCheck` in `vite.config.ts`), and migration 041's CHECK lists the token names. Use the utilities from `src/index.css` (`text-ink`, `text-body`, `text-muted`, `text-link`, `bg-surface`, `bg-tint`, `bg-action`, `border-brand/20`...) so dark mode works; a literal only for something that must look the same in both modes (white on a dark band, a platform's color). Data colors (accents, event and region colors) go through `withAlpha`, `accentText` and `readableOn` in `src/lib/color.ts`, never `${color}55`. A palette color in a component or CSS file is `var(--pal--)`, not its hex, so the color blind modes reach it. - **Icons are Phosphor** (`@phosphor-icons/react`), weight `bold` (or `fill` for play/star). No hand-drawn `` icons and no Unicode glyphs as icons (× › ▶ →). Brand marks are the exception: `DoveMark`, `PlatformIcon`, the Google logo, the group map. - **Accents come from `src/lib/color.ts`:** `BRAND` (the teal, via the button token so the admin palette reaches it) and `ACCENTS` (deep, green, olive), all from `PALETTE` (the site's 16-color grid). Not a new hex in a page. - **Corners: square.** Everything is square except buttons, which use the `btn` utility (Poppins Bold, a small `var(--btn-radius)` corner, also for plain CSS), video players (small rounded) and things round by nature (dots, radio marks, the play button). A note in place of content (empty section, "coming soon") uses the `notice` utility (corner brackets), not a dashed border. Cards sit on `bg-raised` with a shadow so they stand off the page. Nothing glows: no blur blobs, no glow shadows. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index a186be5..2bbeb97 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -279,7 +279,7 @@ The numbers band's "Number Source" dropdown works the same way: | The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | | A page section's accent color | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a color there, not a hex in a page. Each is readable as text on white and the tints. | | The palette (the 16-color grid the theme is drawn from) | `PALETTE` in `src/lib/color.ts` | Four families, a column each. `PALETTE_LIGHT` / `PALETTE_DARK` are the fills things colored by data use (a person's initials tile, `paletteFill`); the page background's layers (how many circles, their sizes and parallax speeds) are `LAYERS` in `src/components/PageBackdrop.tsx` and its shades are in `PageBackdrop.css`; the admin home's two alternating group colors are `BLOCK_COLORS` in `src/pages/admin/AdminHome.tsx`. | -| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode swaps palette families (`SWAPS`, picked by simulating each type: see the comment there) in code, in data colors as they load (`src/lib/api.ts`, never under /admin) and in CSS (the `--green-*` variables in `src/index.css`); a hex from the green family in a component should be one of those variables. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | +| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal--)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | | Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. | | Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | | Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | diff --git a/src/components/AccessibilityPanel.tsx b/src/components/AccessibilityPanel.tsx index 9f25f16..38fd39b 100644 --- a/src/components/AccessibilityPanel.tsx +++ b/src/components/AccessibilityPanel.tsx @@ -6,10 +6,10 @@ Dyslexia-friendly font every typeface becomes OpenDyslexic (self-hosted, index.css) - Reading mode the page as plain text: one column of - ink on white, no colors, pictures, - cards or motion; a picture's - description stays in its place + Reading mode the page as text: its headings, + paragraphs, links and described + pictures in one column, nothing else + (ReaderView.tsx) Color blind mode the palette swapped so its colors stay apart for that type of color blindness, or grays (color.ts, VISIONS) @@ -53,7 +53,7 @@ const SETTINGS = [ key: 'site-reading', on: 'on', label: 'Reading mode', - help: 'The page as plain text: one column, larger type, no colors, pictures or motion.', + help: 'The page as text: headings, paragraphs, links and pictures in one column, nothing else.', }, ] as const @@ -87,30 +87,6 @@ function apply(attribute: string, key: string, value: string | null) { } } -/* Reading mode hides pictures, video and maps; their descriptions - (alt, title, aria-label) go on the parent as data-reading-alt, - which index.css shows in their place. An attribute rather than a - new element, so React's own nodes are left alone. */ -const DESCRIBED = 'main img[alt]:not([alt=""]), main iframe[title], main video[aria-label]' - -function describeMedia() { - for (const el of document.querySelectorAll(DESCRIBED)) { - const words = el.getAttribute('alt') ?? el.getAttribute('title') ?? el.getAttribute('aria-label') - const kind = el.tagName === 'IMG' ? 'Image' : 'Video' - el.parentElement?.setAttribute('data-reading-alt', `${kind}: ${words}`) - } -} - -function useMediaDescriptions(on: boolean) { - useEffect(() => { - if (!on) return undefined - describeMedia() - const observer = new MutationObserver(describeMedia) - observer.observe(document.body, { childList: true, subtree: true }) - return () => observer.disconnect() - }, [on]) -} - export default function AccessibilityPanel() { const [open, setOpen] = useState(false) const [state, setState] = useState(() => Object.fromEntries(SETTINGS.map((s) => [s.key, isOn(s)]))) @@ -120,8 +96,6 @@ export default function AccessibilityPanel() { const firstRef = useRef(null) const panelId = useId() - useMediaDescriptions(state['site-reading']) - useEffect(() => { const root = document.documentElement for (const { attribute, key } of PUBLIC_ONLY) { @@ -187,7 +161,7 @@ export default function AccessibilityPanel() { id={panelId} role="region" aria-label="Accessibility" - className="reading-solid absolute right-0 bottom-full mb-3 w-[min(20rem,calc(100vw-2rem))] border border-brand/20 bg-raised p-4 shadow-xl" + className="absolute right-0 bottom-full mb-3 w-[min(20rem,calc(100vw-2rem))] border border-brand/20 bg-raised p-4 shadow-xl" >

Accessibility

diff --git a/src/components/Banner.tsx b/src/components/Banner.tsx index a8fb404..e03d1c6 100644 --- a/src/components/Banner.tsx +++ b/src/components/Banner.tsx @@ -25,7 +25,7 @@ export default function Banner() { if (!visible) return null; const linkClass = - "underline underline-offset-4 decoration-[var(--green-2)] hover:text-white transition-colors"; + "underline underline-offset-4 decoration-[var(--pal-green-2)] hover:text-white transition-colors"; return (
(null); const location = useLocation(); const lastPath = useRef(location.pathname); + const reading = useReadingMode(); + // The page itself, drawn hidden for the reader view to read. + const pageRef = useRef(null); const sectionsOf = useNavSections(); @@ -124,19 +129,20 @@ export default function Layout() { ); ro.observe(el); return () => ro.disconnect(); - }, []); + }, [reading]); // On the root, so anything can read it: index.css keeps focused // and jumped-to things clear of the header with it // (scroll-padding-top), and PostContents offsets by it. useEffect(() => { const root = document.documentElement; - root.style.setProperty("--header-h", `${headerHeight}px`); + // Reading mode has no header to stay clear of. + root.style.setProperty("--header-h", `${reading ? 0 : headerHeight}px`); // The admin has no fixed header: nothing to stay clear of there. return () => { root.style.removeProperty("--header-h"); }; - }, [headerHeight]); + }, [headerHeight, reading]); // Router does not scroll on navigation. Go to top on a new page, // or to the anchor if the URL carries one (handles deep links too). @@ -151,17 +157,42 @@ export default function Layout() { if (newPage) document.getElementById("main")?.focus({ preventScroll: true }); }, [location.pathname, location.hash, location.key]); + const skipLink = ( + + Skip to content + + ); + + // Reading mode: the page as plain text (ReaderView.tsx), with no + // header, backdrop, footer or notices; the panel stays, to turn it + // off. The page itself still renders, hidden, for the reader to + // read, so every page works without a version of its own. + if (reading) { + return ( +
+ {skipLink} +
+ + +
+ +
+ ); + } + return ( // overflow-x-clip, not -hidden: hidden makes this div a scroll // container, and then nothing inside it can be position: sticky // (a blog post's contents column scrolled away with the page).
- - Skip to content - + {skipLink} {/* ── NAV ─────────────────────────────────────────────── */}
@@ -212,7 +243,7 @@ export default function Layout() { className={({ isActive }) => `block text-base font-bold pb-1 border-b-2 transition-colors duration-200 ${ isActive - ? "text-white border-[var(--green-2)]" + ? "text-white border-[var(--pal-green-2)]" : "text-white/75 hover:text-white border-transparent" }` } @@ -233,13 +264,13 @@ export default function Layout() { >
    {pageSections.map((section) => (
  • {section.label} @@ -299,8 +330,8 @@ export default function Layout() { {/* Mobile menu */} {mobileMenuOpen && (
    `block text-2xl font-bold py-3 transition-colors ${ - isActive ? "text-[var(--green-2)]" : "text-white hover:text-[#f0bd4f]" + isActive ? "text-[var(--pal-green-2)]" : "text-white hover:text-[var(--pal-amber-2)]" }` } > @@ -337,13 +368,13 @@ export default function Layout() { {isActive && pageSections.length > 0 && (
    {pageSections.map((section) => ( setMobileMenuOpen(false)} > {section.label} diff --git a/src/components/PageBackdrop.css b/src/components/PageBackdrop.css index 62c165e..91a5327 100644 --- a/src/components/PageBackdrop.css +++ b/src/components/PageBackdrop.css @@ -18,10 +18,10 @@ pointer-events: none; --pb-opacity: 0.6; - --pb-0: #d6f5fa; - --pb-1: var(--green-3); - --pb-2: #fdf1d6; - --pb-3: #d6f5fa; + --pb-0: var(--pal-teal-3); + --pb-1: var(--pal-green-3); + --pb-2: var(--pal-amber-3); + --pb-3: var(--pal-teal-3); } /* A circle's place: across by its left, down its layer's whole @@ -71,18 +71,18 @@ toggle's choice, or the system's when there is none. */ :root[data-theme="dark"] .page-backdrop { --pb-opacity: 0.3; - --pb-0: #003a45; - --pb-1: var(--green-1); - --pb-2: #4a2e00; - --pb-3: #003a45; + --pb-0: var(--pal-teal-1); + --pb-1: var(--pal-green-1); + --pb-2: var(--pal-amber-1); + --pb-3: var(--pal-teal-1); } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .page-backdrop { --pb-opacity: 0.3; - --pb-0: #003a45; - --pb-1: var(--green-1); - --pb-2: #4a2e00; - --pb-3: #003a45; + --pb-0: var(--pal-teal-1); + --pb-1: var(--pal-green-1); + --pb-2: var(--pal-amber-1); + --pb-3: var(--pal-teal-1); } } diff --git a/src/components/PageShell.css b/src/components/PageShell.css index 4d4bac7..744d6b0 100644 --- a/src/components/PageShell.css +++ b/src/components/PageShell.css @@ -5,7 +5,7 @@ on the page backdrop (PageBackdrop.css). */ .side-nav-circle { - background: #d6f5fa; + background: var(--pal-teal-3); /* A slight drop shadow, as the cards have: down and soft, no glow. */ box-shadow: 0 4px 12px rgb(0 16 17 / 0.14); /* Color by section; size and place between centered on the list @@ -18,32 +18,32 @@ top 0.6s ease-in-out; } .side-nav-circle[data-family="green"] { - background: var(--green-3); + background: var(--pal-green-3); } .side-nav-circle[data-family="amber"] { - background: #fdf1d6; + background: var(--pal-amber-3); } /* Dark mode: the toggle's choice, or the system's when there is none. */ :root[data-theme="dark"] .side-nav-circle { - background: #003a45; + background: var(--pal-teal-1); box-shadow: 0 4px 12px rgb(0 0 0 / 0.45); } :root[data-theme="dark"] .side-nav-circle[data-family="green"] { - background: var(--green-1); + background: var(--pal-green-1); } :root[data-theme="dark"] .side-nav-circle[data-family="amber"] { - background: #4a2e00; + background: var(--pal-amber-1); } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .side-nav-circle { - background: #003a45; + background: var(--pal-teal-1); box-shadow: 0 4px 12px rgb(0 0 0 / 0.45); } :root:not([data-theme="light"]) .side-nav-circle[data-family="green"] { - background: var(--green-1); + background: var(--pal-green-1); } :root:not([data-theme="light"]) .side-nav-circle[data-family="amber"] { - background: #4a2e00; + background: var(--pal-amber-1); } } diff --git a/src/components/PrivacyNotice.tsx b/src/components/PrivacyNotice.tsx index eb926b4..d95af47 100644 --- a/src/components/PrivacyNotice.tsx +++ b/src/components/PrivacyNotice.tsx @@ -43,7 +43,7 @@ export default function PrivacyNotice() {

    No tracking cookies here. Videos and maps come from YouTube, Facebook or Google only when you press diff --git a/src/components/ReaderView.tsx b/src/components/ReaderView.tsx new file mode 100644 index 0000000..05d991c --- /dev/null +++ b/src/components/ReaderView.tsx @@ -0,0 +1,217 @@ +/* ═══════════════════════════════════════════════════════════════ + READER VIEW: reading mode (AccessibilityPanel.tsx) + + The page as text: its headings, paragraphs, links and pictures, + one column, nothing else. No buttons, cards, colors, carousels or + forms. + + The real page still renders, hidden (Layout.tsx), so every page + and section works without a reading version of its own; this reads + what it drew and writes it out plainly, again whenever it changes + (data arriving, a new page). + + What's kept: + h1 to h6 headings, at their level + p, li, td, quote... paragraphs, with their links + a links (a card that is one link gives its + heading the link) + img with alt text pictures; one with empty alt is decoration + (a card's faded background) and is left out + a button that opens its words, as a line: a person's tile, a + something schedule row (aria-expanded) + What's dropped: other buttons, form fields, navigation lists, video and + map frames, drawings, and anything hidden from screen readers + (aria-hidden, the copies a carousel draws for its turns). + ═══════════════════════════════════════════════════════════════ */ + +import { useEffect, useState, type ReactNode, type RefObject } from 'react' +import { Link } from 'react-router-dom' + +import { PAGE_LINKS } from '../navConfig.ts' + +type Inline = string | { href: string; children: Inline[] } +type Block = + | { kind: 'heading'; level: number; content: Inline[] } + | { kind: 'text'; content: Inline[] } + | { kind: 'image'; src: string; alt: string } + +const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'NAV', 'IFRAME', 'VIDEO', 'AUDIO', 'CANVAS', 'DIALOG', 'svg']) +const HEADINGS = new Set(['H1', 'H2', 'H3', 'H4', 'H5', 'H6']) +const TEXT_BLOCKS = new Set(['P', 'LI', 'DT', 'DD', 'BLOCKQUOTE', 'FIGCAPTION', 'CAPTION', 'ADDRESS', 'TH', 'TD']) +const BLOCK_SELECTOR = 'div,section,article,header,footer,aside,main,p,ul,ol,li,dl,dt,dd,table,tr,figure,blockquote,h1,h2,h3,h4,h5,h6,img,form,fieldset' + +/* A button that opens something (a person's tile, a schedule row): + its words name content, so it's read as a line, not dropped. */ +const opens = (el: Element) => el.tagName === 'BUTTON' && el.hasAttribute('aria-expanded') + +const skipped = (el: Element) => + (SKIP.has(el.tagName) && !opens(el)) || + el.getAttribute('aria-hidden') === 'true' || + el.hasAttribute('hidden') || + ['button', 'switch', 'tab', 'slider', 'presentation', 'none'].includes(el.getAttribute('role') ?? '') + +/* A link's address as the app routes it: a path for this site, so + it opens without reloading; the full address for anywhere else. */ +function hrefOf(a: HTMLAnchorElement): string | null { + const raw = a.getAttribute('href') + if (!raw || raw.startsWith('javascript:')) return null + try { + const url = new URL(raw, location.href) + return url.origin === location.origin ? url.pathname + url.search + url.hash : url.href + } catch { + return null + } +} + +function inline(node: Node): Inline[] { + if (node.nodeType === Node.TEXT_NODE) return [node.textContent ?? ''] + if (!(node instanceof Element) || skipped(node) || node.tagName === 'IMG') return [] + if (node.tagName === 'BR') return [' '] + const children = [...node.childNodes].flatMap(inline) + if (node instanceof HTMLAnchorElement) { + const href = hrefOf(node) + return href ? [{ href, children }] : children + } + return children +} + +const textOf = (parts: Inline[]): string => + parts.map((p) => (typeof p === 'string' ? p : textOf(p.children))).join('').replace(/\s+/g, ' ').trim() + +const isBlock = (el: Element) => opens(el) || el.matches(BLOCK_SELECTOR) || el.querySelector(BLOCK_SELECTOR) !== null + +function extract(root: Element): Block[] { + const blocks: Block[] = [] + const text = (content: Inline[]) => { + if (textOf(content)) blocks.push({ kind: 'text', content }) + } + + function walk(el: Element, link: string | null) { + // The root is the hidden copy of the page itself: read inside it. + if (el !== root && skipped(el)) return + if (opens(el)) { + // Each part on its own line in the page (a name, a title) joins + // with a comma. + const parts = [...el.querySelectorAll('*')] + .filter((part) => !part.closest('[aria-hidden="true"]') && [...part.childNodes].some((n) => n.nodeType === Node.TEXT_NODE && n.textContent?.trim())) + .map((part) => [...part.childNodes].filter((n) => n.nodeType === Node.TEXT_NODE).map((n) => n.textContent).join('').trim()) + text([parts.join(', ')]) + return + } + if (HEADINGS.has(el.tagName)) { + const content = [...el.childNodes].flatMap(inline) + if (textOf(content)) { + blocks.push({ kind: 'heading', level: Number(el.tagName[1]), content: link ? [{ href: link, children: content }] : content }) + } + return + } + if (el.tagName === 'IMG') { + const img = el as HTMLImageElement + const alt = img.getAttribute('alt')?.trim() + const src = img.currentSrc || img.getAttribute('src') + if (alt && src) blocks.push({ kind: 'image', src, alt }) + return + } + if (TEXT_BLOCKS.has(el.tagName) && !el.querySelector('p,li,h1,h2,h3,h4,h5,h6,img')) { + text([...el.childNodes].flatMap(inline)) + return + } + if (el.tagName === 'TR') { + const cells = [...el.children].map((cell) => [...cell.childNodes].flatMap(inline)).filter((c) => textOf(c)) + text(cells.flatMap((cell, i) => (i ? [' · ', ...cell] : cell))) + return + } + // A link around a whole card: its parts, with the link on the first + // heading (or, with none, kept as a line of its own). + const href = el instanceof HTMLAnchorElement ? hrefOf(el) : null + if (href && isBlock(el)) { + const before = blocks.length + for (const child of el.children) walk(child, href) + if (!blocks.slice(before).some((b) => b.kind === 'heading')) { + const label = el.getAttribute('aria-label') + if (label) blocks.splice(before, 0, { kind: 'text', content: [{ href, children: [label] }] }) + } + return + } + + // Anything else: its loose text and inline parts make paragraphs, + // broken where a block of its own comes. + let run: Inline[] = [] + for (const child of el.childNodes) { + if (child instanceof Element && !skipped(child) && isBlock(child)) { + text(run) + run = [] + walk(child, link) + } else { + run.push(...inline(child)) + } + } + text(run) + } + + walk(root, null) + // Carousels and repeated strips can say the same line twice in a row. + return blocks.filter((b, i) => { + const prev = blocks[i - 1] + return !prev || prev.kind !== b.kind || JSON.stringify(prev) !== JSON.stringify(b) + }) +} + +function render(parts: Inline[]): ReactNode[] { + return parts.map((part, i) => { + if (typeof part === 'string') return part + const children = render(part.children) + return part.href.startsWith('/') ? ( + + {children} + + ) : ( + + {children} + + ) + }) +} + +export default function ReaderView({ source }: { source: RefObject }) { + const [blocks, setBlocks] = useState([]) + + useEffect(() => { + const root = source.current + if (!root) return undefined + let frame = 0 + const update = () => { + frame = 0 + setBlocks(extract(root)) + } + const schedule = () => { + if (!frame) frame = requestAnimationFrame(update) + } + update() + const observer = new MutationObserver(schedule) + observer.observe(root, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['src', 'alt', 'href', 'hidden', 'aria-hidden'] }) + return () => { + observer.disconnect() + if (frame) cancelAnimationFrame(frame) + } + }, [source]) + + return ( +

    +

    + {PAGE_LINKS.map((page, i) => ( + + {i > 0 && ' · '} + {page.label} + + ))} +

    + {blocks.map((block, i) => { + if (block.kind === 'image') return {block.alt} + if (block.kind === 'text') return

    {render(block.content)}

    + const Heading = `h${block.level}` as 'h1' + return {render(block.content)} + })} +
    + ) +} diff --git a/src/components/VideoPlayer.tsx b/src/components/VideoPlayer.tsx index 1bd1392..cf4d52d 100644 --- a/src/components/VideoPlayer.tsx +++ b/src/components/VideoPlayer.tsx @@ -90,7 +90,7 @@ export default function VideoPlayer({ className="block aspect-video w-full object-cover" /> ) : ( - + )}
    {(when || where) && ( @@ -505,7 +505,7 @@ function EventPanel({ event }: { event: HeroEvent }) { className={`inline-flex items-center gap-2 btn px-6 py-3 transition-transform hover:scale-105 ${ index === 0 ? 'text-[#001011]' : 'border border-white/35 text-white hover:bg-white/10' }`} - style={index === 0 ? { background: '#f0bd4f' } : undefined} + style={index === 0 ? { background: 'var(--pal-amber-2)' } : undefined} > {link.label} diff --git a/src/pages/sections/home/StatsBand.tsx b/src/pages/sections/home/StatsBand.tsx index 8bf3839..5217e62 100644 --- a/src/pages/sections/home/StatsBand.tsx +++ b/src/pages/sections/home/StatsBand.tsx @@ -48,7 +48,7 @@ export default function StatsBand({ id, title, blurb, stats }: StatsBandProps) { id={id} ref={ref} className="relative overflow-hidden py-24" - style={{ background: '#003a45' }} + style={{ background: 'var(--pal-teal-1)' }} >

    @@ -65,7 +65,7 @@ export default function StatsBand({ id, title, blurb, stats }: StatsBandProps) { >
    - {stat.suffix && {stat.suffix}} + {stat.suffix && {stat.suffix}}
    {stat.label} From 502a294940716dd306ec8e7c0877f8daff946c16 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sat, 3 Oct 2026 16:46:41 -0500 Subject: [PATCH 02/94] Reading mode spacing, phone map width, no fixed back links - Reading mode: parts the page draws on their own lines get a space between them, so words no longer run together; the column is 60rem (was 42rem) and headings are bold in the display face. - Local groups map scales to its column on a phone instead of holding 34rem and scrolling sideways. - Group, region, partner and team pages drop their fixed back link (records are reached from many pages); orgListHref is gone. Not-found pages keep theirs. Co-Authored-By: Claude Opus 5.5 --- docs/updating-data-in-code.md | 4 ++-- src/components/ReaderView.tsx | 10 +++++----- src/index.css | 4 +++- src/lib/hrefs.ts | 15 --------------- src/pages/OrganizationDetail.tsx | 11 ++--------- src/pages/TeamDetail.tsx | 8 -------- src/pages/sections/OrgList-Map.tsx | 20 ++++++++------------ 7 files changed, 20 insertions(+), 52 deletions(-) diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 2bbeb97..af3b74a 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -166,7 +166,7 @@ also in `server/src/admin-schema/` and a CHECK): | Entity → field | Stored values | Labeled? | Also used on the public site by | | --- | --- | --- | --- | -| Organizations → Kind (+ list filter) | national, region, group, partner | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses) and `orgListHref` there (its back link) | +| Organizations → Kind (+ list filter) | national, region, group, partner | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses) | | Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it | | Organizations → Region areas → Edge | top, bottom | no | the group map (`OrgList-Map.tsx`) | | Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) | @@ -283,7 +283,7 @@ The numbers band's "Number Source" dropdown works the same way: | Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. | | Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | | Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | -| Organization kind labels ("Region", "Group") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin); `orgListHref` in `src/lib/hrefs.ts` (the public back link, "All regions") | | +| Organization kind labels ("Region", "Group") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin) | | | Admin account roles | `src/lib/roles.ts` (labels, notes) and `ROLES` in `server/src/auth.js` | Adding a role is also a CHECK change on `admin_users.role`. | | Admin navigation | `src/pages/admin/adminNav.ts` | | | Newsletter parts and their defaults (Tools → Newsletter) | `PARTS_SPEC`, `PART_TYPES` and `STARTER` in `src/pages/admin/AdminNewsletter.tsx`; `PICK_DEFAULTS`, `DEFAULT_TITLE` and `COLOR` in `src/lib/newsletter.ts` | A draft is one JSON list of parts (`newsletters.layout`, 060), so adding a part or a setting needs no migration: a field in `PARTS_SPEC` and its drawing in `newsletter.ts`. The color choices are `PALETTE`; `COLOR` holds the defaults as hex, since an inbox has no theme tokens. `STARTER` is what a new draft starts with. The social bar's icons are PNGs in `public/email/` (Gmail and Outlook don't show SVG), made from `PlatformIcon.tsx` by `node scripts/email-icons.mjs`: run it again after adding a platform. A social bar with no links shows the footer's, `SOCIAL_LINKS` in `src/data/socialLinks.ts`. The countdown picture is `server/src/routes/countdown.js`, counting to local midnight in its `TIME_ZONE` (America/Chicago). | diff --git a/src/components/ReaderView.tsx b/src/components/ReaderView.tsx index 05d991c..a784efe 100644 --- a/src/components/ReaderView.tsx +++ b/src/components/ReaderView.tsx @@ -68,11 +68,11 @@ function inline(node: Node): Inline[] { if (!(node instanceof Element) || skipped(node) || node.tagName === 'IMG') return [] if (node.tagName === 'BR') return [' '] const children = [...node.childNodes].flatMap(inline) - if (node instanceof HTMLAnchorElement) { - const href = hrefOf(node) - return href ? [{ href, children }] : children - } - return children + const href = node instanceof HTMLAnchorElement ? hrefOf(node) : null + const parts: Inline[] = href ? [{ href, children }] : children + // A part the page draws on its own line (a span set to block, a + // flex row's items) has no space in its text: give it one. + return getComputedStyle(node).display.startsWith('inline') ? parts : [' ', ...parts, ' '] } const textOf = (parts: Inline[]): string => diff --git a/src/index.css b/src/index.css index 533d1cb..bfa7216 100644 --- a/src/index.css +++ b/src/index.css @@ -305,7 +305,7 @@ iframe[src*="churchcenter"] { } } .reader { - max-width: 42rem; + max-width: 60rem; margin-inline: auto; padding: 2.5rem 1rem 6rem; line-height: 1.75; @@ -315,6 +315,8 @@ iframe[src*="churchcenter"] { } .reader :is(h1, h2, h3, h4, h5, h6) { margin-top: 2rem; + font-family: var(--font-display); + font-weight: 700; line-height: 1.3; } .reader h1 { font-size: 2rem; } diff --git a/src/lib/hrefs.ts b/src/lib/hrefs.ts index cdee8aa..5ec719a 100644 --- a/src/lib/hrefs.ts +++ b/src/lib/hrefs.ts @@ -151,18 +151,3 @@ export function refHref( return null } } - -/* Where "back" goes from a record page. A group belongs to - /community, a retreat to /retreats. */ -export function orgListHref(kind?: string | null): { to: string; label: string } { - switch (kind) { - case 'region': - return { to: '/community#regions', label: 'All regions' } - case 'group': - return { to: '/community#groups', label: 'All groups' } - case 'partner': - return { to: '/community#partners', label: 'All partner organizations' } - default: - return { to: '/community', label: 'Community' } - } -} diff --git a/src/pages/OrganizationDetail.tsx b/src/pages/OrganizationDetail.tsx index a25d013..8335141 100644 --- a/src/pages/OrganizationDetail.tsx +++ b/src/pages/OrganizationDetail.tsx @@ -26,7 +26,7 @@ import { useOrganization, type OrganizationRecord, } from '../lib/useContent.ts' -import { orgHref, orgListHref } from '../lib/hrefs.ts' +import { orgHref } from '../lib/hrefs.ts' import { mediaUrl } from '../lib/media.ts' import { initialsFor } from '../lib/organizations.ts' import Logo from '../components/Logo.tsx' @@ -70,7 +70,6 @@ export default function OrganizationDetail() { } const accent = org.color || BRAND - const back = orgListHref(org.kind) const sections: any[] = [ { @@ -79,7 +78,7 @@ export default function OrganizationDetail() { accent, content: (
    - + {org.description.map((paragraph, index) => (

    @@ -211,11 +210,9 @@ export default function OrganizationDetail() { function Facts({ org, accent, - back, }: { org: OrganizationRecord accent: string - back: { to: string; label: string } }) { const where = org.location_label || [org.locality, org.state_code].filter(Boolean).join(', ') @@ -248,10 +245,6 @@ function Facts({ Since {org.details.started} )} {org.is_online && Online} - - - {back.label} -

    ) } diff --git a/src/pages/TeamDetail.tsx b/src/pages/TeamDetail.tsx index 0e6b6a0..6b82dcf 100644 --- a/src/pages/TeamDetail.tsx +++ b/src/pages/TeamDetail.tsx @@ -142,14 +142,6 @@ function Facts({ {orgName} - - - Back to {orgName} -

    ) } diff --git a/src/pages/sections/OrgList-Map.tsx b/src/pages/sections/OrgList-Map.tsx index 538b9ba..8ded152 100644 --- a/src/pages/sections/OrgList-Map.tsx +++ b/src/pages/sections/OrgList-Map.tsx @@ -960,18 +960,14 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) {
    {/* Map */}
    - {/* On a phone the map keeps a readable size (tiles big enough - to read and tap) and scrolls sideways in its own box. */} -
    -
    - -
    -
    + {/* Scales to the column's width at every size; on a phone the + legend and the list below are the easier way in. */} + Date: Sat, 3 Oct 2026 16:54:55 -0500 Subject: [PATCH 03/94] Reading mode: text versions of the front page's bands - Stats: one line per number, no longer stuck at 0 (the count waited for the band to scroll into view, which the hidden page never does); reduced motion shows the numbers at once too. - Calendar: the next six weeks from today as a list (date, linked title, time, type, place), wherever a calendar is drawn. - Featured cards: a linked heading and its words each; a video card links to its video. - Countdown: left out, the retreats band shows the same event. Co-Authored-By: Claude Opus 5.5 --- docs/updating-data-in-code.md | 2 +- src/components/FeaturedCards.tsx | 23 ++++++++++ src/pages/sections/EventCalendar.tsx | 42 ++++++++++++++++++- .../sections/home/NextEventCountdown.tsx | 5 +++ src/pages/sections/home/StatsBand.tsx | 28 +++++++++++-- 5 files changed, 95 insertions(+), 5 deletions(-) diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index af3b74a..12872b3 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -279,7 +279,7 @@ The numbers band's "Number Source" dropdown works the same way: | The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | | A page section's accent color | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a color there, not a hex in a page. Each is readable as text on white and the tints. | | The palette (the 16-color grid the theme is drawn from) | `PALETTE` in `src/lib/color.ts` | Four families, a column each. `PALETTE_LIGHT` / `PALETTE_DARK` are the fills things colored by data use (a person's initials tile, `paletteFill`); the page background's layers (how many circles, their sizes and parallax speeds) are `LAYERS` in `src/components/PageBackdrop.tsx` and its shades are in `PageBackdrop.css`; the admin home's two alternating group colors are `BLOCK_COLORS` in `src/pages/admin/AdminHome.tsx`. | -| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal--)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | +| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal--)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. A part it can't read well draws its own text version when `useReadingMode()` (`src/lib/readingMode.ts`) is on: the stats band, the calendar (the next six weeks as a list) and the featured cards; the countdown draws nothing. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | | Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. | | Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | | Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx index 9476633..5f5b4d6 100644 --- a/src/components/FeaturedCards.tsx +++ b/src/components/FeaturedCards.tsx @@ -23,6 +23,9 @@ fall outside), 4px thick. With three or more cards the first is the large one, two rows tall, and the next two stack beside it, so it no longer stretches its neighbor. + + Reading mode (readingMode.ts) gets each card as a linked heading + and its words, a video card linking to its video. ═══════════════════════════════════════════════════════════════ */ @@ -31,6 +34,7 @@ import VideoPlayer from './VideoPlayer.tsx' import { refHref } from '../lib/hrefs.ts' import { mediaUrl } from '../lib/media.ts' import type { FeaturedCard } from '../lib/useFrontPage.ts' +import { useReadingMode } from '../lib/readingMode.ts' import { useSmallImage } from '../lib/useSmallImage.ts' /* Image kinds that are photographs, drawn edge to edge. Anything @@ -131,7 +135,26 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) { ) } +function ReadingCards({ cards }: { cards: FeaturedCard[] }) { + return ( + <> + {cards.map((card, index) => { + const href = card.kind === 'video' ? card.url : hrefFor(card) + return ( +
    + {card.eyebrow &&

    {card.eyebrow}

    } + {card.title &&

    {href ? {card.title} : card.title}

    } + {card.blurb &&

    {card.blurb}

    } +
    + ) + })} + + ) +} + export default function FeaturedCards({ cards }: { cards: FeaturedCard[] }) { + const reading = useReadingMode() + if (reading) return const leadLarge = cards.length >= 3 return (
    diff --git a/src/pages/sections/EventCalendar.tsx b/src/pages/sections/EventCalendar.tsx index 794b670..926fa0b 100644 --- a/src/pages/sections/EventCalendar.tsx +++ b/src/pages/sections/EventCalendar.tsx @@ -39,6 +39,9 @@ Below md the grid would be seven unreadable slivers, so the month view shows the list there instead. The toggle still works; it just has one answer on a phone. + + Reading mode (readingMode.ts) gets no grid or controls: the next + six weeks from today as a list, one line per event (ReadingList). ═══════════════════════════════════════════════════════════════ */ import { ArrowRight, ArrowLeft, CaretRight, CaretLeft } from '@phosphor-icons/react' @@ -52,6 +55,7 @@ import { eventHref } from '../../lib/hrefs.ts' import type { EventListItem } from '../../lib/useContent.ts' import { withAlpha, accentText, readableOn, BRAND } from '../../lib/color.ts' import { localISO } from '../../lib/timeline.ts' +import { useReadingMode } from '../../lib/readingMode.ts' export type CalendarControl = 'scope' | 'type' | 'online' | 'search' export type CalendarView = 'month' | 'list' @@ -225,7 +229,43 @@ function nextDateAfter(events: EventListItem[], after: string): string | null { /* ── Component ───────────────────────────────────────────────── */ -export default function EventCalendar({ +export default function EventCalendar(props: EventCalendarProps) { + return useReadingMode() ? : +} + +/* How many days from today the reading mode list covers. */ +const READING_DAYS = 42 + +/* Reading mode: what's on from today for six weeks, as text. */ +function ReadingList({ scope, host, status, type }: EventCalendarProps) { + const today = iso(new Date()) + const to = addDays(today, READING_DAYS - 1) + const { events, loading, error } = useEvents({ scope, host, status, type, from: today, to }) + const items = useMemo(() => occurrencesIn(events, today, to), [events, today, to]) + + if (error) return

    Couldn’t load the calendar. {error}

    + if (loading && items.length === 0) return

    Loading the calendar…

    + if (items.length === 0) return

    Nothing on the calendar in the next six weeks.

    + + return ( +
      + {items.map((item) => { + const { event } = item + const when = item.start !== item.end ? rangeLabel(item.start, item.end) : longDay(item.start) + const where = event.location_label || (event.is_online ? 'Online' : null) + return ( +
    • + {when}: {event.title} + {event.status === 'cancelled' && ' (canceled)'} + {[item.time, eventTypeLabel(event.event_type), where].filter(Boolean).map((part) => `, ${part}`)} +
    • + ) + })} +
    + ) +} + +function CalendarGrid({ scope, host, status, diff --git a/src/pages/sections/home/NextEventCountdown.tsx b/src/pages/sections/home/NextEventCountdown.tsx index 7971339..f14917c 100644 --- a/src/pages/sections/home/NextEventCountdown.tsx +++ b/src/pages/sections/home/NextEventCountdown.tsx @@ -26,6 +26,7 @@ import { eventHref } from '../../../lib/hrefs.ts' import { upcomingOccurrences } from '../../../lib/eventSeries.ts' import type { CountdownEvent } from '../../../lib/useFrontPage.ts' import { withAlpha, accentText, BRAND } from '../../../lib/color.ts' +import { useReadingMode } from '../../../lib/readingMode.ts' /* Local midnight (or HH:MM) on a 'YYYY-MM-DD'. */ @@ -63,6 +64,7 @@ export default function NextEventCountdown({ event: CountdownEvent overlap: boolean }) { + const reading = useReadingMode() const now = useNow(1000) const when = target(event) const accent = event.color || BRAND @@ -79,6 +81,9 @@ export default function NextEventCountdown({ const where = event.location_label || (event.is_online ? 'Online' : null) + // Reading mode: the event is already in the retreats band. + if (reading) return null + return (
    (null) - const [seen, setSeen] = useState(false) + // Less motion: no wait for the band to scroll into view (reading + // mode's hidden page never does). + const [seen, setSeen] = useState(prefersLessMotion) useEffect(() => { const el = ref.current @@ -43,6 +47,24 @@ export default function StatsBand({ id, title, blurb, stats }: StatsBandProps) { return () => observer.disconnect() }, [seen]) + if (useReadingMode()) { + return ( +
    +

    {title}

    + {blurb &&

    {blurb}

    } +
      + {stats.map((stat, index) => ( +
    • + {stat.value} + {stat.suffix} {stat.label} + {stat.note && `: ${stat.note}`} +
    • + ))} +
    +
    + ) + } + return (
    {value} - const n = reduced || !run ? (run ? target : 0) : shown + const n = reduced ? target : run ? shown : 0 return ( {n.toLocaleString(undefined, { From 27e5fbd690ee2f7d3901a83ddefe83da4768ffb4 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sat, 3 Oct 2026 17:12:27 -0500 Subject: [PATCH 04/94] Reading mode: every page and section reads as text The reader (ReaderView.tsx) now reads an icon-only link's label, puts a card's link on its first line or picture when it has no heading, gives each item of a row of facts or links its own line, keeps line breaks, skips what CSS hides, turns a form into one line saying it can't be used there, shows empty table cells as "-", keeps section and heading ids so #links land, and opens file links as files. What it can't read draws its own text version (useReadingMode()): the hero, pathfinder, front page history, event lists (every event, past ones too), org lists and groups map (every region and group, linked), history timeline (every year open), schedules (every day, fold-outs included), people tiles (everyone, with details) and videos. Also: org names are linked headings, heading levels fixed where cards repeated their section's, Team pages lose the doubled "Members", Giving links the treasurer's email and names Church Center. Co-Authored-By: Claude Opus 5.5 --- docs/updating-data-in-code.md | 2 +- src/components/ContentBlocks.tsx | 43 ++++- src/components/FeaturedCards.tsx | 22 ++- src/components/OrgContact.tsx | 11 ++ src/components/PeopleTiles.tsx | 69 +++++++- src/components/ReaderView.tsx | 148 ++++++++++++++---- src/components/ScheduleBlock.tsx | 57 ++++++- src/components/VideoPlayer.tsx | 14 ++ src/pages/Giving.tsx | 8 +- src/pages/NotFound.tsx | 11 +- src/pages/OrganizationDetail.tsx | 21 ++- src/pages/PersonDetail.tsx | 46 ++++-- src/pages/TeamDetail.tsx | 2 +- src/pages/sections/CommunityBlog.tsx | 24 +-- src/pages/sections/EventList-Cards.tsx | 83 ++++++---- src/pages/sections/OrgList-Card.tsx | 19 ++- src/pages/sections/OrgList-Map.tsx | 76 ++++++++- src/pages/sections/OrgList-Vertical.tsx | 57 ++++--- src/pages/sections/history/TimelineEntry.tsx | 19 +++ .../sections/history/TimelineUpcoming.tsx | 41 +++-- src/pages/sections/history/TimelineYear.tsx | 52 +++--- .../sections/home/FeaturedTimelineRail.tsx | 35 +++++ src/pages/sections/home/HeroStage.tsx | 80 ++++++++++ src/pages/sections/home/Pathfinder.tsx | 28 ++++ 24 files changed, 788 insertions(+), 180 deletions(-) diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 12872b3..93da289 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -279,7 +279,7 @@ The numbers band's "Number Source" dropdown works the same way: | The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | | A page section's accent color | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a color there, not a hex in a page. Each is readable as text on white and the tints. | | The palette (the 16-color grid the theme is drawn from) | `PALETTE` in `src/lib/color.ts` | Four families, a column each. `PALETTE_LIGHT` / `PALETTE_DARK` are the fills things colored by data use (a person's initials tile, `paletteFill`); the page background's layers (how many circles, their sizes and parallax speeds) are `LAYERS` in `src/components/PageBackdrop.tsx` and its shades are in `PageBackdrop.css`; the admin home's two alternating group colors are `BLOCK_COLORS` in `src/pages/admin/AdminHome.tsx`. | -| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal--)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. A part it can't read well draws its own text version when `useReadingMode()` (`src/lib/readingMode.ts`) is on: the stats band, the calendar (the next six weeks as a list) and the featured cards; the countdown draws nothing. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | +| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal--)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. A part it can't read well (a carousel, tabs, details behind a click, a map) draws its own text version when `useReadingMode()` (`src/lib/readingMode.ts`) is on: the hero, pathfinder, stats, history rail, event lists, calendar (the next six weeks), featured cards, org lists and groups map, history timeline, schedule, people tiles and video player; the countdown draws nothing. A new component with any of those should do the same. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | | Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. | | Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | | Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index 3283f8d..cb5c621 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -35,6 +35,10 @@ "Formatted" is InlineText.tsx: **bold**, *italic*, [text](url), line breaks, and a blank line for a new paragraph. + Reading mode (readingMode.ts): a linked image with no alt text + is a line linking with its caption, and a video's caption is its + link (VideoPlayer), not said twice. + An unknown `type` renders its text as a paragraph rather than disappearing. A block somebody typed into the admin should be visible even if the renderer hasn't caught up with it. @@ -50,6 +54,7 @@ import { accentText, BRAND } from '../lib/color.ts' import { headingAnchors } from '../lib/contents.ts' import { SITE_NAME } from '../lib/site.ts' import { useSmallImage } from '../lib/useSmallImage.ts' +import { useReadingMode } from '../lib/readingMode.ts' const BODY = 'var(--color-muted)' @@ -66,11 +71,20 @@ export default function ContentBlocks({ // Headings get ids so a post's contents (PostContents) and a shared // link (#getting-there) can point at them. const { idAt } = headingAnchors(blocks) + // The heading level a block's own headings take: under the last + // heading (h3) or subheading (h4) before it, else the section's h2. + let under = 2 + const levels = blocks.map((block) => { + const level = (under + 1) as 3 | 4 | 5 + if (block.type === 'heading') under = 3 + if (block.type === 'subheading') under = 4 + return level + }) return (
    {blocks.map((block, index) => ( - + ))}
    ) @@ -135,8 +149,19 @@ function Caption({ text }: { text?: string | null }) { ) } -function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; anchor?: string }) { +function Block({ + block, + accent, + anchor, + level, +}: { + block: ContentBlock + accent: string + anchor?: string + level: 3 | 4 | 5 +}) { const text = block.text ?? '' + const reading = useReadingMode() switch (block.type) { case 'heading': @@ -294,6 +319,14 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; case 'image': { const src = mediaUrl(block.media) if (!src) return null + // The reader leaves out a picture with no alt, and its link with it. + if (reading && block.href && !block.alt) { + return ( +

    + {text || 'Open link'} +

    + ) + } const img = (
    - + {!reading && } ) @@ -335,8 +368,8 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string; if (!block.team_id && picked.length === 0) return null return (
    - {block.team_id && } - {picked.length > 0 && } + {block.team_id && } + {picked.length > 0 && }
    ) } diff --git a/src/components/FeaturedCards.tsx b/src/components/FeaturedCards.tsx index 5f5b4d6..6b23755 100644 --- a/src/components/FeaturedCards.tsx +++ b/src/components/FeaturedCards.tsx @@ -25,7 +25,8 @@ longer stretches its neighbor. Reading mode (readingMode.ts) gets each card as a linked heading - and its words, a video card linking to its video. + and its words, a video card linking to its video. `level` is that + heading's level, one under the heading above the cards. ═══════════════════════════════════════════════════════════════ */ @@ -84,8 +85,9 @@ function VideoPicture({ card }: { card: FeaturedCard }) { const RULE = 'border-brand' -function Card({ card, large }: { card: FeaturedCard; large: boolean }) { +function Card({ card, large, level }: { card: FeaturedCard; large: boolean; level: 3 | 4 }) { const href = hrefFor(card) + const Title = level === 4 ? 'h4' : 'h3' const text = (
    @@ -93,7 +95,7 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) {

    {card.eyebrow}

    )} {card.title && ( -

    + {href ? ( // Stretched over the whole card, so the picture and the // blurb are part of the click without nesting links. @@ -106,7 +108,7 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) { ) : ( card.title )} - </h3> + )} {card.blurb && (

    {card.blurb}

    @@ -135,7 +137,10 @@ function Card({ card, large }: { card: FeaturedCard; large: boolean }) { ) } -function ReadingCards({ cards }: { cards: FeaturedCard[] }) { +type FeaturedCardsProps = { cards: FeaturedCard[]; level?: 3 | 4 } + +function ReadingCards({ cards, level = 3 }: FeaturedCardsProps) { + const Title = level === 4 ? 'h4' : 'h3' return ( <> {cards.map((card, index) => { @@ -143,7 +148,7 @@ function ReadingCards({ cards }: { cards: FeaturedCard[] }) { return (
    {card.eyebrow &&

    {card.eyebrow}

    } - {card.title &&

    {href ? {card.title} : card.title}

    } + {card.title && {href ? <HomeLink url={href}>{card.title}</HomeLink> : card.title}} {card.blurb &&

    {card.blurb}

    }
    ) @@ -152,9 +157,9 @@ function ReadingCards({ cards }: { cards: FeaturedCard[] }) { ) } -export default function FeaturedCards({ cards }: { cards: FeaturedCard[] }) { +export default function FeaturedCards({ cards, level = 3 }: FeaturedCardsProps) { const reading = useReadingMode() - if (reading) return + if (reading) return const leadLarge = cards.length >= 3 return (
    @@ -164,6 +169,7 @@ export default function FeaturedCards({ cards }: { cards: FeaturedCard[] }) { key={`${card.kind}-${card.ref?.id ?? card.url}-${index}`} card={card} large={leadLarge && index === 0} + level={level} /> ))}

diff --git a/src/components/OrgContact.tsx b/src/components/OrgContact.tsx index 3df7ebb..8d2ad16 100644 --- a/src/components/OrgContact.tsx +++ b/src/components/OrgContact.tsx @@ -5,11 +5,20 @@ filled in its accent, then its website, email and socials outlined. Nothing at all when it has none. Used on an organization's page and on the Organization page (NGU's own). + A platform's icon has its name beside it for screen readers and + reading mode, unless the label already says it (PlatformName). ═══════════════════════════════════════════════════════════════ */ import PlatformIcon from './PlatformIcon.tsx' import type { OrganizationRecord } from '../lib/useContent.ts' import { accentText } from '../lib/color.ts' +import { PLATFORMS } from '../lib/platforms.ts' + +function PlatformName({ platform, label }: { platform?: string | null; label?: string | null }) { + const name = PLATFORMS.find((p) => p.id === platform)?.label + if (!name || label?.toLowerCase().includes(name.toLowerCase())) return null + return {label ? `${name}: ` : name} +} export default function OrgContact({ org, accent }: { org: OrganizationRecord; accent: string }) { const hasAny = @@ -29,6 +38,7 @@ export default function OrgContact({ org, accent }: { org: OrganizationRecord; a style={{ background: accent }} > + {link.label} ))} @@ -51,6 +61,7 @@ export default function OrgContact({ org, accent }: { org: OrganizationRecord; a style={{ borderColor: accent, color: accentText(accent) }} > + {link.label} ))} diff --git a/src/components/PeopleTiles.tsx b/src/components/PeopleTiles.tsx index 33321e1..a435261 100644 --- a/src/components/PeopleTiles.tsx +++ b/src/components/PeopleTiles.tsx @@ -18,6 +18,7 @@ import { isBadId, personHref } from "../lib/hrefs.ts"; import { mediaUrl, initials } from "../lib/media.ts"; import { useSmallImage } from "../lib/useSmallImage.ts"; import { paletteFill } from "../lib/color.ts"; +import { useReadingMode } from "../lib/readingMode.ts"; import "./PeopleTiles.css"; /** @@ -71,6 +72,10 @@ import "./PeopleTiles.css"; * with no photo gets their initials on a palette color * (paletteFill in color.ts). * + * Reading mode (readingMode.ts) gets everyone, no "Show all", each + * a heading (linked to their profile) and their title, facts and bio + * as lines (ReadingPeople). + * * Field names follow the API (is_owner, location_label), so a row * from /api/teams/:id/people drops in unchanged. * @@ -122,7 +127,8 @@ export interface PeopleGroupInput extends Omit { export interface TeamSpec { id: string; - /** Heading for the members group. Defaults to the team's name. */ + /** Heading for the members group beside a lead group, or among + * several teams. Defaults to the team's name. */ label?: string; /** Heading for the lead group. Defaults to the lead's own title. */ leadLabel?: string; @@ -146,6 +152,9 @@ export interface PeopleTilesProps align?: "start" | "center"; accent?: string; tilt?: boolean; + /** The group labels' heading level, by what they sit under (3 under + * a section's h2). In reading mode the names are one level under. */ + headingLevel?: 3 | 4 | 5; /** How long a fetched team or person is reused, in ms. */ ttl?: number; emptyMessage?: string; @@ -372,8 +381,10 @@ function buildTeamGroups( return [ { id: data.team.id, - // One unlabeled team needs no heading; several always do. - label: teamCount > 1 || spec.label ? name : undefined, + // One team alone needs no heading (its page or section names + // it); several always do. `label` names the members beside a + // lead group. + label: teamCount > 1 ? name : undefined, accent, people: data.people, }, @@ -408,6 +419,7 @@ export function PeopleTilesView({ accent, tilt = false, emptyMessage = "No one listed yet.", + headingLevel = 3, onExpand, className = "", style, @@ -426,6 +438,7 @@ export function PeopleTilesView({ const [clipped, setClipped] = useState>(() => new Set()); const rootRef = useRef(null); const probeRef = useRef(null); + const reading = useReadingMode(); const resolvedSize: PeopleTilesSize = SIZE_FEATURES[size] ? size : "md"; const features = SIZE_FEATURES[resolvedSize]; @@ -532,6 +545,8 @@ export function PeopleTilesView({ if (!resolvedGroups.length) { return emptyMessage ?

{emptyMessage}

: null; } + if (reading) return ; + const Label = `h${headingLevel}` as "h3"; const open = openKey ? findByKey(resolvedGroups, openKey) : null; const oneRow = @@ -598,7 +613,7 @@ export function PeopleTilesView({ > {(group.label || group.note) && (
- {group.label &&

{group.label}

} + {group.label && } {group.note &&

{group.note}

}
)} @@ -883,6 +898,52 @@ function DetailPanel({ ); } +/* Reading mode: every person and what their details panel says. */ +function ReadingPeople({ groups, level }: { groups: PeopleGroup[]; level: 3 | 4 | 5 }) { + const Label = `h${level}` as "h3"; + return ( +
+ {groups.map((group) => { + // Names sit under the group's label, or take its place. + const Name = `h${group.label ? level + 1 : level}` as "h4"; + return ( +
+ {group.label && } + {group.note &&

{group.note}

} + {group.people.map((person, index) => { + const href = profileHref(person); + const title = titleOf(person); + const org = resolveOrg(person.org); + const bio = Array.isArray(person.bio) ? person.bio : [person.bio]; + return ( +
+ {href ? {person.name} : person.name} + {title &&

{title}

} + {person.pronouns &&

Pronouns: {person.pronouns}

} + {org && ( +

+ Home organization: {org.href ? {org.name} : org.name} +

+ )} + {person.location_label &&

Based in: {person.location_label}

} + {person.public_email && ( +

+ Email: {person.public_email} +

+ )} + {bio.filter(Boolean).map((paragraph, i) => ( +

{paragraph}

+ ))} +
+ ); + })} +
+ ); + })} +
+ ); +} + function Chevron() { return (
); diff --git a/src/pages/NotFound.tsx b/src/pages/NotFound.tsx index 70ae336..2864570 100644 --- a/src/pages/NotFound.tsx +++ b/src/pages/NotFound.tsx @@ -6,7 +6,8 @@ record (GET /directory), scored by suggest.ts against the address. So /organisation offers Organization, /retreat offers Retreats, and an old /chapters/lynnwood offers the Lynnwood group. - Below them, the main pages to start from. + Below them, the main pages to start from, except in reading mode, + whose own line of page links (ReaderView) already gives them. The server sends this same page with a 404 status for an unknown address (routes/pages.js), so search engines drop it. @@ -23,6 +24,7 @@ import { useDirectory, type Directory } from '../lib/useContent.ts' import { blogHref, eventHref, orgHref, personHref, teamHref, awardHref } from '../lib/hrefs.ts' import { suggest, type Candidate } from '../lib/suggest.ts' import { ACCENTS, BRAND } from '../lib/color.ts' +import { useReadingMode } from '../lib/readingMode.ts' const ORG_KIND_LABEL: Record = { national: 'Organization', @@ -64,6 +66,7 @@ export default function NotFound() { const { pathname } = useLocation() const { data: directory, loading } = useDirectory() const matches = useMemo(() => suggest(pathname, candidates(directory ?? null)), [pathname, directory]) + const reading = useReadingMode() return ( ) : (

- Try one of the main pages below, or the menu at the top. + {reading ? 'Try one of the main pages at the top.' : 'Try one of the main pages below, or the menu at the top.'}

)}
), }, - { + ...(reading ? [] : [{ id: 'start', title: 'Start from', accent: ACCENTS.green, @@ -126,7 +129,7 @@ export default function NotFound() { ))}
), - }, + }]), ]} /> ) diff --git a/src/pages/OrganizationDetail.tsx b/src/pages/OrganizationDetail.tsx index 8335141..236c0a2 100644 --- a/src/pages/OrganizationDetail.tsx +++ b/src/pages/OrganizationDetail.tsx @@ -31,6 +31,7 @@ import { mediaUrl } from '../lib/media.ts' import { initialsFor } from '../lib/organizations.ts' import Logo from '../components/Logo.tsx' import { withAlpha, accentText, readableOn, BRAND } from '../lib/color.ts' +import { useReadingMode } from '../lib/readingMode.ts' const BODY = 'var(--color-muted)' @@ -38,6 +39,7 @@ export default function OrganizationDetail() { const { id } = useParams() const { pathname } = useLocation() const { data: org, loading, error, notFound, reload } = useOrganization(id) + const reading = useReadingMode() if (!org) { return ( @@ -143,12 +145,25 @@ export default function OrganizationDetail() { } if (org.awards.length > 0) { + const recipients = (count: number) => + count === 0 ? 'No recipients yet' : `${count} recipient${count === 1 ? '' : 's'}` sections.push({ id: 'awards', title: 'Awards', blurb: `Given by ${org.short_name || org.name}.`, accent, - content: ( + // Reading mode: a card reads as one long link, so each award is + // a line with its name linked. + content: reading ? ( +
    + {org.awards.map((award) => ( +
  • + {award.name} + {award.description && `: ${award.description}`} ({recipients(award.recipient_count)}) +
  • + ))} +
+ ) : (
{org.awards.map((award) => ( )} - {award.recipient_count === 0 - ? 'No recipients yet' - : `${award.recipient_count} recipient${award.recipient_count === 1 ? '' : 's'}`} + {recipients(award.recipient_count)} ))} diff --git a/src/pages/PersonDetail.tsx b/src/pages/PersonDetail.tsx index 8e6e4c5..a9fa9a5 100644 --- a/src/pages/PersonDetail.tsx +++ b/src/pages/PersonDetail.tsx @@ -37,6 +37,7 @@ import { mediaUrl, initials } from '../lib/media.ts' import { eventTypeLabel } from '../lib/eventTypes.ts' import { capitalize } from '../lib/text.ts' import { accentText, BRAND } from '../lib/color.ts' +import { useReadingMode } from '../lib/readingMode.ts' const BODY = 'var(--color-muted)' @@ -205,7 +206,7 @@ export default function PersonDetail() { {(posts) => (
    {posts.map((post) => ( - + ))}
)} @@ -231,7 +232,9 @@ function Capped({ children: (shown: T[]) => ReactNode }) { const [all, setAll] = useState(false) - const more = !all && items.length > SHOW_FIRST + // Reading mode has no button to press: everything shows. + const reading = useReadingMode() + const more = !all && !reading && items.length > SHOW_FIRST return ( <> {children(more ? items.slice(0, SHOW_FIRST) : items)} @@ -253,6 +256,8 @@ function Capped({ function Facts({ person, accent }: { person: PersonRecord; accent: string }) { const photo = mediaUrl(person.photo) + // Each fact reads on a line of its own there, so it says what it is. + const reading = useReadingMode() return (
@@ -274,22 +279,35 @@ function Facts({ person, accent }: { person: PersonRecord; accent: string }) { )} - {person.pronouns && {person.pronouns}} - - {person.org && ( - - {person.org.name} - + {person.pronouns && ( + + {reading && 'Pronouns: '} + {person.pronouns} + )} - {person.location_label && {person.location_label}} + {person.org && ( + + {reading && 'Home organization: '} + + {person.org.name} + + + )} + + {person.location_label && ( + + {reading && 'Based in: '} + {person.location_label} + + )} - Leadership + {reading ? 'All leadership' : 'Leadership'}
) diff --git a/src/pages/TeamDetail.tsx b/src/pages/TeamDetail.tsx index 6b82dcf..3a8659a 100644 --- a/src/pages/TeamDetail.tsx +++ b/src/pages/TeamDetail.tsx @@ -91,7 +91,7 @@ export default function TeamDetail() { sections.push({ id: 'members', - title: hasAbout ? 'Members' : team.name, + title: 'Members', accent, content: (
diff --git a/src/pages/sections/CommunityBlog.tsx b/src/pages/sections/CommunityBlog.tsx index 73da079..ed73083 100644 --- a/src/pages/sections/CommunityBlog.tsx +++ b/src/pages/sections/CommunityBlog.tsx @@ -35,8 +35,12 @@ const DEFAULTS = { const EXCERPT_CHARS = 180 -/* One post as a card; person pages list their posts with it too. */ -export function PostCard({ post, accent }: { post: BlogPostSummary; accent: string }) { +/* One post as a card; person pages list their posts with it too. + `level` is the title's heading level, one under the heading above + the cards. The date line comes after the title in the page, so it + reads as this post's (not the one before), and is drawn above it. */ +export function PostCard({ post, accent, level = 4 }: { post: BlogPostSummary; accent: string; level?: 3 | 4 }) { + const Title = level === 3 ? 'h3' : 'h4' const cover = useSmallImage(mediaUrl(post.cover_image)) const date = postDate(post.published_on) const authors = post.authors.map((author) => author.name).join(', ') @@ -49,19 +53,19 @@ export function PostCard({ post, accent }: { post: BlogPostSummary; accent: stri
)}
- {(date || post.tags.length > 0) && ( -

- {[date, ...post.tags].filter(Boolean).join(' · ')} -

- )} -

+ <Link to={blogHref(post.id)} className="after:absolute after:inset-0 after:content-[''] hover:underline" > {post.title} </Link> - </h4> + + {(date || post.tags.length > 0) && ( +

+ {[date, ...post.tags].filter(Boolean).join(' · ')} +

+ )} {post.excerpt && (

{preview(post.excerpt, EXCERPT_CHARS)}

)} @@ -137,7 +141,7 @@ export default function CommunityBlog({ accent = BRAND }: { accent?: string }) {

{external.cards.length > 0 && (
- +
)}
diff --git a/src/pages/sections/EventList-Cards.tsx b/src/pages/sections/EventList-Cards.tsx index 5d8de43..5d866c9 100644 --- a/src/pages/sections/EventList-Cards.tsx +++ b/src/pages/sections/EventList-Cards.tsx @@ -10,6 +10,7 @@ import { mediaUrl } from "../../lib/media.ts"; import { useSmallImage } from "../../lib/useSmallImage.ts"; import Logo from "../../components/Logo.tsx"; import { accentText, withAlpha, readableOn, BRAND } from '../../lib/color.ts' +import { useReadingMode } from "../../lib/readingMode.ts"; /* ═══════════════════════════════════════════════════════════════ EVENT LIST: CARDS @@ -29,6 +30,10 @@ import { accentText, withAlpha, readableOn, BRAND } from '../../lib/color.ts' off, the band takes every kind it finds and grows a row of chips to narrow by, but only once it holds more than one, so a band of nothing but retreats shows no control at all. + + Reading mode (readingMode.ts) gets every event as the grid lists + them, carousel or not, with every past event shown and no + buttons to open or page through them. ═══════════════════════════════════════════════════════════════ */ @@ -152,6 +157,11 @@ function TitleLink({ ev, linked, children }) { `linked` is the one thing a caller turns off: a card on the event's own page shouldn't link to the page it's already on. + + `level` is the title's heading level, one under the heading the + card sits beneath. In reading mode the type badge (which would + read before the title, as if the last card's) and the "Event + details" link (the title already links there) are left out. ═══════════════════════════════════════════════════════════════ */ export function Card({ ev, @@ -161,7 +171,10 @@ export function Card({ interactive = true, linked = true, showType = false, + level = 3, }) { + const reading = useReadingMode(); + const Title = level === 4 ? "h4" : "h3"; const past = ev.status === "past"; const color = ev.color || defaultColor; const orgLogo = mediaUrl(ev.org_logo) || DEFAULT_ORG_LOGO; @@ -177,7 +190,7 @@ export function Card({ on every card in a row of nothing but retreats is noise, and the card can't tell on its own, it only ever sees one event. */ const typeBadge = - showType && ev.event_type ? ( + showType && ev.event_type && !reading ? (
{typeBadge} -

+ <TitleLink ev={ev} linked={linked}> {ev.title} </TitleLink> - </h3> + {ev.theme && (

"{ev.theme}"

)} @@ -250,11 +263,11 @@ export function Card({
{typeBadge} -

+ <TitleLink ev={ev} linked={linked}> {ev.title} </TitleLink> - </h3> + {ev.theme && (

"{ev.theme}"

)} @@ -338,7 +351,7 @@ export function Card({ )} {/* Last, so Register reads first when there is one. */} - {linked && ( + {linked && !reading && ( setIndex(i => Math.max(0, i - 1)); const next = () => setIndex(i => Math.min(events.length - 1, i + 1)); @@ -595,7 +611,7 @@ export default function EventListCards({ ? empty : `· No ${eventTypeLabel(activeType).toLowerCase()} events in this section yet ·`, ) - ) : view === "grid" ? ( + ) : view === "grid" || reading ? ( /* ── GRID VIEW: upcoming first, past events collapsed below ── */
{upcoming.length > 0 && ( @@ -630,16 +646,16 @@ export default function EventListCards({
{pastDrawn.map(ev => ( ))}
-
- {showPast && pastShown < pastEvents.length && ( + {!reading && ( +
+ {showPast && pastShown < pastEvents.length && ( + + )} - )} - -
+
+ )}
)}

diff --git a/src/pages/sections/OrgList-Card.tsx b/src/pages/sections/OrgList-Card.tsx index b5ceb20..b8d44e5 100644 --- a/src/pages/sections/OrgList-Card.tsx +++ b/src/pages/sections/OrgList-Card.tsx @@ -1,4 +1,5 @@ import { ArrowUpRight } from '@phosphor-icons/react'; +import { Link } from "react-router-dom"; import ArrowLink from "../../components/ArrowLink.tsx"; import OrgLogo from "../../components/OrgLogo.tsx"; import { @@ -7,6 +8,7 @@ import { byName, } from "../../lib/organizations.ts"; import { accentText } from '../../lib/color.ts' +import { useReadingMode } from '../../lib/readingMode.ts' /* ═══════════════════════════════════════════════════════════════ ORGANIZATION LIST: CARDS @@ -33,9 +35,12 @@ const FALLBACK_COLOR = "#3b5456"; const CARD_MIN = "20rem"; const GRID_MAX = "88rem"; -function OrgCard({ org, accent, pageLabel, siteLabel }) { +/* Under a block title the card names are a level below it. */ +function OrgCard({ org, accent, pageLabel, siteLabel, titled }) { const color = org.color || accent; const path = orgPath(org); + const reading = useReadingMode(); + const Name = titled ? "h4" : "h3"; // Tagline first, then where they are. Partners often have one and // not the other, so this is the line that's most likely to say @@ -51,9 +56,9 @@ function OrgCard({ org, accent, pageLabel, siteLabel }) {
-

- {org.name} -

+ + {path ? {org.name} : org.name} + {subtitle && (

{subtitle} @@ -63,8 +68,9 @@ function OrgCard({ org, accent, pageLabel, siteLabel }) { {/* Top-right rather than in the footer: the footer holds outbound links, and the arrow goes somewhere different - in kind, deeper into this site. */} - {path && ( + in kind, deeper into this site. Reading mode has the + name's link and leaves it out. */} + {path && !reading && ( ))}

diff --git a/src/pages/sections/OrgList-Map.tsx b/src/pages/sections/OrgList-Map.tsx index 8ded152..0f5bdeb 100644 --- a/src/pages/sections/OrgList-Map.tsx +++ b/src/pages/sections/OrgList-Map.tsx @@ -1,5 +1,5 @@ import { CaretRight, MagnifyingGlass, X } from '@phosphor-icons/react'; -import { useEffect, useMemo, useRef, useState } from "react"; +import { Fragment, useEffect, useMemo, useRef, useState } from "react"; import { useCommunity } from "../../lib/useCommunity.ts"; import { useOrganization } from "../../lib/useContent.ts"; import { Link } from "react-router-dom"; @@ -9,6 +9,7 @@ import { orgPath } from "../../lib/organizations.ts"; import { AREAS, AREA_NAMES } from "../../data/mapGrid.ts"; import { accentText, readableOn } from '../../lib/color.ts' import { scrollBehavior } from "../../lib/motion.ts"; +import { useReadingMode } from "../../lib/readingMode.ts"; /* ═══════════════════════════════════════════════════════════════ ORGANIZATION LIST: MAP @@ -58,6 +59,7 @@ const GRID_CAP = 12; const US_TITLE = "US Unity Regions"; const INTL_TITLE = "International Unity Regions"; +const ONLINE_TITLE = "Online Unity Regions"; /* ── Body content ────────────────────────────────────────────── A group's description is ordered blocks rather than one @@ -753,6 +755,65 @@ function GroupGrid({ regions, groups, groupsIn, subtextFor, openId, setOpenId }) ); } +/* ═══════════════════════════════════════════════════════════════ + READING MODE + Either view as text: the regions grouped as the list groups them, + each with every one of its groups (no cap, no search), and no map. + ═══════════════════════════════════════════════════════════════ */ + +function ReadingRegions({ domestic, international, virtual, groupsIn, subtextFor }) { + const region = r => { + const path = orgPath(r); + const subtext = subtextFor(r); + const list = groupsIn(r.id); + return ( + +

{path ? {r.name} : r.name}

+ {subtext &&

{subtext}

} + {list.length === 0 ? ( +

No groups yet. Interested in starting one?

+ ) : ( +
    + {list.map(c => ( +
  • + {orgPath(c) ? {c.name} : c.name} + {[c.location_label, c.meets].filter(Boolean).map(part => `, ${part}`).join("")} + {c.website && ( + <> + , Website + + )} + {c.email && ( + <> + , Contact + + )} +
  • + ))} +
+ )} +
+ ); + }; + + return ( + <> + {([ + [US_TITLE, domestic], + [INTL_TITLE, international], + [ONLINE_TITLE, virtual], + ] as [string, any[]][]).map(([title, list]) => + list.length > 0 ? ( + +

{title}

+ {list.map(region)} +
+ ) : null + )} + + ); +} + /* The control for the section heading's action bar. */ export function OrgMapToggle({ view, setView, accent }) { const btn = active => ({ @@ -806,6 +867,7 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) { const [hovered, setHovered] = useState(null); const [openId, setOpenId] = useState(null); // no card open on arrival const [query, setQuery] = useState(""); + const reading = useReadingMode(); // The list scrolls itself to whatever the map or legend points at. const listRef = useRef(null); @@ -936,6 +998,18 @@ export default function OrgListMap({ view = "map", accent = FALLBACK_COLOR }) { ); } + if (reading) { + return shell( + + ); + } + if (view === "grid") { return ( ; } -function OrgRow({ org, pageLabel, siteLabel }) { +function OrgRow({ org, pageLabel, siteLabel, titled }) { const [open, setOpen] = useState(false); const panelId = useId(); + const reading = useReadingMode(); + // Under a block title the names are a level below it. + const Name = titled ? "h4" : "h3"; const color = org.color || FALLBACK_COLOR; const path = orgPath(org); @@ -102,28 +107,36 @@ function OrgRow({ org, pageLabel, siteLabel }) { return (
- + {summary && ( + + {summary} + + )} + + + )}
{org.website && ( @@ -140,7 +153,7 @@ function OrgRow({ org, pageLabel, siteLabel }) { {/* Last in the row, so the arrow lines up down the right edge whether or not a row has an outbound site. */} - {path && ( + {path && !reading && ( )} {orgs.map(org => ( - + ))} ); diff --git a/src/pages/sections/history/TimelineEntry.tsx b/src/pages/sections/history/TimelineEntry.tsx index eff6f4e..422905b 100644 --- a/src/pages/sections/history/TimelineEntry.tsx +++ b/src/pages/sections/history/TimelineEntry.tsx @@ -3,6 +3,7 @@ import { MONTH_LABELS, type PersonRef, type TimelineItem } from '../../../lib/ti import { hrefFor, logoSrc } from '../../../lib/timelineRefs.ts' import { initials, mediaUrl } from '../../../lib/media.ts' import { useSmallImage } from '../../../lib/useSmallImage.ts' +import { useReadingMode } from '../../../lib/readingMode.ts' const KIND_NAMES: Record = { milestone: 'Milestone', @@ -57,6 +58,7 @@ type Props = { export default function TimelineEntry({ item, variant = 'inline' }: Props) { const featured = variant === 'featured' + const reading = useReadingMode() const href = hrefFor(item) const logo = logoSrc(item) @@ -117,6 +119,23 @@ export default function TimelineEntry({ item, variant = 'inline' }: Props) { // An explicit href may point off-site; Link is for in-app routes only. const external = !!href && /^(https?:)?\/\//.test(href) + // Reading mode: the card's link has no heading to carry it, so the + // title would read twice and the date not at all. Plain lines instead. + if (reading) { + const title = !href ? item.title : external ? {item.title} : {item.title} + const facts = [item.precision === 'year' ? '' : fullMarker(item), item.meta].filter(Boolean) + return ( +
  • +

    + {title} + {facts.map((fact) => `, ${fact}`).join('')} +

    + {item.blurb ?

    {item.blurb}

    : null} + {roster} +
  • + ) + } + return (
  • {href && external ? ( diff --git a/src/pages/sections/history/TimelineUpcoming.tsx b/src/pages/sections/history/TimelineUpcoming.tsx index 7f8b52f..3648ade 100644 --- a/src/pages/sections/history/TimelineUpcoming.tsx +++ b/src/pages/sections/history/TimelineUpcoming.tsx @@ -2,6 +2,7 @@ import { CaretDown, CaretUp } from '@phosphor-icons/react' import { useState } from 'react' import type { GroupedYear, SortDirection } from '../../../lib/timeline.ts' import TimelineYear from './TimelineYear.tsx' +import { useReadingMode } from '../../../lib/readingMode.ts' type Props = { years: GroupedYear[] @@ -28,7 +29,11 @@ export default function TimelineUpcoming({ openYears, onToggleYear, }: Props) { - const [open, setOpen] = useState(false) + const [chosen, setOpen] = useState(false) + // Reading mode can't press the button: the list is open, under a + // heading (its years are h4s, like a decade's) in place of it. + const reading = useReadingMode() + const open = chosen || reading if (count === 0) return null return ( @@ -36,22 +41,24 @@ export default function TimelineUpcoming({ className={`site-tl__upcoming${open ? ' site-tl__upcoming--open' : ''}`} aria-label="Upcoming" > - + {reading ?

    Still to come

    : ( + + )} {open ? (
    diff --git a/src/pages/sections/history/TimelineYear.tsx b/src/pages/sections/history/TimelineYear.tsx index 2c3ad84..d8c01d7 100644 --- a/src/pages/sections/history/TimelineYear.tsx +++ b/src/pages/sections/history/TimelineYear.tsx @@ -1,6 +1,7 @@ import type { CSSProperties } from 'react' import type { GroupedYear } from '../../../lib/timeline.ts' import TimelineEntry from './TimelineEntry.tsx' +import { useReadingMode } from '../../../lib/readingMode.ts' /** A solid teal dot per year, its size growing with the year's * entries so the rail reads as a density chart. (A vine or tree @@ -15,8 +16,13 @@ type Props = { onToggle: (year: number) => void } -export default function TimelineYear({ year, open, onToggle }: Props) { +export default function TimelineYear({ year, open: chosen, onToggle }: Props) { + // Reading mode can't open a year, so every year is open, the year a + // heading in place of its button, and an empty year left out. + const reading = useReadingMode() + const open = chosen || reading const empty = year.count === 0 + const MonthLabel = reading ? 'h5' : 'h4' const panelId = `site-tl-year-${year.year}` const className = [ @@ -28,25 +34,31 @@ export default function TimelineYear({ year, open, onToggle }: Props) { .filter(Boolean) .join(' ') + if (reading && empty) return null + return (
    - + {reading ? ( +

    {year.year}

    + ) : ( + + )} {open ? ( empty ? ( @@ -65,7 +77,7 @@ export default function TimelineYear({ year, open, onToggle }: Props) { {year.months.map((month) => (
    -

    {month.label}

    + {month.label}
      {month.items.map((item) => ( @@ -76,7 +88,7 @@ export default function TimelineYear({ year, open, onToggle }: Props) { {year.undated.length > 0 ? (
      -

      Elsewhere in {year.year}

      + Elsewhere in {year.year}
        {year.undated.map((item) => ( diff --git a/src/pages/sections/home/FeaturedTimelineRail.tsx b/src/pages/sections/home/FeaturedTimelineRail.tsx index fa7383a..f032ec1 100644 --- a/src/pages/sections/home/FeaturedTimelineRail.tsx +++ b/src/pages/sections/home/FeaturedTimelineRail.tsx @@ -17,6 +17,9 @@ doesn't open it. Nothing featured, and the section doesn't render at all. + + Reading mode (readingMode.ts) gets the entries as text, oldest + first, each a linked heading with its date and words (ReadingRail). ═══════════════════════════════════════════════════════════════ */ import { ArrowRight, CaretRight, CaretLeft } from '@phosphor-icons/react'; @@ -29,6 +32,7 @@ import { hrefFor, logoSrc } from '../../../lib/timelineRefs.ts' import { MONTH_LABELS, type TimelineItem } from '../../../lib/timeline.ts' import { accentText, BRAND } from '../../../lib/color.ts' import { scrollBehavior } from '../../../lib/motion.ts'; +import { useReadingMode } from '../../../lib/readingMode.ts' const DRAG_SLOP = 6 @@ -43,9 +47,29 @@ export default function FeaturedTimelineRail({ id, title, blurb }: RailProps) { const railRef = useRef(null) const drag = useRef({ x: 0, left: 0, moved: false, active: false }) const [dragging, setDragging] = useState(false) + const reading = useReadingMode() if (!loading && !error && featured.length === 0) return null + if (reading) { + return ( +
        +

        {title}

        + {blurb &&

        {blurb}

        } + {error ? ( +

        Couldn’t load the timeline. {error}

        + ) : loading ? ( +

        Loading the timeline…

        + ) : ( + featured.map((item) => ) + )} +

        + See the full history +

        +
        + ) + } + const step = (direction: number) => { const rail = railRef.current const card = rail?.querySelector('li') @@ -182,6 +206,17 @@ function dateLabel(item: TimelineItem): string { return y } +function ReadingEntry({ item }: { item: TimelineItem }) { + const href = hrefFor(item) + return ( + <> +

        {href ? {item.title} : item.title}

        +

        {[dateLabel(item), item.meta].filter(Boolean).join(', ')}

        + {item.blurb &&

        {item.blurb}

        } + + ) +} + function RailCard({ item, showYear }: { item: TimelineItem; showYear: boolean }) { const href = hrefFor(item) const logo = logoSrc(item) diff --git a/src/pages/sections/home/HeroStage.tsx b/src/pages/sections/home/HeroStage.tsx index 7449e5b..0d13328 100644 --- a/src/pages/sections/home/HeroStage.tsx +++ b/src/pages/sections/home/HeroStage.tsx @@ -32,6 +32,10 @@ `hero` is null while the page config loads or when it failed; the stage still draws, empty, so the page doesn't jump when it arrives. The error itself is shown by Home, not here. + + Reading mode (readingMode.ts) gets it as text (ReadingHero): the + words and buttons, every photo's caption at once (no slideshow), + then the feature as a link, or the event's card. ═══════════════════════════════════════════════════════════════ */ import { ArrowRight, Play, Pause, Star } from '@phosphor-icons/react' @@ -47,6 +51,7 @@ import { livestreamEmbedUrl, videoSource, type VideoSource } from '../../../lib/ import { mediaUrl } from '../../../lib/media.ts' import { prefersLessMotion } from '../../../lib/motion.ts' import { focusOnMount } from '../../../lib/focus.ts' +import { useReadingMode } from '../../../lib/readingMode.ts' import { eventHref } from '../../../lib/hrefs.ts' import { seriesLabel } from '../../../lib/eventSeries.ts' import type { Hero, HeroBackdrop, HeroEvent, HeroFeature, HeroSlide } from '../../../lib/useFrontPage.ts' @@ -73,6 +78,14 @@ export default function HeroStage({ hero }: { hero: Hero | null }) { // Every feature shares a layout: words left, feature right. const beside = feature !== 'none' + if (useReadingMode()) { + return ( +
        + {hero && } +
        + ) + } + return (
        slide.caption) + return ( + <> + {feature === 'none' && hero.eyebrow &&

        {hero.eyebrow}

        } +

        {hero.headline}

        + {hero.subhead &&

        {hero.subhead}

        } + {[hero.primary, hero.secondary].map( + (button) => + button && ( +

        + {button.label} +

        + ), + )} + + {captions.length > 0 && ( +
          + {captions.map((slide, index) => ( +
        • + {slide.link_url ? {slide.caption} : slide.caption} +
        • + ))} +
        + )} + + {feature === 'livestream' && hero.livestream && ( +

        + Live now{hero.livestream.title && `: ${hero.livestream.title}`}.{' '} + Watch live +

        + )} + + {feature === 'video' && hero.video && ( +

        + Featured video:{' '} + {video?.kind === 'file' ? ( + {hero.video.title || 'Watch the video'} + ) : ( + {hero.video.title || 'Watch the video'} + )} +

        + )} + + {feature === 'event' && hero.event && ( + <> +

        Featured event

        + + + )} + + ) +} + /* ── The hero's buttons ────────────────────────────────────────── Both set: one cell in two halves, the primary filled on the left and the secondary clear on the right, split by a slash (the diff --git a/src/pages/sections/home/Pathfinder.tsx b/src/pages/sections/home/Pathfinder.tsx index 21201ae..ae30366 100644 --- a/src/pages/sections/home/Pathfinder.tsx +++ b/src/pages/sections/home/Pathfinder.tsx @@ -19,6 +19,9 @@ paths are a strip of cells along the top, the chosen one filled flat in its accent; under it, the path's blurb and its actions are cells of the same block. + + Reading mode (readingMode.ts) gets every path at once, no tabs: + its label as a heading, its blurb and a list of its actions. ═══════════════════════════════════════════════════════════════ */ import { ArrowRight, ArrowUpRight, BookOpen, Dot, CalendarBlank, ChatCircle, Compass, GraduationCap, HandHeart, Heart, House, MapPin, MusicNotes, Sparkle, Star, Tent, UsersThree, type Icon } from '@phosphor-icons/react' @@ -27,6 +30,7 @@ import { useId, useRef, useState, type CSSProperties, type KeyboardEvent } from import HomeLink, { isExternal } from './HomeLink.tsx' import type { FrontPagePath } from '../../../lib/useFrontPage.ts' import { ACCENTS, accentText, readableOn } from '../../../lib/color.ts' +import { useReadingMode } from '../../../lib/readingMode.ts' type PathfinderProps = { id: string @@ -69,9 +73,33 @@ export default function Pathfinder({ id, title, blurb, paths }: PathfinderProps) const [selected, setSelected] = useState(0) const tabs = useRef>([]) const base = useId().replace(/:/g, '') + const reading = useReadingMode() if (paths.length === 0) return null + if (reading) { + return ( +
        +

        {title}

        + {blurb &&

        {blurb}

        } + {paths.map((option, index) => ( +
        +

        {option.label}

        + {option.blurb &&

        {option.blurb}

        } +
          + {option.actions.map((action, i) => ( +
        • + {action.label} + {action.description && `: ${action.description}`} +
        • + ))} +
        +
        + ))} +
        + ) + } + const path = paths[Math.min(selected, paths.length - 1)] const accent = PATH_ACCENTS[selected % PATH_ACCENTS.length] From 0ed73151565399fbc09aa147ef08ae50f7a350b4 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sat, 3 Oct 2026 22:57:34 -0500 Subject: [PATCH 05/94] People directories, ministries, organization contacts (migrations 062 to 064) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - People tags (062): Data → People tags (Musicians seeded); a person's Directories repeater tags them and their Specialty line shows on their tile. A People directory section preset shows a tag's first 12 and links to its full page, /directory/, with page meta and a sitemap entry. Tiles' details panels show a person's links. - Ministries (063): a new organization kind. A group picks its ministry and its page says "Ministry: ", linked to the ministry's website. Ministries have no public page, list, sitemap or timeline entry, and aren't offered where a record links to its organization. organizations is rebuilt for the kind CHECK. - Organization contacts (064): Data → Contact types; a private Contacts repeater on each organization (editors and up, readRole on a child collection). Tools → Newsletter → Recipients filters them by type, kind, region and published and downloads a Mailchimp CSV. - A trigger refusing a save with a sentence is shown as that message. Co-Authored-By: Claude Opus 5.5 --- docs/updating-data-in-code.md | 13 +- server/src/admin-crud.js | 6 + server/src/admin-schema.js | 19 +- server/src/admin-schema/contactTypes.js | 25 ++ server/src/admin-schema/organizations.js | 19 +- server/src/admin-schema/people.js | 9 + server/src/admin-schema/personTags.js | 24 ++ server/src/admin-schema/sitePages.js | 2 + server/src/migrations/062_people_tags.sql | 89 +++++++ server/src/migrations/063_ministries.sql | 114 +++++++++ server/src/migrations/064_org_contacts.sql | 38 +++ server/src/pageMeta.js | 29 ++- server/src/routes/admin-entities.js | 10 +- server/src/routes/admin.js | 51 ++++ server/src/routes/content.js | 17 +- server/src/routes/directory.js | 2 +- server/src/routes/history.js | 2 + server/src/routes/people.js | 53 ++++- server/src/routes/sitePages.js | 2 +- src/App.tsx | 2 + src/components/PeopleTiles.css | 13 + src/components/PeopleTiles.tsx | 34 ++- src/components/admin/NewsletterRecipients.tsx | 222 ++++++++++++++++++ src/lib/adminSchema.ts | 4 + src/lib/adminSchema/contactTypes.ts | 32 +++ src/lib/adminSchema/organizations.ts | 33 ++- src/lib/adminSchema/people.ts | 24 ++ src/lib/adminSchema/personTags.ts | 35 +++ src/lib/adminSchema/sitePages.ts | 20 +- src/lib/useContent.ts | 3 + src/lib/useDirectory.ts | 19 ++ src/lib/useSitePages.ts | 2 + src/pages/DirectoryPage.tsx | 50 ++++ src/pages/OrganizationDetail.tsx | 19 ++ src/pages/SitePage.tsx | 5 + src/pages/admin/AdminNewsletter.tsx | 6 + src/pages/admin/adminNav.ts | 10 + src/pages/sections/PeopleDirectory.tsx | 80 +++++++ 38 files changed, 1108 insertions(+), 29 deletions(-) create mode 100644 server/src/admin-schema/contactTypes.js create mode 100644 server/src/admin-schema/personTags.js create mode 100644 server/src/migrations/062_people_tags.sql create mode 100644 server/src/migrations/063_ministries.sql create mode 100644 server/src/migrations/064_org_contacts.sql create mode 100644 src/components/admin/NewsletterRecipients.tsx create mode 100644 src/lib/adminSchema/contactTypes.ts create mode 100644 src/lib/adminSchema/personTags.ts create mode 100644 src/lib/useDirectory.ts create mode 100644 src/pages/DirectoryPage.tsx create mode 100644 src/pages/sections/PeopleDirectory.tsx diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 93da289..6800fbd 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -28,9 +28,10 @@ what a dropdown in the admin editor says. | If it's… | It lives in… | Change it by… | | ------------------------------------------------------------ | ---------------- | ------------------------------------ | | A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin | +| People tags (directories, eg. Musicians, at `/directory/`) and contact types (Minister, General info), and organizations' contacts | the database | Admin → Data → People tags, Contact types; who carries a tag is set on the person, contacts on the organization | | The front page's words, photos, bands, stats and paths | the database | Admin → Pages → Front page | | Blog posts, and the Community page's blog settings (headings, pins, feeds) | the database | Admin → Data → Blog posts, and Admin → Pages → Community | -| The sections of Retreats, Community, Resources, Organization and History: titles, blurbs, accents, their content blocks and presets (the blog, groups map, regions, partners, events, timeline) | the database | Admin → Pages → the page. A section title is 30 characters at most (it's listed in the side nav); a front page heading fits about 60. Preset names: `PRESETS` in `src/lib/adminSchema/sitePages.ts`, what each draws: `PRESETS` in `src/pages/SitePage.tsx` | +| The sections of Retreats, Community, Resources, Organization and History: titles, blurbs, accents, their content blocks and presets (the blog, groups map, regions, partners, events, timeline, a people directory) | the database | Admin → Pages → the page. A section title is 30 characters at most (it's listed in the side nav); a front page heading fits about 60. Preset names: `PRESETS` in `src/lib/adminSchema/sitePages.ts`, what each draws: `PRESETS` in `src/pages/SitePage.tsx` | | The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | | The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | | Navigation, colors, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | @@ -166,7 +167,7 @@ also in `server/src/admin-schema/` and a CHECK): | Entity → field | Stored values | Labeled? | Also used on the public site by | | --- | --- | --- | --- | -| Organizations → Kind (+ list filter) | national, region, group, partner | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses) | +| Organizations → Kind (+ list filter) | national, region, group, partner, ministry | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses). A ministry has no page or list on the public site (the public routes, `pageMeta.js` and the sitemap leave it out, `ORG_KINDS` in `server/src/routes/content.js` doesn't take it); only its groups name it. `KINDS` in `src/components/admin/NewsletterRecipients.tsx` (the export's filter) lists every kind too. | | Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it | | Organizations → Region areas → Edge | top, bottom | no | the group map (`OrgList-Map.tsx`) | | Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) | @@ -188,6 +189,7 @@ also in `server/src/admin-schema/` and a CHECK): | Front page → Stats → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` | `STAT_QUERIES` in `server/src/routes/home.js`; see [below](#front-page-stat-sources) | | Front page → Featured cards → Card type (Community → Community blog: pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | | Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` | +| Pages → Sections → Preset | community_blog, group_map, region_list, partner_list, events, timeline, people_directory | **yes**, `PRESETS` in `src/lib/adminSchema/sitePages.ts` (which pages offer which, the list passed to each `sitePage`) | `PRESETS` in `src/pages/SitePage.tsx`. A People directory shows its tag's first `DIRECTORY_PREVIEW` people (`src/pages/sections/PeopleDirectory.tsx`), linking to `/directory/`. | | Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a | "No, shows values" means the dropdown currently shows the raw value, @@ -199,11 +201,14 @@ code): | Dropdown | `optionsFrom` | Comes from | | --- | --- | --- | | Group → Region | `regions` | organizations of kind region | +| Group → Ministry | `ministries` | organizations of kind ministry | +| People → Directories → Tag; Pages → Sections → Directory: tag | `person_tag_types` | Data → People tags | +| Organizations → Contacts → Type | `contact_types` | Data → Contact types | | Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) | -| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labeled by name | +| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labeled by name, except ministries (they have no page to link to) | | Event hosts / event people / team members / timeline people → Person | `people` | people | | Community → Community blog: pinned posts (ours) → Post | `blog_posts` | blog posts, newest first | -| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it | +| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization (but ministries), award, person and team, narrowed by the type picked beside it | | Affiliations → Team | `teams` | teams, filtered to the chosen organization | | Person awards → Award | `awards` | awards, labeled "Award (Organization)" | | Person awards → Presented at; Front page → Count down to; Front page → Featured event | `events` | events | diff --git a/server/src/admin-crud.js b/server/src/admin-crud.js index baaa667..c1c0461 100644 --- a/server/src/admin-crud.js +++ b/server/src/admin-crud.js @@ -669,6 +669,12 @@ function wrapDbErrors(fn) { ); } + // A trigger that refuses with a sentence (RAISE(ABORT, 'A group's + // ministry must be a ministry.')) is its own message. + if (err.errcode === 1811 && /\s/.test(message) && /[.!?]$/.test(message)) { + throw new HttpError(422, message); + } + throw err; } } diff --git a/server/src/admin-schema.js b/server/src/admin-schema.js index 5bca3db..eb89bc1 100644 --- a/server/src/admin-schema.js +++ b/server/src/admin-schema.js @@ -16,7 +16,9 @@ extensions 1:1 side tables, optionally gated on a column value (organizations.kind decides whether a regions or groups row should exist) - children ordered collections, replaced wholesale on save + children ordered collections, replaced wholesale on save; + `readRole` on one hides it from lesser roles, as + on an extension (an organization's contacts) singleton the one id this entity ever has; the engine refuses create and delete (see front_page) check (db, id) => void, run after a save has written @@ -52,6 +54,8 @@ import { frontPage } from "./admin-schema/frontPage.js"; import { blogPosts } from "./admin-schema/blog.js"; import { siteSettings } from "./admin-schema/siteSettings.js"; import { newsletters } from "./admin-schema/newsletters.js"; +import { personTagTypes } from "./admin-schema/personTags.js"; +import { contactTypes } from "./admin-schema/contactTypes.js"; import { communityPage, retreatsPage, @@ -64,6 +68,8 @@ export const ENTITIES = { organizations, events, people, + person_tag_types: personTagTypes, + contact_types: contactTypes, teams, awards, timeline, @@ -81,13 +87,20 @@ export const ENTITIES = { /* ── Options for the form's select inputs ────────────────────── */ export const OPTION_QUERIES = { + // Ministries have no public page (063_ministries.sql), so nothing + // that links to its organization can pick one; a group picks its + // ministry from `ministries`. organizations: - "SELECT id, name AS label, kind FROM organizations ORDER BY kind, name", + "SELECT id, name AS label, kind FROM organizations WHERE kind <> 'ministry' ORDER BY kind, name", regions: "SELECT id, name AS label FROM organizations WHERE kind = 'region' ORDER BY name", + ministries: + "SELECT id, name AS label FROM organizations WHERE kind = 'ministry' ORDER BY name", event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order", events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title", people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name", + person_tag_types: "SELECT id, name AS label FROM person_tag_types ORDER BY sort_order, name", + contact_types: "SELECT id, name AS label FROM contact_types ORDER BY sort_order, name", blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title", // org_id rides along so the affiliation row can filter the list @@ -103,7 +116,7 @@ export const OPTION_QUERIES = { record_refs: ` SELECT 'event' AS kind, id, title AS label FROM events UNION ALL - SELECT 'organization', id, name || ' (' || kind || ')' FROM organizations + SELECT 'organization', id, name || ' (' || kind || ')' FROM organizations WHERE kind <> 'ministry' UNION ALL SELECT 'award', id, name FROM awards UNION ALL diff --git a/server/src/admin-schema/contactTypes.js b/server/src/admin-schema/contactTypes.js new file mode 100644 index 0000000..8df732a --- /dev/null +++ b/server/src/admin-schema/contactTypes.js @@ -0,0 +1,25 @@ +import { text, int } from "./columns.js"; + +/* ── Contact types (064_org_contacts.sql) ──────────────────────── + + The roles an organization's contacts hold (Minister, General + info...), made in the admin. Its own entity, not a repeater, + because organization_contacts points at it; a type still in use + can't be deleted. The contacts themselves are edited on the + organization. */ + +export const contactTypes = { + key: "contact_types", + table: "contact_types", + idColumn: "id", + idKind: "slug", + + list: { + columns: ["id", "name", "sort_order"], + filters: [], + search: ["name", "id"], + order: "sort_order, name", + }, + + columns: [text("name", { required: true }), int("sort_order")], +}; diff --git a/server/src/admin-schema/organizations.js b/server/src/admin-schema/organizations.js index 2fdc388..8f19d14 100644 --- a/server/src/admin-schema/organizations.js +++ b/server/src/admin-schema/organizations.js @@ -28,7 +28,7 @@ export const organizations = { }, columns: [ - enumeration("kind", ["national", "region", "group", "partner"], { + enumeration("kind", ["national", "region", "group", "partner", "ministry"], { required: true, }), text("name", { required: true }), @@ -62,13 +62,28 @@ export const organizations = { table: "groups", idColumn: "id", when: { column: "kind", value: "group" }, - columns: [text("region_id"), text("meets"), text("started")], + columns: [text("region_id"), text("ministry_id"), text("meets"), text("started")], }, ], children: [ linksChild("organization"), blocksChild("organization"), + // Who to write to there, by role (064_org_contacts.sql): private, + // for the Newsletter's recipient export. + { + key: "contacts", + table: "organization_contacts", + owner: { column: "org_id" }, + order: "sort_order", + readRole: "editor", + columns: [ + text("type_id", { required: true }), + text("name"), + text("email"), + text("phone"), + ], + }, { key: "region_areas", table: "region_areas", diff --git a/server/src/admin-schema/people.js b/server/src/admin-schema/people.js index 32cb15e..32a3b48 100644 --- a/server/src/admin-schema/people.js +++ b/server/src/admin-schema/people.js @@ -30,6 +30,7 @@ export const people = { text("sort_name"), text("pronouns"), text("tagline"), + text("specialty"), text("photo"), text("bio"), text("primary_org_id"), @@ -61,6 +62,14 @@ export const people = { ], children: [ + // The directories they're in (person_tag_types). + { + key: "tags", + table: "person_tags", + owner: { column: "person_id" }, + order: "sort_order", + columns: [text("tag_id", { required: true })], + }, linksChild("person"), blocksChild("person"), { diff --git a/server/src/admin-schema/personTags.js b/server/src/admin-schema/personTags.js new file mode 100644 index 0000000..8bf1dca --- /dev/null +++ b/server/src/admin-schema/personTags.js @@ -0,0 +1,24 @@ +import { text, int } from "./columns.js"; + +/* ── People tags (062_people_tags.sql) ─────────────────────────── + + What a person can be tagged as for a directory (Musicians first). + Its own entity, not a repeater, because person_tags points at it: + deleting a tag takes its rows on people with it (cascade). Which + people carry a tag is edited on the person. */ + +export const personTagTypes = { + key: "person_tag_types", + table: "person_tag_types", + idColumn: "id", + idKind: "slug", + + list: { + columns: ["id", "name", "blurb", "sort_order"], + filters: [], + search: ["name", "id"], + order: "sort_order, name", + }, + + columns: [text("name", { required: true }), text("blurb"), int("sort_order")], +}; diff --git a/server/src/admin-schema/sitePages.js b/server/src/admin-schema/sitePages.js index d8c57e0..0a79f2d 100644 --- a/server/src/admin-schema/sitePages.js +++ b/server/src/admin-schema/sitePages.js @@ -30,10 +30,12 @@ const sectionsChild = { "partner_list", "events", "timeline", + "people_directory", ]), text("scope_id"), enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]), enumeration("view", ["carousel", "grid", "map"]), + text("tag_id"), ], children: [blocksChild("page_section")], }; diff --git a/server/src/migrations/062_people_tags.sql b/server/src/migrations/062_people_tags.sql new file mode 100644 index 0000000..9728d0c --- /dev/null +++ b/server/src/migrations/062_people_tags.sql @@ -0,0 +1,89 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 062 PEOPLE TAGS AND THE PEOPLE DIRECTORY +-- +-- A tag marks people for a directory, rather than making a team of +-- them: Musician first, more (Speakers, Teachers) added in the admin +-- (Data → People tags) with no code. +-- +-- person_tag_types the tags: a name, the full directory page's +-- intro (/directory/) and their order +-- person_tags which people carry which tags; a person's +-- own repeater, so deleting a tag takes its +-- rows with it (cascade) +-- people.specialty one line shown in a directory, eg. "Vocals, +-- piano · Gospel, folk" +-- page_sections a 'people_directory' preset drawing one tag's +-- people (tag_id), a short list linking to the +-- full page; rebuilt for the preset CHECK as 058 +-- did, then its index and trigger again +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE person_tag_types ( + id TEXT PRIMARY KEY + CONSTRAINT "A tag's URL ID can use only lowercase letters, numbers and hyphens, eg. musician." + CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'), + name TEXT NOT NULL, -- 'Musicians', the directory's title + blurb TEXT, -- the full directory page's intro + sort_order INTEGER NOT NULL DEFAULT 0 +) STRICT; + +INSERT INTO person_tag_types (id, name, blurb, sort_order) VALUES + ('musician', 'Musicians', 'Musicians in the NGU community, for services, retreats and events.', 0); + +CREATE TABLE person_tags ( + person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE, + tag_id TEXT NOT NULL REFERENCES person_tag_types (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (person_id, tag_id) +) STRICT; + +CREATE INDEX person_tags_tag_idx ON person_tags (tag_id); + +ALTER TABLE people ADD COLUMN specialty TEXT; + + +-- ── page_sections: the directory preset ──────────────────────── + +CREATE TABLE page_sections_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + page_id TEXT NOT NULL REFERENCES site_pages (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + anchor TEXT NOT NULL + CONSTRAINT "A section's URL ID can use only lowercase letters, numbers and hyphens, eg. leadership." + CHECK (anchor <> '' AND anchor NOT GLOB '*[^a-z0-9-]*'), + title TEXT NOT NULL + CONSTRAINT "A section title can be 30 characters at most (it's listed in the page's side nav)." + CHECK (length(title) <= 30), + blurb TEXT, + accent TEXT CHECK (accent IN ('teal', 'deep', 'green', 'amber')), + preset TEXT CHECK (preset IN ('community_blog', 'group_map', 'region_list', 'partner_list', + 'events', 'timeline', 'people_directory')), + -- An events preset's filter and first view. + scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL, + event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')), + view TEXT CHECK (view IN ('carousel', 'grid', 'map')), + -- A people_directory preset's tag. + tag_id TEXT REFERENCES person_tag_types (id) ON DELETE SET NULL, + UNIQUE (page_id, anchor) +) STRICT; + +INSERT INTO page_sections_new + (id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view) +SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view + FROM page_sections; + +PRAGMA legacy_alter_table = ON; +DROP TABLE page_sections; +ALTER TABLE page_sections_new RENAME TO page_sections; +PRAGMA legacy_alter_table = OFF; + +CREATE INDEX page_sections_page_idx ON page_sections (page_id, sort_order); + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER page_sections_cleanup +AFTER DELETE ON page_sections +BEGIN + DELETE FROM content_blocks WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT); +END; diff --git a/server/src/migrations/063_ministries.sql b/server/src/migrations/063_ministries.sql new file mode 100644 index 0000000..1f32099 --- /dev/null +++ b/server/src/migrations/063_ministries.sql @@ -0,0 +1,114 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 063 MINISTRIES +-- +-- A Unity ministry (a church) is an organization of its own kind, so +-- the list of them is kept here and an NGU group can name the one it +-- belongs to. Ministries have no page and no list on the public site: +-- a group's page says "Ministry: ", linked to the ministry's +-- website when it has one. +-- +-- organizations.kind gains 'ministry' (the CHECK changes, so the +-- table is rebuilt as 052 did, then its indexes +-- and triggers again) +-- groups.ministry_id the group's ministry, cleared if the ministry +-- is deleted; the trigger below keeps it to +-- ministries +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE organizations_new ( + id TEXT PRIMARY KEY, -- slug: 'northwest', 'lynnwood' + kind TEXT NOT NULL + CHECK (kind IN ('national', 'region', 'group', 'partner', 'ministry')), + + name TEXT NOT NULL, + short_name TEXT, + tagline TEXT, -- one line, for the card + color TEXT, + logo TEXT, -- an upload's filename + + venue TEXT, + address TEXT, + locality TEXT, + state_code TEXT, -- US only + country TEXT NOT NULL DEFAULT 'US', + location_label TEXT, + latitude REAL, + longitude REAL, + is_online INTEGER NOT NULL DEFAULT 0 CHECK (is_online IN (0, 1)), + + is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)), + sort_order INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + in_timeline INTEGER NOT NULL DEFAULT 0 CHECK (in_timeline IN (0, 1)), + is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1)) +) STRICT; + +INSERT INTO organizations_new + (id, kind, name, short_name, tagline, color, logo, + venue, address, locality, state_code, country, location_label, + latitude, longitude, is_online, + is_published, sort_order, created_at, updated_at, in_timeline, is_listed) +SELECT id, kind, name, short_name, tagline, color, logo, + venue, address, locality, state_code, country, location_label, + latitude, longitude, is_online, + is_published, sort_order, created_at, updated_at, in_timeline, is_listed + FROM organizations; + +PRAGMA legacy_alter_table = ON; +DROP TABLE organizations; +ALTER TABLE organizations_new RENAME TO organizations; +PRAGMA legacy_alter_table = OFF; + +CREATE INDEX organizations_kind_idx ON organizations (kind, is_published, sort_order); +CREATE INDEX organizations_state_idx ON organizations (state_code); + + +-- ── groups.ministry_id ───────────────────────────────────────── + +ALTER TABLE groups ADD COLUMN ministry_id TEXT REFERENCES organizations (id) ON DELETE SET NULL; + + +-- ── Triggers last (see CLAUDE.md, Migrations) ── + +CREATE TRIGGER organizations_cleanup +AFTER DELETE ON organizations +BEGIN + DELETE FROM content_blocks WHERE owner_kind = 'organization' AND owner_id = old.id; + DELETE FROM links WHERE owner_kind = 'organization' AND owner_id = old.id; +END; + +CREATE TRIGGER timeline_organizations_cleanup +AFTER DELETE ON organizations +BEGIN + DELETE FROM timeline_entries WHERE ref_kind = 'organization' AND ref_id = old.id; +END; + +CREATE TRIGGER organizations_featured_cleanup +AFTER DELETE ON organizations +BEGIN + DELETE FROM featured_cards WHERE ref_kind = 'organization' AND ref_id = old.id; +END; + +CREATE TRIGGER organizations_touch +AFTER UPDATE ON organizations +FOR EACH ROW WHEN new.updated_at = old.updated_at +BEGIN + UPDATE organizations SET updated_at = datetime('now') WHERE id = new.id; +END; + +CREATE TRIGGER groups_ministry_kind +BEFORE INSERT ON groups +FOR EACH ROW WHEN new.ministry_id IS NOT NULL + AND (SELECT kind FROM organizations WHERE id = new.ministry_id) IS NOT 'ministry' +BEGIN + SELECT RAISE(ABORT, 'A group''s ministry must be a ministry.'); +END; + +CREATE TRIGGER groups_ministry_kind_update +BEFORE UPDATE OF ministry_id ON groups +FOR EACH ROW WHEN new.ministry_id IS NOT NULL + AND (SELECT kind FROM organizations WHERE id = new.ministry_id) IS NOT 'ministry' +BEGIN + SELECT RAISE(ABORT, 'A group''s ministry must be a ministry.'); +END; diff --git a/server/src/migrations/064_org_contacts.sql b/server/src/migrations/064_org_contacts.sql new file mode 100644 index 0000000..21ca21a --- /dev/null +++ b/server/src/migrations/064_org_contacts.sql @@ -0,0 +1,38 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 064 ORGANIZATION CONTACTS +-- +-- Who to write to at an organization, by role, so a mailing list can +-- be exported (Tools → Newsletter → Recipients) filtered by role, +-- kind and region. Private: never sent to the public site. +-- +-- contact_types the roles, made in the admin (Data → +-- Contact types), eg. Minister, General +-- info; none are seeded +-- organization_contacts an organization's contacts, each with a +-- role; its own repeater on the organization. +-- A role still in use can't be deleted (the +-- foreign key refuses it) +-- ═══════════════════════════════════════════════════════════════ + +CREATE TABLE contact_types ( + id TEXT PRIMARY KEY + CONSTRAINT "A contact type's URL ID can use only lowercase letters, numbers and hyphens, eg. minister." + CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'), + name TEXT NOT NULL, -- 'Minister' + sort_order INTEGER NOT NULL DEFAULT 0 +) STRICT; + +CREATE TABLE organization_contacts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + org_id TEXT NOT NULL REFERENCES organizations (id) ON DELETE CASCADE, + sort_order INTEGER NOT NULL DEFAULT 0, + type_id TEXT NOT NULL REFERENCES contact_types (id), + name TEXT, + email TEXT, + phone TEXT, + CONSTRAINT "A contact needs an email or a phone number." + CHECK (email IS NOT NULL OR phone IS NOT NULL) +) STRICT; + +CREATE INDEX organization_contacts_org_idx ON organization_contacts (org_id, sort_order); +CREATE INDEX organization_contacts_type_idx ON organization_contacts (type_id); diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js index 65ff79d..3fbe257 100644 --- a/server/src/pageMeta.js +++ b/server/src/pageMeta.js @@ -252,8 +252,9 @@ function eventMeta(site, db, id, meta) { function organizationMeta(site, db, id, kind, meta) { const row = db.prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1`).get(id); // /regions/x must be a region: the same slug under the wrong route - // is a page the site doesn't have. - if (!row || (kind && row.kind !== kind)) return notFound(meta); + // is a page the site doesn't have. A ministry has no page at all + // (063_ministries.sql). + if (!row || (kind && row.kind !== kind) || row.kind === "ministry") return notFound(meta); return { ...meta, title: titled(site, row.name), @@ -307,6 +308,17 @@ function personMeta(site, db, id, meta) { }; } +/* A people tag's directory (062_people_tags.sql), /directory/:id. */ +function directoryMeta(site, db, id, meta) { + const row = db.prepare(`SELECT * FROM person_tag_types WHERE id = ?`).get(id); + if (!row) return notFound(meta); + return { + ...meta, + title: titled(site, row.name), + description: plainText(row.blurb) ?? meta.description, + }; +} + function blogMeta(site, db, id, meta) { const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id); if (!row) return notFound(meta); @@ -388,7 +400,7 @@ export function metaFor(db, rawPath) { return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description }; } - const match = pathname.match(/^\/(events|regions|groups|partners|organizations|teams|awards|people|blog)\/([^/]+)$/); + const match = pathname.match(/^\/(events|regions|groups|partners|organizations|teams|awards|people|blog|directory)\/([^/]+)$/); if (!match) return notFound(meta); const [, base, rawId] = match; @@ -418,6 +430,8 @@ export function metaFor(db, rawPath) { return personMeta(site, db, id, meta); case "blog": return blogMeta(site, db, id, meta); + case "directory": + return directoryMeta(site, db, id, meta); } return notFound(meta); } @@ -522,7 +536,10 @@ export function sitemap(db) { .all() .map((r) => ({ loc: `/events/${r.id}`, lastmod: day(r.updated_at) })), ...db - .prepare(`SELECT id, kind, updated_at FROM organizations WHERE is_published = 1 AND is_listed = 1`) + .prepare( + `SELECT id, kind, updated_at FROM organizations + WHERE is_published = 1 AND is_listed = 1 AND kind <> 'ministry'`, + ) .all() .map((r) => ({ loc: `${ORG_ROUTES[r.kind] ?? "/organizations"}/${r.id}`, lastmod: day(r.updated_at) })), ...db @@ -545,6 +562,10 @@ export function sitemap(db) { .prepare(`SELECT id, updated_at FROM blog_posts WHERE is_published = 1 AND is_listed = 1`) .all() .map((r) => ({ loc: `/blog/${r.id}`, lastmod: day(r.updated_at) })), + ...db + .prepare(`SELECT id FROM person_tag_types`) + .all() + .map((r) => ({ loc: `/directory/${r.id}` })), ]; const xml = entries diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js index f7ff12f..2ead205 100644 --- a/server/src/routes/admin-entities.js +++ b/server/src/routes/admin-entities.js @@ -53,13 +53,17 @@ function entityForWrite(c) { return entity; } -/* An extension can ask for more than a sign-in to be read - (readRole): a person's private details need editor. Blanked on - every row sent back, so a write's reply can't leak it either. */ +/* An extension or a child collection can ask for more than a + sign-in to be read (readRole): a person's private details and an + organization's contacts need editor. Blanked on every row sent + back, so a write's reply can't leak it either. */ function visible(c, entity, row) { for (const ext of entity.extensions ?? []) { if (ext.readRole && !hasRole(c.get("user"), ext.readRole)) row[ext.key] = null; } + for (const child of entity.children ?? []) { + if (child.readRole && !hasRole(c.get("user"), child.readRole)) row[child.key] = []; + } return row; } diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 8962f5f..ecd593d 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -364,4 +364,55 @@ admin.get("/request-files", async (c) => { ); }); +/* ── Contacts for a mailing list (064_org_contacts.sql) ────────── + GET /contacts?types=minister,info&kinds=group®ion=northwest + Every organization contact matching the filters, for the + Newsletter's recipient export (a CSV made in the browser). Each + filter is optional; a region keeps the region itself and the + groups in it. Private, so editors and up only. Unpublished + organizations are left out unless ?unpublished=1. */ +const CONTACT_KINDS = ["national", "region", "group", "partner", "ministry"]; +const listParam = (value) => (value ?? "").split(",").map((v) => v.trim()).filter(Boolean); + +admin.get("/contacts", requireRole("editor"), (c) => { + const db = c.get("db"); + const types = listParam(c.req.query("types")); + const kinds = listParam(c.req.query("kinds")).filter((k) => CONTACT_KINDS.includes(k)); + const region = c.req.query("region") || null; + + const where = []; + const params = []; + if (types.length) { + where.push(`oc.type_id IN (${types.map(() => "?").join(",")})`); + params.push(...types); + } + if (kinds.length) { + where.push(`o.kind IN (${kinds.map(() => "?").join(",")})`); + params.push(...kinds); + } + if (region) { + where.push(`(o.id = ? OR g.region_id = ?)`); + params.push(region, region); + } + if (c.req.query("unpublished") !== "1") where.push(`o.is_published = 1`); + + const rows = db + .prepare( + `SELECT oc.name, oc.email, oc.phone, + ct.id AS type_id, ct.name AS type_name, + o.id AS org_id, o.name AS org_name, o.kind AS org_kind, + r.name AS region_name + FROM organization_contacts oc + JOIN contact_types ct ON ct.id = oc.type_id + JOIN organizations o ON o.id = oc.org_id + LEFT JOIN groups g ON g.id = o.id + LEFT JOIN organizations r ON r.id = COALESCE(g.region_id, CASE o.kind WHEN 'region' THEN o.id END) + ${where.length ? `WHERE ${where.join(" AND ")}` : ""} + ORDER BY o.kind, o.name, ct.sort_order, ct.name, oc.sort_order`, + ) + .all(...params); + + return c.json({ contacts: rows }, 200, NO_STORE); +}); + export default admin; diff --git a/server/src/routes/content.js b/server/src/routes/content.js index 4ec6e7e..d03fdb3 100644 --- a/server/src/routes/content.js +++ b/server/src/routes/content.js @@ -70,6 +70,8 @@ const content = new Hono(); // anything. stale-while-revalidate keeps the page instant while the // refresh happens behind it. +// Kinds with a public page. A ministry (063_ministries.sql) has none: +// it's only named on its groups' pages, so no route here serves one. const ORG_KINDS = ["national", "region", "group", "partner"]; /* ── Loaders ───────────────────────────────────────────────── */ @@ -327,9 +329,14 @@ function attachGroupDetails(db, orgs) { const rows = db .prepare( `SELECT c.id, c.region_id, c.meets, c.started, - r.name AS region_name, r.color AS region_color + r.name AS region_name, r.color AS region_color, + m.name AS ministry_name, + (SELECT url FROM links + WHERE owner_kind = 'organization' AND owner_id = m.id AND kind = 'website' + ORDER BY sort_order LIMIT 1) AS ministry_url FROM groups c LEFT JOIN organizations r ON r.id = c.region_id + LEFT JOIN organizations m ON m.id = c.ministry_id AND m.is_published = 1 WHERE c.id IN (${marks(ids.length)})`, ) .all(...ids); @@ -343,6 +350,10 @@ function attachGroupDetails(db, orgs) { region_id: row.region_id ?? null, region_name: row.region_name ?? null, region_color: row.region_color ?? null, + // The Unity ministry it belongs to: a name, and its website + // when it has one (ministries have no page here). + ministry_name: row.ministry_name ?? null, + ministry_url: row.ministry_url ?? null, meets: row.meets ?? null, started: row.started ?? null, }; @@ -610,7 +621,7 @@ content.get("/organizations", (c) => { const rows = db .prepare( `SELECT * FROM organizations - WHERE is_published = 1 AND is_listed = 1 ${filter} + WHERE is_published = 1 AND is_listed = 1 AND kind <> 'ministry' ${filter} ORDER BY kind, sort_order, name`, ) .all(...kinds); @@ -639,7 +650,7 @@ content.get("/organizations/:id", (c) => { const id = c.req.param("id"); const row = db - .prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1`) + .prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1 AND kind <> 'ministry'`) .get(id); if (!row) return c.json({ error: "No such organization" }, 404); diff --git a/server/src/routes/directory.js b/server/src/routes/directory.js index ced9fa2..1c40e6c 100644 --- a/server/src/routes/directory.js +++ b/server/src/routes/directory.js @@ -48,7 +48,7 @@ directory.get("/directory", (c) => { organizations: all( `SELECT id, name, kind FROM organizations - WHERE is_published = 1 AND is_listed = 1 + WHERE is_published = 1 AND is_listed = 1 AND kind <> 'ministry' ORDER BY kind, name`, ), teams: all( diff --git a/server/src/routes/history.js b/server/src/routes/history.js index 50714f2..c94208a 100644 --- a/server/src/routes/history.js +++ b/server/src/routes/history.js @@ -105,6 +105,8 @@ history.get("/history", (c) => { WHERE is_published = 1 -- A standalone milestone reports null here and is unaffected. AND (ref_is_published IS NULL OR ref_is_published = 1) + -- A ministry has no public page (063_ministries.sql). + AND (org_kind IS NULL OR org_kind <> 'ministry') AND effective_date IS NOT NULL ORDER BY effective_date DESC, sort_order, id`, ) diff --git a/server/src/routes/people.js b/server/src/routes/people.js index dd6bef9..c8172c8 100644 --- a/server/src/routes/people.js +++ b/server/src/routes/people.js @@ -4,6 +4,9 @@ GET /teams/:id/people current public members of a team GET /people?ids=a,b,c named people, any order GET /people/:id one person's page + GET /directories/:tag a tag's directory: its name and + intro, and its published, listed + people with their specialty and links The team route reads v_org_leadership, which already decides who counts as current and public, affiliation still open, marked @@ -21,7 +24,7 @@ import { Hono } from "hono"; -import { asBool, json, loadOwned, marks, paragraphs, splitLinks } from "../shape.js"; +import { asBool, json, loadLinks, loadOwned, marks, paragraphs, splitLinks } from "../shape.js"; import { postsBy } from "./blog.js"; const people = new Hono(); @@ -136,6 +139,54 @@ people.get("/people", (c) => { return json(c, { people: rows.map(shapePerson) }); }); +/* ── A tag's directory ───────────────────────────────────────── + Everyone carrying the tag (062_people_tags.sql), in name order, + each as a tile wants them plus their specialty line and links + (website, music, booking email). Unlisted people stay off it, as + they stay off every list. + ───────────────────────────────────────────────────────────── */ + +people.get("/directories/:tag", (c) => { + const db = c.get("db"); + const tag = db + .prepare(`SELECT id, name, blurb FROM person_tag_types WHERE id = ?`) + .get(c.req.param("tag")); + if (!tag) return c.json({ error: "No such directory." }, 404); + + const rows = db + .prepare( + `SELECT p.id, + p.display_name, + p.pronouns, + p.photo, + p.tagline, + p.specialty, + p.location_label, + p.public_email, + p.bio, + o.id AS primary_org_id, + o.name AS primary_org_name + FROM person_tags t + JOIN people p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1 + LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1 + WHERE t.tag_id = ? + ORDER BY COALESCE(p.sort_name, p.display_name)`, + ) + .all(tag.id); + const links = loadLinks(db, "person", rows.map((row) => row.id)); + + return json(c, { + directory: { + ...tag, + people: rows.map((row) => ({ + ...shapePerson(row), + specialty: row.specialty, + links: links.get(row.id) ?? [], + })), + }, + }); +}); + /* ── One person's page ───────────────────────────────────────── Everything public that points at this person, each list with the same visibility rules its own page applies: a role needs a diff --git a/server/src/routes/sitePages.js b/server/src/routes/sitePages.js index 73c614d..1eb76d7 100644 --- a/server/src/routes/sitePages.js +++ b/server/src/routes/sitePages.js @@ -37,7 +37,7 @@ sitePages.get("/site-pages/:id", (c) => { const rows = db .prepare( - `SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view + `SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, tag_id FROM page_sections WHERE page_id = ? ORDER BY sort_order, id`, ) .all(id); diff --git a/src/App.tsx b/src/App.tsx index 5111b83..af3fa83 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -69,6 +69,7 @@ const TeamDetail = lazyPage(() => import("./pages/TeamDetail.tsx")) const AwardDetail = lazyPage(() => import("./pages/AwardDetail.tsx")) const PersonDetail = lazyPage(() => import("./pages/PersonDetail.tsx")) const BlogPost = lazyPage(() => import("./pages/BlogPost.tsx")) +const DirectoryPage = lazyPage(() => import("./pages/DirectoryPage.tsx")) /*Admin Pages*/ const AdminLayout = lazyPage(() => import("./pages/admin/AdminLayout.tsx")) @@ -100,6 +101,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/PeopleTiles.css b/src/components/PeopleTiles.css index 32f755f..4e54733 100644 --- a/src/components/PeopleTiles.css +++ b/src/components/PeopleTiles.css @@ -396,6 +396,19 @@ text-underline-offset: 2px; } +/* A directory person's links: one per line's worth, wrapping. */ +.pl__links { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.75rem; +} + +.pl__links a { + display: inline-flex; + align-items: center; + gap: 0.3rem; +} + .pl__bio-text { margin: 0; font-size: 0.9375rem; diff --git a/src/components/PeopleTiles.tsx b/src/components/PeopleTiles.tsx index a435261..d0371a7d 100644 --- a/src/components/PeopleTiles.tsx +++ b/src/components/PeopleTiles.tsx @@ -19,6 +19,7 @@ import { mediaUrl, initials } from "../lib/media.ts"; import { useSmallImage } from "../lib/useSmallImage.ts"; import { paletteFill } from "../lib/color.ts"; import { useReadingMode } from "../lib/readingMode.ts"; +import PlatformIcon from "./PlatformIcon.tsx"; import "./PeopleTiles.css"; /** @@ -96,6 +97,8 @@ export interface Person { pronouns?: string | null; location_label?: string | null; public_email?: string | null; + /** Their website, music and social links (a directory's people). */ + links?: PersonLink[] | null; org?: string | { id?: string; name: string; href?: string } | null; bio?: string | string[] | null; accent?: string; @@ -105,6 +108,13 @@ export interface Person { isOwner?: boolean; } +export interface PersonLink { + kind?: string; + platform?: string | null; + label: string; + url: string; +} + /** A person named by slug. Any other field overrides the record. */ export interface PersonRef extends Partial> { peopleslug: string; @@ -881,6 +891,19 @@ function DetailPanel({
    )} + {person.links?.length ? ( +
    +
    Links
    +
    + {person.links.map((link) => ( + + + {link.label} + + ))} +
    +
    + ) : null} {paragraphs.filter(Boolean).map((paragraph, index) => ( @@ -931,6 +954,11 @@ function ReadingPeople({ groups, level }: { groups: PeopleGroup[]; level: 3 | 4 Email: {person.public_email}

    )} + {person.links?.map((link) => ( +

    + {link.label} +

    + ))} {bio.filter(Boolean).map((paragraph, i) => (

    {paragraph}

    ))} @@ -1022,7 +1050,11 @@ function hasDetails(person: Person): boolean { return true; } return Boolean( - person.pronouns || resolveOrg(person.org) || person.location_label || person.public_email, + person.pronouns || + resolveOrg(person.org) || + person.location_label || + person.public_email || + person.links?.length, ); } diff --git a/src/components/admin/NewsletterRecipients.tsx b/src/components/admin/NewsletterRecipients.tsx new file mode 100644 index 0000000..5c27d67 --- /dev/null +++ b/src/components/admin/NewsletterRecipients.tsx @@ -0,0 +1,222 @@ +/* ═══════════════════════════════════════════════════════════════ + NEWSLETTER RECIPIENTS (Tools → Newsletter) + + Organization contacts (064_org_contacts.sql) as a mailing list: + pick contact types, organization kinds and a region, see who + matches, and download a CSV that Mailchimp (or a spreadsheet) + imports. Contacts are added on each organization; their types are + Data → Contact types. Private, so editors and up only (the API + says no to anyone else too: GET /admin/contacts). + ═══════════════════════════════════════════════════════════════ */ + +import { DownloadSimple } from '@phosphor-icons/react' +import { useEffect, useState } from 'react' + +import { get } from '../../lib/api.ts' + +type Option = { id: string; label: string } + +type Contact = { + name: string | null + email: string | null + phone: string | null + type_name: string + org_name: string + org_kind: string + region_name: string | null +} + +/* The organization kinds, as the CHECK on organizations.kind has them. */ +const KINDS: Array<[string, string]> = [ + ['national', 'National'], + ['region', 'Regions'], + ['group', 'Groups'], + ['partner', 'Partners'], + ['ministry', 'Ministries'], +] + +/* How many matches show under the filters; the CSV has them all. */ +const PREVIEW_ROWS = 8 + +const MUTED = 'var(--color-muted)' +const input = + 'border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25' +const button = + 'btn inline-flex items-center gap-2 border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50' + +const toggle = (list: string[], value: string) => + list.includes(value) ? list.filter((v) => v !== value) : [...list, value] + +/* "Jane Q. Doe" → Jane, Q. Doe: Mailchimp's First and Last Name. */ +function splitName(name: string | null): [string, string] { + const parts = (name ?? '').trim().split(/\s+/).filter(Boolean) + return [parts[0] ?? '', parts.slice(1).join(' ')] +} + +const csvCell = (value: string | null) => { + const text = value ?? '' + return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text +} + +function toCsv(rows: Contact[]): string { + const head = ['Email', 'First Name', 'Last Name', 'Phone', 'Organization', 'Kind', 'Region', 'Contact type'] + const lines = rows.map((row) => { + const [first, last] = splitName(row.name) + return [row.email, first, last, row.phone, row.org_name, row.org_kind, row.region_name, row.type_name] + .map(csvCell) + .join(',') + }) + return [head.join(','), ...lines].join('\n') +} + +export default function NewsletterRecipients() { + const [types, setTypes] = useState([]) + const [regions, setRegions] = useState([]) + const [picked, setPicked] = useState([]) + const [kinds, setKinds] = useState([]) + const [region, setRegion] = useState('') + const [unpublished, setUnpublished] = useState(false) + const [contacts, setContacts] = useState(null) + const [error, setError] = useState(null) + + useEffect(() => { + get('/admin/options?only=contact_types,regions', { ttl: 0 }) + .then((data: { options: { contact_types: Option[]; regions: Option[] } }) => { + setTypes(data.options.contact_types) + setRegions(data.options.regions) + }) + .catch((err) => setError(err instanceof Error ? err.message : 'Couldn’t load the contact types.')) + }, []) + + useEffect(() => { + const query = new URLSearchParams() + if (picked.length) query.set('types', picked.join(',')) + if (kinds.length) query.set('kinds', kinds.join(',')) + if (region) query.set('region', region) + if (unpublished) query.set('unpublished', '1') + let live = true + get(`/admin/contacts?${query}`, { ttl: 0 }) + .then((data: { contacts: Contact[] }) => { + if (!live) return + setContacts(data.contacts) + setError(null) + }) + .catch((err) => live && setError(err instanceof Error ? err.message : 'Couldn’t load the contacts.')) + return () => { + live = false + } + }, [picked, kinds, region, unpublished]) + + const withEmail = contacts?.filter((row) => row.email) ?? [] + + function download() { + const blob = new Blob([toCsv(withEmail)], { type: 'text/csv' }) + const link = document.createElement('a') + link.href = URL.createObjectURL(blob) + link.download = `newsletter-recipients-${new Date().toISOString().slice(0, 10)}.csv` + link.click() + URL.revokeObjectURL(link.href) + } + + return ( +
    +

    Recipients

    +

    + Organization contacts as a mailing list. Add contacts on each organization; make their types under Data → Contact + types. Nothing picked in a filter means all of it. +

    + +
    +
    + Contact types + {types.length === 0 && ( +

    + None yet: add them under Data → Contact types. +

    + )} + {types.map((type) => ( + + ))} +
    + +
    + Organization kinds + {KINDS.map(([kind, label]) => ( + + ))} +
    + +
    + +

    + The region itself and the groups in it +

    + +
    +
    + +
    + +

    + {error ?? + (contacts === null + ? 'Loading…' + : `${withEmail.length} with an email` + + (contacts.length > withEmail.length ? ` (${contacts.length - withEmail.length} more have only a phone, left out)` : ''))} +

    +
    + + {withEmail.length > 0 && ( +
    + + + + + + + + + + + {withEmail.slice(0, PREVIEW_ROWS).map((row, index) => ( + + + + + + + ))} + +
    EmailNameOrganizationType
    {row.email}{row.name || '-'}{row.org_name}{row.type_name}
    + {withEmail.length > PREVIEW_ROWS && ( +

    + and {withEmail.length - PREVIEW_ROWS} more in the CSV +

    + )} +
    + )} +
    + ) +} diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts index dc2ed24..ed59ef4 100644 --- a/src/lib/adminSchema.ts +++ b/src/lib/adminSchema.ts @@ -27,6 +27,8 @@ import { timeline } from "./adminSchema/timeline.ts"; import { frontPage } from "./adminSchema/frontPage.ts"; import { blogPosts } from "./adminSchema/blog.ts"; import { siteSettings } from "./adminSchema/siteSettings.ts"; +import { personTagTypes } from "./adminSchema/personTags.ts"; +import { contactTypes } from "./adminSchema/contactTypes.ts"; import { communityPage, retreatsPage, @@ -39,6 +41,8 @@ export const ADMIN_ENTITIES: Record = { organizations, events, people, + person_tag_types: personTagTypes, + contact_types: contactTypes, teams, awards, timeline, diff --git a/src/lib/adminSchema/contactTypes.ts b/src/lib/adminSchema/contactTypes.ts new file mode 100644 index 0000000..dd47e0a --- /dev/null +++ b/src/lib/adminSchema/contactTypes.ts @@ -0,0 +1,32 @@ +/* ── Contact types (064_org_contacts.sql) ──────────────────────── + Data → Contact types: the roles an organization's contacts hold, + eg. Minister, General info. Contacts are added on each + organization; Tools → Newsletter → Recipients exports them by + type. A type still in use can't be deleted. Server side: + server/src/admin-schema/contactTypes.js. */ + +export const contactTypes = { + key: "contact_types", + label: "Contact types", + singular: "contact type", + idLabel: "URL ID", + slugFrom: "name", + + list: { + columns: [ + { key: "name", label: "Name", primary: true }, + { key: "sort_order", label: "Order" }, + ], + filters: [], + }, + + groups: [ + { + legend: "Contact type", + fields: [ + { path: "name", label: "Name", required: true, help: "eg. Minister, General info" }, + { path: "sort_order", label: "Sort order", widget: "number" }, + ], + }, + ], +}; diff --git a/src/lib/adminSchema/organizations.ts b/src/lib/adminSchema/organizations.ts index 71ead47..0459b82 100644 --- a/src/lib/adminSchema/organizations.ts +++ b/src/lib/adminSchema/organizations.ts @@ -20,7 +20,7 @@ export const organizations = { { key: "is_listed", label: "Listed", widget: "bool" }, ], filters: [ - { key: "kind", label: "Kind", options: ["national", "region", "group", "partner"] }, + { key: "kind", label: "Kind", options: ["national", "region", "group", "partner", "ministry"] }, { key: "is_published", label: "Published", options: [["1", "Live"], ["0", "Hidden"]] }, { key: "is_listed", label: "Listed", options: [["1", "Listed"], ["0", "Link only"]] }, ], @@ -34,9 +34,9 @@ export const organizations = { path: "kind", label: "Kind", widget: "select", - options: ["national", "region", "group", "partner"], + options: ["national", "region", "group", "partner", "ministry"], required: true, - help: "Changing this swaps which extra fields apply", + help: "Changing this swaps which extra fields apply. A ministry (a Unity church) has no page; its groups name it", }, { path: "name", label: "Name", required: true }, { path: "short_name", label: "Short name" }, @@ -70,6 +70,14 @@ export const organizations = { optionsFrom: "regions", blankLabel: "Default: none", }, + { + path: "group.ministry_id", + label: "Ministry", + widget: "select", + optionsFrom: "ministries", + blankLabel: "Default: none", + help: "The Unity ministry it belongs to, named on its page (linked to the ministry's website)", + }, { path: "group.meets", label: "Meets", help: "2nd Sundays, 6:00pm" }, { path: "group.started", label: "Started", help: "Since 2021" }, ], @@ -101,6 +109,25 @@ export const organizations = { { path: "note", label: "Note", help: "details to explain why it's half or other note" }, ], }, + { + key: "contacts", + label: "Contacts", + note: + "Private: never on the public site, and only editors and up see them. " + + "Tools → Newsletter → Recipients exports them. Types are made under Data → Contact types.", + addLabel: "Add contact", + title: (row, options) => + [options?.contact_types?.find((t) => t.id === row.type_id)?.label, row.name || row.email] + .filter(Boolean) + .join(" · ") || "New contact", + blank: { type_id: "", name: "", email: "", phone: "" }, + fields: [ + { path: "type_id", label: "Type", widget: "select", optionsFrom: "contact_types", required: true }, + { path: "name", label: "Name" }, + { path: "email", label: "Email", help: "An email or a phone is needed" }, + { path: "phone", label: "Phone" }, + ], + }, linksChild, blocksChild, ], diff --git a/src/lib/adminSchema/people.ts b/src/lib/adminSchema/people.ts index b39fd44..3370d18 100644 --- a/src/lib/adminSchema/people.ts +++ b/src/lib/adminSchema/people.ts @@ -32,6 +32,12 @@ export const people = { { path: "sort_name", label: "Sort name", help: "Doe, Jane" }, { path: "pronouns", label: "Pronouns" }, { path: "tagline", label: "Tagline", full: true }, + { + path: "specialty", + label: "Specialty", + full: true, + help: "One line shown in directories, eg. Vocals, piano · Gospel, folk", + }, { path: "photo", label: "Photo", widget: "image", resolve: mediaUrl, full: true }, { path: "primary_org_id", @@ -80,6 +86,24 @@ export const people = { ], children: [ + { + key: "tags", + label: "Directories", + note: "Tags that list this person in a directory, eg. Musicians. Tags are made under Data → People tags.", + addLabel: "Add tag", + title: (row, options) => + options?.person_tag_types?.find((t) => t.id === row.tag_id)?.label ?? "New tag", + blank: { tag_id: "" }, + fields: [ + { + path: "tag_id", + label: "Tag", + widget: "select", + optionsFrom: "person_tag_types", + required: true, + }, + ], + }, { key: "affiliations", label: "Roles and organizations", diff --git a/src/lib/adminSchema/personTags.ts b/src/lib/adminSchema/personTags.ts new file mode 100644 index 0000000..23552b0 --- /dev/null +++ b/src/lib/adminSchema/personTags.ts @@ -0,0 +1,35 @@ +/* ── People tags (062_people_tags.sql) ─────────────────────────── + Data → People tags: what a person can be tagged as for a + directory (Musicians first). Which people carry a tag is edited on + the person; a page shows a tag's people with the People directory + preset, and every tag has its full page at /directory/. + Server side: server/src/admin-schema/personTags.js. */ + +export const personTagTypes = { + key: "person_tag_types", + label: "People tags", + singular: "tag", + idLabel: "URL ID", + slugFrom: "name", + + list: { + columns: [ + { key: "name", label: "Name", primary: true }, + { key: "blurb", label: "Intro" }, + { key: "sort_order", label: "Order" }, + ], + filters: [], + }, + + groups: [ + { + legend: "Tag", + note: "Its full directory is at /directory/ and its URL ID, eg. /directory/musician.", + fields: [ + { path: "name", label: "Name", required: true, help: "The directory's title, eg. Musicians" }, + { path: "blurb", label: "Intro", widget: "textarea", full: true, help: "A line under the full directory's title" }, + { path: "sort_order", label: "Sort order", widget: "number" }, + ], + }, + ], +}; diff --git a/src/lib/adminSchema/sitePages.ts b/src/lib/adminSchema/sitePages.ts index 73a3c36..ef5006c 100644 --- a/src/lib/adminSchema/sitePages.ts +++ b/src/lib/adminSchema/sitePages.ts @@ -18,6 +18,7 @@ const PRESETS = { partner_list: "Partner organization cards", events: "Event carousel or grid", timeline: "Timeline", + people_directory: "People directory (a tag's people)", }; const ACCENT_OPTIONS = [ @@ -99,6 +100,19 @@ const sectionsChild = (presets: string[]) => ({ }, ] : []), + ...(presets.includes("people_directory") + ? [ + { + path: "tag_id", + label: "Directory: tag", + widget: "select", + optionsFrom: "person_tag_types", + blankLabel: "Default: none (shows nothing)", + help: "Shows the first of its people and links to the full directory", + when: { path: "preset", value: "people_directory" }, + }, + ] + : []), ...(presets.includes("group_map") ? [ { @@ -139,7 +153,7 @@ const sitePage = (id: string, label: string, presets: string[], more: Record + useRecord(detailPath('/directories', id), 'directory') diff --git a/src/lib/useSitePages.ts b/src/lib/useSitePages.ts index 71fbd52..80435ef 100644 --- a/src/lib/useSitePages.ts +++ b/src/lib/useSitePages.ts @@ -15,6 +15,8 @@ export type SitePageSection = { scope_id?: string | null event_type?: string | null view?: string | null + /** A people_directory preset's tag (Data → People tags). */ + tag_id?: string | null blocks: ContentBlock[] } diff --git a/src/pages/DirectoryPage.tsx b/src/pages/DirectoryPage.tsx new file mode 100644 index 0000000..e8363f1 --- /dev/null +++ b/src/pages/DirectoryPage.tsx @@ -0,0 +1,50 @@ +/* ═══════════════════════════════════════════════════════════════ + DIRECTORY PAGE: /directory/:id + + A people tag's full directory (Data → People tags), eg. + /directory/musician: its name and intro, then everyone carrying + the tag (PeopleDirectory, no limit). A page section can show the + first of them with the People directory preset, linking here. + ═══════════════════════════════════════════════════════════════ */ + +import { useParams } from 'react-router-dom' + +import PageShell from '../components/PageShell.tsx' +import PageState from '../components/PageState.tsx' +import PeopleDirectory from './sections/PeopleDirectory.tsx' +import { useDirectory } from '../lib/useDirectory.ts' +import { BRAND } from '../lib/color.ts' + +export default function DirectoryPage() { + const { id } = useParams() + const { data: directory, loading, error, notFound, reload } = useDirectory(id) + + if (!directory) { + return ( + + ) + } + + return ( + , + }, + ]} + /> + ) +} diff --git a/src/pages/OrganizationDetail.tsx b/src/pages/OrganizationDetail.tsx index 236c0a2..eac294a 100644 --- a/src/pages/OrganizationDetail.tsx +++ b/src/pages/OrganizationDetail.tsx @@ -251,6 +251,25 @@ function Facts({ )} + {org.kind === 'group' && org.details.ministry_name && ( + + Ministry:{' '} + {org.details.ministry_url ? ( + + {org.details.ministry_name} + + ) : ( + org.details.ministry_name + )} + + )} + {org.kind === 'group' && org.details.meets && ( Meets {org.details.meets} )} diff --git a/src/pages/SitePage.tsx b/src/pages/SitePage.tsx index 595dbcb..7a826d3 100644 --- a/src/pages/SitePage.tsx +++ b/src/pages/SitePage.tsx @@ -31,6 +31,7 @@ import OrgListCards from './sections/OrgList-Card.tsx' import EventListCards, { EventCardsToggle } from './sections/EventList-Cards.tsx' import CommunityBlog from './sections/CommunityBlog.tsx' import HistoryTimeline from './sections/history/HistoryTimeline.tsx' +import PeopleDirectory, { DIRECTORY_PREVIEW } from './sections/PeopleDirectory.tsx' /* Year the program starts: decades ending before it get the pre-program look on the timeline. */ @@ -84,6 +85,10 @@ const PRESETS: Record Record> }, }), timeline: () => ({ Component: Timeline }), + people_directory: (section) => ({ + Component: PeopleDirectory, + props: { tag: section.tag_id, limit: DIRECTORY_PREVIEW }, + }), } export default function SitePage({ id }: { id: string }) { diff --git a/src/pages/admin/AdminNewsletter.tsx b/src/pages/admin/AdminNewsletter.tsx index 5d83216..0bf8c73 100644 --- a/src/pages/admin/AdminNewsletter.tsx +++ b/src/pages/admin/AdminNewsletter.tsx @@ -14,6 +14,9 @@ unpublished blog post: its blocks and picks as the post's body, opened in the post's editor to finish. + Under it, Recipients exports organization contacts as a mailing + list (NewsletterRecipients.tsx), for editors and up. + Picked blog posts are read from their public pages, so only a post visitors can open makes it in, with its excerpt and cover. Links and images are the live site's (SITE_ORIGIN), since an @@ -30,6 +33,7 @@ import { canDelete, canWrite } from '../../lib/roles.ts' import { slugify } from '../../lib/adminSchema.ts' import { blocksChild, BLOCK_TYPES } from '../../lib/adminSchema/shared.ts' import { Repeater } from '../../components/admin/fields.tsx' +import NewsletterRecipients from '../../components/admin/NewsletterRecipients.tsx' import { useEvents } from '../../lib/eventData.ts' import { useFrontPage, type FeaturedCard } from '../../lib/useFrontPage.ts' import type { BlogPostRecord } from '../../lib/useBlog.ts' @@ -603,6 +607,8 @@ export default function AdminNewsletter() { />
  • + + {canWrite(user) && }
    ) } diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts index b2cff06..a73150d 100644 --- a/src/pages/admin/adminNav.ts +++ b/src/pages/admin/adminNav.ts @@ -60,6 +60,11 @@ export const DATA_NAV = { label: "Organizations", blurb: "The national organization, regions, groups and partners.", }, + { + to: "/admin/contact_types", + label: "Contact types", + blurb: "Roles an organization's contacts hold, eg. Minister. Contacts are added on the organization.", + }, { to: "/admin/teams", label: "Teams", @@ -75,6 +80,11 @@ export const DATA_NAV = { label: "People", blurb: "Bios, contact details, affiliations and awards received.", }, + { + to: "/admin/person_tag_types", + label: "People tags", + blurb: "Directories people can be tagged into, eg. Musicians. Who carries a tag is edited on the person.", + }, { to: "/admin/blog_posts", label: "Blog posts", diff --git a/src/pages/sections/PeopleDirectory.tsx b/src/pages/sections/PeopleDirectory.tsx new file mode 100644 index 0000000..a5a4452 --- /dev/null +++ b/src/pages/sections/PeopleDirectory.tsx @@ -0,0 +1,80 @@ +/* ═══════════════════════════════════════════════════════════════ + PEOPLE DIRECTORY + + A tag's people (Data → People tags, eg. Musicians) as person + tiles: the People directory preset on a page, and the whole list + on the tag's own page (DirectoryPage.tsx, /directory/:id). + + + + Each tile's line under the name is the person's specialty (eg. + "Vocals, piano · Gospel, folk"), or their tagline without one; + their details panel adds their links. With a limit, the first that + many show and a link leads to the full directory. + ═══════════════════════════════════════════════════════════════ */ + +import { ArrowRight } from '@phosphor-icons/react' +import { Link } from 'react-router-dom' + +import { PeopleTilesView } from '../../components/PeopleTiles.tsx' +import { useDirectory } from '../../lib/useDirectory.ts' +import { accentText, BRAND } from '../../lib/color.ts' + +/* How many people a section shows before "See the full directory". */ +export const DIRECTORY_PREVIEW = 12 + +export const directoryHref = (tag: string) => `/directory/${encodeURIComponent(tag)}` + +type PeopleDirectoryProps = { + tag?: string | null + /** Show this many, then a link to the full directory. */ + limit?: number + accent?: string +} + +export default function PeopleDirectory({ tag, limit, accent = BRAND }: PeopleDirectoryProps) { + const { data: directory, loading, error, notFound } = useDirectory(tag ?? undefined) + + if (!tag || notFound) { + return ( +
    +

    · This directory isn’t set up yet ·

    +
    + ) + } + + if (!directory) { + return ( +
    + {error ? ( +

    Couldn’t load the directory. {error}

    + ) : ( + loading &&
    + )} +
    + ) + } + + const people = directory.people.map((person) => ({ ...person, title: person.specialty || person.tagline })) + const shown = limit ? people.slice(0, limit) : people + + return ( +
    + + {limit && people.length > 0 && ( + + {people.length > limit ? `See all ${people.length} ${directory.name.toLowerCase()}` : 'Open the full directory'}{' '} +
    + ) +} From f8f1c42b2e58125ad9450466a44b6329c53fb0a6 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 02:03:50 -0500 Subject: [PATCH 06/94] Version v1.13.0-data Co-Authored-By: Claude Opus 5.5 --- src/lib/version.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/version.ts b/src/lib/version.ts index 63bde40..e8317dd 100644 --- a/src/lib/version.ts +++ b/src/lib/version.ts @@ -7,4 +7,4 @@ box or a build banner can read the same value later. ═══════════════════════════════════════════════════════════════ */ -export const SITE_VERSION = "NGU-Web.v1.12.1-accessibility"; +export const SITE_VERSION = "NGU-Web.v1.13.0-data"; From b8012c75e99c098bd01f5a606870aa25729f0833 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:35:08 -0500 Subject: [PATCH 07/94] Video frame stills for featured cards; newsletter Pick from fix - Image fields take frameFrom/frameWhen: "Frame at" saves a still from the row's YouTube or Facebook link to /uploads/thumbnails/ (POST /api/admin/video-frame, grabFrame in clips.js). Used on video featured cards. - clock/parseClock moved to src/lib/clock.ts, shared with Video clips. - Newsletter: new drafts no longer store source 'events' (the Pick from select's blank choice), which showed as "events no longer exists"; older drafts load it as blank. Co-Authored-By: Claude Opus 5.5 --- docs/video-clips.md | 6 +++ server/src/clips.js | 59 ++++++++++++++++++++++++++- server/src/routes/media.js | 23 ++++++++++- src/components/admin/MediaLibrary.tsx | 54 ++++++++++++++++++++++++ src/components/admin/fields.tsx | 5 ++- src/lib/adminSchema/shared.ts | 4 +- src/lib/clock.ts | 21 ++++++++++ src/pages/admin/AdminClips.tsx | 20 +-------- src/pages/admin/AdminNewsletter.tsx | 5 ++- 9 files changed, 172 insertions(+), 25 deletions(-) create mode 100644 src/lib/clock.ts diff --git a/docs/video-clips.md b/docs/video-clips.md index 3faf4d2..c83f006 100644 --- a/docs/video-clips.md +++ b/docs/video-clips.md @@ -14,6 +14,12 @@ it: **Save to library** and **Save to Drive** on the download itself. It stays on the server to cut clips from either way (until the day's sweep). +The same tools take stills: a video featured card's Image field has +**Frame at** (editors and up), which saves the frame at a typed time to +`/uploads/thumbnails/` (`grabFrame` in `server/src/clips.js`). It +downloads only that frame, outside the queue. A link's own `t=` (eg. +`?t=83`) fills in the time. + Clips queue and run one at a time. A finished clip is deleted from the server once it's downloaded, unless **Save to library** is pressed first, which puts it in the media library as an upload (usable as a featured diff --git a/server/src/clips.js b/server/src/clips.js index 97c71d4..b8fec0e 100644 --- a/server/src/clips.js +++ b/server/src/clips.js @@ -49,7 +49,7 @@ import { spawn } from "node:child_process"; import { randomBytes } from "node:crypto"; -import { access, constants, copyFile, mkdir, readdir, rm, stat } from "node:fs/promises"; +import { access, constants, copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises"; import path from "node:path"; import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js"; @@ -446,6 +446,63 @@ async function cut(db, job) { }); } +/* ── A single frame ──────────────────────────────────────── */ + +/* One frame of a YouTube or Facebook video as a JPEG, for a card's + picture. yt-dlp only finds the stream's address and ffmpeg seeks + in it, so nothing is downloaded but that frame; light enough to + run in the request, outside the queue. */ +export async function grabFrame(sourceUrl, seconds) { + const link = checkSourceUrl(sourceUrl); + if (!Number.isFinite(seconds) || seconds < 0 || seconds > MAX_SOURCE_SECONDS) { + throw new ClipError(400, "That isn't a time in the video."); + } + await mkdir(CLIPS_DIR, { recursive: true }); + const id = `frame-${randomBytes(6).toString("hex")}`; + const out = path.join(CLIPS_DIR, `${id}.jpg`); + const cookies = await cookieArgs(id); + let stream = null; + try { + await run( + YTDLP, + [ + "--ignore-config", + ...cookies.args, + "--js-runtimes", + `node:${process.execPath}`, + "--no-playlist", + "-f", + "bv*[height<=1080]/b[height<=1080]/b", + "--get-url", + "--", + link, + ], + { onLine: (line) => (stream ??= /^https:\/\//.test(line.trim()) ? line.trim() : null) }, + ); + } catch (err) { + if (err instanceof ClipError) throw err; + console.error(`frame ${link}: ${err.message}`); + throw new ClipError(422, "The video couldn't be opened. It may be private or removed."); + } finally { + await cookies.cleanup(); + } + if (!stream) throw new ClipError(422, "The video couldn't be opened. It may be private or removed."); + + try { + // -ss before -i seeks in the stream instead of reading up to it. + await run(FFMPEG, ["-hide_banner", "-loglevel", "error", "-ss", String(seconds), "-i", stream, "-frames:v", "1", "-q:v", "2", "-y", out]); + return await readFile(out); + } catch (err) { + // Past the end, ffmpeg finishes without writing anything. + if (err.code === "ENOENT") throw new ClipError(422, "The video doesn't run that long."); + if (err instanceof ClipError) throw err; + console.error(`frame ${link} at ${seconds}: ${err.message}`); + throw new ClipError(422, "The frame couldn't be taken from the video."); + } finally { + await rm(out, { force: true }); + } +} + let running = false; let dbRef = null; diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 907c924..41e15e0 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -41,6 +41,7 @@ import { store, } from "../media.js"; import { fetchImage, previewLink } from "../linkPreview.js"; +import { ClipError, grabFrame } from "../clips.js"; import { NO_STORE } from "../shape.js"; const media = new Hono(); @@ -204,6 +205,26 @@ media.post("/link-preview", requireRole("editor"), async (c) => { ); }); +/* A frame of a YouTube or Facebook video at `seconds`, saved as a + thumbnail for a video card's picture. */ +media.post("/video-frame", requireRole("editor"), async (c) => { + const user = c.get("user"); + let body; + try { + body = (await c.req.json()) ?? {}; + } catch { + return c.json({ error: "Expected a JSON body." }, 400); + } + const row = await addToLibrary(c.get("db"), await grabFrame(body.url, Number(body.seconds)), { + originalName: `video frame ${Math.floor(Number(body.seconds))}s`, + folder: "thumbnails", + keepOriginal: false, + userId: user.id, + }); + console.log(`video frame ${String(body.url).slice(0, 200)} at ${body.seconds}s by ${user.email}`); + return c.json({ media: shape(row) }, 201, NO_STORE); +}); + /* Every TEXT column of every content table, searched for any of the exact values a record can use to name the file: its /uploads/ path, that path escaped, or (for a file copied in by hand and @@ -273,7 +294,7 @@ media.delete("/media/:id", requireRole("admin"), async (c) => { }); media.onError((err, c) => { - if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE); + if (err instanceof MediaError || err instanceof ClipError) return c.json({ error: err.message }, err.status, NO_STORE); console.error(err); return c.json({ error: "Something went wrong." }, 500); }); diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx index 53308a3..4423916 100644 --- a/src/components/admin/MediaLibrary.tsx +++ b/src/components/admin/MediaLibrary.tsx @@ -44,6 +44,7 @@ import { useLocation } from "react-router-dom"; import { ApiError, get, post, upload } from "../../lib/api.ts"; import { useAuth } from "../../lib/auth.tsx"; +import { clock, parseClock } from "../../lib/clock.ts"; import { canWrite as roleCanWrite } from "../../lib/roles.ts"; import { useSmallImage } from "../../lib/useSmallImage.ts"; @@ -524,6 +525,7 @@ export function ImageInput({ value, resolve, folder, + videoUrl, locked, className, onChange, @@ -533,6 +535,8 @@ export function ImageInput({ resolve?: (file?: string | null) => string | null; /** The field's `folder` (logos for logo fields); default images. */ folder?: string; + /** A video link to take a frame from (the field's `frameFrom`). */ + videoUrl?: string | null; locked: boolean; className: string; onChange: (value: string) => void; @@ -587,6 +591,7 @@ export function ImageInput({ )}
    )} + {editable && videoUrl && }
    {picking && ( @@ -601,6 +606,55 @@ export function ImageInput({ ); } +/* ── Frame from a video ──────────────────────────────────────── */ + +/* A link's own start time (YouTube's t=83 or t=83s), so a link + copied at the moment wanted starts the picker there. */ +function startOf(url: string): number { + try { + const t = new URL(url).searchParams.get("t") ?? ""; + return /^\d+s?$/.test(t) ? parseInt(t, 10) : 0; + } catch { + return 0; + } +} + +function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) { + const [text, setText] = useState(() => clock(startOf(url))); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const timeId = useId(); + const seconds = parseClock(text); + + async function take() { + setBusy(true); + setError(null); + try { + const { media } = await post("/admin/video-frame", { url, seconds }); + onSaved(media.url); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't take that frame."); + } finally { + setBusy(false); + } + } + + return ( +
    + +
    + setText(e.target.value)} placeholder="eg. 1:23" className={className} /> +
    + + {error && {error}} +
    + ); +} + /* ── Link preview field ──────────────────────────────────────── */ /* Fills only what's empty: a title somebody already typed is theirs, diff --git a/src/components/admin/fields.tsx b/src/components/admin/fields.tsx index 023f9b8..d6b6b14 100644 --- a/src/components/admin/fields.tsx +++ b/src/components/admin/fields.tsx @@ -71,7 +71,9 @@ `resolve` option is the media.ts helper for the field's public/ directory, so a bare filename previews from the right place. Its `folder` ("logos" for logo and icon fields) is where uploads go and - the tab the library opens on. + the tab the library opens on. `frameFrom` names the row's video + link field and adds "Frame at" (a still at a typed time, saved to + thumbnails/); `frameWhen` limits it to rows that match. Two options change the box itself rather than what goes in it: @@ -383,6 +385,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }: value={value} resolve={field.resolve} folder={field.folder} + videoUrl={field.frameFrom && fieldShown({ when: field.frameWhen }, row) ? getPath(row, field.frameFrom) : null} locked={locked} className={locked ? inputLocked : common.className} onChange={onChange} diff --git a/src/lib/adminSchema/shared.ts b/src/lib/adminSchema/shared.ts index e994c81..492c562 100644 --- a/src/lib/adminSchema/shared.ts +++ b/src/lib/adminSchema/shared.ts @@ -191,7 +191,9 @@ export const featuredCardsChild = { widget: "image", resolve: mediaUrl, full: true, - help: "Default: the record's own picture, or for a YouTube video, its thumbnail.", + frameFrom: "url", + frameWhen: { path: "kind", value: "video" }, + help: "Default: the record's own picture, or for a YouTube video, its thumbnail. For a video, Frame at takes a still from it instead.", }, ], }; diff --git a/src/lib/clock.ts b/src/lib/clock.ts new file mode 100644 index 0000000..34d93e0 --- /dev/null +++ b/src/lib/clock.ts @@ -0,0 +1,21 @@ +/* Times in a video, as typed and shown: Tools → Video clips and the + image field's frame picker. */ + +/* 83.5 → "1:23.5"; 3723 → "1:02:03". */ +export function clock(seconds: number | null | undefined): string { + if (seconds == null || !Number.isFinite(seconds)) return "-"; + const whole = Math.floor(seconds); + const tenths = Math.round((seconds - whole) * 10); + const h = Math.floor(whole / 3600); + const m = Math.floor((whole % 3600) / 60); + const s = whole % 60; + const ss = `${String(s).padStart(2, "0")}${tenths ? `.${tenths % 10}` : ""}`; + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +} + +/* "1:23.5", "83.5" or "1:02:03" → seconds; null when it isn't a time. */ +export function parseClock(text: string): number | null { + const parts = text.trim().split(":"); + if (!parts.length || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null; + return parts.reduce((total, part) => total * 60 + Number(part), 0); +} diff --git a/src/pages/admin/AdminClips.tsx b/src/pages/admin/AdminClips.tsx index cb86a8d..3db94f8 100644 --- a/src/pages/admin/AdminClips.tsx +++ b/src/pages/admin/AdminClips.tsx @@ -18,6 +18,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react" import { Link } from "react-router-dom"; import { ApiError, del, get, post } from "../../lib/api.ts"; +import { clock, parseClock } from "../../lib/clock.ts"; import { accentText, BRAND } from '../../lib/color.ts' const MUTED = "var(--color-muted)"; @@ -56,25 +57,6 @@ const SHAPES: Array<[string, string, number | null]> = [ ["vertical", "Vertical 9:16 (Reels, Shorts, TikTok)", 9 / 16], ]; -/* 83.5 → "1:23.5"; 3723 → "1:02:03". */ -function clock(seconds: number | null | undefined): string { - if (seconds == null || !Number.isFinite(seconds)) return "-"; - const whole = Math.floor(seconds); - const tenths = Math.round((seconds - whole) * 10); - const h = Math.floor(whole / 3600); - const m = Math.floor((whole % 3600) / 60); - const s = whole % 60; - const ss = `${String(s).padStart(2, "0")}${tenths ? `.${tenths % 10}` : ""}`; - return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; -} - -/* "1:23.5", "83.5" or "1:02:03" → seconds; null when it isn't a time. */ -function parseClock(text: string): number | null { - const parts = text.trim().split(":"); - if (!parts.length || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null; - return parts.reduce((total, part) => total * 60 + Number(part), 0); -} - function sizeOf(bytes: number | null): string { if (!bytes) return ""; return bytes > 1024 * 1024 * 1024 diff --git a/src/pages/admin/AdminNewsletter.tsx b/src/pages/admin/AdminNewsletter.tsx index 0bf8c73..b81d442 100644 --- a/src/pages/admin/AdminNewsletter.tsx +++ b/src/pages/admin/AdminNewsletter.tsx @@ -230,7 +230,7 @@ const STARTER: NewsletterPart[] = [ { type: 'header' }, { type: 'title', text: '' }, { type: 'paragraph', text: '' }, - { type: 'picks', source: 'events', picked: [] }, + { type: 'picks', picked: [] }, { type: 'picks', source: 'posts', picked: [] }, { type: 'picks', source: 'cards', picked: [] }, { type: 'footer' }, @@ -287,7 +287,8 @@ export default function AdminNewsletter() { if (row) { try { const parsed = JSON.parse(row.layout || '[]') - layout = Array.isArray(parsed) ? parsed : [] + // Events is the blank choice of Pick from, so an older draft's 'events' reads as blank. + layout = Array.isArray(parsed) ? parsed.map((part) => (part.source === 'events' ? { ...part, source: '' } : part)) : [] } catch { // A hand-edited draft: start its parts over. } From 636388730fb71f2ea3ca925b09eb4f6e51bee717 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:44:25 -0500 Subject: [PATCH 08/94] Plausible analytics reports to Discord (migration 065) Daily (yesterday) and weekly (Mondays, last 7 days vs the 7 before) summaries: visitors, pageviews, bounce rate, visit length, top pages and sources. Each has its own switch in Site settings > Reports; off until PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL are set. Sent at 8:00 REPORT_TZ (default America/Chicago); analytics_reports keeps one a day. node src/analyticsReport.js daily|weekly sends one by hand. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- server/src/admin-schema/siteSettings.js | 2 + server/src/analyticsReport.js | 203 ++++++++++++++++++ server/src/index.js | 2 + .../src/migrations/065_analytics_reports.sql | 19 ++ src/lib/adminSchema/siteSettings.ts | 27 +++ 6 files changed, 254 insertions(+), 1 deletion(-) create mode 100644 server/src/analyticsReport.js create mode 100644 server/src/migrations/065_analytics_reports.sql diff --git a/CLAUDE.md b/CLAUDE.md index f4630a0..6d667e5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. -- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. +- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`). - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. diff --git a/server/src/admin-schema/siteSettings.js b/server/src/admin-schema/siteSettings.js index 2947291..41c7f89 100644 --- a/server/src/admin-schema/siteSettings.js +++ b/server/src/admin-schema/siteSettings.js @@ -34,6 +34,8 @@ export const siteSettings = { text("access_group_viewer"), text("access_group_editor"), text("access_group_admin"), + enumeration("report_daily", ["on", "off"]), + enumeration("report_weekly", ["on", "off"]), ], children: [ diff --git a/server/src/analyticsReport.js b/server/src/analyticsReport.js new file mode 100644 index 0000000..10cc4eb --- /dev/null +++ b/server/src/analyticsReport.js @@ -0,0 +1,203 @@ +/* ═══════════════════════════════════════════════════════════════ + ANALYTICS REPORTS + + Plausible's numbers for this site, posted to a Discord channel: + daily yesterday: visitors, pageviews, bounce rate, visit + length, top pages and sources + weekly Mondays: the last 7 days, with the change from the 7 + before + Each is switched on in Panel → Site settings → Reports. Both go + out at SEND_HOUR in REPORT_TZ, or as soon after as the server is + up that day; analytics_reports (065) keeps it to one a day. + + ── Configuration (the ngu-api service environment) ── + PLAUSIBLE_API_KEY a Stats API key (Plausible → Account + settings → API keys) + DISCORD_WEBHOOK_URL the channel's webhook (Discord → channel + settings → Integrations → Webhooks) + PLAUSIBLE_URL default http://127.0.0.1:8000, where the + self-hosted Plausible listens + REPORT_TZ default America/Chicago + Off until the first two are set. The site counted is the hostname + of site.json's url, as in pageMeta.js's analyticsTag. + + To send one now (eg. to try the setup), whatever the switches say: + DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly + ═══════════════════════════════════════════════════════════════ */ + +import { pathToFileURL } from "node:url"; + +import { siteFor } from "./pageMeta.js"; + +const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, ""); +const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null; +const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null; +const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago"; +const SEND_HOUR = 8; +const TICK_MS = 15 * 60 * 1000; +const KINDS = ["daily", "weekly"]; + +export const reportsReady = () => Boolean(PLAUSIBLE_API_KEY && DISCORD_WEBHOOK_URL); + +/* Today's date and the hour in REPORT_TZ, and whether it's Monday. */ +function localNow(now = new Date()) { + const parts = Object.fromEntries( + new Intl.DateTimeFormat("en-US", { + timeZone: REPORT_TZ, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + hourCycle: "h23", + weekday: "short", + }) + .formatToParts(now) + .map((part) => [part.type, part.value]), + ); + return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), monday: parts.weekday === "Mon" }; +} + +/* "2026-10-04" moved by `days`. */ +function shift(date, days) { + const d = new Date(`${date}T00:00:00Z`); + d.setUTCDate(d.getUTCDate() + days); + return d.toISOString().slice(0, 10); +} + +/* ── Plausible ─────────────────────────────────────────────── */ + +async function query(siteId, body) { + const res = await fetch(`${PLAUSIBLE_URL}/api/v2/query`, { + method: "POST", + headers: { Authorization: `Bearer ${PLAUSIBLE_API_KEY}`, "Content-Type": "application/json" }, + body: JSON.stringify({ site_id: siteId, ...body }), + signal: AbortSignal.timeout(20_000), + }); + if (!res.ok) throw new Error(`Plausible answered ${res.status}: ${(await res.text()).slice(0, 200)}`); + return (await res.json()).results ?? []; +} + +const METRICS = ["visitors", "pageviews", "bounce_rate", "visit_duration"]; + +async function totals(siteId, range) { + const [row] = await query(siteId, { metrics: METRICS, date_range: range }); + return Object.fromEntries(METRICS.map((metric, i) => [metric, row?.metrics[i] ?? 0])); +} + +async function top(siteId, dimension, range, limit) { + const rows = await query(siteId, { + metrics: ["visitors"], + dimensions: [dimension], + date_range: range, + order_by: [["visitors", "desc"]], + pagination: { limit }, + }); + return rows.length ? rows.map((r) => `${r.dimensions[0]}: ${r.metrics[0]}`).join("\n") : "-"; +} + +/* ── The message ───────────────────────────────────────────── */ + +const duration = (seconds) => `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`; + +function change(now, before) { + if (!before) return now ? " (new)" : ""; + const percent = Math.round(((now - before) / before) * 100); + return ` (${percent >= 0 ? "+" : ""}${percent}%)`; +} + +/* The Discord message for `kind` as of `today` (a REPORT_TZ date): + yesterday, or the 7 days ending yesterday. */ +export async function buildReport(db, kind, today) { + const siteId = new URL(siteFor(db).url).hostname; + const to = shift(today, -1); + const from = kind === "weekly" ? shift(to, -6) : to; + const range = [from, to]; + const limit = kind === "weekly" ? 5 : 3; + + const [now, before, pages, sources] = await Promise.all([ + totals(siteId, range), + kind === "weekly" ? totals(siteId, [shift(from, -7), shift(to, -7)]) : null, + top(siteId, "event:page", range, limit), + top(siteId, "visit:source", range, limit), + ]); + const vs = (metric) => (before ? change(now[metric], before[metric]) : ""); + + return { + embeds: [ + { + title: kind === "weekly" ? `${siteId}: week of ${from} to ${to}` : `${siteId}: ${to}`, + fields: [ + { name: "Visitors", value: `${now.visitors}${vs("visitors")}`, inline: true }, + { name: "Pageviews", value: `${now.pageviews}${vs("pageviews")}`, inline: true }, + { name: "Bounce rate", value: `${now.bounce_rate}%`, inline: true }, + { name: "Visit length", value: duration(now.visit_duration), inline: true }, + { name: "Top pages", value: pages }, + { name: "Top sources", value: sources }, + ], + }, + ], + }; +} + +export async function sendReport(db, kind, today = localNow().date) { + const res = await fetch(DISCORD_WEBHOOK_URL, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(await buildReport(db, kind, today)), + signal: AbortSignal.timeout(20_000), + }); + if (!res.ok) throw new Error(`Discord answered ${res.status}: ${(await res.text()).slice(0, 200)}`); +} + +/* ── Schedule ──────────────────────────────────────────────── */ + +export function startAnalyticsReports(db) { + if (!reportsReady()) return; + let running = false; + const tick = async () => { + const { date, hour, monday } = localNow(); + if (running || hour < SEND_HOUR) return; + running = true; + try { + const settings = db.prepare(`SELECT report_daily, report_weekly FROM site_settings WHERE id = 'site'`).get() ?? {}; + for (const kind of KINDS) { + if (settings[`report_${kind}`] !== "on" || (kind === "weekly" && !monday)) continue; + if (db.prepare(`SELECT 1 FROM analytics_reports WHERE kind = ? AND sent_for = ?`).get(kind, date)) continue; + // Marked before sending: a Plausible or Discord failure is + // logged once that day, not every tick. + db.prepare( + `INSERT INTO analytics_reports (kind, sent_for) VALUES (?, ?) + ON CONFLICT (kind) DO UPDATE SET sent_for = excluded.sent_for`, + ).run(kind, date); + try { + await sendReport(db, kind, date); + console.log(`analytics ${kind} report sent for ${date}`); + } catch (err) { + console.error(`analytics ${kind} report failed: ${err.message}`); + } + } + } finally { + running = false; + } + }; + tick(); + setInterval(tick, TICK_MS).unref(); +} + +/* ── By hand ───────────────────────────────────────────────── */ + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + const kind = process.argv[2]; + if (!KINDS.includes(kind)) { + console.error("usage: node src/analyticsReport.js daily|weekly"); + process.exit(1); + } + if (!reportsReady()) { + console.error("Set PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL first."); + process.exit(1); + } + const { openDatabase } = await import("./db.js"); + const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db"); + await sendReport(db, kind); + console.log(`Sent the ${kind} report.`); +} diff --git a/server/src/index.js b/server/src/index.js index 1014a53..873fdcc 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -45,6 +45,7 @@ import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { logSafe, startSessionSweeper } from "./auth.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { startGroupSync } from "./accessGroups.js"; +import { startAnalyticsReports } from "./analyticsReport.js"; import { ENTITIES } from "./admin-schema.js"; const HOST = process.env.HOST ?? "127.0.0.1"; @@ -241,6 +242,7 @@ app.route("/", pages); startSessionSweeper(db); startGroupSync(db); startClipWorker(db); +startAnalyticsReports(db); console.log(`clips ${CLIPS_DIR}`); app.notFound((c) => c.json({ error: "Not found" }, 404)); diff --git a/server/src/migrations/065_analytics_reports.sql b/server/src/migrations/065_analytics_reports.sql new file mode 100644 index 0000000..fec1e6f --- /dev/null +++ b/server/src/migrations/065_analytics_reports.sql @@ -0,0 +1,19 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 065 ANALYTICS REPORTS +-- +-- Plausible's numbers posted to Discord (server/src/analyticsReport.js). +-- +-- site_settings.report_daily 'on': yesterday's numbers each morning +-- site_settings.report_weekly 'on': last week's each Monday morning +-- Blank or 'off': not sent +-- analytics_reports the local date each kind was last sent +-- for, so a restart doesn't post twice +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE site_settings ADD COLUMN report_daily TEXT CHECK (report_daily IN ('on', 'off')); +ALTER TABLE site_settings ADD COLUMN report_weekly TEXT CHECK (report_weekly IN ('on', 'off')); + +CREATE TABLE analytics_reports ( + kind TEXT PRIMARY KEY CHECK (kind IN ('daily', 'weekly')), + sent_for TEXT NOT NULL +) STRICT; diff --git a/src/lib/adminSchema/siteSettings.ts b/src/lib/adminSchema/siteSettings.ts index fe74e66..3dbee2e 100644 --- a/src/lib/adminSchema/siteSettings.ts +++ b/src/lib/adminSchema/siteSettings.ts @@ -145,6 +145,33 @@ export const siteSettings = { }, ], }, + { + legend: "Reports", + fields: [ + { + path: "report_daily", + label: "Daily analytics report", + widget: "select", + options: [ + ["on", "On"], + ["off", "Off"], + ], + blankLabel: "Default: off", + help: "Yesterday's visitors, pageviews and top pages from Plausible, posted to Discord each morning. Needs PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL on the server (server/src/analyticsReport.js).", + }, + { + path: "report_weekly", + label: "Weekly analytics report", + widget: "select", + options: [ + ["on", "On"], + ["off", "Off"], + ], + blankLabel: "Default: off", + help: "The last 7 days, with the change from the week before, posted to Discord each Monday morning.", + }, + ], + }, { legend: "Notices", fields: [ From aaab1a945c991d5f1941d106dfb9c83c5f2e5303 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:46:32 -0500 Subject: [PATCH 09/94] Docs: setting up the Plausible reports to Discord Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/analytics-reports.md | 162 ++++++++++++++++++++++++++++++++++ server/src/analyticsReport.js | 2 + 3 files changed, 165 insertions(+), 1 deletion(-) create mode 100644 docs/analytics-reports.md diff --git a/CLAUDE.md b/CLAUDE.md index 6d667e5..b6ea106 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. -- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`). +- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. diff --git a/docs/analytics-reports.md b/docs/analytics-reports.md new file mode 100644 index 0000000..f506f05 --- /dev/null +++ b/docs/analytics-reports.md @@ -0,0 +1,162 @@ +# Analytics reports to Discord + +The API can post the site's Plausible numbers to a Discord channel +(`server/src/analyticsReport.js`, migration 065): + +- **Daily**: yesterday's visitors, pageviews, bounce rate, visit length, + and the top 3 pages and sources. +- **Weekly**, on Mondays: the last 7 days (Monday to Sunday), each + total with its change from the week before, and the top 5 pages and + sources. + +Each one has its own switch in Panel → Site settings → Reports, and both +are off until it's turned on. They go out at 8:00 in `REPORT_TZ`. If the +server is down then, they go out when it comes back up later that day. +A restart never posts the same report twice. Nothing else on the site +depends on this. + +| Setting on the `ngu-api` service | What it is | +| --- | --- | +| `PLAUSIBLE_API_KEY` | A Plausible Stats API key (step 1) | +| `DISCORD_WEBHOOK_URL` | The channel's webhook address (step 2) | +| `PLAUSIBLE_URL` | Where the API can reach Plausible. Default `http://127.0.0.1:8000` | +| `REPORT_TZ` | The time zone for "yesterday" and 8:00. Default `America/Chicago` | + +Without the first two, no reports are sent, whatever the switches say. + +## 1. The Plausible API key + +1. Sign in to Plausible (the self-hosted one behind `/pa/`) as an owner + of the site. +2. Account settings → API keys → New API key. Pick **Stats API** if it + asks for a type, and name it eg. `ngu-api reports`. +3. Copy the key now. Plausible shows it only once. + +The site has to exist in Plausible under the same domain the pages count +under: the hostname of `site.json`'s `url`, eg. `nextgenerationofunity.org` +(not `www.` and not `https://`). It already does if the dashboard shows +visits. + +The reports use the Stats API v2 (`/api/v2/query`), which needs +Plausible Community Edition 2.1 or later. Check Settings or the page +footer for the version, and upgrade an older one first. + +### Where Plausible listens + +`PLAUSIBLE_URL` is the address the API calls directly, not the public +`/pa/` path. nginx's proxy for `/pa/` already points at it: + +```sh +grep proxy_pass /etc/nginx/snippets/plausible-proxy.conf +``` + +If that shows `http://127.0.0.1:8000`, leave `PLAUSIBLE_URL` unset. +Otherwise set it to that address, eg. `http://127.0.0.1:8001`, or +`https://plausible.io` for Plausible's own hosting. + +## 2. The Discord webhook + +1. In Discord, open the channel's settings (the gear by its name) → + Integrations → Webhooks → New Webhook. +2. Name it eg. `NGU analytics`, give it an avatar if you like, and check + that it posts to the right channel. +3. Copy Webhook URL. It looks like + `https://discord.com/api/webhooks/123456789/AbCdEf...`. + +You need Manage Webhooks on the channel. Anyone who has the address can +post to the channel, so treat it as a password. + +## 3. The service + +Both values are secrets, so put them in a file only root can read +rather than in the unit itself (a `systemctl edit` override is readable +by every user on the box): + +```sh +sudo mkdir -p /etc/ngu +sudo tee /etc/ngu/analytics-reports.env >/dev/null <<'EOF' +PLAUSIBLE_API_KEY= +DISCORD_WEBHOOK_URL= +EOF +sudo chmod 600 /etc/ngu/analytics-reports.env +``` + +Add `PLAUSIBLE_URL=` or `REPORT_TZ=` lines to the same file if you need +them. Then point the service at it: + +```sh +sudo systemctl edit ngu-api +``` + +```ini +[Service] +EnvironmentFile=/etc/ngu/analytics-reports.env +``` + +systemd reads the file as root before it starts the service, so the +service's own user doesn't need to be able to read it. + +Back up the database first (migration 065 adds the switches and runs at +the next start), then: + +```sh +sudo systemctl restart ngu-api +``` + +No nginx change is needed: the API calls Plausible and Discord itself. + +## 4. Try it + +Send one straight away, whatever the switches say, while the service is +running: + +```sh +cd /srv/ngu-api +sudo bash -c 'set -a; . /etc/ngu/analytics-reports.env; set +a; + SITE_CONFIG=/srv/ngu-api/site.json DB_PATH=/var/lib/ngu/ngu.db \ + node src/analyticsReport.js daily' +``` + +`Sent the daily report.` means it's in the channel. Use `weekly` for the +weekly one. Sending one by hand doesn't stop that day's scheduled +report. + +## 5. Turn them on + +Panel → Site settings → Reports: set **Daily analytics report** and/or +**Weekly analytics report** to On, and save. Set one back to Off (or +blank) to stop it. The change counts from the next check, within 15 +minutes. + +The switches are per database, so the dev server only posts if its own +database has them on and its own service has the settings. Leave the +settings off dev, or it reports as `dev.nextgenerationofunity.org`. + +## Checking it + +Every report is logged: + +```sh +journalctl -u ngu-api --since today --no-pager | grep analytics +``` + +- `analytics daily report sent for 2026-10-05`: it went out. +- `Plausible answered 401`: the API key is wrong or was deleted. Make a + new one (step 1). +- `Plausible answered 400` or `404` naming the site: Plausible has no + site under that domain. Compare `site.json`'s `url` with the domain in + Plausible's site list. +- `Plausible answered 404` with no site named: Plausible is older than + 2.1 and has no v2 API. +- `fetch failed` or `ECONNREFUSED`: Plausible isn't at `PLAUSIBLE_URL` + (see Where Plausible listens). +- `Discord answered 401` or `404`: the webhook was deleted or the + address is wrong. Make a new one (step 2). +- Nothing at all: check that both settings are in the service's + environment (`sudo systemctl show ngu-api -p EnvironmentFiles`), that + the switch is On, that it's past 8:00 in `REPORT_TZ`, and for the + weekly report, that it's Monday. + +A failed report isn't retried that day, so a broken setup logs one line +a day, not one every 15 minutes. Fix the cause, then send it by hand +(step 4) if you still want it. diff --git a/server/src/analyticsReport.js b/server/src/analyticsReport.js index 10cc4eb..3f5b36c 100644 --- a/server/src/analyticsReport.js +++ b/server/src/analyticsReport.js @@ -23,6 +23,8 @@ To send one now (eg. to try the setup), whatever the switches say: DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly + + Setup: docs/analytics-reports.md. ═══════════════════════════════════════════════════════════════ */ import { pathToFileURL } from "node:url"; From 33be6183318c3e696daaca84d5d236cb1b0c3d95 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Sun, 4 Oct 2026 21:55:05 -0500 Subject: [PATCH 10/94] Captions for uploaded videos (migration 066) Video blocks get a Captions field and the hero a Video captions field, each a WebVTT upload drawn as on a video file. The media library takes .vtt (sniffed by its WEBVTT header, kept as is, always in /uploads/captions/) with its own tab. Newsletter parts leave the field out. nginx needs text/vtt in mime.types: docs/media-uploads.md, step 5. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/media-uploads.md | 19 ++++++++- server/src/admin-schema/columns.js | 2 + server/src/admin-schema/frontPage.js | 1 + server/src/media.js | 34 +++++++++------- server/src/migrations/066_video_captions.sql | 13 ++++++ server/src/routes/home.js | 2 +- server/src/routes/media.js | 4 +- server/src/shape.js | 3 +- src/components/ContentBlocks.tsx | 2 +- src/components/VideoPlayer.tsx | 7 +++- src/components/admin/MediaLibrary.tsx | 43 ++++++++++++-------- src/lib/adminSchema/frontPage.ts | 9 ++++ src/lib/adminSchema/shared.ts | 10 +++++ src/lib/useContent.ts | 2 + src/lib/useFrontPage.ts | 2 +- src/pages/admin/AdminNewsletter.tsx | 2 +- src/pages/sections/home/HeroStage.tsx | 9 +++- 18 files changed, 123 insertions(+), 43 deletions(-) create mode 100644 server/src/migrations/066_video_captions.sql diff --git a/CLAUDE.md b/CLAUDE.md index b6ea106..53fb340 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `api.ts` is the shared caching client used by frontend data hooks. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. -- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). +- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). ## Rules and gotchas - **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. diff --git a/docs/media-uploads.md b/docs/media-uploads.md index a0e025e..6e3bfdb 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -15,8 +15,10 @@ in the `media` table (`server/src/migrations/028_media.sql`). - **Keep original** stores the file exactly as uploaded (up to 10 MB), metadata and all. - SVGs are always kept as they are. -- Accepted types: JPEG, PNG, GIF, WebP, SVG. The type is read from the - file's contents, not its name. +- Accepted types: JPEG, PNG, GIF, WebP, SVG, and WebVTT captions + (`.vtt`, kept as they are, always in `captions/`). The type is read + from the file's contents, not its name: a captions file has to start + with `WEBVTT`. - Editors and up can upload. Admins and up can delete. The Media page shows which tables still use a file before deleting it, because nothing stops a file a record uses from being deleted. @@ -33,6 +35,7 @@ Images are kept in folders by what they're for (`FOLDERS` in | `logos/` | Uploads from logo and icon fields (organization, team, award and event logos, the favicon and home-screen icon): the fields with `folder: "logos"` in `src/lib/adminSchema/` | | `images/` | Every other upload: photos, backgrounds, covers, block images | | `thumbnails/` | Pictures the site saves by itself: link previews (Fetch preview) and Drive files' first pages | +| `captions/` | WebVTT files for uploaded videos: the Captions field of video blocks and the hero's Video captions (migration 066). YouTube, Vimeo and Facebook videos show their own | Each image's `-640.webp` small copy sits beside it. Video and audio clips (Tools → Video clips) stay in the root. The Media page and every @@ -100,3 +103,15 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies 4. `sharp` is a server dependency now: run `pnpm install` in `/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries, so no build tools are needed. + +5. Captions need nginx to send `.vtt` files as `text/vtt` (Firefox + won't show them otherwise, and `nosniff` stops guessing). Check: + + ```sh + grep vtt /etc/nginx/mime.types + ``` + + If nothing comes back, add `text/vtt vtt;` inside the `types { }` + block of `/etc/nginx/mime.types`, then + `sudo nginx -t && sudo systemctl reload nginx`. Not in the site's + own file: a `types` block there replaces the whole list. diff --git a/server/src/admin-schema/columns.js b/server/src/admin-schema/columns.js index 49a0f15..bb96ef9 100644 --- a/server/src/admin-schema/columns.js +++ b/server/src/admin-schema/columns.js @@ -159,6 +159,8 @@ export const blocksChild = (ownerKind) => ({ url("href"), text("alt"), text("cite"), + // Video blocks only (066): an uploaded video's WebVTT file. + text("captions"), // People blocks only (054): whose team's tiles to show. text("team_id"), ], diff --git a/server/src/admin-schema/frontPage.js b/server/src/admin-schema/frontPage.js index 346d709..3d11224 100644 --- a/server/src/admin-schema/frontPage.js +++ b/server/src/admin-schema/frontPage.js @@ -44,6 +44,7 @@ export const frontPage = { text("livestream_title"), url("video_url"), text("video_title"), + text("video_captions"), text("countdown_event_id"), text("countdown_scope_id"), enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]), diff --git a/server/src/media.js b/server/src/media.js index ccbe11f..19f3f2c 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -15,8 +15,9 @@ ── What ── The type is read from the file's first bytes, never from its name or the browser's Content-Type, both of which the uploader - controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything - else is refused. + controls. JPEG, PNG, GIF, WebP and SVG are accepted, and WebVTT + captions (a text file starting "WEBVTT"); anything else is + refused. ── Processing ── By default a raster image is turned upright (EXIF orientation), @@ -25,7 +26,7 @@ `keepOriginal` stores the bytes exactly as uploaded instead, under the tighter KEEP_MAX_BYTES. An SVG is always kept as it is: it's already small, and rasterizing it would lose the point - of it. + of it. So is a WebVTT file, always into captions/. Names are random, so two uploads of "logo.png" can't collide and a filename says nothing about what's in it. @@ -33,8 +34,8 @@ ── Folders ── Each upload goes in a folder by what it's for (FOLDERS): logos/ for logo and icon fields, thumbnails/ for pictures the site saves - by itself (link previews, Drive files' first pages), images/ for - the rest. A stored name includes it: 'logos/3f9c….webp', served at + by itself (link previews, Drive files' first pages), captions/ + for videos' WebVTT files, images/ for the rest. A stored name includes it: 'logos/3f9c….webp', served at /uploads/logos/3f9c….webp. The small copy sits beside it. Clips keep a bare name in the root. @@ -66,7 +67,7 @@ const MB = 1024 * 1024; /* The largest file accepted at all, before processing: room for a full-size phone photo. */ /* Where an upload goes, by what it's for (see Folders above). */ -export const FOLDERS = ["logos", "images", "thumbnails"]; +export const FOLDERS = ["logos", "images", "thumbnails", "captions"]; export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images"); /* A name this library stores: a bare name in the root, or one inside @@ -131,8 +132,12 @@ const TYPES = { gif: { mime: "image/gif", ext: ".gif" }, webp: { mime: "image/webp", ext: ".webp" }, svg: { mime: "image/svg+xml", ext: ".svg" }, + vtt: { mime: "text/vtt", ext: ".vtt" }, }; +/* Kinds stored exactly as uploaded, with no small copy: text, not pixels. */ +const AS_IS = new Set(["svg", "vtt"]); + function startsWith(buf, bytes, offset = 0) { return bytes.every((byte, i) => buf[offset + i] === byte); } @@ -151,6 +156,7 @@ function sniff(buf) { if (/^(<\?xml[\s\S]*?\?>\s*)?(\s*|]*>\s*)*]/i.test(head)) { return "svg"; } + if (/^WEBVTT(\s|$)/.test(head)) return "vtt"; return null; } @@ -169,10 +175,10 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { const kind = sniff(buf); if (!kind) { - throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded."); + throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images, and WebVTT (.vtt) captions, can be uploaded."); } - const convert = kind !== "svg" && !keepOriginal; + const convert = !AS_IS.has(kind) && !keepOriginal; if (!convert && buf.length > KEEP_MAX_BYTES) { throw new MediaError( @@ -200,7 +206,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { width = info.width; // An animated image reports the whole strip's height. height = info.pageHeight ?? info.height; - } else if (kind !== "svg") { + } else if (!AS_IS.has(kind)) { const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; height = meta.pageHeight ?? meta.height ?? null; @@ -209,7 +215,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { throw new MediaError(415, "That image couldn't be read. It may be damaged."); } - const dir = folderOf(folder); + const dir = kind === "vtt" ? "captions" : folderOf(folder); const base = `${randomBytes(12).toString("hex")}${type.ext}`; const filename = `${dir}/${base}`; @@ -219,7 +225,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`); await writeFile(tmp, out); await rename(tmp, path.join(UPLOADS_DIR, filename)); - if (kind !== "svg") await writeThumb(filename, out); + if (!AS_IS.has(kind)) await writeThumb(filename, out); return { filename, @@ -269,10 +275,10 @@ export async function writeMissingThumbs() { const present = new Set(names); let made = 0; for (const name of names) { - if (THUMB.test(name) || /\.svg$/i.test(name)) continue; + if (THUMB.test(name) || /\.(svg|vtt)$/i.test(name)) continue; if (present.has(thumbName(name))) continue; const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null); - if (!buf || !sniff(buf) || sniff(buf) === "svg") continue; + if (!buf || !sniff(buf) || AS_IS.has(sniff(buf))) continue; await writeThumb(name, buf); made += 1; } @@ -309,7 +315,7 @@ async function describe(filename) { let width = null; let height = null; - if (kind !== "svg") { + if (!AS_IS.has(kind)) { try { const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); width = meta.width ?? null; diff --git a/server/src/migrations/066_video_captions.sql b/server/src/migrations/066_video_captions.sql new file mode 100644 index 0000000..50a31e6 --- /dev/null +++ b/server/src/migrations/066_video_captions.sql @@ -0,0 +1,13 @@ +-- ═══════════════════════════════════════════════════════════════ +-- 066 VIDEO CAPTIONS +-- +-- A WebVTT file for an uploaded video, drawn as its captions track +-- (WCAG 1.2.2). YouTube, Vimeo and Facebook embeds bring their own. +-- The file is an upload in /uploads/captions/ (media.js). +-- +-- content_blocks.captions a video block's +-- front_page.video_captions the hero's featured video's +-- ═══════════════════════════════════════════════════════════════ + +ALTER TABLE content_blocks ADD COLUMN captions TEXT; +ALTER TABLE front_page ADD COLUMN video_captions TEXT; diff --git a/server/src/routes/home.js b/server/src/routes/home.js index 5a8ab80..054a450 100644 --- a/server/src/routes/home.js +++ b/server/src/routes/home.js @@ -225,7 +225,7 @@ home.get("/front-page", (c) => { ? { url: page.livestream_url, title: page.livestream_title } : null, video: page.video_url - ? { url: page.video_url, title: page.video_title } + ? { url: page.video_url, title: page.video_title, captions: page.video_captions } : null, event: shapeHeroEvent(db, heroEvent), }, diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 41e15e0..74b3c4e 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -3,12 +3,12 @@ GET /media the library, newest first, ?q=name, ?type=image|video|audio, - ?folder=logos|images|thumbnails. + ?folder=logos|images|thumbnails|captions. Picks up images copied into the uploads folder by hand first (registerLooseFiles, at most every SCAN_EVERY_MS) - POST /media upload one image (multipart: file, + POST /media upload one image or .vtt (multipart: file, keep_original, folder: FOLDERS in media.js, default images) GET /media/:id/uses which records name this file diff --git a/server/src/shape.js b/server/src/shape.js index 751bea9..51acb01 100644 --- a/server/src/shape.js +++ b/server/src/shape.js @@ -66,7 +66,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { const blockRows = db .prepare( - `SELECT id, owner_id, type, text, media, href, alt, cite, team_id + `SELECT id, owner_id, type, text, media, href, alt, cite, captions, team_id FROM content_blocks WHERE owner_kind = ? AND slot = ? AND owner_id IN (${placeholders(ids.length)}) ORDER BY owner_id, sort_order`, @@ -85,6 +85,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") { href: row.href, alt: row.alt, cite: row.cite, + captions: row.captions, team_id: row.team_id, items: [], }; diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx index cb5c621..d0f6cbf 100644 --- a/src/components/ContentBlocks.tsx +++ b/src/components/ContentBlocks.tsx @@ -351,7 +351,7 @@ function Block({ return (
    - +
    {!reading && }
    diff --git a/src/components/VideoPlayer.tsx b/src/components/VideoPlayer.tsx index b8ed3d8..a7f38f7 100644 --- a/src/components/VideoPlayer.tsx +++ b/src/components/VideoPlayer.tsx @@ -33,11 +33,14 @@ export default function VideoPlayer({ url, still, title, + captions, className = '', }: { url?: string | null /** An image URL to show before it plays. */ still?: string | null + /** A WebVTT file's URL, for an uploaded video; embeds bring their own. */ + captions?: string | null title?: string | null className?: string }) { @@ -66,7 +69,9 @@ export default function VideoPlayer({ playsInline aria-label={title || 'Video'} className={`aspect-video w-full rounded-md bg-black ${className}`} - /> + > + {captions && } + ) : (