v1.14.0-profiles: profile accounts, drafts, page management, Planning Center #32

Merged
ngu-git-admin merged 15 commits from page-management into main 2026-10-28 07:00:10 +00:00
144 changed files with 7918 additions and 2567 deletions

View file

@ -40,6 +40,8 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`.
- Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at `/account`. Public reads of people go through the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`.
- Planning Center (migration 085): Data → Planning Center compares a Planning Center People list (Site settings → Planning Center) with the site's people and applies what an admin picks: link (`people.pco_id`), update the name and private email and phone, or add unpublished. Off until `PCO_APP_ID` and `PCO_SECRET` are set: `docs/planning-center.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`.
## Git workflow
@ -61,13 +63,13 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- All pages use `PageShell.tsx` as the wrapper unless explicitly noted otherwise.
- Pages live in `src/pages/`; section-level components go in `src/pages/sections/`.
- `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite, through hooks in `src/lib/`.
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
- Pages are rows of `site_pages` (migration 080), edited in Pages → Page management: address, title, intro, Hidden (Not found below viewer) and Disabled (out of the menus, sitemap and search). Every page is a page of sections, the front page included (its hero and bands are section types: `src/pages/sections/Bands.tsx`, their settings in `section_*` tables read by `server/src/sectionData.js`; forms and embeds are section types too, `src/pages/sections/FormSections.tsx`), and new ones are made there; `PageAtPath.tsx` (the `*` route) draws whatever page is at an address. The pages the code links to (`CORE_PAGES` in `server/src/admin-schema/sitePages.js`: /give, /feedback, /request, /qr, /privacy, /terms) keep their address and can't be deleted. Record routes (`/events/:id`...) stay in `App.tsx`, and their first path segments are reserved. Menu links are Pages → Navigation (`site_nav_links`, `server/src/siteNav.js`, read through `src/lib/useSiteNav.ts`); `navConfig.ts` only holds the defaults the app starts from before that loads.
- `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), `/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/<file>` (`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.
- **Role checks must use ladder comparisons, never equality.** Roles rank member → viewer → editor → admin → superadmin (member is a profile account: the site and its own profile, never the admin; `/api/admin` needs viewer, `requireStaff`). Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `isStaff`, `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.
- **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.
@ -83,10 +85,12 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema/` (server, one file per entity, registered in `admin-schema.js`) and `src/lib/adminSchema/` (client, one file per entity, registered in `adminSchema.ts`) generate SQL and form fields from declarative entity configs. Adding an entity should mean adding a descriptor, not new CRUD code.
- Child collections are deleted and reinserted wholesale. Unsafe for entities referenced by foreign keys elsewhere.
- `reindex: false` prevents cross-entity sort order collisions.
- A child collection can have `extensions` of its own (1:1 side tables keyed by the child row's id, eg. a page section's `section_hero`), and both those and its nested collections take a `when` on the row's values (a section's preset). A `when` value can be a list.
- `check: (db, id) => void` runs after a save has written everything, inside its transaction; throwing an `HttpError` refuses the save (Site settings uses it for the color contrast check, `server/src/theme.js`).
- The `OMIT` sentinel distinguishes unsent fields from deliberate clears.
- `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree.
- `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift.
- Drafts (migration 077, `server/src/drafts.js`, `docs/drafts.md`): any existing record can be saved as a draft (one per record), previewed on the real page and published (the ordinary PATCH, which drops the draft). Checking and previewing apply the draft in a transaction that is rolled back; `tx()` nests as a savepoint for that, so never call `BEGIN` by hand. A new entity with a public page adds its path to `PREVIEW_PATHS` in `src/lib/adminSchema.ts`.
## Migrations
- `server/src/migrations/066_schema.sql` is the baseline: the whole schema, consolidated on 2026-10-04 from the old 023–066 (generated from the live schema, so the comments are the ones inside each table). `066_seed.sql` runs right after it with the least a new database needs (single rows, event scopes, the site pages' sections, the Musicians tag); content is typed in through the admin. Both only run on an empty database; the runner refuses a database between v1 and v65 (bring it to v66 with a release from before the consolidation first). It's the place to read the schema, not to change it: a database that already exists never re-runs it.

111
TODO.md
View file

@ -13,8 +13,7 @@
- [ ] Are these three tabs, three sections (each in the side nav), or a filter over one list? Answer:
- [ ] Does each resource belong to exactly one audience, or can it be in several (eg. a tag per audience)? Answer:
- [ ] What happens to the page's current sections: move under an audience, or replaced? Answer:
- [ ] **Library (New Thought Nexus)**: a library for NGUers.
- [ ] Which name: Library, New Thought Nexus, or both (Nexus as the page, Library as a section)? Answer:
- [ ] **Library**: a library for NGUers.
- [ ] What goes in it: links out, uploaded files (Drive "Media"), books, videos, our own articles? Answer:
- [ ] Public, or only for NGUers? If only NGUers, how do they sign in (there are only admin accounts today)? Answer:
- [ ] Is the metaphysics dictionary / Metaphysical Bible Dictionary part of it (see Future: Poetry Builder needs the same import)? Answer:
@ -43,37 +42,23 @@
- [ ] Linked from the footer next to the version, or only in the blog? Answer:
## Sections
- [ ] **Hero text that flips**: the headline's word changes (Next, Now, and other words for our generation), or mirrors.
- [ ] Which words, and are they edited in Front page (a list) or fixed? Answer:
- [ ] What motion: a flip like a card, a fade, letters typing, a mirror? Answer:
- [ ] Respect reduced motion by showing one word (the first)? [ ] yes
- [ ] "Next generation of New Thought": is that the line it plays on, or a second line under the headline? Answer:
- [ ] **NGU and partners**: "How does this partner with An Awakened Path and antn" (from the notes; unclear).
- [ ] What is "antn" (an organization's name)? Answer:
- [ ] Is this a section to build (eg. on Organization or Partners), or a question to answer in a blog post? Answer:
## Page Features
- [ ] **Full profiles**: people get full profile pages.
- [ ] **Full profiles**: people get full profile pages. Profile accounts, claiming and visibility are done (Part 2, Accounts); what's left is the page itself.
- [ ] What is missing from a person's page today that makes it "full": bio, more photos, links, events they spoke at, groups, blog posts they wrote? Answer:
- [ ] Do people edit their own profile (they'd need accounts), or do admins edit them? Answer:
- [ ] Every person, or only those with a profile switched on (privacy)? Answer:
- [ ] Ties to Planning Center sync (Data) and the gamification below? Answer:
- [ ] **Page preview images per page**: the event's banner on event pages, the person's photo on theirs, the org's logo on org pages.
- Already done in `server/src/pageMeta.js`: events use the event photo, then the event logo, then its org's logo; people their photo; orgs, teams and awards their logo; blog posts their cover. SVG logos are skipped (social sites don't show them).
- [ ] Which page showed the wrong picture, and where (Discord, iMessage, Facebook)? Answer:
- [ ] Is it production (not deployed yet?) or the SVG skip? Should an SVG logo get a PNG copy made at upload for previews? Answer:
- [ ] Should event pages prefer the card background ("banner") over the event photo? Answer:
- [ ] **Blog page tabs**: a blog index with tabs (there is no /blog index page today, only /blog/<id>).
- [ ] Tabs by tag, by author, or fixed kinds (eg. News, Stories, Guides, Website updates)? Answer:
- [ ] A new /blog page in the nav, or tabs on the Community blog section? Answer:
- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord.
- [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer:
- [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer:
- [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer:
- [ ] How do we match a person to their Discord account (they link it themselves)? Answer:
- [ ] **Site version names**: each update gets a name, "The ___ Update", Minecraft style.
- [ ] Shown where: the footer next to the version, the changelog, both? Answer:
- [ ] Does the tag suffix become the name (v1.13.2-region-cards → "The Region Cards Update"), or a name of its own? Answer:
- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord. Linking a profile to Discord is done (Part 2, Accounts); the bot, points and badges are next.
- [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer: all of the above, we could create badges on profiles.
- [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer: shown on profiles when logged in, no leaderboard for now, and when using a command in discord. this content would not show on the public bio section of a user when viewing from a people tile.
- [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer: would like a bot built, for if things in discord update or affect gamification shown on the website. most things will be assigned to users by moderators.
- [ ] How do we match a person to their Discord account (they link it themselves)? Answer: they can link it, admins can overwrite and update/set
- [ ] **Site version names**: in the footers now (Part 2, Page features); still to show them in the changelog once it's built (Pages: Website changelog).
## Accessibility Features
- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner.
@ -83,49 +68,21 @@
- [ ] A Listen button in the Accessibility panel, or on each page by its title? Answer:
## Mobile
- [ ] **Featured event label on the front page**: where it sits doesn't make sense, at least on mobile.
- [ ] Where should it go: above the card, on the card's photo, or dropped on mobile? Answer:
- [ ] Same change on desktop? [ ] yes
## Page Editing
- [ ] **Draft edits of sections and pages**: change a page or section without publishing it straight away.
- [ ] Which editors: Pages (Front page, Retreats, Community...) only, or every record (events, people...) too? Answer:
- [ ] Preview the draft on the real page before publishing? [ ] yes
- [ ] Can editors save drafts and only admins publish (an approval step), or does anyone who can edit publish? Answer:
- [ ] One draft per page at a time, or several? Answer:
- [ ] **Page management revamp**, in steps (answers from 2026-10-16: disabled means out of the menus, sitemap and search with the address still working; admins can make new pages; the front page, the Community blog's settings, the form and embed pages and Privacy/Terms all become pages of sections; section types like the hero, stats, featured cards, calendar and countdown can go on any page, each with its own content).
- [x] Step 1, the page registry (Done, below).
- [x] Step 2, the core pages as sections (Done, below).
- [x] Step 3, section types with their own settings and the front page as sections (Done, below).
## Admin
## Data
- [ ] **Planning Center sync to People**: Planning Center People into the site's people records.
- [ ] One way (Planning Center → site), or both? Answer:
- [ ] Who gets synced: everyone, or a Planning Center list or tag (eg. "Website")? Most people in Planning Center shouldn't have a public page. Answer:
- [ ] Which fields: name, photo, email, phone, birthday? Which win when both sides differ? Answer:
- [ ] How often: a button in Data, hourly, nightly? Answer:
- [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer:
- [ ] **New Thought young adult directory**: authors and TikTok and Instagram creators (faceless but organic).
- [ ] People records with a new People tag (like Musicians), or a separate list of links (they aren't NGU people)? Answer:
- [ ] What does "faceless but organic" mean for what's shown: no photo, only their handle and a link? Answer:
- [ ] Do they agree to be listed, or is it a public list of public accounts? Answer:
- [ ] Where does it show: Resources (For Young Adults), the Library, Community? Answer:
- [ ] **New Thought young adult directory**: the tabs are built (Part 2, Page features). Content: make the People tags (eg. Authors, Creators), tag people, and set Community's Directories section to them.
## Navigation
- [ ] **Shop button** at the top right of the header.
- [ ] Where does it go: an existing store (which URL), or a shop we build? Answer:
- [ ] Shown on mobile too (in the menu, or beside it)? Answer:
- [ ] **Manage the nav, sitemap and page headers from the admin**, so pages that aren't done can be hidden.
- [ ] Hidden means: out of the nav and sitemap only (the address still works, like Unlisted), or the page returns Not found to non-admins? Answer:
- [ ] What else is editable: link order, labels, which header menu a link is in, page titles and their blurbs? Answer:
- [ ] `navConfig.ts` is the source of truth today; OK to move the editable parts into the database with navConfig as the defaults? [ ] yes
## Tools
- [ ] **File conversion**: a simple tool, eg. WebP to JPG.
- [ ] Which conversions: images only (WebP, JPG, PNG, HEIC?), or also documents (Word to PDF) and video? Answer:
- [ ] In the browser (nothing uploaded, images only), or on the server (more formats)? Answer:
- [ ] Also a "Download as JPG" on files in the Media library? [ ] yes
- [ ] **What is needed for SEE**: list it.
- [ ] What is SEE (an event, a program, a system)? Answer:
- [ ] Is the list a page on the site, a TODO here, or a document? Answer:
## Content
- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post.
@ -154,6 +111,46 @@
# Part 2: Done
## v1.14.0-profiles: page management (branch `page-management`, on top of `page-features`, no PR yet; migrations 080 to 085, back up the database before deploying)
- [x] **Planning Center sync** (Data, migration 085, `docs/planning-center.md`): Data → Planning Center (admins and up) fetches one Planning Center People list (Site settings → Planning Center) and compares each member with the site: linked, or suggested by the same email, else the same name, with the fields that would change (name, sort name, private email and phone) side by side. For each: link (and update; Planning Center wins), link to someone else, make a new unpublished person, or skip; Apply writes it all at once. One way, by hand. Off until `PCO_APP_ID` and `PCO_SECRET` are on the service. Tested against a stand-in for Planning Center's API only.
- [ ] Check with the real list: the token, a list number, a compare, an apply.
- [x] **Rotating words** (Sections, migration 084): text typed as `{Next|Now|Rising}` cycles through its choices, in the hero's headline, section titles (bands' too), headings, paragraphs, callouts and quotes, eg. `{Next|Now} Generation of {Unity|New Thought}`. Five motions (slide, flip like a card, fade, type letter by letter, mirror turning round), from the top or the bottom, a number of seconds per word: defaults in Site settings → Animated words, and a hero or a block can set its own. Each word's space is the longest's, so the line doesn't jump. Less motion (the system's setting, or reading mode) shows the first word, still, and screen readers always get the first; menus, tab titles, search descriptions and newsletters use the first word too (`src/components/RotatingWords.tsx`, `src/lib/words.ts`).
- [ ] Check in a browser: each motion and direction, a group in a section title and a paragraph, the space it keeps on a phone, reduced motion.
- [x] **Section types with their own settings, and the front page as sections** (migration 083): the front page is Home in Page management, a page of sections like the others: its hero first, then its bands in their old order (hidden ones stay hidden), each a section type that can go on any page with content of its own: Hero (words, buttons, photos, video, livestream or event), Event countdown, Event calendar, Numbers, Featured cards, Connect nav, and a Timeline shown as the rail of featured moments. The Community blog's slots, pinned posts and feeds moved into its section, so it can go on any page too. Any section can be Hidden. The Front page editor is gone (its fields are each section's), and so are its tables and the Community page's. On the front page the bands look as they did and any other section is a band in the same style; on other pages a band brings its own heading. The National Retreats band became an Events section with an All retreats button. The newsletter's "featured cards" come from the front page's featured card sections. Admin engine: a child collection can have its own side tables and gated nested collections.
- [ ] Check in a browser: the front page (every band, the countdown overlapping the hero, reading mode, the menu's Home dropdown), editing the hero and a band in Page management, a Hero and a Numbers section put on another page, hiding a section, the Community blog (pinned posts, feeds), a draft preview of the front page, the newsletter's featured cards.
- [x] **Core pages as sections** (migrations 081, 082): Feedback, Request, QR codes, Give, Privacy and Terms are pages of sections now, edited in Page management like any other. Their forms and embeds are section types any page can use (Website feedback form, Request form, Data request form, Giving button, QR code maker); Give's words, and all of Privacy and Terms, are blocks (headings, paragraphs, lists), with "Last updated" in the section's blurb. The privacy contact email was written into the policy's text and its Site settings field is gone. These pages keep their address (the site's code links to them) and can't be deleted. The privacy notice's link now goes to #cookies-and-browser-storage.
- [ ] Check in a browser: each of the six pages (reading width of Privacy and Terms, the giving modal opening), editing a Privacy paragraph, a Request form section put on another page.
- [x] **Page registry** (migration 080): every page of the site is a row in Pages → Page management (admins and up): its address, title, intro, Hidden (Not found below viewer) and Disabled (out of the menus, the sitemap and search; the address still works), and the order of its admin card. New pages are made there, as pages of sections at the address given (any address but the admin's, the API's, the records' and the account pages'). The admin home's Pages group opens with a Page management banner (New page, Menus), then a card per page. The six page editors (Retreats, Community...) are one editor now; site.json's `pages` and Navigation's page list moved into the registry and are gone. The fixed pages (Feedback, Request, Give, QR codes, Privacy, Terms, the front page) take their words from it too and can't be deleted.
- [ ] Check in a browser: the admin home's banner and page cards, making a page (address, sections) and opening it, hiding and disabling one (menus, the page signed out), renaming Feedback, the Under page select in Navigation.
## v1.14.0-profiles: page features (branch `page-features`, with `nav-access` under it, no PR yet; migrations 078 and 079, back up the database before deploying)
- [x] **Featured event label** (Mobile): the "Featured event" badge left the headline; from lg up it sits above the event's card it names, and on a phone (the card under the words) it's left out.
- [x] **Site version names**: the tag's words after the number are the version's name, `v1.13.2-region-cards` → "The Region Cards Update" (`src/lib/version.ts`), shown with the number in the site's footer and beside the version in the admin's footer and home.
- [x] **Image converter** (Tools → Image converter): pictures to JPG, PNG or WebP in the browser (nothing uploaded): pick or drop several, a quality slider for JPG and WebP, download each or all. JPG fills transparency white. Media's images each have a Download as… (JPG, PNG, WebP) doing the same (`src/lib/convertImage.ts`).
- [x] **Directory tabs** (migration 078): the People directory preset takes several People tags, a tab each in the order picked (Directory: tags under the section); one tag shows without tabs, reading mode lists every tag. Each section's old single tag became its first.
- [x] **Blog post tabs** (migration 079): a Tab block in a post (its text the tab's title) starts a tab holding the blocks after it; blocks before the first Tab are the intro above the tabs. The contents list follows the open tab, a link to a heading in another tab opens it, and Download PDF and reading mode show every tab under its title. Outside a post a Tab block reads as a heading.
- [x] **Featured event card height** (Sections): from lg up the event's photo sits beside its words instead of above them, with tighter type and buttons, so the card is about as tall as the hero's text beside it; stacked as before on a phone. The photo stays whole (16:9).
- [x] **Word import, more of it** (Page Features): a line starting `Tab:` (any style) starts a tab; the Quote style becomes a Quote (a dash and a name at the end is who said it), Intense Quote a Callout, a line of `---` a Divider, a YouTube, Vimeo or Facebook link alone on its line a Video, and `Button: Register` with Register linked a Button. Blog posts → What becomes what (beside Import from Word) shows the whole mapping; `docs/importing.md` too. The note after an import counts tabs and the rest.
- [x] **Side nav sun into the footer** (Navigation): the sun is far bigger than the sticky layer that carries it, so once the last section went up past the list it hung over the footer. It now fades out as the list leaves with the last section, and back in on the way up.
- [ ] Check in a browser: the featured event card beside a two-line headline at 1024, 1280 and 1536px; What becomes what and a real Word document with Tab: lines, a quote and a video link; the side nav sun fading at the end of a long page (2xl screen) and with a tall footer; the featured event hero at phone and desktop width, the footers' version line, converting a PNG with transparency to JPG and a JPG to WebP (and Download as in Media), a Directories section with two tags and with one, a post with an intro and three tabs (contents, keyboard arrows, PDF, reading mode).
## Page Editing (branch `nav-access`, no PR yet; migration 077)
- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft.
- [x] **Preview on the real page**: Preview saves the draft and opens the record's page in a new tab with it applied, under an amber "Previewing a draft" bar, for signed-in admin accounts only; anyone else sees the live page. The server answers that tab's reads from a second connection holding the draft in a transaction it rolls back, so no page needed code of its own.
- [ ] Check in a browser: save a draft of an event, a site page (a section's title) and Navigation (a link), preview each, publish one, discard one; open the same address signed out.
## Accounts (branch `nav-access`, no PR yet; migration 076, back up the database before deploying)
- [x] **Profile accounts** (migration 076, `docs/profile-accounts.md`): a member role below viewer, signed in to the site and their own profile, never the admin (`/api/admin` now refuses anything under viewer). By invite only: Data → Profile accounts (admins and up) adds an email and shows its link once; Email invite sends a fresh one through Gmail. The link (`/account/welcome`) sets a password, or they sign in with Google under that email, any Google account. A New sign-in link on the account doubles as a password reset.
- [x] **Claiming a People record**: on `/account` (Your profile; the footer's Sign in link) they ask to be a record; admins approve or decline it under Claims, or set it directly on the account.
- [x] **Editing it and choosing what shows**: with a record, they edit its pronouns, tagline, location, public email and phone, bio and photo, and hide any of photo, pronouns, tagline, bio, email, phone, location, links. Hidden parts stay in the record (the People editor shows the same switches) and are left out everywhere on the site: every public read of people goes through the new `v_people_public` view, and the views that read people were rebuilt over it.
- [x] **Discord linking**: a profile links its Discord account (identify scope: id and name) from `/account`; an admin can set or clear it on the account. Off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set on the service.
- [ ] Check in a browser: invite (copy link and Email invite), the welcome page with a password and with a non-org Google account, a claim and its approval, editing and hiding (then the person's page, a team page and a people tile signed out), Discord linking once it's set up, a member opening /admin.
## Navigation (branch `nav-access`, no PR yet; migration 075, back up the database before deploying)
- [x] **Pages → Navigation** (migration 075): the header's pages and buttons, the footer's Get in Touch and bottom row, edited in the admin (admins and up): place, order, label, link (a page, a #section or an address elsewhere), a header page set under another page's menu (after its sections), a filled button (Give's style, also beside the footer's logo), new tab. `navConfig.ts` is now only the defaults the app starts from before the nav loads. Page titles and intros moved here from Site settings (the old rows came along).
- [x] **Hidden pages**: a page ticked Hidden in Navigation answers Not found (404, noindex) to everyone below viewer, server and app both, and is out of the menus, the sitemap and the not-found page's suggestions; links to it are only sent to viewers and up. Signed in, it shows with a bar saying it's hidden. Its sections aren't cached (`server/src/siteNav.js`, `GET /api/nav`).
- [x] **Shop**: a Shop page of sections at `/shop` (Pages → Shop, empty for now), starting hidden, with a Shop button in the header (beside Contact Us and Give, and in the phone menu's list with them). Unhide it in Navigation once it has content; its sections can link out to the Bonfire store.
- [ ] Check in a browser: the header and phone menu, a page set under another's menu, the footer, signed out and signed in (the hidden bar, Shop showing), light and dark.
## Feature updates (branch `feature-updates`, v1.13.x, no PR yet; migrations 069 to 071, back up the database before deploying)
- [x] **Partner cards, logo first**: the organization cards (Partners, Ministries) lead with the logo, large and centered, the name under it as a small line (still the heading); with no logo, its initials. Cards sit raised with a shadow and an accent top edge.
- [x] **Frame a photo on upload**: photo fields (people, event photo and card background, blog cover and guest photo, hero photos, link card pictures, block images, schedule graphics and map images; not logos) open Frame the photo for a JPEG, PNG or WebP: drag (or arrow keys) to place, zoom slider, a shape menu (the field's own first; As uploaded keeps the photo's). The framed part is what uploads; Upload as is skips. Nothing stored beside the picture, so re-framing is uploading again.

46
docs/drafts.md Normal file
View file

@ -0,0 +1,46 @@
# Drafts
Any record the admin edits (events, people, organizations, blog posts,
the front page, the site pages, Navigation, Site settings...) can be
saved as a draft instead of going live (migration 077). One draft per
record; anyone who can edit the record can save, preview, publish or
discard it.
## In the editor
- **Save draft** keeps the form as the record's draft. It's checked the
way a save is (same field errors), but nothing on the site changes.
- **Preview** saves the draft and opens the record's page in a new tab
showing it, with an amber bar ("Previewing a draft"). Only a
signed-in admin account (viewer and up) sees the draft; anyone else
opening that address sees the live page. Stop previewing in the bar
returns the tab to the live site.
- **Publish** (the Save button, while there's a draft) saves it for
real and drops the draft.
- **Discard draft** throws it away; the live version is untouched.
Opening a record that has a draft opens the draft, with a note saying
who saved it and when. If the live record was saved after the draft was
started, the note says so: publishing replaces those changes. Lists
mark records with a draft.
Records not yet created have no drafts: Create is the only save (leave
them unpublished until they're ready).
## How it works
`server/src/drafts.js`. A draft is the editor's whole form, as a save
would send it. Saving one applies it inside a transaction that is
always rolled back (`rolledBackSync` in `server/src/db.js`), so it's
validated without being written. A preview is a public API read sent
with `X-Draft-Preview: <entity>/<id>` (`src/lib/api.ts` adds it in a tab
opened with `?preview=`): the server opens a second connection to the
database, applies the draft in a transaction there, answers the read
from it, and rolls back. WAL keeps those writes unseen by every other
request. Public reads carry `Vary: X-Draft-Preview`, so a browser never
mixes a cached live answer with a preview.
`tx()` nests as a savepoint, which is what lets a save run inside the
rolled-back transaction. Where each entity's page is: `PREVIEW_PATHS` in
`src/lib/adminSchema.ts` (an entity without one has drafts but no
Preview button).

View file

@ -6,12 +6,16 @@ off until the service has an OAuth client ID and secret.
## Who gets in
Two kinds of account can sign in with Google:
Three kinds of account can sign in with Google:
- **Group accounts**, when access groups are set up (below): anyone in
one of the site's Workspace groups. Their account is made at their
first sign-in, and their role follows the group.
- **Accounts made with admin-cli**, as before.
- **Profile accounts** (members, `docs/profile-accounts.md`), invited
from Data → Profile accounts. These are the one case outside the
Workspace: any Google account under the invited email, from the
site's `/sign-in` page or the invite's welcome page.
Created with
`admin-cli.js add <email>` (the password it asks for stays as a way in
@ -23,7 +27,8 @@ changes. `admin-cli.js list` shows which accounts are linked.
Refused, with a message on the login page: no admin account for that
email (and in no access group), an email already linked to a different Google account, a
disabled account, any account outside the Workspace domain (checked by
Google's `hd` claim, not just the email), an unverified email.
Google's `hd` claim, not just the email) unless it's a profile account's,
an unverified email.
Code: `server/src/googleAuth.js` (the Google side),
`server/src/routes/auth.js` (matching and linking accounts) and

View file

@ -18,6 +18,19 @@ authors and a cover, then tick Published.
| Tables | Table blocks: a row per line, cells split by `\|`, the first row the header |
| Bold, italic, links (http, https, mailto) | `**bold**`, `*italic*`, `[text](url)`, in paragraphs, list items and table cells |
And lines written a certain way, in any style:
| In the document | In the post |
| --- | --- |
| A line starting `Tab:`, eg. `Tab: Overview` | A Tab block: the post is split into tabs from there (the blocks before the first are the intro above the tabs) |
| The Quote style | A Quote block; a dash and a name at the end (`... - Jane Doe`) is who said it |
| The Intense Quote style | A Callout block |
| A line of `---` alone | A Divider |
| A YouTube, Vimeo or Facebook link alone on its line (the link text can be anything) | A Video block |
| `Button: Register`, with "Register" linked | A Button block, its label and link |
The same table is on Blog posts, beside Import from Word (What becomes what).
A post with three headings or more gets **Show contents** turned on. The
URL ID is the title as a slug, with `-2`, `-3` when it's taken.

View file

@ -41,15 +41,14 @@ also take a separate `http2 on;`.
## The bundle
Only the home page is in the main bundle. Every other page, and the
whole admin, loads when first visited (`src/App.tsx`). A tab still
running an old build that asks for a page removed by a deploy reloads
once to pick up the new one.
Every page, the front page included, and the whole admin, loads when
first visited (`src/App.tsx`). A tab still running an old build that
asks for a page removed by a deploy reloads once to pick up the new
one.
The home page asks for events and the timeline alongside its own data
(`src/pages/Home.tsx`), and the server tells the browser to fetch
`/api/front-page` and the first hero photo while the JS downloads
(`preload` in `server/src/pageMeta.js`).
The server tells the browser to fetch the front page's data
(`/api/site-pages/home`) and its hero's first photo while the JS
downloads (`preload` in `server/src/pageMeta.js`).
## Images

46
docs/planning-center.md Normal file
View file

@ -0,0 +1,46 @@
# Planning Center
Admin → Data → Planning Center (admins and up) brings one Planning
Center People list into the site's people, by hand (migration 085).
One way: nothing is sent to Planning Center.
## Setup
1. In Planning Center, make (or pick) a People **list** of the people who
should be on the site, eg. "Website". Its number is in its address:
`people.planningcenteronline.com/lists/1234567`.
2. Admin → Panel → Site settings → **Planning Center → People list**: that
number.
3. A personal access token: https://api.planningcenteronline.com/oauth/applications
→ Personal Access Tokens → New, as an account that can see that list.
Put its two halves on the service (`systemctl edit ngu-api`):
```
[Service]
Environment=PCO_APP_ID=...
Environment=PCO_SECRET=...
```
then `systemctl restart ngu-api`. (`PCO_BASE` overrides the API's
address, for testing.)
## Using it
**Compare with Planning Center** fetches the list. Each member shows:
- the site person they're **linked** to, or one **suggested** by the
same email (private or public), else the same name;
- for that person, each field that would change: name, sort name
("Last, First"), private email and private phone, the site's value
beside Planning Center's.
For each, choose **Link to** the suggestion (and whether to update it
from Planning Center), link to **someone else**, **make a new person**
(unpublished, to fill in and publish later), or **Skip**. **Apply**
writes what you chose, all at once; nothing changes before. Planning
Center wins where both have a value; a blank in Planning Center leaves
the site's. Once linked, a person is matched by Planning Center's id
from then on, whatever their name or email becomes.
Code: `server/src/planningCenter.js` (the API, the comparison, the
writes), `server/src/routes/pco.js`, `src/pages/admin/AdminPco.tsx`.

78
docs/profile-accounts.md Normal file
View file

@ -0,0 +1,78 @@
# Profile accounts
People can have an account on the site for their own profile (migration
076). Nobody signs up: an admin invites them.
## How it goes
1. **Invite.** Data → Profile accounts → Invite someone (admins and up):
an email, and a name if you like. That makes a *member* account with
no password, and shows its invite link once, for 14 days. Copy it to
send yourself, or press Email invite to send a fresh one through
Gmail (needs Gmail set up, `docs/google-drive-and-mail.md`; the link
shown before stops working).
2. **Sign up.** The link opens `/account/welcome`: they set a password,
or continue with Google under the invited email (any Google account,
not only @nextgenerationofunity.org, when Google sign-in is on,
`docs/google-sign-in.md`). Either takes up the invite.
3. **Claim.** On `/account` (Your profile, also the footer's Sign in
link) they pick the People record that's them and send the request.
It waits under Claims on Data → Profile accounts until an admin
approves or declines it. An admin can also set an account's record
directly there.
4. **Edit.** With a record, they edit its pronouns, tagline, location,
public email and phone, bio and photo, and tick what to hide on the
site. Their name, publishing and everything else stay the admin's.
Changes are live as soon as they save.
A member is below viewer: signed in to the site, never to the admin
(`/api/admin` refuses anything under viewer, `requireStaff` in
`server/src/auth.js`). Staff accounts can claim a record too, from
`/account`.
Forgotten password: on the account's row, New sign-in link (or Email a
sign-in link); opening it sets a new password.
Turn off stops an account signing in and ends its sessions. Remove
deletes the account; its People record stays.
## What "hidden" does
Each hidden part (photo, pronouns, tagline, bio, public email, public
phone, location, links) stays in the record, and the admin's People
editor shows the same switches (Hidden on the site). The site never
shows it: every public read goes through the `v_people_public` view,
which nulls hidden fields, and person links are left out when links are
hidden (`loadLinks` in `server/src/shape.js`). When adding a public
query on people, read `v_people_public`, not `people`.
## Discord
A profile can link its Discord account (the `identify` scope only: the
Discord user id and name), kept for the gamification to come. Off until
the service has a Discord application:
1. https://discord.com/developers/applications → New Application.
2. OAuth2 → Redirects: add `https://nextgenerationofunity.org/api/account/discord/callback`
(and the dev server's address, if you test there).
3. Copy the Client ID and Client Secret into the service's environment
(`systemctl edit ngu-api`):
```
[Service]
Environment=DISCORD_CLIENT_ID=...
Environment=DISCORD_CLIENT_SECRET=...
```
`DISCORD_REDIRECT_URI` overrides the return address (default: site.json's
`url` plus `/api/account/discord/callback`).
4. `systemctl restart ngu-api`.
An admin can set or clear an account's Discord id by hand on its row
(the long number from Discord: Developer Mode, then Copy User ID).
Code: `server/src/invites.js`, `server/src/discordAuth.js`,
`server/src/routes/account.js` (the member's own routes),
`server/src/routes/profiles.js` (the admin's), `src/pages/Account.tsx`,
`src/pages/AccountWelcome.tsx`, `src/pages/SignIn.tsx`,
`src/pages/admin/AdminProfiles.tsx`.

View file

@ -23,7 +23,7 @@ same build.
| --- | --- |
| Site name, address, default description | `site.json`: `title`, `url`, `description` (blank uses the front page's subhead) |
| Default preview image | `site.json`: `openGraph.image`, eg. `/uploads/<file>` from Admin → Tools → Media. Blank means pages without their own image have none. |
| Static pages (Retreats, Community, History…) | `site.json`: `pages`. The page's heading and intro read the same entry, so they can't drift. A new static page needs an entry. |
| The site's pages (Retreats, Community, History…) | Admin → Pages → Page management (`site_pages`). The page's heading and intro read the same row, so they can't drift. Disabled pages are `noindex` and out of the sitemap; hidden ones are a 404 to search engines. |
| Records (events, organizations, teams, awards, people, posts) | The database: the record's name, then its tagline or first paragraph; its own image (an event's card background, else its logo; a post's cover; a person's photo; an organization's logo). SVGs aren't used as previews. |
| Whether search may list it | `site.json` `robots.index` for the whole site; per record, published and listed is indexed, published but unlisted is `noindex`, anything else is a 404. `/admin` is always `noindex`. |

View file

@ -15,8 +15,8 @@ what a dropdown in the admin editor says.
- [Renaming what a dropdown shows](#renaming-what-a-dropdown-shows)
- [Adding, removing or renaming a stored value](#adding-removing-or-renaming-a-stored-value)
- [Every dropdown in the editor](#every-dropdown-in-the-editor)
- [Front page section names](#front-page-section-names)
- [Front page stat sources](#front-page-stat-sources)
- [Front page sections](#front-page-sections)
- [Stat sources](#stat-sources)
- [Other content that lives in code](#other-content-that-lives-in-code)
- [Writing text in the editor](#writing-text-in-the-editor)
- [Making the change](#making-the-change)
@ -36,7 +36,8 @@ what a dropdown in the admin editor says.
| 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) |
| A static page's title and intro (also its search title and description), the site's name, description, preview image, icons, search indexing, privacy contact email | the database, over `site.json` | Admin → Panel → Site settings (superadmins). Blank uses `site.json`, which also holds the site's address and the pages' defaults. See `docs/seo.md` |
| A page's title and intro (also its search title and description), its address, Hidden and Disabled | the database (`site_pages`, 080) | Admin → Pages → Page management (admins and up), where new pages are made too |
| The site's name, description, preview image, icons, search indexing, privacy contact email | the database, over `site.json` | Admin → Panel → Site settings (superadmins). Blank uses `site.json`, which also holds the site's address. See `docs/seo.md` |
| Uploaded images | disk + the `media` table | Admin → Tools → Media, or any image field. See `docs/media-uploads.md` |
The rule of thumb from `CLAUDE.md`: data belongs in the database,
@ -153,8 +154,9 @@ together, in one branch:
3. **`src/lib/adminSchema/<entity>.ts`**: the `options` on the form field, and on
the list filter if there is one.
4. **Anywhere the public site renders or relies on the value**, listed in
the table below (for example `EVENT_TYPES` for event types, or the
`SECTIONS` map in `Home.tsx` for front page sections).
the table below (for example `EVENT_TYPES` for event types, or
`PRESETS` in `SitePage.tsx` and `BANDS` in `sections/Bands.tsx` for
section types).
If the server descriptor and the database disagree, the API refuses to
start: `admin-schema-sync.js` compares them at boot and throws with a
@ -183,16 +185,15 @@ also in `server/src/admin-schema/` and a CHECK):
| Timeline → Kind (+ list filter) | milestone, event, organization, award, people | no | `KIND_NAMES` in `src/pages/sections/history/TimelineEntry.tsx` |
| Timeline → Points at (+ list filter) | event, organization, award, person, team | no | `refHref` in `src/lib/hrefs.ts` |
| Timeline → Precision (and on events/orgs) | year, month, day | no | the history page's grouping |
| Front page → Countdown → Only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/routes/home.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. |
| Front page → Background | brand, photos | **yes** | `HeroStage.tsx` |
| Front page → Feature | none, livestream, video, event | **yes** | `HeroStage.tsx`; the event is picked in `server/src/routes/home.js` |
| Front page → Sections → Section | countdown, retreats, calendar, stats, timeline, connect, featured | **yes**, `FRONT_PAGE_SECTIONS` | `SECTIONS` in `src/pages/Home.tsx`; see [below](#front-page-section-names) |
| 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 Content → Columns (073) | 2, 3, 4 | **yes**, inline in `src/lib/adminSchema/frontPage.ts` | `GRID_COLUMNS` in `FeaturedCards.tsx`; the CHECK on `front_page.featured_columns` |
| Front page → Featured cards → Size (073; front page only, regions and the Community blog stay automatic) | normal, wide, tall, large | **yes**, inline in `src/lib/adminSchema/frontPage.ts` | `SPANS` and `sizeOf` in `FeaturedCards.tsx`; the CHECK on `featured_cards.size` |
| 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/<tag>`. |
| Pages → Sections → Countdown: only this type | retreat, class, workshop, meeting, other | **yes** | `server/src/sectionData.js` (picks the countdown event). The same values as Events → Type, so adding a type widens both CHECKs. |
| Pages → Sections → Hero: background | brand, photos | **yes** | `HeroStage.tsx` |
| Pages → Sections → Hero: feature | none, livestream, video, event | **yes** | `HeroStage.tsx`; the event is picked in `server/src/sectionData.js` |
| Pages → Sections → Numbers → Number Source | manual, years_since, regions, … | **yes**, `STAT_SOURCES` in `src/lib/adminSchema/sitePages.ts` | `STAT_QUERIES` in `server/src/sectionData.js`; see [below](#stat-sources) |
| Featured cards → Card type (a Community blog's pinned community posts offer link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
| Pages → Sections → Featured cards: columns (073) | 2, 3, 4 | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `GRID_COLUMNS` in `FeaturedCards.tsx`; the CHECK on `section_featured.columns` |
| Featured cards → Size (073; featured card sections only, regions and the Community blog stay automatic) | normal, wide, tall, large | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `SPANS` and `sizeOf` in `FeaturedCards.tsx`; the CHECK on `featured_cards.size` |
| 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 (section type) | community_blog, group_map, region_list, partner_list, events, timeline, people_directory, feedback_form, request_form, data_request_form, giving, qr_maker, hero, countdown, calendar, stats, featured_cards, connect | **yes**, `PRESETS` in `src/lib/adminSchema/sitePages.ts`, every page offers them all | `PRESETS` in `src/pages/SitePage.tsx`; the bands (hero, countdown, calendar, numbers, featured cards, connect, and a timeline shown as a rail) in `src/pages/sections/Bands.tsx`, their data from `server/src/sectionData.js`; forms and embeds in `src/pages/sections/FormSections.tsx`. A People directory shows each tag's first `DIRECTORY_PREVIEW` people (`src/pages/sections/PeopleDirectory.tsx`), linking to `/directory/<tag>`. |
| Pages → Sections → Cards: list (organization cards preset, 067) | partner, ministry, partner,ministry | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `partner_list` in `PRESETS` in `src/pages/SitePage.tsx` passes it as the kind to `OrgListCards`; a section's hand-picked Cards: organizations (`page_section_orgs`) replace it |
| Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a |
@ -209,67 +210,49 @@ code):
| People → Directories → Tag; Pages → Sections → Directory: tag | `person_tag_types` | Data → People tags |
| Organizations and Events → Tags → Tag | `tags` | Data → 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 → Scope (+ list filter); Pages → Sections → 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, 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 |
| Pages → Sections → Blog: pinned posts (ours) → Post | `blog_posts` | blog posts, newest first |
| 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 |
| Person awards → Presented at; Pages → Sections → Count down to, Hero: featured event | `events` | events |
---
## Front page section names
## Front page sections
"Section name" means three different things on the front page, and
each is changed in a different place:
The front page is a page of sections like the others (Admin → Pages →
Page management → Home, migration 083): the hero first, then its
bands, each a section with a type. Its heading is the section's title
(up to 60 characters on the front page), its anchor the section's URL
ID (`#retreats`, `#calendar`, `#numbers`, `#connect`), which the
header's Home dropdown lists (not the hero or the countdown). Rename
a heading freely; change a URL ID only if you mean to break links to
it. The names in the section type dropdown are `PRESETS` in
`src/lib/adminSchema/sitePages.ts`.
| What you see | Where it's set |
| --- | --- |
| **The heading on the page** ("National Retreats", "What's on") | **Admin → Pages → Front page → Page sections → Heading.** Blank uses the default below. |
| The default heading when that field is blank | `SECTIONS` in `src/pages/Home.tsx`, the `title` of each entry |
| **The name in the admin's Section dropdown** ("Events Carousel (National Retreats)") | `FRONT_PAGE_SECTIONS` in `src/lib/adminSchema/frontPage.ts` |
| The links in the header's Home dropdown | the bands shown, under their headings (`src/lib/navSections.ts`) |
To rename a band **for visitors**, use the admin. To rename how it
reads **in the editor's dropdown**, edit `FRONT_PAGE_SECTIONS`:
```ts
const FRONT_PAGE_SECTIONS = [
["countdown", "Event Countdown"],
["retreats", "Events Carousel (National Retreats)"], // ← the right-hand side is the label
["calendar", "Event Calendar"],
...
];
```
The subnav links jump to each band by its anchor: the `id` passed in
each band's `render` in `Home.tsx` (`#retreats`, `#calendar`,
`#numbers`, `#connect`, and `#hero` for the hero). If you rename a
subnav label in `navConfig.ts`, leave its `hash` alone unless you also
change the band's `id`.
**Adding a new kind of band** (not just renaming one) is a feature,
not a relabel: it needs a component, an entry in `SECTIONS` in
`Home.tsx`, the key added to `FRONT_PAGE_SECTIONS`, to the
`enumeration("section", …)` in `server/src/admin-schema/frontPage.js`, to the
`FrontPageSectionKey` type in `src/lib/useFrontPage.ts`, and to the
CHECK on `front_page_sections.section` via a migration.
**Adding a new kind of band** is a feature, not a relabel: its
component and an entry in `BANDS` (`src/pages/sections/Bands.tsx`),
its settings table (a migration) and extension or collection in
`sectionsChild` (`server/src/admin-schema/sitePages.js`), its data in
`server/src/sectionData.js`, its fields in `src/lib/adminSchema/sitePages.ts`,
and its value added to the CHECK on `page_sections.preset`.
---
## Front page stat sources
## Stat sources
The numbers band's "Number Source" dropdown works the same way:
A Numbers section's "Number Source" dropdown works the same way:
- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema/frontPage.ts`.
- **Relabel a source:** `STAT_SOURCES` in `src/lib/adminSchema/sitePages.ts`.
- **Change what a count counts:** its query in `STAT_QUERIES` in
`server/src/routes/home.js`. Keep it counting exactly what the
`server/src/sectionData.js`. Keep it counting exactly what the
matching public page shows (published rows), or the number and the
page will disagree.
- **Add a source:** the CHECK on `front_page_stats.source` (migration),
the `enumeration("source", …)` in `server/src/admin-schema/frontPage.js`,
- **Add a source:** the CHECK on `section_stats.source` (migration),
the `enumeration("source", …)` in `server/src/admin-schema/sitePages.js`,
`STAT_SOURCES`, and a query in `STAT_QUERIES`.
---
@ -278,19 +261,18 @@ The numbers band's "Number Source" dropdown works the same way:
| What | File | Notes |
| --- | --- | --- |
| Header and footer navigation, each page's sections (the header dropdowns, mobile menu and footer site map) | `src/navConfig.ts` | `PAGE_LINKS` (order), `NAV_ACTIONS`. Each page's sections aren't listed there: they follow the page itself, through `src/lib/navSections.ts` (the site pages' sections from Admin → Pages; the front page's bands it shows, with `src/lib/frontPageBands.ts` giving each band's anchor and default heading). A new page also needs a route in `src/App.tsx`. |
| Section titles, blurbs and colors on Feedback, Privacy, Terms | the page file in `src/pages/` | the `SECTIONS` array at the top. |
| Header and footer navigation, each page's sections (the header dropdowns, mobile menu and footer site map) | Admin → Pages → Navigation (the database, `075_site_nav.sql`); `src/navConfig.ts` is only the defaults the app starts from before it loads | Links: where each shows (header pages, header buttons, footer Get in Touch, footer bottom row), order, label, a header page set under another's menu, a filled button, new tab. Each page's sections aren't listed there: they follow the page itself, through `src/lib/navSections.ts` (every page's sections from Admin → Pages → Page management, the front page's included, but its hero and countdown). A new page is made in Page management, no code: it's a page of sections at the address given. |
| Site-wide announcement banner | `src/data/bannerConfig.ts` | `enabled: false` hides it. Bump `id` when the message changes, so people who dismissed the old one see the new one. |
| History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. |
| Group map tiles and area names | `src/data/mapGrid.ts` | `AREAS` (tile positions) and `AREA_NAMES`. Which region paints which tile is in the database (Admin → Data → Organizations → a region → Map areas). |
| Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. |
| Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints, the name field's question and each type's `fields` (the details it asks for, and where each lands in the admin editor: a field path, a link row or a description paragraph) are client-only: the server stores whatever detail keys come as JSON (`feedback.details`, 049), so adding a field needs no migration. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `<RequestLink>` (`src/components/RequestLink.tsx`). |
| The site's colors, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colors (superadmins): pick a color, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A color that arrives as data (a page accent, an event's or region's color) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| 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. |
| The icons a Connect nav section's 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 `<html>` 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-<family>-<shade>)` (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) is a stored hex, 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. |
| Privacy Policy and Terms wording | the database (082) | Admin → Pages → Page management → Privacy Policy or Terms of Service: their sections' blocks, and the "Last updated" date in the section's blurb whenever the wording changes. The privacy contact email is in the policy's text. 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) | |
@ -305,6 +287,14 @@ The numbers band's "Number Source" dropdown works the same way:
## Writing text in the editor
Rotating words: type the choices in braces, `{Next|Now|Rising}`, in a
hero headline, a section title, a heading, a paragraph, a callout or a
quote, and the word cycles through them. How it moves is Admin →
Panel → Site settings → Animated words, or the hero's or block's own
Rotating words fields. Menus, tab titles, search and emails show the
first choice. The component is `src/components/RotatingWords.tsx`; its
motions are CSS in `RotatingWords.css`.
Conventions for any label, help text or option added to the admin, so
the editor reads consistently:

View file

@ -139,7 +139,9 @@ function coerceRow(columns, data, { prefix = "" } = {}) {
return { values, errors };
}
const applies = (gate, row) => !gate || row[gate.column] === gate.value;
/* A gate on a column's value: one value, or any of a list. */
const applies = (gate, row) =>
!gate || (Array.isArray(gate.value) ? gate.value.includes(row[gate.column]) : row[gate.column] === gate.value);
/* ── Read ────────────────────────────────────────────────────── */
@ -242,6 +244,12 @@ function readChildren(db, child, ownerId) {
)
.all(...params);
// A row's own 1:1 side tables (a section's settings for its type:
// its hero's words, its blog's slots).
for (const ext of child.extensions ?? []) {
for (const row of rows) row[ext.key] = readExtension(db, ext, row.id);
}
// Nested collections, to any depth: a page's sections, each
// section's blocks, each block's items. The id goes as text: a JS
// number binds as REAL, which a TEXT owner column (a section's
@ -411,6 +419,10 @@ export function deleteRow(db, entity, rawId) {
}
const id = normalizeId(entity, rawId);
// Records the site can't do without (the pages it draws in code).
if (entity.undeletable?.includes(id)) {
throw new HttpError(405, "The site needs this one: it can be hidden or disabled, not deleted.");
}
const result = wrapDbErrors(() =>
db.prepare(`DELETE FROM ${entity.table} WHERE ${entity.idColumn} = ?`).run(id),
);
@ -419,7 +431,7 @@ export function deleteRow(db, entity, rawId) {
/* ── Write helpers ───────────────────────────────────────────── */
function writeExtensions(db, entity, id, payload, parentValues) {
function writeExtensions(db, entity, id, payload, parentValues, prefix = "") {
for (const ext of entity.extensions ?? []) {
if (!applies(ext.when, parentValues)) {
// The gate closed (the kind changed away from this side
@ -431,7 +443,7 @@ function writeExtensions(db, entity, id, payload, parentValues) {
}
const { values, errors } = coerceRow(ext.columns, payload[ext.key] ?? {}, {
prefix: `${ext.key}.`,
prefix: `${prefix}${ext.key}.`,
});
if (Object.keys(errors).length) {
throw new HttpError(422, "Validation failed", errors);
@ -584,8 +596,13 @@ function writeRows(db, child, ownerId, incomingRaw, prefix, parentValues) {
.run(...params),
);
const rowId = Number(result.lastInsertRowid);
// Its own side tables, gated on its values (a section's preset),
// then its collections, gated the same way.
if (child.extensions) writeExtensions(db, child, rowId, raw, values, rowPrefix);
for (const child2 of child.children ?? []) {
writeRows(db, child2, String(result.lastInsertRowid), raw[child2.key], `${rowPrefix}${child2.key}.`, values);
if (!applies(child2.when, values)) continue;
writeRows(db, child2, String(rowId), raw[child2.key], `${rowPrefix}${child2.key}.`, values);
}
});
}

View file

@ -85,6 +85,13 @@ function collectGroups(entity) {
...Object.keys(child.owner.inherit ?? {}),
].filter(Boolean),
});
for (const ext of child.extensions ?? []) {
groups.push({
table: ext.table,
columns: ext.columns ?? [],
engineSupplied: [ext.idColumn, ext.owner?.column, ext.owner?.kindColumn].filter(Boolean),
});
}
for (const nested of child.children ?? []) walk(nested);
};

View file

@ -18,9 +18,14 @@
regions or groups row should exist)
children ordered collections, replaced wholesale on save;
`readRole` on one hides it from lesser roles, as
on an extension (an organization's contacts)
on an extension (an organization's contacts). A
child may have `extensions` of its own (a page
section's settings for its type), and its nested
collections a `when` on its values
singleton the one id this entity ever has; the engine
refuses create and delete (see front_page)
refuses create and delete (see navigation)
undeletable ids the engine refuses to delete (the pages the
site draws in code)
check (db, id) => void, run after a save has written
everything, inside its transaction: throw an
HttpError to refuse it (site settings' colors)
@ -50,21 +55,15 @@ import { people } from "./admin-schema/people.js";
import { teams } from "./admin-schema/teams.js";
import { awards } from "./admin-schema/awards.js";
import { timeline } from "./admin-schema/timeline.js";
import { frontPage } from "./admin-schema/frontPage.js";
import { blogPosts } from "./admin-schema/blog.js";
import { siteSettings } from "./admin-schema/siteSettings.js";
import { siteNav } from "./admin-schema/siteNav.js";
import { newsletters } from "./admin-schema/newsletters.js";
import { personTagTypes } from "./admin-schema/personTags.js";
import { tags } from "./admin-schema/tags.js";
import { contactTypes } from "./admin-schema/contactTypes.js";
import { redirects } from "./admin-schema/redirects.js";
import {
communityPage,
retreatsPage,
resourcesPage,
organizationPage,
historyPage,
} from "./admin-schema/sitePages.js";
import { pages } from "./admin-schema/sitePages.js";
export const ENTITIES = {
organizations,
@ -77,13 +76,9 @@ export const ENTITIES = {
teams,
awards,
timeline,
front_page: frontPage,
blog_posts: blogPosts,
community_page: communityPage,
retreats_page: retreatsPage,
resources_page: resourcesPage,
organization_page: organizationPage,
history_page: historyPage,
pages,
navigation: siteNav,
site_settings: siteSettings,
newsletters,
};
@ -112,6 +107,8 @@ export const OPTION_QUERIES = {
// Link fields with `redirects: true` pick from these (068).
redirects: "SELECT id, id || ' (' || target_url || ')' AS label FROM redirects ORDER BY id",
blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title",
// Navigation's Under page: a page by its address (080).
site_pages: "SELECT path AS id, title || ' (' || path || ')' AS label FROM site_pages ORDER BY sort_order, title",
// org_id rides along so the affiliation row can filter the list
// down to teams of the organization it already names.

View file

@ -152,6 +152,8 @@ export const blocksChild = (ownerKind) => ({
"table",
"cards",
"people",
// A blog post's tab (079): its text is the tab's title.
"tab",
],
{ required: true },
),
@ -162,6 +164,10 @@ export const blocksChild = (ownerKind) => ({
text("cite"),
// Video blocks only (066): an uploaded video's WebVTT file.
text("captions"),
// Its rotating words (084): blank keeps the site's.
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
enumeration("word_direction", ["top", "bottom"]),
int("word_seconds"),
// People blocks only (054): whose team's tiles to show.
text("team_id"),
],

View file

@ -1,129 +0,0 @@
import { text, url, int, bool, enumeration, featuredCardsChild } from "./columns.js";
/* ── Front page ──────────────────────────────────────────────────
A singleton: one row, id 'home', seeded by the schema and never
created by the admin. `singleton` tells the engine to refuse create
and delete, and the CHECK on front_page.id is what makes a second
row impossible even without it.
Every collection here is owned by page_id and replaced wholesale.
That is safe for the same reason it is for links and blocks
(nothing has a foreign key into these tables), and paths carry
their actions as a nested collection, the shape content blocks
and their items already use. */
export const frontPage = {
key: "front_page",
table: "front_page",
idColumn: "id",
idKind: "slug",
singleton: "home",
concurrency: "updated_at",
list: {
columns: ["id", "headline", "hero_backdrop", "hero_feature", "updated_at"],
filters: [],
search: [],
order: "id",
},
columns: [
enumeration("hero_backdrop", ["brand", "photos"]),
enumeration("hero_feature", ["none", "livestream", "video", "event"]),
text("hero_event_id"),
text("eyebrow"),
text("headline"),
text("subhead"),
text("primary_label"),
url("primary_url"),
text("secondary_label"),
url("secondary_url"),
int("slide_seconds"),
url("livestream_url"),
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"]),
int("featured_columns"),
text("video_still"),
],
children: [
{
key: "slides",
table: "front_page_slides",
owner: { column: "page_id" },
order: "sort_order",
columns: [
text("media", { required: true }),
text("alt"),
text("caption"),
url("link_url"),
],
},
{
key: "sections",
table: "front_page_sections",
owner: { column: "page_id" },
order: "sort_order",
columns: [
enumeration(
"section",
["countdown", "retreats", "calendar", "stats", "timeline", "connect", "featured"],
{ required: true },
),
text("title"),
text("blurb"),
bool("is_hidden"),
],
},
{
key: "stats",
table: "front_page_stats",
owner: { column: "page_id" },
order: "sort_order",
columns: [
text("label", { required: true }),
enumeration("source", [
"manual",
"years_since",
"regions",
"groups",
"partners",
"events_held",
"retreats_held",
"people",
"awards_given",
]),
text("value"),
text("suffix"),
text("note"),
],
},
featuredCardsChild("front_page"),
{
key: "paths",
table: "front_page_paths",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("label", { required: true }), text("icon"), text("blurb")],
children: [
{
key: "actions",
table: "front_page_path_actions",
owner: { column: "path_id" },
order: "sort_order",
columns: [
text("label", { required: true }),
text("description"),
url("url", { required: true }),
],
},
],
},
],
};

View file

@ -42,6 +42,9 @@ export const people = {
text("location_label"),
bool("is_published"),
bool("is_listed"),
// What's taken off the site (076): its owner's choice on their
// profile, or an admin's. v_people_public applies it.
...["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"].map((key) => bool(`hide_${key}`)),
],
extensions: [

View file

@ -0,0 +1,36 @@
import { text, bool, enumeration } from "./columns.js";
/* ── Navigation (075_site_nav.sql) ───────────────────────────────
Pages → Navigation: the header's and footer's links, in order
(siteNav.js reads them for the site; the pages themselves are
Page management's, sitePages.js). Admins and up. */
export const siteNav = {
key: "navigation",
table: "site_nav",
idColumn: "id",
idKind: "slug",
singleton: "site",
concurrency: "updated_at",
writeRole: "admin",
list: { columns: ["id", "updated_at"], filters: [], search: [], order: "id" },
columns: [],
children: [
{
key: "links",
table: "site_nav_links",
owner: { column: "nav_id" },
order: "sort_order",
columns: [
enumeration("place", ["main", "action", "footer", "legal"], { required: true }),
text("label", { required: true }),
text("path", { required: true }),
text("parent_path"),
enumeration("style", ["filled"]),
bool("new_tab"),
],
},
],
};

View file

@ -1,17 +1,25 @@
import { text, url, int, enumeration, featuredCardsChild, blocksChild } from "./columns.js";
import { HttpError } from "../admin-crud.js";
import { text, url, int, bool, enumeration, featuredCardsChild, blocksChild } from "./columns.js";
/* ── The site's own pages (056_site_pages.sql) ───────────────────
/* ── The site's pages (056_site_pages.sql, 080_page_registry.sql) ──
Community, Retreats, Resources, Organization and History: one
site_pages row each, edited as its own singleton, with its
sections nested under it and each section's blocks under that
Pages → Page management: every page of the site, one site_pages
row each (its address, title, intro, Hidden and Disabled), with
its sections nested under it and each section's blocks under that
(the blocks' items under them, as on any record). A section is
either its blocks or a preset, a prebuilt part of the site
(SitePage.tsx draws both).
(SitePage.tsx draws both). New pages are made here.
Community also carries the blog section's settings: the
community_page row (same id) as an extension, and its pinned
posts, cards and feeds, all owned by that id. */
A section type that needs more than its blocks keeps its settings
in tables of its own (083_section_settings.sql), the section's
extensions and collections here, each gated on its preset: a
hero's words and slides, a countdown's event, a stats band's
numbers, a pathfinder's paths, featured cards, a Community blog's
slots, pinned posts and feeds. The front page is a page of
sections like the rest. */
/* Gates on the section's preset. */
const is = (preset) => ({ column: "preset", value: preset });
const sectionsChild = {
key: "sections",
@ -31,48 +39,76 @@ const sectionsChild = {
"events",
"timeline",
"people_directory",
// What used to be whole pages (081).
"feedback_form",
"request_form",
"data_request_form",
"giving",
"qr_maker",
// The front page's bands, on any page (083).
"hero",
"countdown",
"calendar",
"stats",
"featured_cards",
"connect",
]),
text("scope_id"),
enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]),
enumeration("view", ["carousel", "grid", "map"]),
text("tag_id"),
// Organization cards (067): the kinds listed by themselves.
enumeration("org_kinds", ["partner", "ministry", "partner,ministry"]),
bool("is_hidden"),
],
children: [
blocksChild("page_section"),
{
// Organization cards (067): a hand-picked list, shown instead.
key: "orgs",
table: "page_section_orgs",
owner: { column: "section_id" },
order: "sort_order",
columns: [text("org_id", { required: true })],
},
],
};
const sitePage = (id, more = {}) => ({
key: `${id}_page`,
table: "site_pages",
idColumn: "id",
idKind: "slug",
singleton: id,
concurrency: "updated_at",
list: { columns: ["id", "updated_at"], filters: [], search: [], order: "id" },
columns: [],
...more,
children: [sectionsChild, ...(more.children ?? [])],
});
export const communityPage = sitePage("community", {
extensions: [
{
key: "hero",
table: "section_hero",
idColumn: "section_id",
when: is("hero"),
columns: [
text("eyebrow"),
text("headline"),
text("subhead"),
text("primary_label"),
url("primary_url"),
text("secondary_label"),
url("secondary_url"),
enumeration("backdrop", ["brand", "photos"]),
int("slide_seconds"),
enumeration("feature", ["none", "livestream", "video", "event"]),
url("livestream_url"),
text("livestream_title"),
url("video_url"),
text("video_title"),
text("video_captions"),
text("video_still"),
text("event_id"),
// Its rotating words (084).
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
enumeration("word_direction", ["top", "bottom"]),
int("word_seconds"),
],
},
{
key: "countdown",
table: "section_countdown",
idColumn: "section_id",
when: is("countdown"),
columns: [text("event_id"), text("scope_id"), enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"])],
},
{
key: "featured",
table: "section_featured",
idColumn: "section_id",
when: is("featured_cards"),
columns: [int("columns")],
},
{
key: "blog",
table: "community_page",
idColumn: "id",
table: "section_blog",
idColumn: "section_id",
when: is("community_blog"),
columns: [
text("internal_title"),
int("internal_slots"),
@ -84,25 +120,145 @@ export const communityPage = sitePage("community", {
},
],
children: [
blocksChild("page_section"),
{
key: "pinned_posts",
table: "community_page_pinned_posts",
owner: { column: "page_id" },
// A People directory's tags (078), a tab each, in order.
key: "tags",
table: "page_section_tags",
owner: { column: "section_id" },
order: "sort_order",
columns: [text("tag_id", { required: true })],
},
{
// Organization cards (067): a hand-picked list, shown instead.
key: "orgs",
table: "page_section_orgs",
owner: { column: "section_id" },
order: "sort_order",
columns: [text("org_id", { required: true })],
},
{
key: "slides",
table: "section_slides",
owner: { column: "section_id" },
order: "sort_order",
when: is("hero"),
columns: [text("media", { required: true }), text("alt"), text("caption"), url("link_url")],
},
{
key: "stats",
table: "section_stats",
owner: { column: "section_id" },
order: "sort_order",
when: is("stats"),
columns: [
text("label", { required: true }),
enumeration("source", [
"manual",
"years_since",
"regions",
"groups",
"partners",
"events_held",
"retreats_held",
"people",
"awards_given",
]),
text("value"),
text("suffix"),
text("note"),
],
},
{
key: "paths",
table: "section_paths",
owner: { column: "section_id" },
order: "sort_order",
when: is("connect"),
columns: [text("label", { required: true }), text("icon"), text("blurb")],
children: [
{
key: "actions",
table: "section_path_actions",
owner: { column: "path_id" },
order: "sort_order",
columns: [text("label", { required: true }), text("description"), url("url", { required: true })],
},
],
},
// Featured cards, and a Community blog's pinned community posts.
{ ...featuredCardsChild("page_section"), when: { column: "preset", value: ["featured_cards", "community_blog"] } },
{
key: "blog_posts",
table: "section_blog_posts",
owner: { column: "section_id" },
order: "sort_order",
when: is("community_blog"),
columns: [text("post_id", { required: true })],
},
featuredCardsChild("community_page"),
{
key: "feeds",
table: "community_page_feeds",
owner: { column: "page_id" },
table: "section_feeds",
owner: { column: "section_id" },
order: "sort_order",
when: is("community_blog"),
columns: [url("url", { required: true }), text("label")],
},
],
});
};
export const retreatsPage = sitePage("retreats");
export const resourcesPage = sitePage("resources");
export const organizationPage = sitePage("organization");
export const historyPage = sitePage("history");
/* Pages the site's own code links to (the footer's defaults, the
Request buttons, the privacy notice, Tools → QR codes): renamed,
hidden or disabled, but never moved or deleted. */
export const CORE_PAGES = { home: "/", give: "/give", feedback: "/feedback", request: "/request", qr: "/qr", privacy: "/privacy", terms: "/terms" };
/* Addresses a page can't take: the admin, the API, the uploads, the
records' own pages and the account pages. */
const RESERVED = [
"admin", "api", "uploads", "assets", "pa", "go",
"events", "regions", "groups", "partners", "organizations", "teams", "awards", "people", "blog", "directory",
"sign-in", "account", "sitemap.xml", "robots.txt",
];
/* After a save: the address is one a page may have. */
function checkPage(db, id) {
const page = db.prepare(`SELECT path FROM site_pages WHERE id = ?`).get(id);
const first = page?.path.split("/")[1];
if (first && RESERVED.includes(first)) {
throw new HttpError(422, "Validation failed", { path: `/${first} belongs to another part of the site. Pick another address.` });
}
if (CORE_PAGES[id] && page.path !== CORE_PAGES[id]) {
throw new HttpError(422, "Validation failed", { path: `The site links to this page at ${CORE_PAGES[id]}, so its address stays.` });
}
if (id !== "home" && page.path === "/") throw new HttpError(422, "Validation failed", { path: "/ is the front page." });
}
export const pages = {
key: "pages",
table: "site_pages",
idColumn: "id",
idKind: "slug",
concurrency: "updated_at",
undeletable: Object.keys(CORE_PAGES),
list: {
columns: ["id", "title", "path", "is_hidden", "is_disabled", "updated_at"],
filters: [],
search: ["title", "path"],
order: "sort_order, title",
},
columns: [
text("path", { required: true }),
text("title", { required: true }),
text("description"),
bool("is_hidden"),
bool("is_disabled"),
int("sort_order"),
],
children: [sectionsChild],
check: checkPage,
};

View file

@ -1,10 +1,11 @@
import { THEME_TOKENS, checkTheme } from "../theme.js";
import { text, enumeration } from "./columns.js";
import { text, int, enumeration } from "./columns.js";
/* ── Site settings (035_site_settings.sql) ──────────────────────
A singleton of overrides for what site.json says: name,
description, preview image, icons, search indexing, and static
pages' titles and intros. Superadmins only. pageMeta.js merges it
description, preview image, icons and search indexing (static
pages' titles and intros are Pages → Navigation's, siteNav.js).
Superadmins only. pageMeta.js merges it
over site.json. */
export const siteSettings = {
key: "site_settings",
@ -29,23 +30,21 @@ export const siteSettings = {
text("favicon"),
text("apple_touch_icon"),
enumeration("indexing", ["on", "off"]),
text("privacy_email"),
text("notify_emails"),
text("access_group_viewer"),
text("access_group_editor"),
text("access_group_admin"),
enumeration("report_daily", ["on", "off"]),
enumeration("report_weekly", ["on", "off"]),
// Rotating words' defaults (084).
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
enumeration("word_direction", ["top", "bottom"]),
int("word_seconds"),
// Data → Planning Center's list (085).
text("pco_list_id"),
],
children: [
{
key: "pages",
table: "site_setting_pages",
owner: { column: "settings_id" },
order: "sort_order",
columns: [text("path", { required: true }), text("title"), text("description")],
},
{
key: "colors",
table: "site_setting_colors",

View file

@ -219,14 +219,27 @@ export async function requireAuth(c, next) {
await next();
}
export const ROLES = ["viewer", "editor", "admin", "superadmin"];
const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
/* member is a profile account (076): signed in to the site and their
own profile, below every admin role, so it passes no admin check.
/api/admin as a whole needs viewer (index.js, requireStaff). */
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"];
const RANK = { member: 1, viewer: 2, editor: 3, admin: 4, superadmin: 5 };
/* Whether a user is at least this rank. A ladder, never equality. */
export function hasRole(user, role) {
return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity);
}
/* Anyone who uses the admin: a signed-in account of viewer and up.
A profile account (member) is signed in but gets 403 here. */
export async function requireStaff(c, next) {
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401);
if (!hasRole(user, "viewer")) return c.json({ error: "Not allowed." }, 403);
c.set("user", user);
await next();
}
export function requireRole(...roles) {
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
return async (c, next) => {

View file

@ -36,27 +36,67 @@ export async function openDatabase(path) {
db.exec("PRAGMA busy_timeout = 5000");
db.driverName = "node:sqlite";
// A draft's preview opens its own connection to the same file (drafts.js).
db.path = path;
return db;
}
/* ── Transactions ──────────────────────────────────────────────
node:sqlite has no db.transaction(), so do it by hand. Runs
fn() and commits, or rolls back and rethrows.
fn() and commits, or rolls back and rethrows. Inside another
tx() (or rolledBack(), below) it's a savepoint instead, so a
save can run inside a transaction that's then thrown away:
how a draft is checked and previewed (drafts.js).
───────────────────────────────────────────────────────────── */
export function tx(db, fn) {
db.exec("BEGIN");
const depth = db.txDepth ?? 0;
const savepoint = `tx_${depth}`;
db.exec(depth ? `SAVEPOINT ${savepoint}` : "BEGIN");
db.txDepth = depth + 1;
try {
const result = fn();
db.exec("COMMIT");
db.exec(depth ? `RELEASE ${savepoint}` : "COMMIT");
return result;
} catch (err) {
try {
db.exec("ROLLBACK");
db.exec(depth ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
} catch {
/* already rolled back */
}
throw err;
} finally {
db.txDepth = depth;
}
}
/* Runs fn() in a transaction that is always rolled back, whatever
fn() does: its writes are seen only by fn() itself. fn() may wait,
so only on a connection of its own (a draft's preview, drafts.js):
on the main one, another request would see the writes meanwhile. */
export async function rolledBack(db, fn) {
if (db.txDepth) throw new Error("rolledBack() can't run inside a transaction.");
db.exec("BEGIN");
db.txDepth = 1;
try {
return await fn();
} finally {
db.txDepth = 0;
db.exec("ROLLBACK");
}
}
/* The same for a synchronous fn(), which nothing else can run
during, so the main connection is fine (checking a draft). */
export function rolledBackSync(db, fn) {
if (db.txDepth) throw new Error("rolledBackSync() can't run inside a transaction.");
db.exec("BEGIN");
db.txDepth = 1;
try {
return fn();
} finally {
db.txDepth = 0;
db.exec("ROLLBACK");
}
}

84
server/src/discordAuth.js Normal file
View file

@ -0,0 +1,84 @@
/* ═══════════════════════════════════════════════════════════════
DISCORD LINKING
A profile account links its Discord account (076): OAuth 2.0 with
the identify scope only, which gives the Discord user's id and
name and nothing else (no servers, no messages). The routes are in
routes/account.js; an admin can also set or clear it by hand
(routes/profiles.js). Kept for the gamification to come, which
matches Discord members to people by this id.
DISCORD_CLIENT_ID from the Discord developer portal
DISCORD_CLIENT_SECRET the same; never in the repo
DISCORD_REDIRECT_URI default <site.json url>/api/account/discord/callback
With no client id or secret it's off: the profile page doesn't
offer it and the routes answer 404. Setup: docs/profile-accounts.md.
═══════════════════════════════════════════════════════════════ */
import { randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
const AUTHORIZE = "https://discord.com/oauth2/authorize";
const TOKEN = "https://discord.com/api/oauth2/token";
const ME = "https://discord.com/api/users/@me";
export function discordConfig() {
const clientId = process.env.DISCORD_CLIENT_ID;
const clientSecret = process.env.DISCORD_CLIENT_SECRET;
if (!clientId || !clientSecret) return null;
let redirectUri = process.env.DISCORD_REDIRECT_URI ?? null;
if (!redirectUri) {
try {
const origin = (loadSite().url ?? "").replace(/\/$/, "");
if (origin) redirectUri = `${origin}/api/account/discord/callback`;
} catch {
redirectUri = null;
}
}
return { clientId, clientSecret, redirectUri };
}
/* Where to send the browser, and the state to keep until it's back. */
export function startLink(config) {
const state = randomBytes(24).toString("base64url");
const url = new URL(AUTHORIZE);
url.search = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: "identify",
state,
prompt: "consent",
});
return { url: url.toString(), state };
}
/* Trade the code for a token, then ask who it is. Returns
{ id, name } or throws. */
export async function finishLink(config, code) {
const res = await fetch(TOKEN, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "authorization_code",
code,
redirect_uri: config.redirectUri,
}),
signal: AbortSignal.timeout(10_000),
});
const token = await res.json().catch(() => ({}));
if (!res.ok || !token.access_token) throw new Error(`Discord didn't accept the link (${res.status}).`);
const me = await fetch(ME, {
headers: { Authorization: `Bearer ${token.access_token}` },
signal: AbortSignal.timeout(10_000),
});
const user = await me.json().catch(() => ({}));
if (!me.ok || !user.id) throw new Error(`Discord didn't say who you are (${me.status}).`);
return { id: String(user.id), name: String(user.global_name || user.username || "").slice(0, 100) || null };
}

View file

@ -14,6 +14,17 @@
cells split by |)
bold, italic, links **bold**, *italic*, [text](url)
And a few lines written a certain way (docs/importing.md), any
style:
"Tab: Overview" a tab block (079): the post
is split into tabs there
the Quote style a quote block
the Intense Quote style a callout block
"---" alone a divider
a YouTube, Vimeo or Facebook link a video block
alone on its line
"Button: [Register](https://…)" a button block
Images, text boxes, footnotes and comments aren't carried over;
the result counts what was skipped so the editor can say so.
@ -216,7 +227,7 @@ export function readDocx(buf) {
if (!text) continue;
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
if (!title && (level === 0 || level === 1)) {
if (!title && (level === 0 || level === 1) && !lineBlock(text, style)) {
close();
title = text.replace(/\*/g, "");
continue;
@ -231,6 +242,12 @@ export function readDocx(buf) {
continue;
}
}
const special = lineBlock(text, style);
if (special) {
close();
blocks.push(special);
continue;
}
if (level >= 1) {
close();
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
@ -248,3 +265,37 @@ export function readDocx(buf) {
return { title, date, blocks, skipped: counts };
}
/* ── Lines written a certain way ──────────────────────────────── */
const VIDEO_HOST = /^https?:\/\/(www\.)?(youtube\.com|youtu\.be|m\.youtube\.com|vimeo\.com|player\.vimeo\.com|facebook\.com|fb\.watch)\//i;
/* The one link a line is made of, "[text](url)" or a bare url, or null. */
function loneLink(text) {
const md = /^\[[^\]]*\]\(([^)\s]+)\)$/.exec(text);
if (md) return md[1];
return /^https?:\/\/\S+$/.test(text) ? text : null;
}
/* A block a paragraph stands for by how it's written, or null for an
ordinary one (docs/importing.md). */
function lineBlock(text, style) {
const plain = text.replace(/\*/g, "").trim();
const tab = /^tab:\s*(.+)$/i.exec(plain);
if (tab) return { type: "tab", text: tab[1].trim().slice(0, 80) };
if (/^(-{3,}|_{3,})$/.test(plain)) return { type: "divider" };
const button = /^button:\s*\[([^\]]+)\]\(([^)\s]+)\)$/i.exec(text.trim());
if (button) return { type: "button", text: button[1].replace(/\*/g, ""), href: button[2] };
const link = loneLink(text.trim());
if (link && VIDEO_HOST.test(link)) return { type: "video", href: link };
if (style === "intense quote") return { type: "callout", text };
if (style === "quote") {
// A dash and a name at the end ("… - Jane Doe", any dash) is who said it.
const said = /^(.*\S)\s+[—–-]\s*([^—–-]{2,80})$/.exec(text);
return said ? { type: "quote", text: said[1], cite: said[2].trim() } : { type: "quote", text };
}
return null;
}

156
server/src/drafts.js Normal file
View file

@ -0,0 +1,156 @@
/* ═══════════════════════════════════════════════════════════════
DRAFTS (077_drafts.sql)
A record's changes saved without going live: one per record, of
any entity the admin edits. The draft is the editor's whole form,
exactly what a save would send, so publishing is that save
(PATCH, routes/admin-entities.js), which then drops the draft.
Nothing applies a draft for real until it's published. Twice it's
applied and thrown away:
checking when it's saved, in a transaction on the main
connection that's always rolled back
(rolledBackSync): updateRow is synchronous, so no
other request can see it, and a draft that a save
would refuse is refused now, with the same errors
preview a public API read sent with X-Draft-Preview:
<entity>/<id> by a signed-in viewer and up runs on a
connection of its own (the same file), inside a
transaction holding the applied draft, rolled back
when the answer is made (previewDrafts). The site
draws the real page from it, with no code of its own
for previews. WAL keeps that connection's writes
unseen by everyone else; it holds the write lock
meanwhile, a few milliseconds, which other writes
wait out (busy_timeout).
The draft is applied over the live record as it is now, so a
save made since the draft was started is overwritten when it's
published; the editor says when that's so (stale).
═══════════════════════════════════════════════════════════════ */
import { currentUser, hasRole } from "./auth.js";
import { openDatabase, rolledBack, rolledBackSync } from "./db.js";
import { HttpError, normalizeId, updateRow } from "./admin-crud.js";
import { ENTITIES } from "./admin-schema.js";
/* Who may preview a draft: anyone who can read the admin. */
export const PREVIEWS = "viewer";
export const entityNamed = (key) => (Object.hasOwn(ENTITIES, key) ? ENTITIES[key] : null);
const liveStamp = (db, entity, id) =>
entity.concurrency
? db
.prepare(`SELECT ${entity.concurrency} AS stamp FROM ${entity.table} WHERE ${entity.idColumn} = ?`)
.get(normalizeId(entity, id))?.stamp
: undefined;
/* Writes the draft over the live record, its concurrency stamp taken
from the live row so the check passes. Call inside a rolled-back
transaction, or as the real publish. */
function apply(db, entity, id, payload) {
const stamp = liveStamp(db, entity, id);
return updateRow(db, entity, id, entity.concurrency ? { ...payload, [entity.concurrency]: stamp } : payload);
}
export function readDraft(db, key, id) {
const entity = entityNamed(key);
const row = db
.prepare(
`SELECT d.*, u.name AS updated_by_name, u.email AS updated_by_email
FROM drafts d LEFT JOIN admin_users u ON u.id = d.updated_by
WHERE d.entity = ? AND d.record_id = ?`,
)
.get(key, String(id));
if (!row) return null;
const live = entity ? liveStamp(db, entity, id) : undefined;
return {
payload: JSON.parse(row.payload),
created_at: row.created_at,
updated_at: row.updated_at,
updated_by: row.updated_by_name ?? row.updated_by_email ?? null,
// The live record was saved after the draft was started.
stale: Boolean(entity?.concurrency && row.base_updated_at && live && live !== row.base_updated_at),
};
}
/* The ids of an entity's records that have a draft, for its list. */
export const draftIds = (db, key) =>
db.prepare(`SELECT record_id FROM drafts WHERE entity = ?`).all(key).map((row) => row.record_id);
/* Checks the draft by applying it and throwing that away, then keeps
it. An HttpError from the check (422 with fields, say) refuses it. */
export function saveDraft(db, key, id, payload, userId) {
const entity = entityNamed(key);
if (!entity) throw new HttpError(404, "Unknown entity.");
if (!payload || typeof payload !== "object") throw new HttpError(400, "Expected the record's form.");
rolledBackSync(db, () => apply(db, entity, id, payload));
const existing = db.prepare(`SELECT base_updated_at FROM drafts WHERE entity = ? AND record_id = ?`).get(key, String(id));
const base = existing ? existing.base_updated_at : (payload[entity.concurrency] ?? null);
db.prepare(
`INSERT INTO drafts (entity, record_id, payload, base_updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (entity, record_id) DO UPDATE
SET payload = excluded.payload, updated_by = excluded.updated_by, updated_at = datetime('now')`,
).run(key, String(id), JSON.stringify(payload), base, userId, userId);
return readDraft(db, key, id);
}
export function dropDraft(db, key, id) {
db.prepare(`DELETE FROM drafts WHERE entity = ? AND record_id = ?`).run(key, String(id));
}
/* Middleware for the public API: a GET carrying X-Draft-Preview from
a signed-in viewer and up is answered with that draft applied. Any
other request, or a draft that isn't there, goes on as usual. */
export async function previewDrafts(c, next) {
if (c.req.method !== "GET" || /^\/api\/(admin|auth|account)(\/|$)/.test(c.req.path)) return next();
await answer(c, next);
// A public read may be kept a minute (shape.js, CACHE): never hand
// the live copy to a preview tab, or a preview's to anyone.
c.res.headers.append("Vary", "X-Draft-Preview");
}
async function answer(c, next) {
const wanted = c.req.header("x-draft-preview");
if (!wanted) return next();
const main = c.get("db");
if (!hasRole(currentUser(main, c), PREVIEWS)) return next();
const slash = wanted.indexOf("/");
const key = wanted.slice(0, slash);
let id;
try {
id = decodeURIComponent(wanted.slice(slash + 1));
} catch {
return next();
}
const entity = entityNamed(key);
const draft = slash > 0 && entity ? readDraft(main, key, id) : null;
if (!draft) return next();
const db = await openDatabase(main.path);
try {
await rolledBack(db, async () => {
// A draft the record has outgrown (a field it no longer has,
// say) shows the live page rather than an error; saving it in
// the editor says what's wrong.
try {
apply(db, entity, id, draft.payload);
} catch (err) {
console.warn(`draft preview ${key}/${id} not applied: ${err.message}`);
}
c.set("db", db);
await next();
});
} finally {
db.close();
}
// Only for this tab, never kept.
c.res.headers.set("Cache-Control", "no-store");
}

View file

@ -2,7 +2,7 @@
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), for its "newest community posts".
lists (section_feeds, 083), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets

View file

@ -30,6 +30,12 @@
Nothing here creates an account. A Google login is only let in
if admin-cli has already made one for that email (see auth.js
routes), and is linked to it on first use.
Profile accounts (076) are the one case outside the domain: an
invited member may sign in with any Google account under the
invited email. finishLogin says whether the identity is in the
Workspace domain (inDomain) instead of refusing it, and the
callback lets an outside identity reach a member account only.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
@ -70,8 +76,10 @@ export function googleConfig() {
}
/* The first leg: where to send the browser, and the state and PKCE
verifier to keep (in a short-lived cookie) until it comes back. */
export function startLogin(config) {
verifier to keep (in a short-lived cookie) until it comes back.
anyDomain: a profile account's sign-in, so the account chooser
isn't narrowed to the Workspace. */
export function startLogin(config, { anyDomain = false } = {}) {
const state = base64url(randomBytes(24));
const verifier = base64url(randomBytes(48));
const challenge = base64url(createHash("sha256").update(verifier).digest());
@ -87,7 +95,7 @@ export function startLogin(config) {
code_challenge_method: "S256",
// Only a hint to Google's account chooser; the hd claim is what's
// actually checked on the way back.
hd: config.domain,
...(anyDomain ? {} : { hd: config.domain }),
prompt: "select_account",
});
@ -102,7 +110,7 @@ export class GoogleLoginError extends Error {
}
/* The second leg: trade the code for tokens and check the identity.
Returns { sub, email, name } or throws GoogleLoginError. */
Returns { sub, email, name, inDomain } or throws GoogleLoginError. */
export async function finishLogin(config, code, verifier) {
let res;
try {
@ -145,9 +153,7 @@ export async function finishLogin(config, code, verifier) {
if (!claims.email_verified || !email) {
throw new GoogleLoginError("unverified", "That Google account's email isn't verified.");
}
if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) {
throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`);
}
const inDomain = String(claims.hd ?? "").toLowerCase() === config.domain && email.endsWith(`@${config.domain}`);
return { sub: String(claims.sub), email, name: claims.name ?? null };
return { sub: String(claims.sub), email, name: claims.name ?? null, inDomain };
}

View file

@ -24,7 +24,6 @@ import { rateLimit } from "./rateLimit.js";
import content from "./routes/content.js";
import people from "./routes/people.js";
import history from "./routes/history.js";
import home from "./routes/home.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import sitePages from "./routes/sitePages.js";
@ -32,6 +31,9 @@ import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
import auth from "./routes/auth.js";
import account from "./routes/account.js";
import profiles from "./routes/profiles.js";
import pco from "./routes/pco.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
@ -43,11 +45,12 @@ import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { logSafe, requireStaff, 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";
import { previewDrafts } from "./drafts.js";
const HOST = process.env.HOST ?? "127.0.0.1";
const PORT = Number(process.env.PORT ?? 3001);
@ -134,7 +137,7 @@ app.use(
so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login"]) app.use(path, smallBody);
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */
@ -178,6 +181,10 @@ app.use("*", async (c, next) => {
await next();
});
// A draft's preview (drafts.js): a public read from a signed-in
// viewer with X-Draft-Preview answers with that draft applied.
app.use("/api/*", previewDrafts);
app.get("/api/health", (c) =>
c.json({ ok: true, schema: version, driver: db.driverName }),
);
@ -185,7 +192,6 @@ app.get("/api/health", (c) =>
app.route("/api", content);
app.route("/api", people);
app.route("/api", history);
app.route("/api", home);
app.route("/api", directory);
app.route("/api", blog);
app.route("/api", sitePages);
@ -206,9 +212,19 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,
// and Google has already checked the person by the second.
app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 }));
// The whole admin is for viewer and up; a profile account (member)
// is signed in but kept out. Each router still checks its own.
app.use("/api/admin/*", requireStaff);
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
// A profile account's own page (076); setting a password from an
// invite is held to the login's pace.
app.use("/api/account/accept", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
app.route("/api/account", account);
app.route("/api/admin", admin);
app.route("/api/admin", profiles);
app.route("/api/admin", pco);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);

89
server/src/invites.js Normal file
View file

@ -0,0 +1,89 @@
/* ═══════════════════════════════════════════════════════════════
INVITES: how a profile account (076) comes to exist
Nobody signs up. An admin adds an email (Data → Profile
accounts, routes/profiles.js), which makes a member account with
no password, and issues an invite: a link to /account/welcome
with a random token. The token itself is shown once, to the
admin, and emailed if they press Email invite; the database
keeps only its SHA-256, like a session's. Issuing a new one
replaces the old, so a link sent to the wrong place can be
killed by sending another.
The link lets its holder set a password (routes/account.js).
Signing in with Google under the invited email takes it up too
(routes/auth.js). Either way the token is cleared.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
import { loadSite } from "./pageMeta.js";
import { mailReady, sendMail } from "./googleService.js";
export const INVITE_DAYS = 14;
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
/* A new invite for this account, replacing any before it. Returns
the link, which is never stored. */
export function issueInvite(db, accountId, invitedBy) {
const token = randomBytes(32).toString("base64url");
db.prepare(
`UPDATE admin_users
SET invite_hash = ?, invite_expires_at = datetime('now', ?),
invited_at = datetime('now'), invited_by = ?
WHERE id = ?`,
).run(sha256(token), `+${INVITE_DAYS} days`, invitedBy, accountId);
return inviteLink(token);
}
export function inviteLink(token) {
let origin = "";
try {
origin = (loadSite().url ?? "").replace(/\/$/, "");
} catch {
origin = "";
}
return `${origin}/account/welcome?token=${encodeURIComponent(token)}`;
}
/* The account an unexpired invite token belongs to, or null. */
export function accountForInvite(db, token) {
if (typeof token !== "string" || token.length < 20 || token.length > 100) return null;
return (
db
.prepare(
`SELECT id, email, name, role, is_active
FROM admin_users
WHERE invite_hash = ? AND invite_expires_at > datetime('now') AND is_active = 1`,
)
.get(sha256(token)) ?? null
);
}
/* The invite as an email, through Gmail (googleService.js). */
export async function emailInvite(db, account, link) {
if (!mailReady()) throw new Error("Gmail isn't set up on the server (docs/google-drive-and-mail.md).");
let site = { title: "Next Generation of Unity" };
try {
site = loadSite();
} catch {
// The default name will do.
}
const hello = account.name ? `Hi ${account.name},` : "Hi,";
await sendMail({
to: account.email,
subject: `Your ${site.title} profile`,
text: [
hello,
"",
`You're invited to make a profile account on the ${site.title} website. Open this link to set a password, or to sign in with Google under this email:`,
"",
link,
"",
`The link works once, for ${INVITE_DAYS} days. Once you're in, you can find your profile on the site, ask to claim it, and choose what of it shows.`,
"",
"If you weren't expecting this, you can ignore it.",
].join("\n"),
});
}

View file

@ -0,0 +1,122 @@
-- ═══════════════════════════════════════════════════════════════
-- 075 SITE NAVIGATION
--
-- Pages → Navigation edits what navConfig.ts used to fix in code:
-- the header's links and buttons, the footer's, and each page's
-- title, intro and whether it is hidden. navConfig.ts stays as the
-- defaults the app starts from before this arrives.
--
-- site_nav the editor's one row ('site')
-- site_nav_links every link, in order, by where it shows:
-- main the header's pages (sections drop
-- down under each); with a parent, in
-- that page's dropdown instead
-- action the header's buttons, right side
-- (and the phone menu's list under
-- the pages); a filled one also sits
-- beside the footer's logo
-- footer the footer's Get in Touch list
-- legal the footer's bottom row
-- site_nav_pages a static page's title and intro (the page's
-- heading and its search text) over site.json's,
-- and is_hidden: a hidden page is out of the nav
-- and the sitemap and answers Not found to anyone
-- below viewer (pageMeta.js, siteNav.js)
--
-- site_setting_pages (Site settings → Page titles and intros) moves
-- into site_nav_pages and is dropped.
--
-- The Shop page: site_pages takes 'shop' (a page of sections like
-- the others), rebuilt since its CHECK can't change in place. It
-- starts hidden, with its header button.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_nav (
id TEXT PRIMARY KEY CHECK (id = 'site'),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO site_nav (id) VALUES ('site');
CREATE TABLE site_nav_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nav_id TEXT NOT NULL REFERENCES site_nav (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
place TEXT NOT NULL CHECK (place IN ('main', 'action', 'footer', 'legal')),
label TEXT NOT NULL,
-- '/retreats', '/organization#contact', or an https:// address
path TEXT NOT NULL,
-- main links only: the page whose dropdown it sits in
parent_path TEXT,
-- action links only: null is the outlined button
style TEXT CHECK (style IN ('filled')),
new_tab INTEGER NOT NULL DEFAULT 0 CHECK (new_tab IN (0, 1))
) STRICT;
CREATE INDEX site_nav_links_order_idx ON site_nav_links (nav_id, sort_order);
INSERT INTO site_nav_links (nav_id, sort_order, place, label, path, parent_path, style, new_tab) VALUES
('site', 0, 'main', 'Home', '/', NULL, NULL, 0),
('site', 1, 'main', 'Retreats', '/retreats', NULL, NULL, 0),
('site', 2, 'main', 'Community', '/community', NULL, NULL, 0),
('site', 3, 'main', 'Resources', '/resources', NULL, NULL, 0),
('site', 4, 'main', 'Organization', '/organization', NULL, NULL, 0),
('site', 5, 'main', 'History', '/history', NULL, NULL, 0),
('site', 6, 'action', 'Shop', '/shop', NULL, NULL, 0),
('site', 7, 'action', 'Contact Us', '/organization#contact', NULL, NULL, 0),
('site', 8, 'action', 'Give', '/give', NULL, 'filled', 1),
('site', 9, 'footer', 'Feedback', '/feedback', NULL, NULL, 0),
('site', 10, 'footer', 'Request', '/request', NULL, NULL, 0),
('site', 11, 'footer', 'Contact Us', '/organization#contact', NULL, NULL, 0),
('site', 12, 'legal', 'Privacy Policy', '/privacy', NULL, NULL, 0),
('site', 13, 'legal', 'Terms of Service', '/terms', NULL, NULL, 0);
CREATE TABLE site_nav_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nav_id TEXT NOT NULL REFERENCES site_nav (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
path TEXT NOT NULL, -- '/retreats', a key of site.json's pages
title TEXT, -- null: site.json's
description TEXT, -- null: site.json's
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
UNIQUE (nav_id, path)
) STRICT;
INSERT INTO site_nav_pages (nav_id, sort_order, path, title, description)
SELECT 'site', sort_order, path, title, description
FROM site_setting_pages WHERE settings_id = 'site';
INSERT INTO site_nav_pages (nav_id, sort_order, path, is_hidden)
VALUES ('site', (SELECT coalesce(max(sort_order) + 1, 0) FROM site_nav_pages), '/shop', 1);
DROP TABLE site_setting_pages;
-- site_pages, with 'shop'.
CREATE TABLE site_pages_new (
id TEXT PRIMARY KEY
CHECK (id IN ('community', 'retreats', 'resources', 'organization', 'history', 'shop')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO site_pages_new (id, updated_at) SELECT id, updated_at FROM site_pages;
INSERT INTO site_pages_new (id) VALUES ('shop');
-- page_sections names site_pages; legacy mode leaves it alone
-- through the rename.
PRAGMA legacy_alter_table = ON;
DROP TABLE site_pages;
ALTER TABLE site_pages_new RENAME TO site_pages;
PRAGMA legacy_alter_table = OFF;
CREATE TRIGGER site_nav_touch
AFTER UPDATE ON site_nav
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE site_nav SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER site_pages_touch
AFTER UPDATE ON site_pages
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE site_pages SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -0,0 +1,264 @@
-- ═══════════════════════════════════════════════════════════════
-- 076 PROFILE ACCOUNTS
--
-- Accounts for people, not only for the admin. An admin invites an
-- email (Data → Profile accounts); nobody signs up on their own. The
-- invite's link lets them set a password, or they sign in with
-- Google under that email, any Google account, not only
-- @nextgenerationofunity.org. Then they claim their People record,
-- an admin approves it, and they edit their profile and choose what
-- of it shows.
--
-- admin_users is rebuilt (its CHECKs can't change in place):
-- role takes 'member', below viewer: signs in to the
-- site and their own profile, never to the admin
-- access_source takes 'invite', an account made by an invite
-- person_id the People record it claimed (one account each)
-- invite_hash SHA-256 of the invite link's token, until used
-- invite_expires_at, invited_at, invited_by
-- discord_id, discord_name the linked Discord account, set by
-- its owner through Discord or by an admin
--
-- person_claims: a request to be a People record, approved or
-- declined by an admin.
--
-- people.hide_*: what its owner (or an admin) took off the site.
-- The value stays, for the admin; v_people_public is the record as
-- the site shows it, the hidden fields null, and every public read
-- goes through it, the views below included.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE admin_users_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
-- Stored lowercased. The application lowercases on every read
-- and write, so the UNIQUE index is genuinely case-insensitive
-- without depending on a collation.
email TEXT NOT NULL UNIQUE,
name TEXT,
-- Null for a Google-only account, or an invite not yet taken up.
-- A row with both can use either route in.
password_hash TEXT,
-- Google's stable subject id. Nullable, unique when present,
-- SQLite allows any number of NULLs in a unique index.
google_sub TEXT UNIQUE,
-- Listed low to high. The application treats these as a ladder,
-- not a set: each one passes every check the one below it
-- passes. The default stays 'admin' so no existing tooling
-- starts creating accounts with different powers than it did
-- yesterday.
--
-- member their own profile, on the site; no admin
-- viewer read the admin
-- editor + create and update
-- admin + delete, invite members, approve claims
-- superadmin + accounts, roles and sessions
role TEXT NOT NULL DEFAULT 'admin'
CHECK (role IN ('member', 'viewer', 'editor', 'admin', 'superadmin')),
is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
last_login_at TEXT,
access_source TEXT NOT NULL DEFAULT 'manual'
CHECK (access_source IN ('manual', 'group', 'invite')),
group_disabled INTEGER NOT NULL DEFAULT 0 CHECK (group_disabled IN (0, 1)),
groups_checked_at TEXT,
person_id TEXT UNIQUE REFERENCES people (id) ON DELETE SET NULL,
invite_hash TEXT UNIQUE,
invite_expires_at TEXT,
invited_at TEXT,
invited_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
discord_id TEXT UNIQUE,
discord_name TEXT
) STRICT;
INSERT INTO admin_users_new
(id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
access_source, group_disabled, groups_checked_at)
SELECT id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
access_source, group_disabled, groups_checked_at
FROM admin_users;
-- sessions, media, clip_jobs and drive_files name admin_users;
-- legacy mode leaves them alone through the rename.
PRAGMA legacy_alter_table = ON;
DROP TABLE admin_users;
ALTER TABLE admin_users_new RENAME TO admin_users;
PRAGMA legacy_alter_table = OFF;
CREATE TABLE person_claims (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id INTEGER NOT NULL REFERENCES admin_users (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
message TEXT,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'approved', 'declined')),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
decided_at TEXT,
decided_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL
) STRICT;
CREATE INDEX person_claims_status_idx ON person_claims (status, created_at);
CREATE INDEX person_claims_account_idx ON person_claims (account_id);
-- One open request per account.
CREATE UNIQUE INDEX person_claims_one_pending ON person_claims (account_id) WHERE status = 'pending';
ALTER TABLE people ADD COLUMN hide_photo INTEGER NOT NULL DEFAULT 0 CHECK (hide_photo IN (0, 1));
ALTER TABLE people ADD COLUMN hide_pronouns INTEGER NOT NULL DEFAULT 0 CHECK (hide_pronouns IN (0, 1));
ALTER TABLE people ADD COLUMN hide_tagline INTEGER NOT NULL DEFAULT 0 CHECK (hide_tagline IN (0, 1));
ALTER TABLE people ADD COLUMN hide_bio INTEGER NOT NULL DEFAULT 0 CHECK (hide_bio IN (0, 1));
ALTER TABLE people ADD COLUMN hide_email INTEGER NOT NULL DEFAULT 0 CHECK (hide_email IN (0, 1));
ALTER TABLE people ADD COLUMN hide_phone INTEGER NOT NULL DEFAULT 0 CHECK (hide_phone IN (0, 1));
ALTER TABLE people ADD COLUMN hide_location INTEGER NOT NULL DEFAULT 0 CHECK (hide_location IN (0, 1));
ALTER TABLE people ADD COLUMN hide_links INTEGER NOT NULL DEFAULT 0 CHECK (hide_links IN (0, 1));
-- A person as the site shows them. Every public read uses this, not
-- people; the admin reads people.
CREATE VIEW v_people_public AS
SELECT
id,
display_name,
sort_name,
CASE WHEN hide_pronouns = 0 THEN pronouns END AS pronouns,
CASE WHEN hide_tagline = 0 THEN tagline END AS tagline,
CASE WHEN hide_photo = 0 THEN photo END AS photo,
CASE WHEN hide_email = 0 THEN public_email END AS public_email,
CASE WHEN hide_phone = 0 THEN public_phone END AS public_phone,
CASE WHEN hide_location = 0 THEN locality END AS locality,
CASE WHEN hide_location = 0 THEN state_code END AS state_code,
country,
CASE WHEN hide_location = 0 THEN location_label END AS location_label,
is_published,
created_at,
updated_at,
CASE WHEN hide_bio = 0 THEN bio END AS bio,
primary_org_id,
is_listed,
specialty,
hide_links
FROM people;
-- The views that read people's public fields, over v_people_public.
DROP VIEW v_event_people;
CREATE VIEW v_event_people AS
SELECT
ep.event_id, ep.person_id, ep.role, ep.title, ep.sort_order,
p.display_name, p.pronouns, p.tagline, p.photo
FROM event_people ep
JOIN v_people_public p ON p.id = ep.person_id AND p.is_published = 1
WHERE ep.is_public = 1;
DROP VIEW v_timeline;
CREATE VIEW v_timeline AS
SELECT
t.id,
t.kind,
t.ref_kind,
t.ref_id,
t.precision,
t.is_featured,
t.is_published,
t.sort_order,
COALESCE(t.occurred_on, e.starts_on, pa.awarded_on) AS effective_date,
COALESCE(
t.title,
e.title,
o.name,
aw.name,
p.display_name,
tm.name
) AS effective_title,
COALESCE(t.blurb, e.tagline, o.tagline, aw.description, p.tagline, tm.tagline)
AS effective_blurb,
t.meta,
t.link_url,
-- Filename only. The directory is the frontend's business.
COALESCE(e.event_logo, e.org_logo, o.logo, aw.logo, p.photo, tm.logo)
AS effective_logo,
o.kind AS org_kind,
tm.org_id AS team_org_id,
tm.name AS team_name,
-- Whether the referenced record is itself visible. An entry must not
-- outlive the thing it points at being unpublished, a draft event
-- would otherwise leak its title and date onto a public page. Null
-- for a standalone milestone, which answers to nothing but its own
-- is_published.
CASE t.ref_kind
WHEN 'event' THEN e.is_published
WHEN 'organization' THEN o.is_published
WHEN 'person' THEN p.is_published
WHEN 'team' THEN tm.is_published
ELSE NULL
END AS ref_is_published,
t.occurred_on,
t.title AS title_override
FROM timeline_entries t
LEFT JOIN events e ON t.ref_kind = 'event' AND e.id = t.ref_id
LEFT JOIN organizations o ON t.ref_kind = 'organization' AND o.id = t.ref_id
LEFT JOIN awards aw ON t.ref_kind = 'award' AND aw.id = t.ref_id
LEFT JOIN v_people_public p ON t.ref_kind = 'person' AND p.id = t.ref_id
LEFT JOIN teams tm ON t.ref_kind = 'team' AND tm.id = t.ref_id
LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.ref_id
AND pa.id = (SELECT MIN(id) FROM person_awards
WHERE award_id = t.ref_id);
DROP VIEW v_org_leadership;
CREATE VIEW v_org_leadership AS
SELECT
a.org_id,
a.team_id,
t.name AS team_name,
t.sort_order AS team_sort_order,
a.person_id,
a.title,
a.role,
a.is_owner,
a.sort_order,
p.display_name,
p.sort_name,
p.pronouns,
p.tagline,
p.photo,
p.public_email,
p.location_label,
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM affiliations a
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
LEFT JOIN teams t ON t.id = a.team_id
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE a.is_public = 1
AND a.ended_on IS NULL
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;
DROP VIEW v_event_hosts;
CREATE VIEW v_event_hosts AS
SELECT
eh.id,
eh.event_id,
eh.sort_order,
CASE WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
AS host_kind,
COALESCE(eh.org_id, eh.person_id) AS host_id,
COALESCE(o.name, p.display_name) AS host_name,
o.kind AS host_org_kind,
o.logo AS host_logo,
o.color AS host_color,
p.photo AS host_photo,
COALESCE(o.is_published, p.is_published) AS host_is_published,
t.id AS host_team_id,
t.name AS host_team_name
FROM event_hosts eh
LEFT JOIN organizations o ON o.id = eh.org_id
LEFT JOIN v_people_public p ON p.id = eh.person_id
LEFT JOIN teams t ON t.id = eh.team_id AND eh.org_id IS NOT NULL AND t.is_published = 1;

View file

@ -0,0 +1,25 @@
-- ═══════════════════════════════════════════════════════════════
-- 077 DRAFTS
--
-- A record's changes saved without going live: one draft per
-- record, of any entity the admin edits (events, people, pages,
-- Navigation...). payload is the editor's whole form, as a save
-- would send it; publishing is that save, which then drops the
-- draft. Anyone who can edit the record can save, preview, publish
-- or discard it (drafts.js).
--
-- base_updated_at is the record's updated_at when the draft was
-- started, so the editor can say the live record changed since.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE drafts (
entity TEXT NOT NULL, -- the descriptor key, eg. 'events'
record_id TEXT NOT NULL,
payload TEXT NOT NULL CHECK (json_valid(payload)),
base_updated_at TEXT,
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (entity, record_id)
) STRICT;

View file

@ -0,0 +1,66 @@
-- ═══════════════════════════════════════════════════════════════
-- 078 DIRECTORY TABS
--
-- A People directory section (page_sections.preset
-- 'people_directory') shows several People tags, a tab each, in
-- the order picked: Community's Directories, eg. Musicians, Authors,
-- Creators. page_section_tags holds them; each section's one tag_id
-- becomes its first, and the column goes (page_sections is rebuilt,
-- since a column with a REFERENCES can't be dropped in place).
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE page_section_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
tag_id TEXT NOT NULL REFERENCES person_tag_types (id) ON DELETE CASCADE
) STRICT;
CREATE INDEX page_section_tags_section_idx ON page_section_tags (section_id, sort_order);
INSERT INTO page_section_tags (section_id, sort_order, tag_id)
SELECT id, 0, tag_id FROM page_sections WHERE tag_id IS NOT NULL;
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')),
-- Organization cards (067): the kinds listed by themselves.
org_kinds TEXT CHECK (org_kinds IN ('partner', 'ministry', 'partner,ministry')),
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, org_kinds)
SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
FROM page_sections;
-- page_section_orgs, page_section_tags and content_blocks' owner
-- trigger name page_sections; legacy mode leaves them alone through
-- the rename.
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);
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;

View file

@ -0,0 +1,76 @@
-- ═══════════════════════════════════════════════════════════════
-- 079 TAB BLOCKS
--
-- A blog post can be split into tabs: a 'tab' block (its text the
-- tab's title) starts a tab holding the blocks after it, up to the
-- next one; the blocks before the first are the intro above the
-- tabs. The post's contents follow the open tab (BlogPost.tsx).
-- content_blocks.type's CHECK can't change in place, so the table is
-- rebuilt, then its index and owner trigger are made again.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post', 'page_section',
'newsletter')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body', 'both')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout', 'schedule', 'table', 'cards',
'people', 'tab')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT,
team_id TEXT REFERENCES teams (id) ON DELETE SET NULL,
captions TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions
FROM content_blocks;
-- The block items and the owners' cleanup triggers name
-- content_blocks; legacy mode leaves them alone through the rename.
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
WHEN new.owner_kind = 'page_section'
AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such page section')
WHEN new.owner_kind = 'newsletter'
AND NOT EXISTS (SELECT 1 FROM newsletters WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such newsletter')
END;
END;

View file

@ -0,0 +1,93 @@
-- ═══════════════════════════════════════════════════════════════
-- 080 PAGE REGISTRY
--
-- Every page of the site is a site_pages row: its address, title
-- and intro (the page's heading and its search text), and two
-- switches, all edited in Pages → Page management, where new pages
-- are made too. site.json's "pages" and Navigation's page list
-- (site_nav_pages, 075) both move here and go: this is the one
-- place a page's words live.
--
-- path '/retreats'; a new page's own, eg. '/library'.
-- Unique; '/' is the front page.
-- is_hidden Not found to everyone below viewer, out of the
-- menus and sitemap (siteNav.js)
-- is_disabled out of the menus, the sitemap and search; the
-- address still works
-- sort_order the order of the admin home's page cards
--
-- A page is its sections (page_sections), except the few the site
-- still draws in code (src/pages/fixedPages.ts): the front page,
-- Feedback, Request, Give, QR codes, Privacy and Terms. Those take
-- their title and intro from here all the same, and can't be
-- deleted (admin-schema/pages.js).
--
-- The id stays a slug, as before (page sections, the Community
-- blog's settings and the drafts key on it), so an existing page
-- keeps its id; its address can change.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_pages_new (
id TEXT PRIMARY KEY
CONSTRAINT "A page's URL ID can use only lowercase letters, numbers and hyphens."
CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'),
path TEXT NOT NULL UNIQUE
CONSTRAINT "A page's address starts with / and uses only lowercase letters, numbers, hyphens and /, eg. /library."
CHECK (path = '/' OR (path GLOB '/[a-z0-9]*' AND path NOT GLOB '*[^a-z0-9/-]*' AND path NOT GLOB '*/')),
title TEXT NOT NULL,
description TEXT,
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
is_disabled INTEGER NOT NULL DEFAULT 0 CHECK (is_disabled IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO site_pages_new (id, path, title, description, sort_order) VALUES
('home', '/', 'Home', NULL, 0),
('retreats', '/retreats', 'Retreats', 'Retreats hosted by Next Generation of Unity, our regions, and our partners throughout the year.', 1),
('community', '/community', 'Community', 'Groups, regions and the people who make up Next Generation of Unity.', 2),
('resources', '/resources', 'Resources', 'Teachings, brand assets, and material for groups and partners.', 3),
('organization', '/organization', 'Organization', 'Our mission, vision and values, the people who lead Next Generation of Unity, and how to reach us.', 4),
('history', '/history', 'History', 'A near-complete timeline of Next Generation of Unity (NGU), and other Unity Young Adult programs.', 5),
('shop', '/shop', 'Shop', 'Shirts, stickers and more from Next Generation of Unity. Every purchase supports our retreats and programs.', 6),
('give', '/give', 'Giving', 'Support the work of Next Generation of Unity.', 7),
('feedback', '/feedback', 'Feedback', 'Tell us what''s working, what isn''t, and what you''d like to see next.', 8),
('request', '/request', 'Request', 'Ask for a blog post, an event, or a new or updated group, region, partner, team, award or person on the site.', 9),
('qr', '/qr', 'QR Codes', 'Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colors.', 10),
('privacy', '/privacy', 'Privacy Policy', 'How Next Generation of Unity collects, uses, and protects your information.', 11),
('terms', '/terms', 'Terms of Service', 'The terms that apply when you use this site and our programs.', 12);
-- Each page's sections' save time comes along.
UPDATE site_pages_new
SET updated_at = (SELECT updated_at FROM site_pages WHERE site_pages.id = site_pages_new.id)
WHERE id IN (SELECT id FROM site_pages);
-- What Navigation (or before it Site settings) changed.
UPDATE site_pages_new
SET title = COALESCE((SELECT n.title FROM site_nav_pages n WHERE n.path = site_pages_new.path), title),
description = COALESCE((SELECT n.description FROM site_nav_pages n WHERE n.path = site_pages_new.path), description),
is_hidden = COALESCE((SELECT n.is_hidden FROM site_nav_pages n WHERE n.path = site_pages_new.path), is_hidden);
DROP TABLE site_nav_pages;
-- The admin edits every page as one entity now ('pages'), so a
-- page's draft (077) moves under it.
UPDATE drafts
SET entity = 'pages', record_id = substr(entity, 1, length(entity) - 5)
WHERE entity IN ('community_page', 'retreats_page', 'resources_page', 'organization_page', 'history_page', 'shop_page');
-- page_sections names site_pages; legacy mode leaves it alone
-- through the rename.
PRAGMA legacy_alter_table = ON;
DROP TABLE site_pages;
ALTER TABLE site_pages_new RENAME TO site_pages;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX site_pages_order_idx ON site_pages (sort_order);
CREATE TRIGGER site_pages_touch
AFTER UPDATE ON site_pages
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE site_pages SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -0,0 +1,65 @@
-- ═══════════════════════════════════════════════════════════════
-- 081 SECTION TYPES
--
-- page_sections.preset takes the parts of the site that were whole
-- pages, so those pages become pages of sections like any other
-- (082 builds them):
--
-- feedback_form the website feedback form (Feedback)
-- request_form the request form (Request)
-- data_request_form the data request form (Privacy)
-- giving the Church Center giving button (Give)
-- qr_maker the QR code maker (QR codes)
--
-- and the front page's bands, to go on any page with content of
-- their own (they're offered once they're built): hero, countdown,
-- calendar, stats, featured_cards, connect.
--
-- The CHECK can't change in place, so the table is rebuilt.
-- ═══════════════════════════════════════════════════════════════
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',
'feedback_form', 'request_form', 'data_request_form', 'giving', 'qr_maker',
'hero', 'countdown', 'calendar', 'stats', 'featured_cards', 'connect')),
-- 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')),
-- Organization cards (067): the kinds listed by themselves.
org_kinds TEXT CHECK (org_kinds IN ('partner', 'ministry', 'partner,ministry')),
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, org_kinds)
SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
FROM page_sections;
-- page_section_orgs, page_section_tags and content_blocks' owner
-- trigger name page_sections; legacy mode leaves them alone through
-- the rename.
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);
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;

View file

@ -0,0 +1,98 @@
-- ═══════════════════════════════════════════════════════════════
-- 082 CORE PAGES AS SECTIONS
--
-- Feedback, Request, QR codes, Give, Privacy and Terms were drawn in
-- code; now each is a page of sections like any other, with what
-- it said put in as blocks, so it's edited in Page management:
--
-- Feedback a feedback_form section
-- Request a request_form section
-- QR codes a qr_maker section
-- Give a giving section: its two paragraphs, then the
-- Church Center button
-- Privacy the policy as heading, paragraph and list blocks,
-- then a data_request_form section
-- Terms the terms as blocks
--
-- The privacy contact email (Site settings) was written into the
-- policy's text by the page; it's written into the blocks now, and
-- the setting goes (this text is where it's changed from now on).
-- ═══════════════════════════════════════════════════════════════
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('feedback', 0, 'website', 'Website Feedback', 'Found a broken link, spotted something out of date, or want the site to do something it doesn''t? This form goes straight to the people who maintain it.', 'feedback_form');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('request', 0, 'request', 'Send a request', 'Tell us what you''d like on the site, or what should change. Attach a Word document with the details and we''ll take it from there.', 'request_form');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('qr', 0, 'make', 'Make a QR code', 'Pick a page from the main navigation, any event, organization, team, award, person or blog post, or type any link. Site pages always point at the live site. Choose what sits in the center and the colors; a warning shows if the code might not scan.', 'qr_maker');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('give', 0, 'give', 'Give to NGU', 'Your giving funds scholarships, retreats, leadership development and the continued growth of the Next Generation of Unity leaders, teachers and community members.', 'giving');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'give' AND anchor = 'give'), 'body', 0, 'paragraph', 'Gifts are processed securely through Church Center. The form opens right here on the page and you can give once or set up a recurring gift, and you don''t need an account to do either.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'give' AND anchor = 'give'), 'body', 1, 'paragraph', 'If you would like to send a check, please email our Board Treasurer at [treasurer@nextgenerationofunity.org](mailto:treasurer@nextgenerationofunity.org) to get an address.');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('privacy', 0, 'privacy', 'Privacy Policy', 'Last updated: October 3, 2026', NULL);
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 0, 'heading', 'In short');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 1, 'paragraph', 'We collect some information about the people who use this site and take part in Next Generation of Unity (NGU). We use it to run our programs and this website, we don''t sell it, and we don''t use advertising or tracking cookies.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 2, 'paragraph', 'If you want to see, correct or delete what we hold about you, ' || (CASE WHEN (SELECT privacy_email FROM site_settings WHERE id = 'site') IS NOT NULL THEN 'email [' || (SELECT privacy_email FROM site_settings WHERE id = 'site') || '](mailto:' || (SELECT privacy_email FROM site_settings WHERE id = 'site') || ') or use the ' ELSE 'use the ' END) || '[request form](#requests) below.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 3, 'heading', 'What we collect');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 4, 'paragraph', 'Depending on how you use the site and our programs:');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 5, 'list', NULL);
CREATE TEMP TABLE IF NOT EXISTS _list (id INTEGER);
DELETE FROM _list;
INSERT INTO _list (id) VALUES (last_insert_rowid());
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 0, '**Feedback and requests you send.** Your message, the page it''s about, and, if you give them, your name and email. With it we keep your browser''s description (its user agent) and a scrambled form of your IP address that can''t be turned back into the address; we use it only to spot abuse. Files you attach to a [request](/request) are kept with it.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 1, '**People on the site.** Leaders, speakers and volunteers can appear with a name, photo, role, short bio and public contact details. Staff may also keep private details, such as a birth date, private email, phone number or address, which are never shown on the site and can only be seen by our editors.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 2, '**Server records.** Like most websites, our server keeps short-lived logs of requests (the page asked for, the time, and the IP address that asked) to keep the site running and secure.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 3, '**Staff accounts.** For NGU staff and volunteers who sign in to edit the site: name, email, role, and a record of sign-ins. Passwords are stored only in a form that can''t be read back.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 6, 'heading', 'Young people');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 7, 'paragraph', 'We don''t show information about anyone under 18 on this site: no names, photos or details. If you believe something about a minor appears here, tell us and we''ll take it down.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 8, 'heading', 'How we use it');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 9, 'paragraph', 'To answer you, to run our retreats, groups and other programs, to keep this site accurate and working, and to keep it secure. We don''t sell or rent your information, and we don''t use it for advertising.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 10, 'heading', 'Artificial intelligence');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 11, 'paragraph', 'We used AI tools to help write this website''s code and build its structure. Those tools have no access to our database. Information you give us, and information we hold about the people in our community, is not given to AI systems, and isn''t used to train them.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 12, 'heading', 'Other services');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 13, 'paragraph', 'We try not to rely on other companies, but a few parts of the site are provided by them. When you use those parts, what you enter or do there goes to that company and is covered by its own privacy policy:');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 14, 'list', NULL);
CREATE TEMP TABLE IF NOT EXISTS _list (id INTEGER);
DELETE FROM _list;
INSERT INTO _list (id) VALUES (last_insert_rowid());
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 0, '**Giving** is handled by Church Center (Planning Center), at [ngu.churchcenteronline.com](https://ngu.churchcenteronline.com). Payment details go to them, not to us. Church Center''s script loads when you open our Giving page, and its giving form opens when you press Give; Church Center may use Google Analytics in that form, under its own privacy policy.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 1, '**Videos** come from YouTube, Facebook or Vimeo, and **maps** from Google Maps. Nothing from them loads until you press play or choose to show the map.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 2, '**Links** to social media, Substack and other sites take you to those sites, which follow their own rules.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 3, '**Staff sign-in** can use a Google account on our own domain.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 4, '**Files attached to requests** are stored in our Google Workspace (Google Drive), and our staff may be told of a new request by email through it.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 15, 'paragraph', 'This site runs on a server we rent and manage ourselves; your information is stored there, not with an outside website service, apart from request files as above.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 16, 'heading', 'Cookies and browser storage');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 17, 'paragraph', 'This site doesn''t use advertising or tracking cookies, and doesn''t use Google Analytics. To see which pages are read, we use [Plausible Analytics](https://plausible.io), which we host ourselves on our own server using its free, open-source [Community Edition](https://github.com/plausible/community-edition/): it sets no cookies, doesn''t follow you across sites, and keeps no personal information, only counts of visits to each page; nothing from it is shared or sold. The site also keeps a few small things in your own browser so it works the way you left it:');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 18, 'list', NULL);
CREATE TEMP TABLE IF NOT EXISTS _list (id INTEGER);
DELETE FROM _list;
INSERT INTO _list (id) VALUES (last_insert_rowid());
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 0, 'That you closed the announcement banner or the privacy notice.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 1, 'Whether you chose the light or dark look.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 2, 'Your accessibility choices: the dyslexia-friendly font, reading mode and color blind mode.');
INSERT INTO content_block_items (block_id, sort_order, text) VALUES ((SELECT id FROM _list), 3, 'For staff who sign in: a sign-in cookie that keeps you signed in, and a short-lived one used while signing in with Google.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 19, 'paragraph', 'None of these are shared with anyone. If you press play on a video or show a map, that service (YouTube, Facebook, Vimeo or Google) may set its own cookies from then on. You can clear all of this in your browser''s settings at any time.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 20, 'heading', 'Your choices');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 21, 'paragraph', 'You can ask to see the information we hold about you, to correct it, or to have it deleted. To do that, ' || (CASE WHEN (SELECT privacy_email FROM site_settings WHERE id = 'site') IS NOT NULL THEN 'email [' || (SELECT privacy_email FROM site_settings WHERE id = 'site') || '](mailto:' || (SELECT privacy_email FROM site_settings WHERE id = 'site') || ') or use the ' ELSE 'use the ' END) || '[request form](#requests) below. We may ask you to confirm it''s you before we change or delete anything, and we''ll tell you when it''s done. Some records we may need to keep, such as records of gifts that the law requires; if so, we''ll say which and why.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 22, 'heading', 'Changes to this policy');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'privacy' AND anchor = 'privacy'), 'body', 23, 'paragraph', 'If we change how we handle information, we''ll update this page and the date at the top. See also our [Terms of Service](/terms).');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('privacy', 1, 'requests', 'Data requests', 'Ask to see, correct or delete the information we hold about you.', 'data_request_form');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset) VALUES ('terms', 0, 'terms', 'Terms of Service', 'Last updated: September 28, 2026', NULL);
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 0, 'heading', 'Using this site');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 1, 'paragraph', 'This website belongs to Next Generation of Unity (NGU). By using it you agree to these terms. If you don''t agree, please don''t use the site.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 2, 'paragraph', 'You''re welcome to read, share and link to anything here. Please don''t try to break or overload the site, get into parts of it you haven''t been given access to, or use it to break the law.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 3, 'heading', 'Our content');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 4, 'paragraph', 'The words, logos, photos and videos on this site belong to NGU or to the people who made them, and are used with permission. You can share them for personal and non-commercial use with credit to NGU. For anything else, including using our name or logo, ask us first.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 5, 'heading', 'What you send us');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 6, 'paragraph', 'When you send feedback or a request, you let us use it to answer you and to improve the site and our programs. Please don''t send anything unlawful, abusive, or someone else''s private information.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 7, 'heading', 'Programs, events and giving');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 8, 'paragraph', 'Dates, places and details of retreats and other events can change. The event''s organizers have the final word, and registering for an event may come with its own terms.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 9, 'paragraph', 'Gifts are made through Church Center (Planning Center), under its terms. Questions about a gift can come to us.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 10, 'heading', 'Other sites');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 11, 'paragraph', 'We link to and show videos, maps and posts from other sites. We don''t control them and aren''t responsible for what they say or do; their own terms and privacy policies apply.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 12, 'heading', 'Staff accounts');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 13, 'paragraph', 'Accounts for editing the site are for NGU staff and volunteers we''ve set up. Keep your password and sign-in to yourself. We can change or close an account at any time.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 14, 'heading', 'No guarantees');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 15, 'paragraph', 'We work to keep this site accurate and running, but it''s provided as it is, without guarantees that it will always be available, complete or free of mistakes. To the extent the law allows, NGU isn''t liable for losses that come from using it.');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 16, 'heading', 'Changes');
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text) VALUES ('page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'terms' AND anchor = 'terms'), 'body', 17, 'paragraph', 'We may update these terms; the date at the top says when they last changed. How we handle personal information is in our [Privacy Policy](/privacy), and you can reach us through the [feedback form](/feedback).');
DROP TABLE IF EXISTS _list;
ALTER TABLE site_settings DROP COLUMN privacy_email;

View file

@ -0,0 +1,435 @@
-- ═══════════════════════════════════════════════════════════════
-- 083 SECTION SETTINGS, AND THE FRONT PAGE AS SECTIONS
--
-- A section type that needs more than its blocks keeps its settings
-- in a table of its own, one row per section (and its lists in
-- tables under the section), so it can go on any page with content
-- of its own. The admin engine reads and writes them as the section's
-- own side tables (admin-crud.js, a child's extensions):
--
-- section_hero a hero: words, buttons, backdrop, feature
-- section_slides its photos
-- section_countdown a countdown: the pinned event, or the next
-- one of a scope and type
-- section_stats a stats band's numbers
-- section_paths a pathfinder's paths
-- section_path_actions each path's links
-- section_featured featured cards' columns (the cards are
-- featured_cards owned by 'page_section')
-- section_blog a Community blog's headings and slots
-- section_blog_posts its pinned posts of ours
-- section_feeds the feeds its community posts come from
-- (its pinned community posts are
-- featured_cards owned by 'page_section')
--
-- page_sections gets is_hidden (any section can be left out without
-- deleting it, as the front page's bands could), and a title of up
-- to 60 characters on the front page, which has no side nav; 30
-- elsewhere. The table is rebuilt for that.
--
-- Then what was the front page's own (front_page and its lists, 012
-- to 074) becomes the home page's sections: the hero first, then
-- each band in its order, hidden ones kept hidden; and the Community
-- page's blog settings (community_page) move into its blog section.
-- Those tables go. A timeline section whose view is 'carousel' is
-- the rail of featured moments the front page showed; the full
-- timeline otherwise.
-- ═══════════════════════════════════════════════════════════════
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), 60 on the front page."
CHECK (length(title) <= CASE WHEN page_id = 'home' THEN 60 ELSE 30 END),
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',
'feedback_form', 'request_form', 'data_request_form', 'giving', 'qr_maker',
'hero', 'countdown', 'calendar', 'stats', 'featured_cards', 'connect')),
-- 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')),
-- Organization cards (067): the kinds listed by themselves.
org_kinds TEXT CHECK (org_kinds IN ('partner', 'ministry', 'partner,ministry')),
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
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, org_kinds)
SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
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);
-- ── The settings tables ──────────────────────────────────────────
CREATE TABLE section_hero (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
eyebrow TEXT,
headline TEXT,
subhead TEXT,
primary_label TEXT,
primary_url TEXT,
secondary_label TEXT,
secondary_url TEXT,
backdrop TEXT NOT NULL DEFAULT 'brand' CHECK (backdrop IN ('brand', 'photos')),
slide_seconds INTEGER NOT NULL DEFAULT 7 CHECK (slide_seconds BETWEEN 3 AND 60),
feature TEXT NOT NULL DEFAULT 'none' CHECK (feature IN ('none', 'livestream', 'video', 'event')),
livestream_url TEXT,
livestream_title TEXT,
video_url TEXT,
video_title TEXT,
video_captions TEXT,
video_still TEXT,
event_id TEXT REFERENCES events (id) ON DELETE SET NULL
) STRICT;
CREATE TABLE section_slides (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
media TEXT NOT NULL,
alt TEXT,
caption TEXT,
link_url TEXT
) STRICT;
CREATE INDEX section_slides_section_idx ON section_slides (section_id, sort_order);
CREATE TABLE section_countdown (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
event_id TEXT REFERENCES events (id) ON DELETE SET NULL,
scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other'))
) STRICT;
CREATE TABLE section_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'manual'
CHECK (source IN ('manual', 'years_since', 'regions', 'groups',
'partners', 'events_held', 'retreats_held',
'people', 'awards_given')),
value TEXT,
suffix TEXT,
note TEXT
) STRICT;
CREATE INDEX section_stats_section_idx ON section_stats (section_id, sort_order);
CREATE TABLE section_paths (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
icon TEXT,
blurb TEXT
) STRICT;
CREATE INDEX section_paths_section_idx ON section_paths (section_id, sort_order);
CREATE TABLE section_path_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path_id INTEGER NOT NULL REFERENCES section_paths (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
description TEXT,
url TEXT NOT NULL
) STRICT;
CREATE INDEX section_path_actions_path_idx ON section_path_actions (path_id, sort_order);
CREATE TABLE section_featured (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
columns INTEGER CHECK (columns IN (2, 3, 4))
) STRICT;
CREATE TABLE section_blog (
section_id INTEGER PRIMARY KEY REFERENCES page_sections (id) ON DELETE CASCADE,
internal_title TEXT,
internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12),
external_title TEXT,
external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12),
external_url TEXT,
external_label TEXT
) STRICT;
CREATE TABLE section_blog_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE
) STRICT;
CREATE INDEX section_blog_posts_section_idx ON section_blog_posts (section_id, sort_order);
CREATE TABLE section_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL,
label TEXT
) STRICT;
CREATE INDEX section_feeds_section_idx ON section_feeds (section_id, sort_order);
-- ── featured_cards: owned by a section ───────────────────────────
CREATE TABLE featured_cards_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('page_section', 'organization')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT,
title TEXT,
blurb TEXT,
image TEXT,
size TEXT CHECK (size IN ('normal', 'wide', 'tall', 'large')),
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
-- ── The Community blog into its section ──────────────────────────
INSERT INTO section_blog (section_id, internal_title, internal_slots, external_title, external_slots, external_url, external_label)
SELECT s.id, c.internal_title, c.internal_slots, c.external_title, c.external_slots, c.external_url, c.external_label
FROM page_sections s, community_page c
WHERE s.page_id = 'community' AND s.preset = 'community_blog' AND c.id = 'community';
INSERT INTO section_blog_posts (section_id, sort_order, post_id)
SELECT s.id, p.sort_order, p.post_id
FROM page_sections s JOIN community_page_pinned_posts p ON p.page_id = 'community'
WHERE s.page_id = 'community' AND s.preset = 'community_blog';
INSERT INTO section_feeds (section_id, sort_order, url, label)
SELECT s.id, f.sort_order, f.url, f.label
FROM page_sections s JOIN community_page_feeds f ON f.page_id = 'community'
WHERE s.page_id = 'community' AND s.preset = 'community_blog';
INSERT INTO featured_cards_new
(owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size)
SELECT 'page_section', CAST(s.id AS TEXT), f.sort_order, f.kind, f.ref_kind, f.ref_id, f.url, f.eyebrow, f.title, f.blurb, f.image, f.size
FROM featured_cards f
JOIN page_sections s ON s.page_id = 'community' AND s.preset = 'community_blog'
WHERE f.owner_kind = 'community_page'
AND s.id = (SELECT min(id) FROM page_sections WHERE page_id = 'community' AND preset = 'community_blog');
-- ── The front page into the home page's sections ─────────────────
-- The hero first.
INSERT INTO page_sections (page_id, sort_order, anchor, title, preset)
VALUES ('home', 0, 'hero', 'Welcome', 'hero');
INSERT INTO section_hero
(section_id, eyebrow, headline, subhead, primary_label, primary_url, secondary_label, secondary_url,
backdrop, slide_seconds, feature, livestream_url, livestream_title, video_url, video_title,
video_captions, video_still, event_id)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND anchor = 'hero'),
eyebrow, headline, subhead, primary_label, primary_url, secondary_label, secondary_url,
hero_backdrop, slide_seconds, hero_feature, livestream_url, livestream_title, video_url, video_title,
video_captions, video_still, hero_event_id
FROM front_page WHERE id = 'home';
INSERT INTO section_slides (section_id, sort_order, media, alt, caption, link_url)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND anchor = 'hero'), sort_order, media, alt, caption, link_url
FROM front_page_slides WHERE page_id = 'home';
-- A featured band, hidden, when the front page has cards but no band
-- for them, so they aren't lost.
INSERT INTO front_page_sections (page_id, sort_order, section, is_hidden)
SELECT 'home', 99, 'featured', 1
WHERE NOT EXISTS (SELECT 1 FROM front_page_sections WHERE page_id = 'home' AND section = 'featured')
AND EXISTS (SELECT 1 FROM featured_cards WHERE owner_kind = 'front_page');
-- Each band, in its order: its section type, anchor and heading.
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, preset, scope_id, event_type, view, is_hidden)
SELECT 'home',
b.sort_order + 1,
CASE b.section
WHEN 'countdown' THEN 'next-up'
WHEN 'stats' THEN 'numbers'
WHEN 'timeline' THEN 'story'
ELSE b.section
END,
substr(COALESCE(b.title, CASE b.section
WHEN 'countdown' THEN 'Next up'
WHEN 'retreats' THEN 'National Retreats'
WHEN 'calendar' THEN 'What''s on'
WHEN 'stats' THEN 'By the numbers'
WHEN 'timeline' THEN 'Our story so far'
WHEN 'connect' THEN 'Find your way in'
ELSE 'Featured'
END), 1, 60),
b.blurb,
CASE b.section
WHEN 'retreats' THEN 'events'
WHEN 'featured' THEN 'featured_cards'
ELSE b.section
END,
CASE WHEN b.section = 'retreats' THEN 'national' END,
CASE WHEN b.section = 'retreats' THEN 'retreat' END,
CASE WHEN b.section IN ('retreats', 'timeline') THEN 'carousel' END,
b.is_hidden
FROM front_page_sections b
WHERE b.page_id = 'home'
ORDER BY b.sort_order;
-- The retreats band's link through to the Retreats page, as a button
-- above its carousel.
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text, href)
SELECT 'page_section', CAST(id AS TEXT), 'body', 0, 'button', 'All retreats', '/retreats'
FROM page_sections WHERE page_id = 'home' AND anchor = 'retreats';
INSERT INTO section_countdown (section_id, event_id, scope_id, event_type)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'countdown'),
countdown_event_id, countdown_scope_id, countdown_event_type
FROM front_page
WHERE id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'countdown');
INSERT INTO section_stats (section_id, sort_order, label, source, value, suffix, note)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'stats'),
sort_order, label, source, value, suffix, note
FROM front_page_stats
WHERE page_id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'stats');
INSERT INTO section_paths (id, section_id, sort_order, label, icon, blurb)
SELECT id, (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'connect'),
sort_order, label, icon, blurb
FROM front_page_paths
WHERE page_id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'connect');
INSERT INTO section_path_actions (path_id, sort_order, label, description, url)
SELECT a.path_id, a.sort_order, a.label, a.description, a.url
FROM front_page_path_actions a
WHERE a.path_id IN (SELECT id FROM section_paths);
INSERT INTO section_featured (section_id, columns)
SELECT (SELECT id FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards'), featured_columns
FROM front_page
WHERE id = 'home' AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards');
INSERT INTO featured_cards_new
(owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size)
SELECT 'page_section', (SELECT CAST(id AS TEXT) FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards'),
sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size
FROM featured_cards
WHERE owner_kind = 'front_page'
AND EXISTS (SELECT 1 FROM page_sections WHERE page_id = 'home' AND preset = 'featured_cards');
-- An organization's own cards (072) come along as they are.
INSERT INTO featured_cards_new
(id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size)
SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image, size
FROM featured_cards WHERE owner_kind = 'organization';
-- Drafts of what's gone: the Front page editor is the home page's now.
DELETE FROM drafts WHERE entity = 'front_page';
-- ── What's gone ──────────────────────────────────────────────────
-- The cleanup triggers on events, people, teams, awards and
-- organizations name featured_cards; legacy mode leaves them alone
-- through the rename.
PRAGMA legacy_alter_table = ON;
DROP TABLE featured_cards;
ALTER TABLE featured_cards_new RENAME TO featured_cards;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
DROP TABLE front_page_path_actions;
DROP TABLE front_page_paths;
DROP TABLE front_page_stats;
DROP TABLE front_page_slides;
DROP TABLE front_page_sections;
DROP TABLE front_page;
DROP TABLE community_page_pinned_posts;
DROP TABLE community_page_feeds;
DROP TABLE community_page;
-- ── Triggers, last ───────────────────────────────────────────────
-- A section's blocks and its featured cards go with it.
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);
DELETE FROM featured_cards WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
END;
CREATE TRIGGER featured_cards_owner_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.owner_kind = 'page_section'
AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'featured_cards: no such page section')
END;
END;
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;

View file

@ -0,0 +1,37 @@
-- ═══════════════════════════════════════════════════════════════
-- 084 ROTATING WORDS
--
-- A word typed as {Next|Now|Rising} in a title or text cycles
-- through its choices (src/components/RotatingWords.tsx). How it
-- moves:
--
-- word_motion slide, flip, fade, type or mirror
-- word_direction top or bottom: where a sliding or flipping word
-- comes from
-- word_seconds how long each word shows, 1 to 20
--
-- Site settings hold the defaults (null: slide, from the bottom, 3
-- seconds); a hero and a content block can each set their own, null
-- keeping the site's.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE site_settings ADD COLUMN word_motion TEXT
CHECK (word_motion IN ('slide', 'flip', 'fade', 'type', 'mirror'));
ALTER TABLE site_settings ADD COLUMN word_direction TEXT
CHECK (word_direction IN ('top', 'bottom'));
ALTER TABLE site_settings ADD COLUMN word_seconds INTEGER
CHECK (word_seconds BETWEEN 1 AND 20);
ALTER TABLE section_hero ADD COLUMN word_motion TEXT
CHECK (word_motion IN ('slide', 'flip', 'fade', 'type', 'mirror'));
ALTER TABLE section_hero ADD COLUMN word_direction TEXT
CHECK (word_direction IN ('top', 'bottom'));
ALTER TABLE section_hero ADD COLUMN word_seconds INTEGER
CHECK (word_seconds BETWEEN 1 AND 20);
ALTER TABLE content_blocks ADD COLUMN word_motion TEXT
CHECK (word_motion IN ('slide', 'flip', 'fade', 'type', 'mirror'));
ALTER TABLE content_blocks ADD COLUMN word_direction TEXT
CHECK (word_direction IN ('top', 'bottom'));
ALTER TABLE content_blocks ADD COLUMN word_seconds INTEGER
CHECK (word_seconds BETWEEN 1 AND 20);

View file

@ -0,0 +1,17 @@
-- ═══════════════════════════════════════════════════════════════
-- 085 PLANNING CENTER
--
-- Data → Planning Center brings one Planning Center People list into
-- the site's people, by hand (planningCenter.js, routes/pco.js):
--
-- people.pco_id the Planning Center person a record is
-- linked to, once an admin confirms the
-- match; one record each
-- site_settings.pco_list_id which list (Site settings → Planning
-- Center), eg. 1234567
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE people ADD COLUMN pco_id TEXT;
CREATE UNIQUE INDEX people_pco_id_idx ON people (pco_id) WHERE pco_id IS NOT NULL;
ALTER TABLE site_settings ADD COLUMN pco_list_id TEXT;

View file

@ -14,20 +14,24 @@
── Where it comes from ──
/site.json (SITE_CONFIG): the site's name, address, default
description and image, icons, and each static page's title and
description. Laid over it: Panel → Site settings (the
site_settings table, 035), where anything set wins and anything
blank falls back to site.json. siteFor(db) does the merge. The
default description and image, and icons. Laid over it: Panel →
Site settings (the site_settings table, 035), where anything set
wins and anything blank falls back to site.json. siteFor(db) does
the merge. Each page's title and intro are its site_pages row's
(Pages → Page management, 080). The
pages read the same merged values (renderPage writes them into
the HTML as window.__SITE__, see src/lib/site.ts), so a
heading and its search title can't drift.
The database: records' names, taglines, first paragraphs and
images. A blank site description falls back to the front page's
subhead.
hero's subhead.
── Rules ──
published, listed indexed, in the sitemap
published, unlisted noindex: reachable by link, not by search
unpublished, missing 404 and noindex, with the site defaults
a hidden static page 404 and noindex below viewer, out of the
sitemap (siteNav.js)
/admin noindex
Image paths resolve like src/lib/media.ts does: a bare filename
@ -44,6 +48,7 @@ import { fileURLToPath } from "node:url";
import { loadBlocks, paragraphs } from "./shape.js";
import { themeCss } from "./theme.js";
import { driveReady } from "./googleService.js";
import { allPages, hiddenFrom, navFor, pageAt } from "./siteNav.js";
const here = path.dirname(fileURLToPath(import.meta.url));
@ -71,24 +76,15 @@ const origin = (site) => (site.url ?? "").replace(/\/$/, "");
/* site.json with the admin's Site settings laid over it: a value set
there wins, a blank one falls back. indexing 'on' / 'off' overrides
robots.index for this database only. Page overrides apply only to
pages site.json knows. */
robots.index for this database only. pages: every page's title
and intro, by path (site_pages). */
export function siteFor(db) {
const base = loadSite();
const row = db.prepare(`SELECT * FROM site_settings WHERE id = 'site'`).get() ?? {};
const pages = { ...(base.pages ?? {}) };
const overrides = db
.prepare(`SELECT path, title, description FROM site_setting_pages WHERE settings_id = 'site'`)
.all();
for (const page of overrides) {
const known = pages[page.path];
if (!known) continue;
pages[page.path] = {
title: page.title || known.title,
description: page.description || known.description,
};
}
const pages = Object.fromEntries(
allPages(db).map((page) => [page.path, { title: page.title, description: page.description ?? "" }]),
);
return {
...base,
@ -104,7 +100,8 @@ export function siteFor(db) {
...base.robots,
index: row.indexing ? row.indexing === "on" : base.robots?.index !== false,
},
privacyEmail: row.privacy_email || base.privacyEmail || "",
// Rotating words' defaults (084): blank is the app's own.
words: { motion: row.word_motion ?? null, direction: row.word_direction ?? null, seconds: row.word_seconds ?? null },
// The admin's colors (theme.js): only #rrggbb values and fixed
// text, so safe inside <style>.
themeCss: themeCss(db),
@ -112,13 +109,15 @@ export function siteFor(db) {
};
}
/* What the browser app reads for headings and titles. */
// requestFiles: whether the Request form can take files (Drive set up).
const forBrowser = (site) => ({
/* What the browser app reads for headings, titles and its menus.
requestFiles: whether the Request form can take files (Drive set
up). nav: this visitor's links and the hidden pages (siteNav.js). */
const forBrowser = (site, nav) => ({
title: site.title,
pages: site.pages,
privacyEmail: site.privacyEmail,
requestFiles: driveReady(),
words: site.words,
nav,
});
/* robots.txt for this database's setting, as the build writes it. */
@ -142,6 +141,8 @@ export function plainText(text) {
const flat = String(text)
.slice(0, 2000)
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
// Rotating words ({Next|Now}, 084): the first.
.replace(/\{([^{}|\n]+)(?:\|[^{}|\n]+)+\}/g, "$1")
.replace(/\*\*(.+?)\*\*/g, "$1")
.replace(/\*(.+?)\*/g, "$1")
.replace(/\s+/g, " ")
@ -171,8 +172,18 @@ function firstParagraph(db, ownerKind, id, slot) {
const ORG_ROUTES = { region: "/regions", group: "/groups", partner: "/partners", national: "/organizations" };
/* The front page's first hero (083): its subhead is the site's
description when Site settings and site.json have none. */
const homeHero = (db) =>
db
.prepare(
`SELECT h.* FROM section_hero h JOIN page_sections s ON s.id = h.section_id
WHERE s.page_id = 'home' AND s.is_hidden = 0 ORDER BY s.sort_order LIMIT 1`,
)
.get();
function defaults(site, db, pathname) {
const home = db.prepare(`SELECT headline, subhead FROM front_page WHERE id = 'home'`).get();
const home = homeHero(db);
return {
status: 200,
title: site.title,
@ -296,7 +307,7 @@ function awardMeta(site, db, id, meta) {
}
function personMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
const row = db.prepare(`SELECT * FROM v_people_public WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
@ -326,7 +337,7 @@ function blogMeta(site, db, id, meta) {
.prepare(
`SELECT p.display_name AS name
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id = ? ORDER BY a.sort_order`,
)
.all(id)
@ -358,29 +369,32 @@ function blogMeta(site, db, id, meta) {
};
}
/* The metadata for one request path. */
export function metaFor(db, rawPath) {
/* The profile account pages and their titles (src/pages/SignIn.tsx,
Account.tsx, AccountWelcome.tsx say the same). */
const ACCOUNT_PAGES = { "/sign-in": "Sign in", "/account": "Your profile", "/account/welcome": "Welcome" };
/* The metadata for one request path, for this visitor (the signed-in
user or null, who decides whether a hidden page is there). */
export function metaFor(db, rawPath, user = null) {
const site = siteFor(db);
// Canonical form: no trailing slash (but "/" itself), no query.
const pathname = rawPath.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/";
const meta = defaults(site, db, pathname);
const meta = { ...defaults(site, db, pathname), nav: navFor(db, user) };
if (pathname === "/") {
// The home page's data, and its first hero photo when the hero is
// a slideshow, requested alongside the app's JavaScript instead of
// after it has run.
const hero = db.prepare(`SELECT hero_backdrop FROM front_page WHERE id = 'home'`).get();
const hero = homeHero(db);
const slide =
hero?.hero_backdrop === "photos"
? db
.prepare(`SELECT media FROM front_page_slides WHERE page_id = 'home' ORDER BY sort_order LIMIT 1`)
.get()
hero?.backdrop === "photos"
? db.prepare(`SELECT media FROM section_slides WHERE section_id = ? ORDER BY sort_order LIMIT 1`).get(hero.section_id)
: null;
const slideSrc = slide?.media ? (/^(https?:|\/)/.test(slide.media) ? slide.media : `${UPLOADS}/${slide.media}`) : null;
return {
...meta,
preload: [
{ href: "/api/front-page", as: "fetch" },
{ href: "/api/site-pages/home", as: "fetch" },
...(slideSrc ? [{ href: slideSrc, as: "image" }] : []),
],
jsonLd: {
@ -395,9 +409,21 @@ export function metaFor(db, rawPath) {
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
const page = site.pages?.[pathname];
// A profile account's pages (076): there for anyone, about no one
// in particular, so never indexed or in the sitemap.
if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
// A page of the site (site_pages): hidden is Not found below
// viewer; disabled stays out of search.
const page = pageAt(db, pathname);
if (page && hiddenFrom(db, user, pathname)) return notFound(meta);
if (page) {
return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description };
return {
...meta,
title: titled(site, page.title),
description: plainText(page.description) ?? meta.description,
noindex: page.is_disabled === 1,
};
}
// An event's schedule presentation (SchedulePresent.tsx): the
@ -520,7 +546,7 @@ export function renderPage(html, meta) {
),
// Read by src/lib/site.ts before the app's module runs (a plain
// script in the head runs during parsing; modules wait).
`<script>window.__SITE__ = ${scriptJson(forBrowser(site))}</script>`,
`<script>window.__SITE__ = ${scriptJson(forBrowser(site, meta.nav))}</script>`,
site.themeCss && `<style id="site-colors">${site.themeCss}</style>`,
analyticsTag(site),
].filter(Boolean);
@ -545,7 +571,10 @@ export function sitemap(db) {
const entries = [
{ loc: "/" },
...Object.keys(site.pages ?? {}).map((loc) => ({ loc })),
// Pages that are neither hidden nor disabled.
...allPages(db)
.filter((page) => page.path !== "/" && page.is_hidden !== 1 && page.is_disabled !== 1)
.map((page) => ({ loc: page.path })),
...db
.prepare(`SELECT id, updated_at FROM events WHERE is_published = 1 AND is_listed = 1`)
.all()

View file

@ -0,0 +1,199 @@
/* ═══════════════════════════════════════════════════════════════
PLANNING CENTER
One Planning Center People list into the site's people, by hand:
Data → Planning Center (routes/pco.js) asks for the comparison,
an admin reviews it, and only what they apply is written. Planning
Center wins where both sides have a value. One way only: nothing
is sent back.
name → people.display_name, and sort_name ("Last, First")
email → person_private.private_email (the primary one)
phone → person_private.private_phone (the primary one)
A person is matched by the Planning Center id it was linked to
(people.pco_id, 085), else suggested by the same private or public
email, else the same name; an admin confirms each suggestion, picks
another person, or makes a new one, unpublished.
PCO_APP_ID a personal access token's application id
PCO_SECRET and its secret (api.planningcenteronline.com →
Personal Access Tokens); never in the repo
PCO_BASE default https://api.planningcenteronline.com
The list is Site settings → Planning Center. Setup:
docs/planning-center.md.
═══════════════════════════════════════════════════════════════ */
const BASE = () => (process.env.PCO_BASE ?? "https://api.planningcenteronline.com").replace(/\/$/, "");
const MAX_PAGES = 50; // 100 a page: a list of 5,000 is plenty
export const pcoReady = () => Boolean(process.env.PCO_APP_ID && process.env.PCO_SECRET);
export class PcoError extends Error {}
async function call(url) {
const auth = Buffer.from(`${process.env.PCO_APP_ID}:${process.env.PCO_SECRET}`).toString("base64");
let res;
try {
res = await fetch(url, { headers: { Authorization: `Basic ${auth}`, Accept: "application/json" }, signal: AbortSignal.timeout(20_000) });
} catch {
throw new PcoError("Couldn't reach Planning Center.");
}
if (res.status === 401) throw new PcoError("Planning Center refused the token (PCO_APP_ID and PCO_SECRET).");
if (res.status === 404) throw new PcoError("Planning Center has no such list. Check Site settings → Planning Center.");
if (!res.ok) throw new PcoError(`Planning Center answered ${res.status}.`);
return res.json();
}
/* Everyone on the list: { id, first, last, name, email, phone }. */
export async function listPeople(listId) {
if (!pcoReady()) throw new PcoError("Planning Center isn't set up on the server (PCO_APP_ID, PCO_SECRET).");
if (!/^\d+$/.test(String(listId ?? ""))) throw new PcoError("Pick a list in Site settings → Planning Center (its number).");
const people = [];
let url = `${BASE()}/people/v2/lists/${listId}/people?include=emails,phone_numbers&per_page=100`;
for (let page = 0; url && page < MAX_PAGES; page++) {
const body = await call(url);
const included = new Map((body.included ?? []).map((row) => [`${row.type}:${row.id}`, row]));
for (const row of body.data ?? []) {
const pick = (type, key) => {
const rows = (row.relationships?.[key]?.data ?? []).map((ref) => included.get(`${type}:${ref.id}`)).filter(Boolean);
const main = rows.find((r) => r.attributes?.primary) ?? rows[0];
return main?.attributes ?? null;
};
const a = row.attributes ?? {};
const first = (a.nickname || a.first_name || "").trim();
const last = (a.last_name || "").trim();
people.push({
id: String(row.id),
first,
last,
name: [first, last].filter(Boolean).join(" ") || (a.name ?? "").trim(),
email: pick("Email", "emails")?.address?.trim().toLowerCase() || null,
phone: pick("PhoneNumber", "phone_numbers")?.number?.trim() || null,
});
}
url = body.links?.next ?? null;
}
return people;
}
const norm = (value) => String(value ?? "").trim().toLowerCase().replace(/\s+/g, " ");
/* The comparison: each list member with its match (linked, or a
suggestion) and the fields that would change. */
export function compare(db, members) {
const site = db
.prepare(
`SELECT p.id, p.display_name, p.sort_name, p.public_email, p.pco_id,
v.private_email, v.private_phone
FROM people p LEFT JOIN person_private v ON v.person_id = p.id`,
)
.all();
const byPco = new Map(site.filter((p) => p.pco_id).map((p) => [p.pco_id, p]));
const byEmail = new Map();
for (const p of site) {
for (const email of [p.private_email, p.public_email]) if (email) byEmail.set(norm(email), p);
}
const byName = new Map(site.map((p) => [norm(p.display_name), p]));
return members.map((member) => {
let person = byPco.get(member.id);
let how = person ? "linked" : null;
if (!person && member.email && byEmail.get(norm(member.email))) {
person = byEmail.get(norm(member.email));
how = "email";
}
if (!person && byName.get(norm(member.name))) {
person = byName.get(norm(member.name));
how = "name";
}
// A suggestion that's already some other Planning Center person's isn't one.
if (person && how !== "linked" && person.pco_id && person.pco_id !== member.id) {
person = null;
how = null;
}
const sortName = member.last ? `${member.last}, ${member.first}`.replace(/, $/, "") : null;
const changes = person
? [
["display_name", "Name", person.display_name, member.name],
["sort_name", "Sort name", person.sort_name, sortName],
["private_email", "Private email", person.private_email, member.email],
["private_phone", "Private phone", person.private_phone, member.phone],
]
.filter(([, , now, next]) => next && norm(now) !== norm(next))
.map(([field, label, now, next]) => ({ field, label, site: now ?? null, pco: next }))
: [];
return {
pco: member,
match: person ? { person_id: person.id, name: person.display_name, how } : null,
changes,
};
});
}
const slug = (text) =>
String(text ?? "")
.toLowerCase()
.normalize("NFKD")
.replace(/[^\w\s-]/g, "")
.trim()
.replace(/[\s_]+/g, "-")
.replace(/-+/g, "-")
.slice(0, 60) || "person";
function freeId(db, base) {
let id = base;
for (let n = 2; db.prepare(`SELECT 1 FROM people WHERE id = ?`).get(id); n++) id = `${base}-${n}`;
return id;
}
/* Writes what the admin chose, in one transaction (the caller's):
each decision is { pco: member, action: 'link' | 'create',
person_id, update }. Returns counts. */
export function apply(db, decisions) {
const counts = { linked: 0, created: 0, updated: 0 };
const upsertPrivate = db.prepare(
`INSERT INTO person_private (person_id, private_email, private_phone) VALUES (?, ?, ?)
ON CONFLICT (person_id) DO UPDATE
SET private_email = COALESCE(excluded.private_email, private_email),
private_phone = COALESCE(excluded.private_phone, private_phone),
updated_at = datetime('now')`,
);
for (const d of decisions) {
const m = d.pco;
const sortName = m.last ? `${m.last}, ${m.first}`.replace(/, $/, "") : null;
let personId = d.person_id;
if (d.action === "create") {
personId = freeId(db, slug(m.name));
db.prepare(
`INSERT INTO people (id, display_name, sort_name, is_published, is_listed, pco_id) VALUES (?, ?, ?, 0, 1, ?)`,
).run(personId, m.name || "Unnamed", sortName, m.id);
upsertPrivate.run(personId, m.email, m.phone);
counts.created += 1;
continue;
}
if (d.action !== "link" || !personId) continue;
// A link moves: whoever had this Planning Center person lets go.
db.prepare(`UPDATE people SET pco_id = NULL WHERE pco_id = ? AND id <> ?`).run(m.id, personId);
db.prepare(`UPDATE people SET pco_id = ? WHERE id = ?`).run(m.id, personId);
counts.linked += 1;
if (d.update) {
db.prepare(
`UPDATE people SET display_name = COALESCE(?, display_name), sort_name = COALESCE(?, sort_name),
updated_at = datetime('now')
WHERE id = ?`,
).run(m.name || null, sortName, personId);
upsertPrivate.run(personId, m.email, m.phone);
counts.updated += 1;
}
}
return counts;
}

View file

@ -0,0 +1,333 @@
/* ═══════════════════════════════════════════════════════════════
ACCOUNT ROUTES: a profile account's own page (076), mounted
under /api/account
GET /invite?token= who an invite link is for (welcome page)
POST /accept { token, password }: set the password,
sign in, take up the invite
GET / me: the account, my person (as I edit
it), my claim, Discord
GET /people the People records I could claim
POST /claim { person_id, message }: ask to be one
DELETE /claim take back the open request
PATCH /profile my person's text and what of it shows
POST /photo my person's photo (multipart, `file`)
GET /discord off to Discord to link it
GET /discord/callback back from it
DELETE /discord unlink it
Every route but the first two needs a session; any role will do,
so an admin with a claimed record has a profile too. Only the
account's own person is ever written, and only the fields in
PROFILE_FIELDS: name, published and listed stay the admin's.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import { SECURE_COOKIE, createSession, currentUser, hashPassword } from "../auth.js";
import { accountForInvite } from "../invites.js";
import { discordConfig, finishLink, startLink } from "../discordAuth.js";
import { googleConfig } from "../googleAuth.js";
import { MAX_UPLOAD_BYTES, MediaError, publicPath } from "../media.js";
import { addToLibrary } from "./media.js";
import { NO_STORE } from "../shape.js";
const account = new Hono();
const MIN_PASSWORD = 12;
/* What an owner edits on their own record, and its longest. */
const PROFILE_FIELDS = {
pronouns: 40,
tagline: 160,
bio: 4000,
public_email: 254,
public_phone: 40,
location_label: 120,
};
/* What an owner can take off the site (people.hide_*). */
export const HIDE_FIELDS = ["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"];
async function body(c) {
try {
return (await c.req.json()) ?? {};
} catch {
return null;
}
}
/* ── Invites ─────────────────────────────────────────────────── */
account.get("/invite", (c) => {
const invited = accountForInvite(c.get("db"), c.req.query("token"));
if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404, NO_STORE);
return c.json({ invite: { email: invited.email, name: invited.name, google: Boolean(googleConfig()) } }, 200, NO_STORE);
});
account.post("/accept", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const invited = accountForInvite(db, data.token);
if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404);
const password = String(data.password ?? "");
if (password.length < MIN_PASSWORD) {
return c.json({ error: `Use at least ${MIN_PASSWORD} characters.`, fields: { password: "Too short." } }, 422);
}
if (password.length > 200) return c.json({ error: "That password is too long." }, 422);
db.prepare(
`UPDATE admin_users
SET password_hash = ?, invite_hash = NULL, invite_expires_at = NULL, last_login_at = datetime('now')
WHERE id = ?`,
).run(hashPassword(password), invited.id);
createSession(db, c, invited.id);
console.log(`invite taken up by ${invited.email}`);
return c.json({ user: { id: invited.id, email: invited.email, name: invited.name, role: invited.role } }, 200, NO_STORE);
});
/* ── Signed in from here ─────────────────────────────────────── */
account.use("*", async (c, next) => {
const path = c.req.path;
if (path.endsWith("/invite") || path.endsWith("/accept")) return next();
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401, NO_STORE);
c.set("user", user);
await next();
});
/* My person as I edit it: the stored values, not the public view,
with what's hidden said separately. */
function myPerson(db, accountId) {
const row = db
.prepare(
`SELECT p.* FROM people p JOIN admin_users u ON u.person_id = p.id WHERE u.id = ?`,
)
.get(accountId);
if (!row) return null;
return {
id: row.id,
display_name: row.display_name,
is_published: row.is_published === 1,
photo: row.photo,
...Object.fromEntries(Object.keys(PROFILE_FIELDS).map((key) => [key, row[key]])),
hidden: Object.fromEntries(HIDE_FIELDS.map((key) => [key, row[`hide_${key}`] === 1])),
};
}
account.get("/", (c) => {
const db = c.get("db");
const user = c.get("user");
const row = db.prepare(`SELECT discord_id, discord_name FROM admin_users WHERE id = ?`).get(user.id);
const claim = db
.prepare(
`SELECT c.id, c.person_id, p.display_name, c.status, c.created_at, c.decided_at
FROM person_claims c JOIN people p ON p.id = c.person_id
WHERE c.account_id = ? ORDER BY c.id DESC LIMIT 1`,
)
.get(user.id);
return c.json(
{
account: {
user,
person: myPerson(db, user.id),
claim: claim ?? null,
discord: { enabled: Boolean(discordConfig()), id: row?.discord_id ?? null, name: row?.discord_name ?? null },
},
},
200,
NO_STORE,
);
});
/* Published records nobody has claimed, to pick from. */
account.get("/people", (c) => {
const people = c
.get("db")
.prepare(
`SELECT p.id, p.display_name AS name
FROM people p
WHERE p.is_published = 1
AND NOT EXISTS (SELECT 1 FROM admin_users u WHERE u.person_id = p.id)
ORDER BY COALESCE(p.sort_name, p.display_name)`,
)
.all();
return c.json({ people }, 200, NO_STORE);
});
account.post("/claim", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const user = c.get("user");
if (db.prepare(`SELECT person_id FROM admin_users WHERE id = ?`).get(user.id)?.person_id) {
return c.json({ error: "Your account already has a profile." }, 409);
}
const personId = String(data.person_id ?? "");
const person = db.prepare(`SELECT id FROM people WHERE id = ? AND is_published = 1`).get(personId);
if (!person) return c.json({ error: "Pick a person from the list.", fields: { person_id: "Pick one." } }, 422);
if (db.prepare(`SELECT 1 FROM admin_users WHERE person_id = ?`).get(personId)) {
return c.json({ error: "Someone has already claimed that profile." }, 409);
}
const message = String(data.message ?? "").trim().slice(0, 1000) || null;
try {
db.prepare(`INSERT INTO person_claims (account_id, person_id, message) VALUES (?, ?, ?)`).run(
user.id,
personId,
message,
);
} catch (err) {
if (/UNIQUE/.test(err.message)) return c.json({ error: "You already have a request waiting." }, 409);
throw err;
}
console.log(`claim: ${user.email} asked for ${personId}`);
return c.body(null, 204);
});
account.delete("/claim", (c) => {
c.get("db")
.prepare(`DELETE FROM person_claims WHERE account_id = ? AND status = 'pending'`)
.run(c.get("user").id);
return c.body(null, 204);
});
account.patch("/profile", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const person = myPerson(db, c.get("user").id);
if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
const sets = [];
const values = [];
const fields = {};
for (const [key, max] of Object.entries(PROFILE_FIELDS)) {
if (!(key in data)) continue;
const value = data[key] == null ? "" : String(data[key]).trim();
if (value.length > max) fields[key] = `Up to ${max} characters.`;
sets.push(`${key} = ?`);
values.push(value || null);
}
if (data.public_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(data.public_email).trim())) {
fields.public_email = "That doesn't look like an email address.";
}
if (Object.keys(fields).length) return c.json({ error: "Check the highlighted fields.", fields }, 422);
for (const key of HIDE_FIELDS) {
if (data.hidden && key in data.hidden) {
sets.push(`hide_${key} = ?`);
values.push(data.hidden[key] ? 1 : 0);
}
}
if (sets.length) {
db.prepare(`UPDATE people SET ${sets.join(", ")}, updated_at = datetime('now') WHERE id = ?`).run(
...values,
person.id,
);
console.log(`profile ${person.id} updated by ${c.get("user").email}`);
}
return c.json({ person: myPerson(db, c.get("user").id) }, 200, NO_STORE);
});
account.post(
"/photo",
bodyLimit({ maxSize: MAX_UPLOAD_BYTES + 64 * 1024, onError: (c) => c.json({ error: "That file is too large." }, 413) }),
async (c) => {
const db = c.get("db");
const user = c.get("user");
const person = myPerson(db, user.id);
if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
let form;
try {
form = await c.req.parseBody();
} catch {
return c.json({ error: "Expected a file upload." }, 400);
}
const file = form.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
if (!/^image\/(jpeg|png|webp)$/.test(file.type)) {
return c.json({ error: "Use a JPEG, PNG or WebP photo." }, 415);
}
let row;
try {
row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
originalName: person.display_name,
folder: "images",
userId: user.id,
});
} catch (err) {
if (err instanceof MediaError) return c.json({ error: err.message }, err.status ?? 422);
throw err;
}
db.prepare(`UPDATE people SET photo = ?, updated_at = datetime('now') WHERE id = ?`).run(
publicPath(row.filename),
person.id,
);
console.log(`profile ${person.id} photo ${row.filename} by ${user.email}`);
return c.json({ person: myPerson(db, user.id) }, 200, NO_STORE);
},
);
/* ── Discord ─────────────────────────────────────────────────── */
const DISCORD_COOKIE = SECURE_COOKIE ? "__Host-site_discord" : "site_discord";
const DISCORD_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, sameSite: "Lax", path: "/" };
const backToAccount = (c, result) => c.redirect(`/account?discord=${encodeURIComponent(result)}`, 302);
account.get("/discord", (c) => {
const config = discordConfig();
if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
if (!config.redirectUri) {
console.error("discord link: no return address. Set DISCORD_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.");
return backToAccount(c, "failed");
}
const { url, state } = startLink(config);
setCookie(c, DISCORD_COOKIE, state, { ...DISCORD_COOKIE_OPTIONS, maxAge: 600 });
return c.redirect(url, 302);
});
account.get("/discord/callback", async (c) => {
const config = discordConfig();
if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
const state = getCookie(c, DISCORD_COOKIE);
deleteCookie(c, DISCORD_COOKIE, DISCORD_COOKIE_OPTIONS);
if (c.req.query("error")) return backToAccount(c, "canceled");
const code = c.req.query("code");
if (!state || !code || c.req.query("state") !== state) return backToAccount(c, "expired");
let who;
try {
who = await finishLink(config, code);
} catch (err) {
console.warn(`discord link failed: ${err.message}`);
return backToAccount(c, "failed");
}
const db = c.get("db");
const user = c.get("user");
const taken = db.prepare(`SELECT id FROM admin_users WHERE discord_id = ? AND id <> ?`).get(who.id, user.id);
if (taken) return backToAccount(c, "taken");
db.prepare(`UPDATE admin_users SET discord_id = ?, discord_name = ? WHERE id = ?`).run(who.id, who.name, user.id);
console.log(`discord ${who.id} linked to ${user.email}`);
return backToAccount(c, "linked");
});
account.delete("/discord", (c) => {
c.get("db").prepare(`UPDATE admin_users SET discord_id = NULL, discord_name = NULL WHERE id = ?`).run(c.get("user").id);
return c.body(null, 204);
});
export default account;

View file

@ -6,7 +6,11 @@
GET /api/admin/:entity/:id row with side tables and children
POST /api/admin/:entity create
PATCH /api/admin/:entity/:id replace the row and its children
(publishing a draft too: it's dropped)
DELETE /api/admin/:entity/:id
GET /api/admin/:entity/:id/draft its draft, or null (drafts.js)
PUT /api/admin/:entity/:id/draft save the form as its draft
DELETE /api/admin/:entity/:id/draft discard it
Mounted alongside the existing admin router, which keeps the
feedback routes. Both sit under the same requireAuth.
@ -29,6 +33,7 @@ import {
deleteRow,
} from "../admin-crud.js";
import { NO_STORE } from "../shape.js";
import { draftIds, dropDraft, readDraft, saveDraft } from "../drafts.js";
const entities = new Hono();
@ -84,7 +89,8 @@ entities.get("/options", (c) => {
entities.get("/:entity", (c) => {
const entity = entityOr404(c);
const { rows, total } = listRows(c.get("db"), entity, c.req.query());
return c.json({ rows, total }, 200, NO_STORE);
// Which of them have a draft waiting, for the list to mark.
return c.json({ rows, total, drafts: draftIds(c.get("db"), entity.key) }, 200, NO_STORE);
});
entities.get("/:entity/:id", (c) => {
@ -103,6 +109,8 @@ entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
// Saved for real: any draft of it is published, or overtaken.
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
return c.json({ row }, 200, NO_STORE);
});
@ -111,10 +119,34 @@ entities.delete("/:entity/:id", requireRole("admin"), (c) => {
const entity = entityOr404(c);
const id = c.req.param("id");
deleteRow(c.get("db"), entity, id);
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
/* ── Drafts (drafts.js) ──────────────────────────────────────── */
entities.get("/:entity/:id/draft", (c) => {
const entity = entityOr404(c);
return c.json({ draft: readDraft(c.get("db"), entity.key, c.req.param("id")) }, 200, NO_STORE);
});
entities.put("/:entity/:id/draft", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const draft = saveDraft(c.get("db"), entity.key, id, await json(c), c.get("user").id);
console.log(`${entity.key} ${id} draft saved by ${c.get("user").email}`);
return c.json({ draft }, 200, NO_STORE);
});
entities.delete("/:entity/:id/draft", requireRole("editor"), (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} draft discarded by ${c.get("user").email}`);
return c.body(null, 204);
});
async function json(c) {
try {
return await c.req.json();

View file

@ -5,7 +5,9 @@
POST /api/auth/logout deletes the session row and cookie
GET /api/auth/me who am I, or 401
GET /api/auth/providers which ways in are switched on
GET /api/auth/google off to Google's account chooser
GET /api/auth/google off to Google's account chooser;
?for=account from the site's sign-in
page (any Google account, back there)
GET /api/auth/google/callback back from it: sign in, or
back to the login page with ?error=
@ -27,6 +29,11 @@
email, which then links it. A matching email already linked to a
different Google account is refused rather than relinked.
googleAuth.js checks the identity itself.
Profile accounts (076) are made by an admin's invite
(routes/profiles.js). One may sign in with a Google account
outside the Workspace, under the invited email; an outside
identity reaches nothing else. Signing in takes up the invite.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
@ -153,7 +160,11 @@ const OAUTH_COOKIE_OPTIONS = {
const safeNext = (value) =>
typeof value === "string" && /^\/admin(\/[\w\-/]*)?$/.test(value) ? value : "/admin/home";
const backToLogin = (c, code) => c.redirect(`/admin/login?error=${encodeURIComponent(code)}`, 302);
// The page a sign-in started from: the admin's, or the site's
// (/sign-in, for profile accounts) when `from` is 'account'.
const SIGN_IN_PAGES = { admin: "/admin/login", account: "/sign-in" };
const backToLogin = (c, code, from = "admin") =>
c.redirect(`${SIGN_IN_PAGES[from] ?? SIGN_IN_PAGES.admin}?error=${encodeURIComponent(code)}`, 302);
auth.get("/providers", (c) =>
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
@ -162,17 +173,18 @@ auth.get("/providers", (c) =>
auth.get("/google", (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
const from = c.req.query("for") === "account" ? "account" : "admin";
if (!config.redirectUri) {
// Said in the log, where whoever runs the box will look; the
// person at the login page just learns it didn't work.
console.error(
"google login: no return address. Set GOOGLE_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.",
);
return backToLogin(c, "google_failed");
return backToLogin(c, "google_failed", from);
}
const { url, state, verifier } = startLogin(config);
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
const { url, state, verifier } = startLogin(config, { anyDomain: from === "account" });
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, from, next: safeNext(c.req.query("next")) }), {
...OAUTH_COOKIE_OPTIONS,
maxAge: 600,
});
@ -190,13 +202,15 @@ auth.get("/google/callback", async (c) => {
saved = null;
}
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
const from = saved?.from === "account" ? "account" : "admin";
const back = (code) => backToLogin(c, code, from);
// Pressing Cancel on Google's screen comes back as ?error=.
if (c.req.query("error")) return backToLogin(c, "canceled");
if (c.req.query("error")) return back("canceled");
const code = c.req.query("code");
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
return backToLogin(c, "expired");
return back("expired");
}
let identity;
@ -205,7 +219,7 @@ auth.get("/google/callback", async (c) => {
} catch (err) {
if (err instanceof GoogleLoginError) {
console.warn(`google login refused: ${err.code}`);
return backToLogin(c, err.code);
return back(err.code);
}
throw err;
}
@ -215,6 +229,20 @@ auth.get("/google/callback", async (c) => {
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
// From outside the Workspace, only a profile account: by its
// linked Google id, or its invited email.
if (!identity.inDomain) {
user ??= db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
if (!user || user.role !== "member") {
console.warn(`google login: ${identity.email} is outside the Workspace and has no profile account`);
return back(user ? "wrong_domain" : "no_account");
}
if (user.google_sub && user.google_sub !== identity.sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return back("linked_elsewhere");
}
}
// What the access groups give this person (accessGroups.js), asked
// only when it matters. Unanswerable is a refusal: a sign-in has to
// be shown to be allowed.
@ -232,14 +260,14 @@ auth.get("/google/callback", async (c) => {
if (!byEmail) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
return backToLogin(c, "no_account");
return back("no_account");
}
// In an access group: the account is made now, Google only.
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (found.failed) return back("groups_unreachable");
if (!found.role) {
console.warn(`google login: ${identity.email} is in no access group`);
return backToLogin(c, "not_in_group");
return back("not_in_group");
}
const id = db
.prepare(
@ -251,10 +279,10 @@ auth.get("/google/callback", async (c) => {
user = byId(id);
} else if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
return backToLogin(c, "linked_elsewhere");
return back("linked_elsewhere");
} else {
// Before linking: a refused sign-in mustn't change the account.
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
if (byEmail.is_active !== 1) return back("disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
@ -266,23 +294,30 @@ auth.get("/google/callback", async (c) => {
// and with access groups switched off none gets in (it can't be
// rechecked, so it would keep its last role for good).
if (user.access_source === "group" && user.role !== "superadmin") {
if (!accessEnabled(db)) return backToLogin(c, "not_in_group");
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
if (!accessEnabled(db)) return back("not_in_group");
if (user.is_active !== 1 && user.group_disabled !== 1) return back("disabled");
const found = await roleFromGroups();
if (found.failed) return backToLogin(c, "groups_unreachable");
if (found.failed) return back("groups_unreachable");
applyGroupRole(db, user, found.role);
if (!found.role) return backToLogin(c, "not_in_group");
if (!found.role) return back("not_in_group");
user = byId(user.id);
}
if (user.is_active !== 1) return backToLogin(c, "disabled");
if (user.is_active !== 1) return back("disabled");
createSession(db, c, user.id);
// The invite is taken up: its link stops working.
db.prepare(
`UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
).run(identity.name, user.id);
`UPDATE admin_users
SET last_login_at = datetime('now'), name = COALESCE(name, ?), google_sub = COALESCE(google_sub, ?),
invite_hash = NULL, invite_expires_at = NULL
WHERE id = ?`,
).run(identity.name, identity.sub, user.id);
console.log(`login ${user.email} (google)`);
// A profile account, or a sign-in from the site, goes to the
// profile page; the admin's goes back where it was headed.
if (user.role === "member" || from === "account") return c.redirect("/account", 302);
// Checked again: the cookie came back from the browser.
return c.redirect(safeNext(saved.next), 302);
});

View file

@ -24,13 +24,10 @@
import { Hono } from "hono";
import { asBool, json, loadBlocks, loadFeaturedCards, marks } from "../shape.js";
import { readFeeds } from "../feeds.js";
import { asBool, json, loadBlocks, marks } from "../shape.js";
const blog = new Hono();
const PAGE_ID = "community";
const splitTags = (tags) =>
(tags ?? "")
.split(",")
@ -38,14 +35,14 @@ const splitTags = (tags) =>
.filter(Boolean);
/* Published authors for a batch of posts, keyed by post id. */
function loadAuthors(db, ids) {
export function loadAuthors(db, ids) {
const byPost = new Map();
if (ids.length === 0) return byPost;
const rows = db
.prepare(
`SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id IN (${marks(ids.length)})
ORDER BY a.post_id, a.sort_order`,
)
@ -67,7 +64,7 @@ function loadAuthors(db, ids) {
/* The first paragraph of each post with no excerpt of its own, the
card's fallback text, by post id. Only that one row per post: a
card doesn't need the rest of the body. */
function firstParagraphs(db, rows) {
export function firstParagraphs(db, rows) {
const ids = rows.filter((row) => !row.excerpt).map((row) => row.id);
if (ids.length === 0) return new Map();
const found = db
@ -84,7 +81,7 @@ function firstParagraphs(db, rows) {
return new Map(found.map((row) => [row.owner_id, row.text]));
}
function shapeSummary(row, authors, firstParagraph) {
export function shapeSummary(row, authors, firstParagraph) {
return {
id: row.id,
title: row.title,
@ -148,83 +145,4 @@ blog.get("/blog/:id", (c) => {
});
});
/* ── The Community page's section ──────────────────────────── */
blog.get("/community-blog", async (c) => {
const db = c.get("db");
const page = db.prepare(`SELECT * FROM community_page WHERE id = ?`).get(PAGE_ID);
if (!page) return c.json({ error: "The community page hasn't been set up." }, 500);
// Ours: pinned, then newest.
const pinned = db
.prepare(
`SELECT b.*
FROM community_page_pinned_posts pp
JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1
WHERE pp.page_id = ?
ORDER BY pp.sort_order`,
)
.all(PAGE_ID);
const room = Math.max(0, page.internal_slots - pinned.length);
const pinnedIds = pinned.map((row) => row.id);
const newest = room
? db
.prepare(
`SELECT * FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""}
ORDER BY published_on IS NULL, published_on DESC, created_at DESC
LIMIT ?`,
)
.all(...pinnedIds, room)
: [];
const posts = [...pinned, ...newest];
const ids = posts.map((row) => row.id);
const authors = loadAuthors(db, ids);
const first = firstParagraphs(db, posts);
// Theirs: pinned cards, then the feeds' newest.
const cards = loadFeaturedCards(db, "community_page", PAGE_ID);
const feedRows = db
.prepare(`SELECT url, label FROM community_page_feeds WHERE page_id = ? ORDER BY sort_order`)
.all(PAGE_ID);
const shown = new Set(cards.map((card) => card.url).filter(Boolean));
const spare = Math.max(0, page.external_slots - cards.length);
const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : [];
const latest = fromFeeds
.filter((item) => !shown.has(item.url))
.slice(0, spare)
.map((item) => ({
kind: "link",
ref: null,
url: item.url,
eyebrow: item.source,
title: item.title,
blurb: item.excerpt,
image: item.image ? { file: item.image, kind: "featured" } : null,
published: item.published,
}));
return json(c, {
community_blog: {
internal: {
title: page.internal_title,
posts: posts.map((row) =>
shapeSummary(row, authors.get(row.id) ?? [], first.get(row.id)),
),
},
external: {
title: page.external_title,
url: page.external_url,
label: page.external_label,
cards: [...cards, ...latest],
},
},
});
});
export default blog;

View file

@ -437,7 +437,7 @@ function attachAwards(db, orgs) {
`SELECT a.id, a.org_id, a.name, a.description, a.logo,
(SELECT COUNT(*)
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a
WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 AND a.is_listed = 1
@ -579,7 +579,7 @@ content.get("/events/:id", (c) => {
pa.person_id, p.display_name, p.photo
FROM person_awards pa
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.event_id = ? AND pa.is_public = 1
ORDER BY a.sort_order, a.name, COALESCE(p.sort_name, p.display_name)`,
)
@ -774,7 +774,7 @@ content.get("/awards", (c) => {
`SELECT a.*, o.name AS org_name, o.kind AS org_kind,
(SELECT COUNT(*)
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a
LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1
@ -818,7 +818,7 @@ content.get("/awards/:id", (c) => {
p.display_name, p.photo, p.tagline,
e.id AS event_id, e.title AS event_title
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
LEFT JOIN events e ON e.id = pa.event_id AND e.is_published = 1
WHERE pa.award_id = ? AND pa.is_public = 1
ORDER BY pa.awarded_on DESC, COALESCE(p.sort_name, p.display_name)`,

View file

@ -188,7 +188,7 @@ function loadRosters(db, rows) {
`SELECT tep.entry_id, tep.person_id, tep.note,
p.display_name, p.photo
FROM timeline_entry_people tep
JOIN people p ON p.id = tep.person_id AND p.is_published = 1
JOIN v_people_public p ON p.id = tep.person_id AND p.is_published = 1
WHERE tep.entry_id IN (${marks(ids.length)})
ORDER BY tep.entry_id, tep.sort_order`,
)

View file

@ -1,243 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
FRONT PAGE ROUTE: read-only, mounted under /api
GET /front-page the home page's configuration, resolved
Everything the admin's Front page editor holds, shaped for the
page: hidden sections dropped, stats counted, paths carrying
their actions, and the countdown's event looked up.
The retreats carousel and the timeline rail are not in here.
They fetch /events and /history themselves, as they do on their
own pages, so the rules for which events and entries are public
live in one place each. This route only says whether those bands
appear and under what heading.
── Stats ──
A stat's source picks a query from STAT_QUERIES. Each counts
exactly what the matching public page shows: published, listed
rows, and for awards only public citations to published people
(an award's page names its recipients whether they're listed or
not, so the count does too). A count
that disagreed with the page it summarizes would be worse than
none. 'manual' and 'years_since' read the row's own value.
── Countdown ──
The pinned event if it is still published and not over, listed
or not; otherwise the next published, listed, non-canceled
event that hasn't ended. "Hasn't ended" is COALESCE(ends_on, starts_on) >= today,
so a running series with a start date in the past still counts.
The client works out the next meeting of a series from `series`.
countdown_scope_id and countdown_event_type narrow "the next
event" (National + Retreat skips a sooner regional class). Null
means any. They don't apply to a pinned event: the admin chose
that one by name.
── Hero event ──
With the 'event' feature, the hero draws the pinned hero_event_id
if it's still published and not over, else the countdown's event
(above), so the two never disagree. Its action links ride along
for the card's buttons.
── Featured ──
The featured band's cards, record cards filled in from their
records (loadFeaturedCards in shape.js, which the Community
blog will share).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { asBool, json, loadFeaturedCards, loadLinks, shapeSeries, splitLinks } from "../shape.js";
const home = new Hono();
const PAGE_ID = "home";
const STAT_QUERIES = {
regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1 AND is_listed = 1`,
groups: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'group' AND is_published = 1 AND is_listed = 1`,
partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1 AND is_listed = 1`,
events_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'`,
retreats_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'
AND event_type = 'retreat'`,
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
WHERE pa.is_public = 1`,
};
/* The number as a string, or null when there's nothing to print:
a manual stat nobody filled in, or a year that isn't one. */
function statValue(db, row) {
if (row.source === "manual") return row.value || null;
if (row.source === "years_since") {
const year = Number.parseInt(row.value ?? "", 10);
if (!Number.isInteger(year)) return null;
return String(Math.max(0, new Date().getFullYear() - year));
}
const sql = STAT_QUERIES[row.source];
return sql ? String(db.prepare(sql).get().n) : null;
}
/* The countdown's fields plus what the hero's event card also draws:
its tagline, place, photo and buttons. */
function shapeHeroEvent(db, row) {
if (!row) return null;
const { actions } = splitLinks(loadLinks(db, "event", [row.id]).get(row.id) ?? []);
return {
...shapeCountdown(row),
tagline: row.tagline,
photo: row.photo,
photo_alt: row.photo_alt,
org_logo: row.effective_org_logo,
links: actions,
};
}
function shapeCountdown(row) {
if (!row) return null;
return {
id: row.id,
title: row.title,
theme: row.theme,
starts_on: row.starts_on,
ends_on: row.ends_on,
date_label: row.date_label,
location_label: row.location_label,
is_online: asBool(row.is_online),
color: row.effective_color,
event_logo: row.event_logo,
series: shapeSeries(row),
};
}
home.get("/front-page", (c) => {
const db = c.get("db");
const page = db.prepare(`SELECT * FROM front_page WHERE id = ?`).get(PAGE_ID);
// The schema seeds the row and the engine refuses to delete it,
// so this is a database that hasn't been migrated. Say so.
if (!page) return c.json({ error: "The front page hasn't been set up." }, 500);
const byOrder = (table) =>
db.prepare(`SELECT * FROM ${table} WHERE page_id = ? ORDER BY sort_order`).all(PAGE_ID);
const sections = byOrder("front_page_sections")
.filter((row) => !asBool(row.is_hidden))
.map((row) => ({ section: row.section, title: row.title, blurb: row.blurb }));
const slides = byOrder("front_page_slides").map((row) => ({
media: row.media,
alt: row.alt,
caption: row.caption,
link_url: row.link_url,
}));
const stats = byOrder("front_page_stats")
.map((row) => ({
label: row.label,
value: statValue(db, row),
suffix: row.suffix,
note: row.note,
}))
.filter((stat) => stat.value !== null);
const actions = db.prepare(
`SELECT label, description, url FROM front_page_path_actions
WHERE path_id = ? ORDER BY sort_order`,
);
const paths = byOrder("front_page_paths")
.map((row) => ({
label: row.label,
icon: row.icon,
blurb: row.blurb,
actions: actions.all(row.id),
}))
// A path with nothing to do is a dead tab.
.filter((path) => path.actions.length > 0);
const notOver = `is_published = 1
AND effective_status != 'cancelled'
AND COALESCE(ends_on, starts_on) >= date('now')`;
const pinned = page.countdown_event_id
? db
.prepare(`SELECT * FROM v_events WHERE id = ? AND ${notOver}`)
.get(page.countdown_event_id)
: null;
const filters = [];
const params = [];
if (page.countdown_scope_id) {
filters.push("AND scope_id = ?");
params.push(page.countdown_scope_id);
}
if (page.countdown_event_type) {
filters.push("AND event_type = ?");
params.push(page.countdown_event_type);
}
const next =
pinned ??
db
.prepare(
`SELECT * FROM v_events
WHERE ${notOver} AND is_listed = 1 ${filters.join(" ")}
ORDER BY starts_on, title
LIMIT 1`,
)
.get(...params);
const heroEvent =
page.hero_feature === "event"
? (page.hero_event_id
? db
.prepare(`SELECT * FROM v_events WHERE id = ? AND ${notOver}`)
.get(page.hero_event_id)
: null) ?? next
: null;
return json(c, {
front_page: {
hero: {
backdrop: page.hero_backdrop,
feature: page.hero_feature,
eyebrow: page.eyebrow,
headline: page.headline,
subhead: page.subhead,
primary: page.primary_label && page.primary_url
? { label: page.primary_label, url: page.primary_url }
: null,
secondary: page.secondary_label && page.secondary_url
? { label: page.secondary_label, url: page.secondary_url }
: null,
slide_seconds: page.slide_seconds,
slides,
livestream: page.livestream_url
? { url: page.livestream_url, title: page.livestream_title }
: null,
video: page.video_url
? { url: page.video_url, title: page.video_title, captions: page.video_captions, still: page.video_still }
: null,
event: shapeHeroEvent(db, heroEvent),
},
sections,
stats,
paths,
featured: loadFeaturedCards(db, "front_page", PAGE_ID),
// 2, 3 or 4 across (073); null is the grid's own default.
featured_columns: page.featured_columns,
countdown: shapeCountdown(next),
},
});
});
export default home;

View file

@ -74,6 +74,8 @@ export function importDocx(db, buffer, fileName, byEmail) {
slot: "body",
type: block.type,
text: block.text ?? null,
href: block.href ?? null,
cite: block.cite ?? null,
items: block.items ?? [],
})),
});
@ -87,6 +89,9 @@ export function importDocx(db, buffer, fileName, byEmail) {
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
tabs: count("tab"),
// Quotes, callouts, dividers, videos and buttons.
others: doc.blocks.filter((b) => ["quote", "callout", "divider", "video", "button"].includes(b.type)).length,
skipped: doc.skipped,
},
};

View file

@ -7,7 +7,8 @@
can say no while production says yes
GET /anything the built index.html, its title, description,
preview image, canonical link and structured
data filled in for that path (pageMeta.js)
data filled in for that path (pageMeta.js),
and this visitor's menus (siteNav.js)
In production nginx serves files that exist (the JS, CSS,
uploads) itself and sends everything else here, so a shared link
@ -35,6 +36,7 @@ import { fileURLToPath } from "node:url";
import { Hono } from "hono";
import { currentUser } from "../auth.js";
import { metaFor, renderPage, robotsTxt, siteFor, sitemap } from "../pageMeta.js";
import { CACHE, NO_STORE } from "../shape.js";
@ -109,7 +111,8 @@ pages.get("*", (c, next) => {
let meta;
let page;
try {
meta = metaFor(c.get("db"), pathname);
// Who's asking decides whether a hidden page is there (siteNav.js).
meta = metaFor(c.get("db"), pathname, currentUser(c.get("db"), c));
page = renderPage(html, meta);
} catch (err) {
warnOnce(

79
server/src/routes/pco.js Normal file
View file

@ -0,0 +1,79 @@
/* ═══════════════════════════════════════════════════════════════
PLANNING CENTER ROUTES: Data → Planning Center, mounted under
/api/admin, admins and up (planningCenter.js)
GET /pco whether it's set up, and the list's id
POST /pco/compare the list, each member with its match and what
would change; nothing is written
POST /pco/apply { decisions: [{ pco, action, person_id, update }] }
what the admin chose, in one transaction
The comparison is fetched again for apply's members rather than
trusting the browser's copy of Planning Center's values: only the
choices (which person, link or create, update or not) come from it.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { requireRole } from "../auth.js";
import { tx } from "../db.js";
import { PcoError, apply, compare, listPeople, pcoReady } from "../planningCenter.js";
import { NO_STORE } from "../shape.js";
const pco = new Hono();
pco.use("/pco", requireRole("admin"));
pco.use("/pco/*", requireRole("admin"));
const listId = (db) => db.prepare(`SELECT pco_list_id FROM site_settings WHERE id = 'site'`).get()?.pco_list_id ?? null;
pco.get("/pco", (c) => c.json({ ready: pcoReady(), list_id: listId(c.get("db")) }, 200, NO_STORE));
pco.post("/pco/compare", async (c) => {
const db = c.get("db");
try {
const members = await listPeople(listId(db));
return c.json({ rows: compare(db, members) }, 200, NO_STORE);
} catch (err) {
if (err instanceof PcoError) return c.json({ error: err.message }, 502, NO_STORE);
throw err;
}
});
pco.post("/pco/apply", async (c) => {
const db = c.get("db");
let body;
try {
body = (await c.req.json()) ?? {};
} catch {
return c.json({ error: "Expected a JSON body." }, 400);
}
const chosen = Array.isArray(body.decisions) ? body.decisions : [];
let members;
try {
members = await listPeople(listId(db));
} catch (err) {
if (err instanceof PcoError) return c.json({ error: err.message }, 502, NO_STORE);
throw err;
}
const byId = new Map(members.map((m) => [m.id, m]));
const known = new Set(db.prepare(`SELECT id FROM people`).all().map((r) => r.id));
const decisions = chosen
.map((d) => ({
pco: byId.get(String(d?.pco_id ?? "")),
action: d?.action === "create" ? "create" : d?.action === "link" ? "link" : null,
person_id: d?.person_id && known.has(String(d.person_id)) ? String(d.person_id) : null,
update: Boolean(d?.update),
}))
.filter((d) => d.pco && d.action && (d.action === "create" || d.person_id));
const counts = tx(db, () => apply(db, decisions));
console.log(
`pco sync by ${c.get("user").email}: ${counts.linked} linked, ${counts.updated} updated, ${counts.created} created`,
);
return c.json({ counts }, 200, NO_STORE);
});
export default pco;

View file

@ -129,7 +129,7 @@ people.get("/people", (c) => {
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM people p
FROM v_people_public p
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id IN (${marks(ids.length)})
AND p.is_published = 1`,
@ -167,7 +167,7 @@ people.get("/directories/:tag", (c) => {
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
JOIN v_people_public 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)`,
@ -221,7 +221,7 @@ people.get("/people/:id", (c) => {
o.id AS primary_org_id,
o.name AS primary_org_name,
o.kind AS primary_org_kind
FROM people p
FROM v_people_public p
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id = ? AND p.is_published = 1`,
)

View file

@ -0,0 +1,198 @@
/* ═══════════════════════════════════════════════════════════════
PROFILE ACCOUNT ROUTES (076): Data → Profile accounts, mounted
under /api/admin, admins and up
GET /profiles every profile account, and the
claims waiting
POST /profiles { email, name }: a new account,
invited (its link comes back)
POST /profiles/:id/invite a new link, replacing the old;
{ email: true } also emails it
PATCH /profiles/:id { person_id, discord_id,
discord_name, is_active }: an
admin's own say
DELETE /profiles/:id remove the account
POST /profiles/claims/:id/approve the request's person is theirs
POST /profiles/claims/:id/decline
Only member accounts are listed or changed here. The admin roles
are the Panel's (superadmins), so an admin can't make or touch
another admin from this page.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { destroyAllSessionsFor, logSafe, requireRole } from "../auth.js";
import { tx } from "../db.js";
import { emailInvite, issueInvite } from "../invites.js";
import { mailReady } from "../googleService.js";
import { NO_STORE } from "../shape.js";
const profiles = new Hono();
profiles.use("/profiles", requireRole("admin"));
profiles.use("/profiles/*", requireRole("admin"));
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
async function body(c) {
try {
return (await c.req.json()) ?? {};
} catch {
return null;
}
}
const member = (db, id) =>
db.prepare(`SELECT * FROM admin_users WHERE id = ? AND role = 'member'`).get(Number(id)) ?? null;
profiles.get("/profiles", (c) => {
const db = c.get("db");
const accounts = db
.prepare(
`SELECT u.id, u.email, u.name, u.is_active, u.created_at, u.last_login_at,
u.invited_at, u.invite_expires_at,
(u.invite_hash IS NOT NULL AND u.invite_expires_at > datetime('now')) AS invite_open,
(u.password_hash IS NOT NULL OR u.google_sub IS NOT NULL) AS signed_up,
u.person_id, p.display_name AS person_name,
u.discord_id, u.discord_name
FROM admin_users u
LEFT JOIN people p ON p.id = u.person_id
WHERE u.role = 'member'
ORDER BY u.created_at DESC, u.id DESC`,
)
.all();
const claims = db
.prepare(
`SELECT c.id, c.account_id, u.email, u.name, c.person_id, p.display_name AS person_name,
c.message, c.created_at
FROM person_claims c
JOIN admin_users u ON u.id = c.account_id
JOIN people p ON p.id = c.person_id
WHERE c.status = 'pending'
ORDER BY c.created_at`,
)
.all();
return c.json({ accounts, claims, mail: mailReady() }, 200, NO_STORE);
});
profiles.post("/profiles", async (c) => {
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const db = c.get("db");
const email = String(data.email ?? "").trim().toLowerCase().slice(0, 254);
const name = String(data.name ?? "").trim().slice(0, 120) || null;
if (!EMAIL.test(email)) return c.json({ error: "Enter an email address.", fields: { email: "Needed." } }, 422);
if (db.prepare(`SELECT 1 FROM admin_users WHERE email = ?`).get(email)) {
return c.json({ error: "That email already has an account.", fields: { email: "Already has one." } }, 409);
}
const id = db
.prepare(
`INSERT INTO admin_users (email, name, role, access_source) VALUES (?, ?, 'member', 'invite')`,
)
.run(email, name).lastInsertRowid;
const link = issueInvite(db, id, c.get("user").id);
console.log(`profile account ${logSafe(email)} invited by ${c.get("user").email}`);
return c.json({ id: Number(id), link }, 201, NO_STORE);
});
profiles.post("/profiles/:id/invite", async (c) => {
const db = c.get("db");
const account = member(db, c.req.param("id"));
if (!account) return c.json({ error: "No such profile account." }, 404);
const data = (await body(c)) ?? {};
const link = issueInvite(db, account.id, c.get("user").id);
if (data.email) {
try {
await emailInvite(db, account, link);
} catch (err) {
console.warn(`invite email to ${account.email} failed: ${err.message}`);
return c.json({ link, emailed: false, error: `The email didn't go: ${err.message}` }, 502, NO_STORE);
}
}
console.log(`invite for ${account.email} ${data.email ? "emailed" : "issued"} by ${c.get("user").email}`);
return c.json({ link, emailed: Boolean(data.email) }, 200, NO_STORE);
});
profiles.patch("/profiles/:id", async (c) => {
const db = c.get("db");
const account = member(db, c.req.param("id"));
if (!account) return c.json({ error: "No such profile account." }, 404);
const data = await body(c);
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
const sets = [];
const values = [];
if ("person_id" in data) {
const personId = data.person_id ? String(data.person_id) : null;
if (personId) {
if (!db.prepare(`SELECT 1 FROM people WHERE id = ?`).get(personId)) {
return c.json({ error: "No such person.", fields: { person_id: "Pick one." } }, 422);
}
const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ? AND id <> ?`).get(personId, account.id);
if (holder) return c.json({ error: `${holder.email} already has that profile.` }, 409);
}
sets.push("person_id = ?");
values.push(personId);
}
if ("discord_id" in data) {
const discordId = data.discord_id ? String(data.discord_id).trim() : null;
if (discordId && !/^\d{5,25}$/.test(discordId)) {
return c.json({ error: "A Discord id is the long number (Developer Mode → Copy User ID).", fields: { discord_id: "Digits only." } }, 422);
}
if (discordId && db.prepare(`SELECT 1 FROM admin_users WHERE discord_id = ? AND id <> ?`).get(discordId, account.id)) {
return c.json({ error: "Another account has that Discord id." }, 409);
}
sets.push("discord_id = ?", "discord_name = ?");
values.push(discordId, discordId ? String(data.discord_name ?? "").trim().slice(0, 100) || null : null);
}
if ("is_active" in data) {
sets.push("is_active = ?");
values.push(data.is_active ? 1 : 0);
}
if (!sets.length) return c.json({ error: "Nothing to change." }, 422);
db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run(...values, account.id);
if ("is_active" in data && !data.is_active) destroyAllSessionsFor(db, account.id);
console.log(`profile account ${account.email} changed by ${c.get("user").email}`);
return c.body(null, 204);
});
profiles.delete("/profiles/:id", (c) => {
const db = c.get("db");
const account = member(db, c.req.param("id"));
if (!account) return c.json({ error: "No such profile account." }, 404);
db.prepare(`DELETE FROM admin_users WHERE id = ?`).run(account.id);
console.log(`profile account ${account.email} removed by ${c.get("user").email}`);
return c.body(null, 204);
});
function decide(c, approve) {
const db = c.get("db");
const claim = db
.prepare(`SELECT * FROM person_claims WHERE id = ? AND status = 'pending'`)
.get(Number(c.req.param("id")));
if (!claim) return c.json({ error: "That request was already answered." }, 404);
const taken = tx(db, () => {
if (approve) {
const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ?`).get(claim.person_id);
if (holder) return holder.email;
db.prepare(`UPDATE admin_users SET person_id = ? WHERE id = ?`).run(claim.person_id, claim.account_id);
}
db.prepare(
`UPDATE person_claims SET status = ?, decided_at = datetime('now'), decided_by = ? WHERE id = ?`,
).run(approve ? "approved" : "declined", c.get("user").id, claim.id);
return null;
});
if (taken) return c.json({ error: `${taken} already has that profile. Decline this one.` }, 409);
console.log(`claim ${claim.id} (${claim.person_id}) ${approve ? "approved" : "declined"} by ${c.get("user").email}`);
return c.body(null, 204);
}
profiles.post("/profiles/claims/:id/approve", (c) => decide(c, true));
profiles.post("/profiles/claims/:id/decline", (c) => decide(c, false));
export default profiles;

View file

@ -1,11 +1,18 @@
/* ═══════════════════════════════════════════════════════════════
SITE PAGE ROUTES: read-only, mounted under /api
GET /site-pages every site page's section headings, for
the header's dropdowns and the side nav
GET /site-pages/:id one page's sections, in order: heading,
GET /nav this visitor's header and footer links and
the hidden pages (siteNav.js); not cached,
since it depends on who's signed in
GET /site-pages every page's section headings, by the
page's path, for the header's dropdowns
and the side nav
GET /site-pages/:id one page's title and intro and its shown
sections, in order, each with what its type
shows (sectionData.js): heading,
accent, preset (and an events preset's
filter and view), and its blocks
filter and view), and its blocks; Not
found for a hidden page, below viewer
Edited in the admin as Pages → each page
(admin-schema/sitePages.js). Blocks are shaped as on any record
@ -13,32 +20,46 @@
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { json, loadBlocks } from "../shape.js";
import { currentUser } from "../auth.js";
import { navFor, seesHidden } from "../siteNav.js";
import { NO_STORE, json, loadBlocks } from "../shape.js";
import { withSectionData } from "../sectionData.js";
const sitePages = new Hono();
sitePages.get("/nav", (c) => {
const db = c.get("db");
return c.json({ nav: navFor(db, currentUser(db, c)) }, 200, NO_STORE);
});
sitePages.get("/site-pages", (c) => {
const rows = c
.get("db")
.prepare(`SELECT page_id, anchor, title FROM page_sections ORDER BY page_id, sort_order, id`)
.prepare(
`SELECT p.path, s.anchor, s.title, s.preset FROM page_sections s JOIN site_pages p ON p.id = s.page_id
WHERE s.is_hidden = 0
ORDER BY p.path, s.sort_order, s.id`,
)
.all();
const pages = {};
for (const row of rows) (pages[row.page_id] ??= []).push({ anchor: row.anchor, title: row.title });
for (const row of rows) (pages[row.path] ??= []).push({ anchor: row.anchor, title: row.title, preset: row.preset });
return json(c, { pages });
});
sitePages.get("/site-pages/:id", (c) => {
sitePages.get("/site-pages/:id", async (c) => {
const db = c.get("db");
const id = c.req.param("id");
if (!db.prepare(`SELECT 1 FROM site_pages WHERE id = ?`).get(id)) {
const found = db.prepare(`SELECT title, description, is_hidden FROM site_pages WHERE id = ?`).get(id);
const hidden = found?.is_hidden === 1;
if (!found || (hidden && !seesHidden(currentUser(db, c)))) {
return c.json({ error: "No such page." }, 404);
}
const rows = db
.prepare(
`SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, tag_id, org_kinds
FROM page_sections WHERE page_id = ? ORDER BY sort_order, id`,
`SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
FROM page_sections WHERE page_id = ? AND is_hidden = 0 ORDER BY sort_order, id`,
)
.all(id);
const blocks = loadBlocks(db, "page_section", rows.map((row) => String(row.id)));
@ -52,14 +73,32 @@ sitePages.get("/site-pages/:id", (c) => {
.all(id)) {
picked.set(section_id, [...(picked.get(section_id) ?? []), org_id]);
}
// A People directory's tags (078), in order.
const tags = new Map();
for (const { section_id, tag_id } of db
.prepare(
`SELECT t.section_id, t.tag_id FROM page_section_tags t
JOIN page_sections s ON s.id = t.section_id
WHERE s.page_id = ? ORDER BY t.section_id, t.sort_order, t.id`,
)
.all(id)) {
tags.set(section_id, [...(tags.get(section_id) ?? []), tag_id]);
}
return json(c, {
const sections = await withSectionData(db, rows);
// A hidden page is only for those signed in: never kept.
const send = hidden ? (body) => c.json(body, 200, NO_STORE) : (body) => json(c, body);
return send({
page: {
id,
sections: rows.map(({ id: sectionId, ...section }) => ({
title: found.title,
description: found.description,
sections: sections.map(({ id: sectionId, ...section }) => ({
...section,
blocks: blocks.get(String(sectionId)) ?? [],
org_ids: picked.get(sectionId) ?? [],
tag_ids: tags.get(sectionId) ?? [],
})),
},
});

290
server/src/sectionData.js Normal file
View file

@ -0,0 +1,290 @@
/* ═══════════════════════════════════════════════════════════════
SECTION DATA
What a section type shows beyond its blocks, resolved for the page
(routes/sitePages.js, GET /site-pages/:id), from its settings
tables (083_section_settings.sql):
hero its words, buttons, backdrop, slides, and the
event its card shows (with the 'event' feature)
countdown the event it counts down to
stats its numbers, counted
connect its paths, each with its links
featured_cards its cards, record cards filled in from their
records
community_blog our posts (pinned, then newest) and community
posts (pinned cards, then its feeds' newest)
── Stats ──
A stat's source picks a query from STAT_QUERIES. Each counts
exactly what the matching public page shows: published, listed
rows, and for awards only public citations to published people.
A count that disagreed with the page it summarizes would be worse
than none. 'manual' and 'years_since' read the row's own value.
── Countdown ──
The pinned event if it is still published and not over, listed
or not; otherwise the next published, listed, non-canceled event
that hasn't ended (COALESCE(ends_on, starts_on) >= today, so a
running series still counts), narrowed by the section's scope and
type. The client works out a series' next meeting from `series`.
── Hero event ──
With the 'event' feature, the hero draws its pinned event if it's
still published and not over, else the page's countdown's event,
else the next event, so the two never disagree.
═══════════════════════════════════════════════════════════════ */
import { asBool, loadFeaturedCards, loadLinks, marks, shapeSeries, splitLinks } from "./shape.js";
import { readFeeds } from "./feeds.js";
import { firstParagraphs, loadAuthors, shapeSummary } from "./routes/blog.js";
const STAT_QUERIES = {
regions: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'region' AND is_published = 1 AND is_listed = 1`,
groups: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'group' AND is_published = 1 AND is_listed = 1`,
partners: `SELECT COUNT(*) AS n FROM organizations WHERE kind = 'partner' AND is_published = 1 AND is_listed = 1`,
events_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'`,
retreats_held: `SELECT COUNT(*) AS n FROM v_events
WHERE is_published = 1 AND is_listed = 1 AND effective_status = 'past'
AND event_type = 'retreat'`,
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
WHERE pa.is_public = 1`,
};
/* The number as a string, or null when there's nothing to print. */
function statValue(db, row) {
if (row.source === "manual") return row.value || null;
if (row.source === "years_since") {
const year = Number.parseInt(row.value ?? "", 10);
if (!Number.isInteger(year)) return null;
return String(Math.max(0, new Date().getFullYear() - year));
}
const sql = STAT_QUERIES[row.source];
return sql ? String(db.prepare(sql).get().n) : null;
}
function shapeCountdown(row) {
if (!row) return null;
return {
id: row.id,
title: row.title,
theme: row.theme,
starts_on: row.starts_on,
ends_on: row.ends_on,
date_label: row.date_label,
location_label: row.location_label,
is_online: asBool(row.is_online),
color: row.effective_color,
event_logo: row.event_logo,
series: shapeSeries(row),
};
}
/* The countdown's fields plus what the hero's event card also draws. */
function shapeHeroEvent(db, row) {
if (!row) return null;
const { actions } = splitLinks(loadLinks(db, "event", [row.id]).get(row.id) ?? []);
return {
...shapeCountdown(row),
tagline: row.tagline,
photo: row.photo,
photo_alt: row.photo_alt,
org_logo: row.effective_org_logo,
links: actions,
};
}
const NOT_OVER = `is_published = 1
AND effective_status != 'cancelled'
AND COALESCE(ends_on, starts_on) >= date('now')`;
const pinnedEvent = (db, id) =>
id ? db.prepare(`SELECT * FROM v_events WHERE id = ? AND ${NOT_OVER}`).get(id) ?? null : null;
/* A countdown's event: the pinned one, else the next of its scope and type. */
function countdownEvent(db, settings) {
const pinned = pinnedEvent(db, settings?.event_id);
if (pinned) return pinned;
const filters = [];
const params = [];
if (settings?.scope_id) {
filters.push("AND scope_id = ?");
params.push(settings.scope_id);
}
if (settings?.event_type) {
filters.push("AND event_type = ?");
params.push(settings.event_type);
}
return (
db
.prepare(
`SELECT * FROM v_events
WHERE ${NOT_OVER} AND is_listed = 1 ${filters.join(" ")}
ORDER BY starts_on, title
LIMIT 1`,
)
.get(...params) ?? null
);
}
const byOrder = (db, table, column, id) =>
db.prepare(`SELECT * FROM ${table} WHERE ${column} = ? ORDER BY sort_order, id`).all(id);
function heroOf(db, section, pageCountdown) {
const h = db.prepare(`SELECT * FROM section_hero WHERE section_id = ?`).get(section.id) ?? {};
const event =
h.feature === "event" ? pinnedEvent(db, h.event_id) ?? pageCountdown ?? countdownEvent(db, null) : null;
return {
backdrop: h.backdrop ?? "brand",
feature: h.feature ?? "none",
eyebrow: h.eyebrow ?? null,
headline: h.headline ?? "",
subhead: h.subhead ?? null,
primary: h.primary_label && h.primary_url ? { label: h.primary_label, url: h.primary_url } : null,
secondary: h.secondary_label && h.secondary_url ? { label: h.secondary_label, url: h.secondary_url } : null,
slide_seconds: h.slide_seconds ?? 7,
slides: byOrder(db, "section_slides", "section_id", section.id).map((row) => ({
media: row.media,
alt: row.alt,
caption: row.caption,
link_url: row.link_url,
})),
livestream: h.livestream_url ? { url: h.livestream_url, title: h.livestream_title } : null,
video: h.video_url
? { url: h.video_url, title: h.video_title, captions: h.video_captions, still: h.video_still }
: null,
event: shapeHeroEvent(db, event),
// Its rotating words' motion (084); null keeps the site's.
words: { motion: h.word_motion ?? null, direction: h.word_direction ?? null, seconds: h.word_seconds ?? null },
};
}
function pathsOf(db, section) {
const actions = db.prepare(
`SELECT label, description, url FROM section_path_actions WHERE path_id = ? ORDER BY sort_order, id`,
);
return (
byOrder(db, "section_paths", "section_id", section.id)
.map((row) => ({ label: row.label, icon: row.icon, blurb: row.blurb, actions: actions.all(row.id) }))
// A path with nothing to do is a dead tab.
.filter((path) => path.actions.length > 0)
);
}
async function blogOf(db, section) {
const page = db.prepare(`SELECT * FROM section_blog WHERE section_id = ?`).get(section.id) ?? {
internal_slots: 3,
external_slots: 3,
};
// Ours: pinned, then newest.
const pinned = db
.prepare(
`SELECT b.*
FROM section_blog_posts pp
JOIN blog_posts b ON b.id = pp.post_id AND b.is_published = 1
WHERE pp.section_id = ?
ORDER BY pp.sort_order`,
)
.all(section.id);
const room = Math.max(0, page.internal_slots - pinned.length);
const pinnedIds = pinned.map((row) => row.id);
const newest = room
? db
.prepare(
`SELECT * FROM blog_posts
WHERE is_published = 1 AND is_listed = 1
${pinnedIds.length ? `AND id NOT IN (${marks(pinnedIds.length)})` : ""}
ORDER BY published_on IS NULL, published_on DESC, created_at DESC
LIMIT ?`,
)
.all(...pinnedIds, room)
: [];
const posts = [...pinned, ...newest];
const authors = loadAuthors(db, posts.map((row) => row.id));
const first = firstParagraphs(db, posts);
// Theirs: pinned cards, then the feeds' newest.
const cards = loadFeaturedCards(db, "page_section", String(section.id));
const feedRows = db
.prepare(`SELECT url, label FROM section_feeds WHERE section_id = ? ORDER BY sort_order`)
.all(section.id);
const shown = new Set(cards.map((card) => card.url).filter(Boolean));
const spare = Math.max(0, page.external_slots - cards.length);
const fromFeeds = spare && feedRows.length ? await readFeeds(feedRows) : [];
const latest = fromFeeds
.filter((item) => !shown.has(item.url))
.slice(0, spare)
.map((item) => ({
kind: "link",
ref: null,
url: item.url,
eyebrow: item.source,
title: item.title,
blurb: item.excerpt,
image: item.image ? { file: item.image, kind: "featured" } : null,
published: item.published,
}));
return {
internal: {
title: page.internal_title,
posts: posts.map((row) => shapeSummary(row, authors.get(row.id) ?? [], first.get(row.id))),
},
external: {
title: page.external_title,
url: page.external_url,
label: page.external_label,
cards: [...cards, ...latest],
},
};
}
/* Each section with what its type shows, as `data`. A page's first
countdown is the event its heroes fall back to. */
export async function withSectionData(db, sections) {
const countdown = sections.find((s) => s.preset === "countdown");
const pageCountdown = countdown
? countdownEvent(db, db.prepare(`SELECT * FROM section_countdown WHERE section_id = ?`).get(countdown.id))
: null;
return Promise.all(
sections.map(async (section) => {
switch (section.preset) {
case "hero":
return { ...section, data: heroOf(db, section, pageCountdown) };
case "countdown": {
const settings = db.prepare(`SELECT * FROM section_countdown WHERE section_id = ?`).get(section.id);
const event = section === countdown ? pageCountdown : countdownEvent(db, settings);
return { ...section, data: shapeCountdown(event) };
}
case "stats":
return {
...section,
data: byOrder(db, "section_stats", "section_id", section.id)
.map((row) => ({ label: row.label, value: statValue(db, row), suffix: row.suffix, note: row.note }))
.filter((stat) => stat.value !== null),
};
case "connect":
return { ...section, data: pathsOf(db, section) };
case "featured_cards":
return {
...section,
data: {
cards: loadFeaturedCards(db, "page_section", String(section.id)),
columns: db.prepare(`SELECT columns FROM section_featured WHERE section_id = ?`).get(section.id)?.columns ?? null,
},
};
case "community_blog":
return { ...section, data: await blogOf(db, section) };
default:
return section;
}
}),
);
}

View file

@ -27,11 +27,14 @@ export function loadLinks(db, ownerKind, ids) {
const out = new Map();
if (ids.length === 0) return out;
// A person who took their links off the site (people.hide_links,
// 076) has none here.
const rows = db
.prepare(
`SELECT owner_id, kind, platform, label, url, is_primary
FROM links
WHERE owner_kind = ? AND owner_id IN (${placeholders(ids.length)})
AND NOT (owner_kind = 'person' AND owner_id IN (SELECT id FROM people WHERE hide_links = 1))
ORDER BY owner_id, sort_order`,
)
.all(ownerKind, ...ids);
@ -67,7 +70,8 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
const blockRows = db
.prepare(
`SELECT id, owner_id, type, text, media, href, alt, cite, captions, team_id
`SELECT id, owner_id, type, text, media, href, alt, cite, captions, team_id,
word_motion, word_direction, word_seconds
FROM content_blocks
WHERE owner_kind = ? AND slot IN (?, 'both') AND owner_id IN (${placeholders(ids.length)})
ORDER BY owner_id, sort_order`,
@ -88,6 +92,10 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
cite: row.cite,
captions: row.captions,
team_id: row.team_id,
// Its rotating words' motion (084), when it has its own.
words: row.word_motion || row.word_direction || row.word_seconds
? { motion: row.word_motion, direction: row.word_direction, seconds: row.word_seconds }
: null,
items: [],
};
byId.set(row.id, block);
@ -106,7 +114,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
p.id AS person_id, p.display_name AS person_name,
p.photo AS person_photo, p.tagline AS person_tagline
FROM content_block_items i
LEFT JOIN people p ON p.id = i.person_id AND p.is_published = 1
LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
WHERE i.block_id IN (${placeholders(blockIds.length)})
ORDER BY i.block_id, i.sort_order`,
)
@ -209,7 +217,7 @@ export function splitLinks(links = []) {
first; an empty list means "starts_on's weekday", which the
client resolves since it already holds starts_on. Occurrences
are not sent, they are derived, and the client derives them
against its own today. Shared by /events and /front-page.
against its own today. Shared by /events and the sections (sectionData.js).
───────────────────────────────────────────────────────────── */
const SERIES_WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
@ -266,7 +274,7 @@ const FEATURED_REFS = {
person: {
sql: (marks) =>
`SELECT id, display_name AS title, tagline AS blurb, photo
FROM people WHERE is_published = 1 AND id IN (${marks})`,
FROM v_people_public WHERE is_published = 1 AND id IN (${marks})`,
image: (row) => (row.photo ? { file: row.photo, kind: "person" } : null),
},
team: {

107
server/src/siteNav.js Normal file
View file

@ -0,0 +1,107 @@
/* ═══════════════════════════════════════════════════════════════
SITE NAVIGATION AND PAGES
The site's pages (site_pages, 080_page_registry.sql: Pages →
Page management) and the header's and footer's links (Pages →
Navigation, 075). Read by pageMeta.js (window.__SITE__, each
page's status and title, the sitemap) and served as GET /api/nav
for the app (routes/sitePages.js).
hidden Not found to anyone below viewer, and left out of
what they're sent, links included; a viewer and up
sees it, and the page says it's hidden (Layout.tsx)
disabled out of the menus, the sitemap and search, for
everyone; its address still works
Who's asking is the session cookie, so the same page can be
hidden from one visitor and shown to the next: the HTML is
no-cache already.
═══════════════════════════════════════════════════════════════ */
import { hasRole } from "./auth.js";
/* Who sees hidden pages. */
export const SEES_HIDDEN = "viewer";
export const seesHidden = (user) => hasRole(user, SEES_HIDDEN);
/* A link's page: its path without the #section or ?query, or null
for an address off the site. */
export const pageOf = (href) =>
/^\//.test(href) ? href.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/" : null;
/* Every page, in the admin's order. */
export function allPages(db) {
return db
.prepare(
`SELECT id, path, title, description, is_hidden, is_disabled
FROM site_pages ORDER BY sort_order, title`,
)
.all();
}
/* The page at this path, or null. */
export function pageAt(db, path) {
return (
db
.prepare(`SELECT id, path, title, description, is_hidden, is_disabled FROM site_pages WHERE path = ?`)
.get(pageOf(path) ?? path) ?? null
);
}
/* The paths whose pages are hidden, eg. '/shop'. */
export function hiddenPaths(db) {
return new Set(
db
.prepare(`SELECT path FROM site_pages WHERE is_hidden = 1`)
.all()
.map((row) => row.path),
);
}
/* Whether this path's page is one the user can't see. */
export function hiddenFrom(db, user, pathname) {
return !seesHidden(user) && hiddenPaths(db).has(pageOf(pathname));
}
/* What the app draws its menus and pages from: every page this user
may open, every link they may follow (none to a disabled page),
and which pages are hidden (so the app can say so). */
export function navFor(db, user) {
const sees = seesHidden(user);
const pages = allPages(db).filter((page) => sees || page.is_hidden !== 1);
const hidden = new Set(allPages(db).filter((p) => p.is_hidden === 1).map((p) => p.path));
const disabled = new Set(pages.filter((p) => p.is_disabled === 1).map((p) => p.path));
const links = db
.prepare(
`SELECT place, label, path, parent_path, style, new_tab
FROM site_nav_links WHERE nav_id = 'site' ORDER BY sort_order, id`,
)
.all()
.filter((link) => {
const page = pageOf(link.path);
return !disabled.has(page) && (sees || !hidden.has(page));
})
.map((link) => ({
place: link.place,
label: link.label,
path: link.path,
parent: link.parent_path || null,
filled: link.style === "filled",
newTab: link.new_tab === 1,
}));
return {
links,
pages: pages.map((page) => ({
id: page.id,
path: page.path,
title: page.title,
description: page.description,
hidden: page.is_hidden === 1,
disabled: page.is_disabled === 1,
})),
hidden: sees ? [...hidden] : [],
seesHidden: sees,
};
}

View file

@ -2,7 +2,6 @@
"title": "Next Generation of Unity",
"url": "https://nextgenerationofunity.org",
"description": "",
"privacyEmail": "",
"robots": {
"index": true
},
@ -12,51 +11,5 @@
"accessibility": {
"addBypassLinks": false,
"ignoreReducedMotion": false
},
"pages": {
"/retreats": {
"title": "Retreats",
"description": "Retreats hosted by Next Generation of Unity, our regions, and our partners throughout the year."
},
"/community": {
"title": "Community",
"description": "Groups, regions and the people who make up Next Generation of Unity."
},
"/organization": {
"title": "Organization",
"description": "Our mission, vision and values, the people who lead Next Generation of Unity, and how to reach us."
},
"/resources": {
"title": "Resources",
"description": "Teachings, brand assets, and material for groups and partners."
},
"/history": {
"title": "History",
"description": "A near-complete timeline of Next Generation of Unity (NGU), and other Unity Young Adult programs."
},
"/feedback": {
"title": "Feedback",
"description": "Tell us what's working, what isn't, and what you'd like to see next."
},
"/request": {
"title": "Request",
"description": "Ask for a blog post, an event, or a new or updated group, region, partner, team, award or person on the site."
},
"/qr": {
"title": "QR Codes",
"description": "Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colors."
},
"/give": {
"title": "Giving",
"description": "Support the work of Next Generation of Unity."
},
"/privacy": {
"title": "Privacy Policy",
"description": "How Next Generation of Unity collects, uses, and protects your information."
},
"/terms": {
"title": "Terms of Service",
"description": "The terms that apply when you use this site and our programs."
}
}
}

View file

@ -14,13 +14,12 @@ import { AuthProvider, RequireAuth } from "./lib/auth.tsx"
import RequireRole from "./pages/admin/RequireRole.tsx"
/*Pages*/
// Home is the landing page, so it ships in the main bundle. Every
// other page, and all of the admin, is fetched when first visited:
// a visitor to the front page never downloads the admin, the QR
// encoder, the calendar or the group map. Layout and AdminLayout
// wrap their <Outlet /> in <Suspense>, so the header stays put while
// a page loads.
import Home from "./pages/Home.tsx"
// Every page, the front page included, and all of the admin, is
// fetched when first visited: a visitor never downloads the admin,
// and a page's own parts come with it. The front page's data is asked
// for by its HTML before this runs (pageMeta.js, preload). Layout and
// AdminLayout wrap their <Outlet /> in <Suspense>, so the header stays
// put while a page loads.
/* A page's chunk can be missing when a deploy replaced the build while
this tab still ran the old one. Reload once to pick up the new
@ -49,16 +48,14 @@ const lazyPage = (load) =>
throw err
}),
)
// Community, Retreats, Resources, Organization and History: each
// built in the admin from sections.
// Every page at its address (Pages → Page management): its sections.
const PageAtPath = lazyPage(() => import("./pages/PageAtPath.tsx"))
// The front page: its sections, in the front page's layout.
const SitePage = lazyPage(() => import("./pages/SitePage.tsx"))
const Feedback = lazyPage(() => import("./pages/Feedback.tsx"))
const Request = lazyPage(() => import("./pages/Request.tsx"))
const Giving = lazyPage(() => import("./pages/Giving.tsx"))
const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
const Terms = lazyPage(() => import("./pages/Terms.tsx"))
const NotFound = lazyPage(() => import("./pages/NotFound.tsx"))
// Profile accounts (076): signing in, an invite's welcome, the profile.
const SignIn = lazyPage(() => import("./pages/SignIn.tsx"))
const AccountWelcome = lazyPage(() => import("./pages/AccountWelcome.tsx"))
const Account = lazyPage(() => import("./pages/Account.tsx"))
/*Entity Pages*/
const EventDetail = lazyPage(() => import("./pages/EventDetail.tsx"))
@ -82,19 +79,22 @@ const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.tsx"))
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
const AdminProfiles = lazyPage(() => import("./pages/admin/AdminProfiles.tsx"))
const AdminConvert = lazyPage(() => import("./pages/admin/AdminConvert.tsx"))
const AdminPco = lazyPage(() => import("./pages/admin/AdminPco.tsx"))
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
export default function App() {
return (
<BrowserRouter>
{/* The whole app: the site shows a profile link and hidden pages by who's signed in. */}
<AuthProvider>
<Routes>
{/* Layout renders the nav once and swaps page content into <Outlet /> */}
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="retreats" element={<SitePage key="retreats" id="retreats" />} />
<Route index element={<SitePage key="home" id="home" />} />
<Route path="/events/:id" element={<EventDetail />} />
<Route path="community" element={<SitePage key="community" id="community" />} />
<Route path="/regions/:id" element={<OrganizationDetail />} />
<Route path="/groups/:id" element={<OrganizationDetail />} />
<Route path="/partners/:id" element={<OrganizationDetail />} />
@ -104,16 +104,11 @@ export default function App() {
<Route path="/people/:id" element={<PersonDetail />} />
<Route path="/blog/:id" element={<BlogPost />} />
<Route path="/directory/:id" element={<DirectoryPage />} />
<Route path="organization" element={<SitePage key="organization" id="organization" />} />
<Route path="resources" element={<SitePage key="resources" id="resources" />} />
<Route path="history" element={<SitePage key="history" id="history" />} />
<Route path="feedback" element={<Feedback />} />
<Route path="request" element={<Request />} />
<Route path="qr" element={<QrCodes />} />
<Route path="give" element={<Giving />} />
<Route path="privacy" element={<Privacy />} />
<Route path="terms" element={<Terms />} />
<Route path="*" element={<NotFound />} />
<Route path="sign-in" element={<SignIn />} />
<Route path="account" element={<Account />} />
<Route path="account/welcome" element={<AccountWelcome />} />
{/* Every page of the site: Pages → Page management (PageAtPath). */}
<Route path="*" element={<PageAtPath />} />
</Route>
{/* A schedule as a slideshow for a screen: full screen, no Layout. */}
<Route
@ -126,11 +121,9 @@ export default function App() {
/>
<Route
element={
<AuthProvider>
<Suspense fallback={null}>
<Outlet />
</Suspense>
</AuthProvider>
}
>
<Route path="/admin/login" element={<AdminLogin />} />
@ -146,11 +139,14 @@ export default function App() {
<Route path="requests" element={<AdminFeedback kind="content" />} />
<Route path="media" element={<AdminMedia />} />
<Route path="newsletter" element={<AdminNewsletter />} />
<Route path="convert" element={<AdminConvert />} />
<Route element={<RequireRole role="editor" />}>
<Route path="thumbnails" element={<AdminVideoFrames />} />
</Route>
<Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} />
<Route path="profiles" element={<AdminProfiles />} />
<Route path="pco" element={<AdminPco />} />
</Route>
<Route path=":entity" element={<EntityList />} />
<Route path=":entity/:id" element={<EntityEdit />} />
@ -158,6 +154,7 @@ export default function App() {
</Route>
</Route>
</Routes>
</AuthProvider>
</BrowserRouter>
)
}

View file

@ -55,6 +55,7 @@ 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'
import { WordMotion, Words } from './RotatingWords.tsx'
const BODY = 'var(--color-muted)'
@ -63,10 +64,13 @@ export default function ContentBlocks({
accent = BRAND,
className = '',
presentAt,
anchorPrefix = '',
}: {
blocks?: ContentBlock[] | null
accent?: string
className?: string
/** Put before each heading's id: a blog post's tab (contents.ts, splitTabs). */
anchorPrefix?: string
/** An event page's presentation route: each schedule gets a Present
* button to it, `?block=<n>` naming which schedule (from 0). */
presentAt?: string
@ -74,7 +78,7 @@ export default function ContentBlocks({
if (!blocks?.length) return null
// Headings get ids so a post's contents (PostContents) and a shared
// link (#getting-there) can point at them.
const { idAt } = headingAnchors(blocks)
const { idAt } = headingAnchors(blocks, anchorPrefix)
// 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
@ -93,14 +97,15 @@ export default function ContentBlocks({
return (
<div className={`space-y-6 ${className}`}>
{blocks.map((block, index) => (
<WordMotion key={block.id ?? index} settings={block.words}>
<Block
key={block.id ?? index}
block={block}
accent={accent}
anchor={idAt.get(index)}
level={levels[index]}
presentHref={presentHrefs[index]}
/>
</WordMotion>
))}
</div>
)
@ -182,17 +187,20 @@ function Block({
const reading = useReadingMode()
switch (block.type) {
// A blog post's tab marker (BlogPost.tsx splits the post at
// them); anywhere else, it reads as a heading.
case 'tab':
case 'heading':
return (
<h3 id={anchor} className="text-2xl font-bold" style={{ color: accentText(accent) }}>
{text}
<Words text={text} />
</h3>
)
case 'subheading':
return (
<h4 id={anchor} className="text-lg font-normal" style={{ color: accentText(accent) }}>
{text}
<Words text={text} />
</h4>
)

View file

@ -42,7 +42,7 @@ import HomeLink from '../pages/sections/home/HomeLink.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import { refHref } from '../lib/hrefs.ts'
import { mediaUrl } from '../lib/media.ts'
import type { FeaturedCard, FeaturedColumns, FeaturedSize } from '../lib/useFrontPage.ts'
import type { FeaturedCard, FeaturedColumns, FeaturedSize } from '../lib/sectionTypes.ts'
import { useReadingMode } from '../lib/readingMode.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'

View file

@ -1,31 +1,19 @@
import { Link } from "react-router-dom";
import { PAGE_LINKS, NAV_ACTIONS } from "../navConfig.ts";
import { useNavSections } from "../lib/navSections.ts";
import { useSiteNav } from "../lib/useSiteNav.ts";
import { useAuth } from "../lib/auth.tsx";
import { VERSION_NAME, VERSION_NUMBER } from "../lib/version.ts";
import SiteLink from "./SiteLink.tsx";
import siteLogo from "../assets/logos/NGU_Logo.svg";
import PlatformIcon from "./PlatformIcon.tsx";
import { ORGANIZATION_DETAILS as Organization_Details } from "../data/organizationDetails.ts";
import { SOCIAL_LINKS } from "../data/socialLinks.ts";
// Give's destination lives in navConfig so the footer and the nav can't drift.
// Only the label differs down here.
const giveAction = NAV_ACTIONS.find((a) => a.variant === "fancy");
/* An internal route, or an off-site address opened in a new tab. */
type TouchLink = { label: string } & (
| { external?: false; to: string }
| { external: true; href: string }
);
const Get_In_Touch: TouchLink[] = [
{ label: "Feedback", to: "/feedback"},
{ label: "Request", to: "/request" },
{ label: "Contact Us", to: "/organization#contact" },
];
const Footer_Links = [
{ label: "Privacy Policy", to: "/privacy" },
{ label: "Terms of Service", to: "/terms" },
];
/* Every link here is Pages → Navigation's (useSiteNav): the filled
header buttons (Give) beside the logo, Get in Touch, the site map
(the header's pages, their sections and the pages set under them)
and the bottom row. The bottom row ends with the profile account's
way in (076): Sign in, or Your profile once signed in. */
const footerLinkClass =
"text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors";
@ -41,6 +29,8 @@ const headingClass = "text-white/90 text-sm font-semibold mb-4";
export default function Footer() {
const sectionsOf = useNavSections();
const nav = useSiteNav();
const { user } = useAuth();
return (
<footer className="py-16 px-6" style={{ background: "#001011" }}>
<div className="max-w-6xl mx-auto">
@ -53,17 +43,18 @@ export default function Footer() {
<Link to="/" className="inline-block">
<img src={siteLogo} alt="Next Generation of Unity" className="h-14 w-auto" />
</Link>
{giveAction && (
<a
href={giveAction.to}
target="_blank"
rel="noopener noreferrer"
{nav.actions
.filter((action) => action.filled)
.map((action) => (
<SiteLink
key={`${action.label}${action.path}`}
link={action}
className="btn inline-block whitespace-nowrap px-6 py-2.5 text-sm text-white transition-transform duration-200 hover:-translate-y-0.5"
style={{ background: "var(--color-action)" }}
>
{giveAction.label}
</a>
)}
{action.label}
</SiteLink>
))}
</div>
<address className="mt-5 not-italic text-sm leading-relaxed text-white/60">
@ -100,22 +91,11 @@ export default function Footer() {
<h2 className={headingClass}>Get in Touch</h2>
<ul className="flex flex-col gap-3">
{Get_In_Touch.map((link) => (
<li key={link.label}>
{link.external ? (
<a
href={link.href}
target="_blank"
rel="noopener noreferrer"
className={pageLinkClass}
>
{nav.footer.map((link) => (
<li key={`${link.label}${link.path}`}>
<SiteLink link={link} className={pageLinkClass}>
{link.label}
</a>
) : (
<Link to={link.to} className={pageLinkClass}>
{link.label}
</Link>
)}
</SiteLink>
</li>
))}
</ul>
@ -126,13 +106,25 @@ export default function Footer() {
<nav aria-label="Site map" className="mb-12 border-t border-white/10 pt-10">
<h2 className={headingClass}>Site Map</h2>
<ul className="grid grid-cols-2 gap-x-6 gap-y-6 sm:grid-cols-3 lg:grid-cols-6">
{PAGE_LINKS.map((page) => {
{nav.main.map((page) => {
const sections = sectionsOf(page.path);
return (
<li key={page.path}>
<Link to={page.path} className={pageLinkClass}>
<SiteLink link={page} className={pageLinkClass}>
{page.label}
</Link>
</SiteLink>
{page.children.length > 0 && (
<ul className="flex flex-col">
{page.children.map((child) => (
<li key={child.path}>
<SiteLink link={child} className={pageLinkClass}>
{child.label}
</SiteLink>
</li>
))}
</ul>
)}
{sections.length > 0 && (
<ul className="mt-1 flex flex-col">
@ -155,13 +147,22 @@ export default function Footer() {
</nav>
<div className="border-t border-white/10 pt-8 flex flex-col md:flex-row items-center justify-between gap-4">
<div className="text-center md:text-left">
<p className="text-white/65 text-sm">© 2026 Next Generation of Unity. All rights reserved.</p>
<div className="flex gap-6">
{Footer_Links.map((link) => (
<Link key={link.label} to={link.to} className={footerLinkClass}>
<p className="mt-1 text-white/50 text-xs">
{VERSION_NUMBER}
{VERSION_NAME && <> · {VERSION_NAME}</>}
</p>
</div>
<div className="flex flex-wrap justify-center gap-x-6 gap-y-2">
{nav.legal.map((link) => (
<SiteLink key={`${link.label}${link.path}`} link={link} className={footerLinkClass}>
{link.label}
</Link>
</SiteLink>
))}
<Link to={user ? "/account" : "/sign-in"} className={footerLinkClass}>
{user ? "Your profile" : "Sign in"}
</Link>
</div>
</div>
</div>

View file

@ -0,0 +1,12 @@
/* Google's "G", for the Sign in with Google buttons: a brand mark,
so drawn as Google gives it rather than as a Phosphor icon. */
export default function GoogleLogo({ className = 'h-5 w-5' }: { className?: string }) {
return (
<svg viewBox="0 0 48 48" className={className} aria-hidden="true">
<path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z" />
<path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z" />
<path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.5 39.6 16.2 44 24 44z" />
<path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z" />
</svg>
)
}

View file

@ -4,7 +4,7 @@
The little formatting a content block's text may carry, typed in
the admin as plain characters:
**bold** *italic* [link text](url)
**bold** *italic* [link text](url) {Next|Now} (rotating words)
a line break keeps its place
a blank line starts a new paragraph
@ -21,8 +21,9 @@
import { Fragment, type CSSProperties, type ReactNode } from 'react'
import { Link } from 'react-router-dom'
import { accentText } from '../lib/color.ts'
import { RotatingWords } from './RotatingWords.tsx'
const TOKEN = /\*\*(.+?)\*\*|\*(.+?)\*|\[([^\]]+)\]\(([^)\s]+)\)/g
const TOKEN = /\*\*(.+?)\*\*|\*(.+?)\*|\[([^\]]+)\]\(([^)\s]+)\)|\{([^{}|\n]+(?:\|[^{}|\n]+)+)\}/g
const SAFE_URL = /^(\/(?!\/)|#|https?:\/\/|mailto:|tel:)/i
/** External if it has a scheme or starts with //; otherwise it's
@ -83,9 +84,10 @@ function line(text: string, accent: string, key: string): ReactNode[] {
for (const match of text.matchAll(TOKEN)) {
const at = match.index ?? 0
if (at > last) out.push(text.slice(last, at))
const [whole, bold, italic, label, url] = match
const [whole, bold, italic, label, url, words] = match
const k = `${key}-${n++}`
if (bold != null) out.push(<strong key={k} className="font-semibold">{bold}</strong>)
if (words != null) out.push(<RotatingWords key={k} words={words.split('|').map((word) => word.trim())} />)
else if (bold != null) out.push(<strong key={k} className="font-semibold">{bold}</strong>)
else if (italic != null) out.push(<em key={k}>{italic}</em>)
else if (label != null && SAFE_URL.test(url)) {
out.push(

View file

@ -1,8 +1,10 @@
import { X, List } from "@phosphor-icons/react";
import { Suspense, useState, useEffect, useRef } from "react";
import { X, List, EyeSlash, PencilSimple } from "@phosphor-icons/react";
import { lazy, Suspense, useState, useEffect, useRef } from "react";
import { NavLink, Link, Outlet, useLocation } from "react-router-dom";
import { PAGE_LINKS, NAV_ACTIONS } from "../navConfig.ts";
import type { NavLink as NavLinkItem } from "../navConfig.ts";
import { useNavSections } from "../lib/navSections.ts";
import { useSiteNav } from "../lib/useSiteNav.ts";
import SiteLink from "./SiteLink.tsx";
import Banner from "./Banner.tsx";
import siteLogo from "../assets/logos/NGU_Logo.svg";
import Footer from "./Footer.tsx";
@ -13,26 +15,22 @@ import ReaderView from "./ReaderView.tsx";
import ThemeToggle from "./ThemeToggle.tsx";
import { jumpTo } from "../lib/focus.ts";
import { useReadingMode } from "../lib/readingMode.ts";
import { draftPreview, stopPreview } from "../lib/api.ts";
const NotFound = lazy(() => import("../pages/NotFound.tsx"));
/* ── Right-side nav actions ──────────────────────────────── */
type NavActionItem = {
label: string;
to: string;
variant: string;
external?: boolean;
};
const ACTION_VARIANTS: Record<
string,
{ className: string; style: React.CSSProperties }
> = {
ghost: {
outline: {
className:
"font-semibold border border-white/30 text-white/85 hover:border-white/60 hover:text-white hover:bg-white/10",
style: {},
},
fancy: {
filled: {
className: "font-bold text-white hover:scale-105",
style: { background: "var(--color-action)" },
},
@ -48,33 +46,20 @@ function NavAction({
size = "desktop",
onClick,
}: {
item: NavActionItem;
item: NavLinkItem;
size?: keyof typeof ACTION_SIZES;
onClick?: () => void;
}) {
const v = ACTION_VARIANTS[item.variant] ?? ACTION_VARIANTS.ghost;
const v = ACTION_VARIANTS[item.filled ? "filled" : "outline"];
const className = `inline-block whitespace-nowrap btn transition-all duration-200 active:scale-[0.98] ${ACTION_SIZES[size]} ${v.className}`;
return item.external ? (
<a
href={item.to}
target="_blank"
rel="noopener noreferrer"
className={className}
style={v.style}
onClick={onClick}
>
return (
<SiteLink link={item} className={className} style={v.style} onClick={onClick}>
{item.label}
</a>
) : (
<Link to={item.to} className={className} style={v.style} onClick={onClick}>
{item.label}
</Link>
</SiteLink>
);
}
const navActions = NAV_ACTIONS as NavActionItem[];
/* ── Layout ──────────────────────────────────────────────── */
export default function Layout() {
@ -95,6 +80,31 @@ export default function Layout() {
const pageRef = useRef<HTMLDivElement>(null);
const sectionsOf = useNavSections();
const nav = useSiteNav();
// A hidden page (Pages → Navigation) is Not found below viewer; a
// viewer and up sees it, under a bar saying so. The server answers
// the same (server/src/siteNav.js); this covers the app's own moves.
const hiddenHere = nav.isHidden(location.pathname);
const page = (
<Suspense fallback={null}>{hiddenHere && !nav.seesHidden ? <NotFound /> : <Outlet />}</Suspense>
);
// A draft's preview tab (api.ts): the page as it would be with the
// draft published, for signed-in admin accounts.
const previewBar = draftPreview && (
<p className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 bg-[var(--pal-amber-3)] px-6 py-2 text-center text-sm text-[var(--pal-amber-1)] print:hidden">
<PencilSimple size={18} weight="bold" aria-hidden="true" />
Previewing a draft: this is how it will look once published. Nobody else sees it.
<button type="button" onClick={stopPreview} className="font-semibold underline">
Stop previewing
</button>
</p>
);
const hiddenBar = hiddenHere && nav.seesHidden && (
<p className="flex items-center justify-center gap-2 bg-tint px-6 py-2 text-center text-sm text-ink print:hidden">
<EyeSlash size={18} weight="bold" aria-hidden="true" />
This page is hidden: only signed-in admin accounts can see it. Show it in Pages → Navigation.
</p>
);
// Close the mobile menu whenever the route changes
useEffect(() => {
@ -177,9 +187,7 @@ export default function Layout() {
<main id="main" tabIndex={-1} className="outline-none">
<ReaderView source={pageRef} />
<div ref={pageRef} hidden>
<Suspense fallback={null}>
<Outlet />
</Suspense>
{page}
</div>
</main>
<AccessibilityPanel />
@ -221,14 +229,15 @@ export default function Layout() {
none: it's the logo's link too, and its bands are one
scroll away. */}
<div className="hidden lg:flex items-center gap-6">
{PAGE_LINKS.map((page) => {
{nav.main.map((page) => {
const pageSections = page.path === "/" ? [] : sectionsOf(page.path);
const hasMenu = pageSections.length > 0 || page.children.length > 0;
return (
<div
key={page.path}
className="group relative"
onKeyDown={(e) => {
if (e.key !== "Escape" || pageSections.length === 0) return;
if (e.key !== "Escape" || !hasMenu) return;
setDismissed(page.path);
e.currentTarget.querySelector("a")?.focus();
}}
@ -250,7 +259,7 @@ export default function Layout() {
>
{page.label}
</NavLink>
{pageSections.length > 0 && (
{hasMenu && (
// pt-3 is the bridge the pointer crosses from the
// link into the menu without it closing. Keyboard
// focus opens it too, but only keyboard focus
@ -276,6 +285,17 @@ export default function Layout() {
</Link>
</li>
))}
{/* Pages set under this one (Pages → Navigation), after its sections. */}
{page.children.map((child) => (
<li key={child.path}>
<SiteLink
link={child}
className="block px-4 py-2 text-sm font-semibold text-white/90 transition-colors hover:bg-white/10 hover:text-[var(--pal-amber-2)] focus-visible:bg-white/10"
>
{child.label}
</SiteLink>
</li>
))}
</ul>
</div>
)}
@ -287,8 +307,8 @@ export default function Layout() {
<div className="flex items-center gap-4">
<div className="hidden lg:flex items-center gap-3">
{navActions.map((item) => (
<NavAction key={item.label} item={item} />
{nav.actions.map((item) => (
<NavAction key={`${item.label}${item.path}`} item={item} />
))}
</div>
@ -315,9 +335,9 @@ export default function Layout() {
{/* Page content */}
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
<Suspense fallback={null}>
<Outlet />
</Suspense>
{previewBar}
{hiddenBar}
{page}
</main>
{/*Site Footer applied to every page*/}
@ -346,7 +366,7 @@ export default function Layout() {
</button>
<div className="w-64">
{PAGE_LINKS.map((page) => {
{nav.main.map((page) => {
const pageSections = sectionsOf(page.path);
const isActive = location.pathname === page.path;
@ -364,6 +384,22 @@ export default function Layout() {
{page.label}
</NavLink>
{/* Pages set under this one (Pages → Navigation) */}
{page.children.length > 0 && (
<div className="ml-3 pl-4 mb-2 flex flex-col">
{page.children.map((child) => (
<SiteLink
key={child.path}
link={child}
className="text-white text-xl font-bold py-2 hover:text-[var(--pal-amber-2)] transition-colors"
onClick={() => setMobileMenuOpen(false)}
>
{child.label}
</SiteLink>
))}
</div>
)}
{/* Sections nest under the page they belong to */}
{isActive && pageSections.length > 0 && (
<div
@ -388,9 +424,9 @@ export default function Layout() {
</div>
<div className="mt-8 flex flex-col items-center gap-3">
{navActions.map((item) => (
{nav.actions.map((item) => (
<NavAction
key={item.label}
key={`${item.label}${item.path}`}
item={item}
size="mobile"
onClick={() => setMobileMenuOpen(false)}

View file

@ -1,46 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
LEGAL TEXT
The Privacy and Terms pages: a list of headed parts, each a few
paragraphs or a bullet list, in a readable column. The words live
in the page files; this only lays them out the same way.
═══════════════════════════════════════════════════════════════ */
import type { ReactNode } from 'react'
export type LegalPart = {
/** Anchor for linking to one part, eg. 'cookies'. */
id: string
heading: string
body: ReactNode[]
list?: ReactNode[]
/** After the list. */
after?: ReactNode[]
}
export default function LegalText({ parts }: { parts: LegalPart[] }) {
return (
<div className="mx-auto max-w-3xl space-y-10 px-6 leading-relaxed text-body">
{parts.map((part) => (
<section key={part.id} id={part.id}>
<h3 className="text-xl font-bold text-ink">{part.heading}</h3>
<div className="mt-3 space-y-3">
{part.body.map((paragraph, i) => (
<p key={i}>{paragraph}</p>
))}
{part.list && (
<ul className="list-disc space-y-2 pl-6">
{part.list.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
)}
{part.after?.map((paragraph, i) => (
<p key={i}>{paragraph}</p>
))}
</div>
</section>
))}
</div>
)
}

View file

@ -15,7 +15,12 @@
width 0.6s ease-in-out,
height 0.6s ease-in-out,
left 0.6s ease-in-out,
top 0.6s ease-in-out;
top 0.6s ease-in-out,
opacity 0.4s ease-in-out;
}
/* The page has scrolled into the footer (PageShell.tsx, leaving). */
.side-nav-circle[data-leaving] {
opacity: 0;
}
.side-nav-circle[data-family="green"] {
background: var(--pal-green-3);

View file

@ -45,6 +45,8 @@ import { documentTitle } from "../lib/site.ts";
import { accentText, ACCENTS, BRAND } from '../lib/color.ts'
import { SectionNav, useActiveSection } from "./admin/SectionNav.tsx";
import "./PageShell.css";
import { Words } from "./RotatingWords.tsx"
import { firstWords } from "../lib/words.ts";
export type ShellSection = {
@ -54,6 +56,10 @@ export type ShellSection = {
accent: string;
actions?: ReactNode;
content: ReactNode;
/** It draws its own heading (a band, sections/Bands.tsx): the shell adds none. */
bare?: boolean;
/** Left out of the side nav (the hero, a countdown). */
unlisted?: boolean;
};
type PageShellProps = {
@ -75,8 +81,12 @@ export function Section({ section }: { section: ShellSection }) {
// shell just gives it a place to sit.
actions,
content,
bare,
} = section;
// A band brings its own heading, padding and anchor.
if (bare) return <>{content}</>;
return (
<section
id={id}
@ -89,7 +99,7 @@ export function Section({ section }: { section: ShellSection }) {
<div className="flex flex-wrap items-end justify-between gap-4">
<div>
<h2 className="text-3xl md:text-4xl font-bold" style={{ color: accentText(accent) }}>
{title}
<Words text={title} />
</h2>
{blurb && <p className="mt-2 text-muted max-w-xl">{blurb}</p>}
</div>
@ -179,7 +189,9 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
ro.observe(column);
return () => ro.disconnect();
}, [sideNav]);
const navSections = sideNav ? sections.map((s) => ({ id: s.id, label: s.title, accent: s.accent })) : [];
const navSections = sideNav
? sections.filter((s) => !s.unlisted).map((s) => ({ id: s.id, label: firstWords(s.title), accent: s.accent }))
: [];
const active = useActiveSection(navSections);
const activeAccent = sections.find((s) => s.id === active)?.accent;
@ -215,7 +227,12 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
// Stuck: the page has scrolled the list up to its place under the
// header. The circle then becomes the corner sun (below).
// Leaving: the last section is going up past the list, so the list
// goes with it into the footer; the sun, far bigger than its sticky
// layer, would hang over the footer, so it fades out.
const [stuck, setStuck] = useState(false);
const [leaving, setLeaving] = useState(false);
const listHeight = listBox?.height ?? 0;
useEffect(() => {
const column = columnRef.current;
if (!sideNav || !column) return;
@ -223,7 +240,9 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
const measure = () => {
frame = 0;
const header = parseFloat(getComputedStyle(column).getPropertyValue("--header-h")) || 80;
setStuck(column.getBoundingClientRect().top + listTop <= header + STUCK_TOP + 1);
const box = column.getBoundingClientRect();
setStuck(box.top + listTop <= header + STUCK_TOP + 1);
setLeaving(box.bottom <= header + STUCK_TOP + listHeight + CIRCLE_MARGIN);
};
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(measure);
@ -236,7 +255,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
window.removeEventListener("resize", onScroll);
if (frame) cancelAnimationFrame(frame);
};
}, [sideNav, listTop]);
}, [sideNav, listTop, listHeight]);
// The circle's box, from its layer's top left (which sticks with
// the list). At rest: `rest` above. Stuck: a sun in the corner,
@ -262,7 +281,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
// comes from the server (pageMeta.js), which also sets the page's
// description and preview for search and link sharing.
useEffect(() => {
if (typeof title === "string") document.title = documentTitle(title);
if (typeof title === "string") document.title = documentTitle(firstWords(title));
}, [title]);
// The thin solid banner between sections, the page's full width
@ -282,7 +301,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
<div className="pt-24 pb-12 px-6">
<div className="max-w-6xl mx-auto">
<h1 className="text-4xl sm:text-5xl md:text-6xl font-bold [overflow-wrap:anywhere] hyphens-auto" style={{ color: accentText(BRAND) }}>
{title}
{typeof title === "string" ? <Words text={title} /> : title}
</h1>
{intro && <p className="mt-3 text-lg text-muted max-w-2xl">{intro}</p>}
</div>
@ -314,6 +333,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
<div
className="side-nav-circle absolute rounded-full"
data-family={circleFamily(activeAccent)}
data-leaving={leaving || undefined}
style={{
width: circleBox.width,
height: circleBox.height,

View file

@ -48,7 +48,7 @@ export default function PrivacyNotice() {
<p>
No tracking cookies here. Videos and maps come from YouTube, Facebook or Google only when you press
play or show them, and those services may set their own cookies then.{' '}
<Link to="/privacy#cookies" className="font-semibold text-link underline underline-offset-2">
<Link to="/privacy#cookies-and-browser-storage" className="font-semibold text-link underline underline-offset-2">
Privacy Policy
</Link>
</p>

View file

@ -40,7 +40,7 @@
import { Fragment, useEffect, useState, type ReactNode, type RefObject } from 'react'
import { Link } from 'react-router-dom'
import { PAGE_LINKS } from '../navConfig.ts'
import { useSiteNav } from '../lib/useSiteNav.ts'
type Inline = string | { href: string; children: Inline[] }
@ -240,6 +240,7 @@ function Anchor({ href, children }: { href: string; children: ReactNode }) {
export default function ReaderView({ source }: { source: RefObject<HTMLElement | null> }) {
const [blocks, setBlocks] = useState<Block[]>([])
const { main: pages } = useSiteNav()
useEffect(() => {
const root = source.current
@ -264,7 +265,7 @@ export default function ReaderView({ source }: { source: RefObject<HTMLElement |
return (
<article className="reader">
<p>
{PAGE_LINKS.map((page, i) => (
{pages.map((page, i) => (
<span key={page.path}>
{i > 0 && ' · '}
<Link to={page.path}>{page.label}</Link>

View file

@ -0,0 +1,94 @@
/* Rotating words (RotatingWords.tsx): every word in one grid cell,
so the space is the longest word's; the current one 'in', the one
it replaced 'out', the rest 'idle' (hidden). */
.rotating-words {
display: inline-block;
vertical-align: bottom;
}
.rotating-words-stack {
display: inline-grid;
/* Room for descenders, and clipped so a sliding word comes in from
behind the line, not over the one above. */
padding-bottom: 0.08em;
overflow: hidden;
perspective: 600px;
}
.rotating-word {
grid-area: 1 / 1;
white-space: nowrap;
transition:
transform 0.55s cubic-bezier(0.2, 0.7, 0.2, 1),
opacity 0.55s ease;
backface-visibility: hidden;
}
.rotating-word[data-state="idle"] {
opacity: 0;
transition: none;
}
/* slide */
.rotating-words[data-motion="slide"][data-direction="top"] .rotating-word[data-state="idle"] {
transform: translateY(-100%);
}
.rotating-words[data-motion="slide"][data-direction="top"] .rotating-word[data-state="out"] {
transform: translateY(100%);
opacity: 0;
}
.rotating-words[data-motion="slide"][data-direction="bottom"] .rotating-word[data-state="idle"] {
transform: translateY(100%);
}
.rotating-words[data-motion="slide"][data-direction="bottom"] .rotating-word[data-state="out"] {
transform: translateY(-100%);
opacity: 0;
}
/* flip: like a card turning over on its horizontal edge */
.rotating-words[data-motion="flip"][data-direction="top"] .rotating-word[data-state="idle"] {
transform: rotateX(90deg);
}
.rotating-words[data-motion="flip"][data-direction="top"] .rotating-word[data-state="out"] {
transform: rotateX(-90deg);
opacity: 0;
}
.rotating-words[data-motion="flip"][data-direction="bottom"] .rotating-word[data-state="idle"] {
transform: rotateX(-90deg);
}
.rotating-words[data-motion="flip"][data-direction="bottom"] .rotating-word[data-state="out"] {
transform: rotateX(90deg);
opacity: 0;
}
/* mirror: turning on its upright, the new word coming round from behind */
.rotating-words[data-motion="mirror"] .rotating-word[data-state="idle"] {
transform: rotateY(-180deg);
}
.rotating-words[data-motion="mirror"] .rotating-word[data-state="out"] {
transform: rotateY(180deg);
opacity: 0;
}
/* fade, and type (the letters appear; the old word fades) */
.rotating-words[data-motion="fade"] .rotating-word[data-state="out"],
.rotating-words[data-motion="type"] .rotating-word[data-state="out"] {
opacity: 0;
}
.rotating-words-caret {
display: inline-block;
width: 0.08em;
height: 0.9em;
margin-left: 0.04em;
vertical-align: -0.08em;
background: currentColor;
animation: rotating-words-blink 1s steps(1) infinite;
}
@keyframes rotating-words-blink {
50% {
opacity: 0;
}
}

View file

@ -0,0 +1,117 @@
/* ═══════════════════════════════════════════════════════════════
ROTATING WORDS
A word that cycles through choices in place, typed into any title
or text as {Next|Now|Rising}: the hero's headline, a section's
title, a heading or a paragraph (InlineText.tsx parses the braces).
How it moves comes from the nearest WordMotion (the hero's or a
block's own settings) over the site's defaults (Site settings →
Animated words, window.__SITE__.words):
motion slide, flip, fade, type or mirror
direction where a sliding or flipping word comes from: top
or bottom
seconds how long each word shows
The space it takes is the longest word's, every word stacked in
one grid cell, so the line never jumps. With less motion (the
system's setting, or reading mode) it's the first word, still;
screen readers always get the first word, not a changing one.
═══════════════════════════════════════════════════════════════ */
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import { prefersLessMotion } from '../lib/motion.ts'
import { WORD_DEFAULTS, type WordSettings } from '../lib/site.ts'
import { WORD_GROUP } from '../lib/words.ts'
import './RotatingWords.css'
/* Settings for the words inside: a hero's or a block's (blank keeps
what's around it). */
const WordContext = createContext<WordSettings>(WORD_DEFAULTS)
/* Blank (null) keeps what's around it. */
type WordOverrides = { motion?: WordSettings['motion'] | null; direction?: WordSettings['direction'] | null; seconds?: number | null }
export function WordMotion({ settings, children }: { settings?: WordOverrides | null; children: ReactNode }) {
const around = useContext(WordContext)
const value = {
motion: settings?.motion || around.motion,
direction: settings?.direction || around.direction,
seconds: settings?.seconds || around.seconds,
}
return <WordContext.Provider value={value}>{children}</WordContext.Provider>
}
/** A text with its groups as rotating words, the rest as it is. */
export function Words({ text }: { text?: string | null }) {
const parts: ReactNode[] = []
const source = text ?? ''
let last = 0
let n = 0
for (const match of source.matchAll(WORD_GROUP)) {
const at = match.index ?? 0
if (at > last) parts.push(source.slice(last, at))
parts.push(<RotatingWords key={n++} words={match[1].split('|').map((word) => word.trim())} />)
last = at + match[0].length
}
if (last < source.length) parts.push(source.slice(last))
return <>{parts}</>
}
const TYPE_STEP_MS = 70
export function RotatingWords({ words }: { words: string[] }) {
const { motion, direction, seconds } = useContext(WordContext)
const [index, setIndex] = useState(0)
const [still, setStill] = useState(true)
// For 'type': how many letters of the current word show.
const [typed, setTyped] = useState(words[0]?.length ?? 0)
useEffect(() => {
if (prefersLessMotion() || words.length < 2) return undefined
setStill(false)
const timer = window.setInterval(() => setIndex((i) => (i + 1) % words.length), Math.max(1, seconds) * 1000)
return () => window.clearInterval(timer)
}, [words.length, seconds])
// Typing: the word appears a letter at a time.
useEffect(() => {
if (still || motion !== 'type') return undefined
setTyped(0)
const word = words[index] ?? ''
let shown = 0
const timer = window.setInterval(() => {
shown += 1
setTyped(shown)
if (shown >= word.length) window.clearInterval(timer)
}, TYPE_STEP_MS)
return () => window.clearInterval(timer)
}, [index, motion, still, words])
if (still) return <>{words[0]}</>
return (
<span className="rotating-words" data-motion={motion} data-direction={direction}>
<span className="sr-only">{words[0]}</span>
<span className="rotating-words-stack" aria-hidden="true">
{words.map((word, i) => {
const state = i === index ? 'in' : i === (index + words.length - 1) % words.length ? 'out' : 'idle'
return (
<span key={i} className="rotating-word" data-state={state}>
{motion === 'type' && i === index ? (
<>
{word.slice(0, typed)}
<span className="rotating-words-caret" />
</>
) : (
word
)}
</span>
)
})}
</span>
</span>
)
}

View file

@ -0,0 +1,30 @@
import { Link } from 'react-router-dom'
import type { NavLink } from '../navConfig.ts'
/* A nav link (Pages → Navigation): a route on the site, or a plain
link for an address off it or one set to open in a new tab. */
export default function SiteLink({
link,
children,
...rest
}: {
link: NavLink
children: React.ReactNode
className?: string
style?: React.CSSProperties
onClick?: () => void
}) {
if (!link.path.startsWith('/') || link.newTab) {
return (
<a href={link.path} {...(link.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})} {...rest}>
{children}
</a>
)
}
return (
<Link to={link.path} {...rest}>
{children}
</Link>
)
}

View file

@ -0,0 +1,45 @@
import { useId, useState } from 'react'
import { OUTPUT_FORMATS, convertImage, renamed, saveBlob, type OutputType } from '../../lib/convertImage.ts'
/* A Media library image saved as JPG, PNG or WebP, converted in the
browser (src/lib/convertImage.ts). */
export default function DownloadAs({ url, name }: { url: string; name: string }) {
const id = useId()
const [state, setState] = useState<'idle' | 'busy' | string>('idle')
async function download(type: OutputType) {
setState('busy')
try {
const response = await fetch(url)
if (!response.ok) throw new Error(`Couldn't fetch the picture (HTTP ${response.status}).`)
saveBlob(await convertImage(await response.blob(), type), renamed(name, type))
setState('idle')
} catch (err) {
setState(err instanceof Error ? err.message : "Couldn't convert it.")
}
}
return (
<span className="inline-flex flex-wrap items-center gap-1">
<label htmlFor={id} className="sr-only">
Download {name} as
</label>
<select
id={id}
value=""
disabled={state === 'busy'}
onChange={(e) => e.target.value && download(e.target.value as OutputType)}
className="border border-muted/25 bg-surface px-1 py-0.5 text-xs text-link"
>
<option value="">{state === 'busy' ? 'Converting…' : 'Download as…'}</option>
{OUTPUT_FORMATS.map((format) => (
<option key={format.type} value={format.type}>
{format.label}
</option>
))}
</select>
{state !== 'idle' && state !== 'busy' && <span className="text-xs text-danger">{state}</span>}
</span>
)
}

View file

@ -233,7 +233,8 @@ const helpText = (field, row) => (typeof field.help === "function" ? field.help(
export function Field({ field, value, row, options, error, onChange, onPatch }: any) {
const id = `f-${field.path.replace(/\./g, "-")}`;
const widget = field.widget ?? "text";
const locked = Boolean(field.readOnly);
// readOnly may be a test of the row (a core page's address).
const locked = Boolean(typeof field.readOnly === "function" ? field.readOnly(row) : field.readOnly);
// The select's options, rebuilt only when their source changes
// (or, with filterBy, the row they're filtered by), not on every

View file

@ -1,7 +1,7 @@
/* ═══════════════════════════════════════════════════════════════
PATH ICONS
The icons a "Find your way in" path can show (Front page →
The icons a "Find your way in" path can show (Pages → a page's Connect nav section →
Connect Nav → Icon), as [key, label]. The admin's dropdown lists
the labels; Pathfinder.tsx draws the Phosphor icon for each key.
Adding one is a line here and one in ICONS in Pathfinder.tsx.

View file

@ -216,7 +216,7 @@ h1, h2, h3, h4, h5, h6 {
margin: 1.5cm;
}
/* Church Center's giving modal (Giving.tsx) is a transparent iframe
/* Church Center's giving modal (the giving section, FormSections.tsx) is a transparent iframe
over the whole page, drawn for light pages. On a dark page the
browser sees the iframe's scheme differ from ours and paints its
background opaque, so the page behind goes solid white. Telling it

View file

@ -18,26 +18,21 @@
and never fills in reads as real input instead of being skipped.
═══════════════════════════════════════════════════════════════ */
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from "./hrefs.ts";
import { organizations } from "./adminSchema/organizations.ts";
import { events } from "./adminSchema/events.ts";
import { people } from "./adminSchema/people.ts";
import { teams } from "./adminSchema/teams.ts";
import { awards } from "./adminSchema/awards.ts";
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 { siteNav } from "./adminSchema/siteNav.ts";
import { personTagTypes } from "./adminSchema/personTags.ts";
import { tags } from "./adminSchema/tags.ts";
import { contactTypes } from "./adminSchema/contactTypes.ts";
import { redirects } from "./adminSchema/redirects.ts";
import {
communityPage,
retreatsPage,
resourcesPage,
organizationPage,
historyPage,
} from "./adminSchema/sitePages.ts";
import { pages } from "./adminSchema/sitePages.ts";
export const ADMIN_ENTITIES: Record<string, any> = {
organizations,
@ -50,16 +45,31 @@ export const ADMIN_ENTITIES: Record<string, any> = {
teams,
awards,
timeline,
front_page: frontPage,
blog_posts: blogPosts,
community_page: communityPage,
retreats_page: retreatsPage,
resources_page: resourcesPage,
organization_page: organizationPage,
history_page: historyPage,
pages,
navigation: siteNav,
site_settings: siteSettings,
};
/* Where each entity's record shows on the site, for its draft's
Preview (EntityEdit.tsx opens it with ?preview=, which api.ts sends
on as X-Draft-Preview; server/src/drafts.js). An entity without
one has drafts but nothing to preview them on. */
export const PREVIEW_PATHS: Record<string, (row: any) => string | null> = {
organizations: (row) => (row.kind === "ministry" ? null : orgHref(row.id, row.kind)),
events: (row) => eventHref(row.id),
people: (row) => personHref(row.id),
person_tag_types: (row) => `/directory/${encodeURIComponent(row.id)}`,
teams: (row) => teamHref(row.id),
awards: (row) => awardHref(row.id),
timeline: () => "/history",
blog_posts: (row) => blogHref(row.id),
pages: (row) => row.path || null,
// The menus are on every page.
navigation: () => "/",
site_settings: () => "/",
};
/* The /admin/options request for the option lists `part` of a
manifest names (any `optionsFrom` inside it, at any depth), so a
form gets only the lists its selects use. An empty request would

View file

@ -1,17 +1,42 @@
import { mediaUrl } from "../media.ts";
import { PUBLISHED_FIELD, LISTED_FIELD, blocksChild } from "./shared.ts";
import { PUBLISHED_FIELD, LISTED_FIELD, BLOCK_TYPES, TEXT_TYPES, blocksChild } from "./shared.ts";
/* ── Blog (031_blog.sql) ─────────────────────────────────────────
Posts at /blog/:id. The Community page's blog section is edited
with that page (sitePages.ts). */
/* A post's body is the content blocks without the card/body choice:
a post only has a body. */
a post only has a body. Posts also take Tab blocks (079), which
split the post into tabs (BlogPost.tsx, splitTabs). */
const TAB_TYPE = [
"tab",
"Tab",
"Starts a tab, titled by its text, holding the blocks after it up to the next Tab. Blocks before the first Tab are the intro above the tabs. The contents list follows the open tab.",
];
const POST_BLOCK_TYPES = [...BLOCK_TYPES, TAB_TYPE];
const blogBlocksChild = {
...blocksChild,
label: "Post body",
note: "The post, top to bottom. The first paragraph doubles as the excerpt when that's left blank.",
fields: blocksChild.fields.filter((field) => field.path !== "slot"),
note: "The post, top to bottom. The first paragraph doubles as the excerpt when that's left blank. Add Tab blocks to split it into tabs.",
fields: blocksChild.fields
.filter((field) => field.path !== "slot")
.map((field) =>
field.path === "type"
? {
...field,
options: POST_BLOCK_TYPES.map(([value, label]) => [value, label]),
help: (row) => POST_BLOCK_TYPES.find(([value]) => value === row?.type)?.[2],
}
: field.path === "text"
? {
...field,
label: (row) => (row?.type === "tab" ? "Tab title" : (field.label as any)(row)),
when: { path: "type", value: [...TEXT_TYPES, "tab"] },
help: (row) => (row?.type === "tab" ? "eg. Overview" : (field.help as any)(row)),
}
: field,
),
};
export const blogPosts = {
@ -21,7 +46,32 @@ export const blogPosts = {
idLabel: "URL ID",
slugFrom: "title",
// Blog posts → Import from Word (server/src/routes/import.js).
importer: { label: "Import from Word", endpoint: "/admin/import/docx", accept: ".docx" },
// `guide` is what becomes what (server/src/docx.js, docs/importing.md),
// shown beside the button.
importer: {
label: "Import from Word",
endpoint: "/admin/import/docx",
accept: ".docx",
guide: {
intro: "A .docx becomes a new, unpublished post. In the document:",
rows: [
["The Title style, or the first Heading 1", "The post's title"],
["A date line under it, eg. Sep 28, 2026", "The post's date"],
["Heading 1 and Heading 2", "Heading blocks"],
["Heading 3 and smaller", "Subheading blocks"],
["A line starting Tab:, eg. Tab: Overview (any style)", "A Tab: the post is split into tabs from there"],
["The Quote style", "A Quote (a dash and a name at the end is who said it)"],
["The Intense Quote style", "A Callout"],
["Bulleted or numbered paragraphs", "One List block"],
["Tables", "Table blocks"],
["A line of --- alone", "A Divider"],
["A YouTube, Vimeo or Facebook link alone on its line", "A Video"],
["Button: Register, with Register linked", "A Button, its label and link"],
["Other paragraphs", "Paragraphs, keeping bold, italic and links"],
],
outro: "Images, text boxes, footnotes, comments, colors and fonts aren't carried over: add images as Image blocks after. PDFs: save as .docx first.",
},
},
list: {
columns: [

View file

@ -1,306 +0,0 @@
import { mediaUrl } from "../media.ts";
import { featuredCardsChild } from "./shared.ts";
import { PATH_ICONS } from "../../data/pathIcons.ts";
/* ── Front page ──────────────────────────────────────────────────
One record (see the singleton note in server/src/admin-schema.js).
The groups are the hero; the collections below are the rest of
the page. Photos, the livestream and the featured video are
editable whatever the mode, so each can be ready before the
switch is flipped.
Section keys and stat sources are the CHECK lists on
front_page_sections and front_page_stats. The labels here are what the admin reads; the values are
what the page and the API key on. */
const FRONT_PAGE_SECTIONS = [
["countdown", "Event Countdown"],
["retreats", "Events Carousel (National Retreats)"],
["calendar", "Event Calendar"],
["stats", "Stats"],
["timeline", "Featured Timeline"],
["connect", "Connect Nav"],
["featured", "Featured Content"],
];
const STAT_SOURCES = [
["manual", "Print Value Field"],
["years_since", "Years Since Value"],
["regions", "Count: regions"],
["groups", "Count: groups"],
["partners", "Count: partners"],
["events_held", "Count: past events"],
["retreats_held", "Count: past retreats"],
["people", "Count: people in database"],
["awards_given", "Count: public awards given"],
];
export const frontPage = {
key: "front_page",
label: "Front page",
singular: "front page",
idLabel: "Page",
singleton: "home",
list: { columns: [], filters: [] },
groups: [
{
legend: "Hero - Primary Section",
note: "The first thing a visitor sees. Blank buttons don't render.",
fields: [
{
path: "hero_backdrop",
label: "Background",
widget: "select",
options: [
["brand", "Brand: animated color and the dove"],
["photos", "Photos: cycles through the photos below"],
],
blankLabel: "Default: brand",
help: "Photos with none added shows the brand background",
},
{
path: "hero_feature",
label: "Feature",
widget: "select",
options: [
["none", "Nothing: No additional overlay"],
["livestream", "Livestream: the stream, with a LIVE badge"],
["video", "Featured video: click to play"],
["event", "Featured event: an event's card"],
],
blankLabel: "Default: nothing",
help: "Switch to Livestream when you go live, and back when you're done",
},
{ path: "eyebrow", label: "Eyebrow", help: "Small line above the headline" },
{ path: "headline", label: "Headline", full: true },
{ path: "subhead", label: "Subhead", widget: "textarea", full: true },
{ path: "primary_label", label: "Main button label" },
{ path: "primary_url", label: "Main button link", help: "/page, #section-id or a full URL" },
{ path: "secondary_label", label: "Second button label" },
{ path: "secondary_url", label: "Second button link" },
],
},
{
legend: "Photos, livestream, video and event",
fields: [
{
path: "slide_seconds",
label: "Seconds per photo",
widget: "number",
help: "Photos Background. Set from 3 to 60 seconds",
},
{
path: "livestream_url",
label: "Livestream link",
full: true,
help: "A YouTube, Facebook or Vimeo link, or any embed URL",
},
{ path: "livestream_title", label: "Livestream title", full: true },
{
path: "video_url",
label: "Featured video",
full: true,
help:
"A YouTube, Vimeo or Facebook link, or a video file: a filename in " +
"the uploads folder, or a link ending in .mp4 or .webm",
},
{
path: "video_still",
label: "Video still",
widget: "image",
crop: 16 / 9,
resolve: mediaUrl,
full: true,
frameFrom: "video_url",
help: "Shown before it plays. Default: YouTube's own thumbnail, or a video file's first frame. Frame at takes a still from a YouTube or Facebook video.",
},
{
path: "video_captions",
label: "Video captions",
widget: "image",
folder: "captions",
resolve: mediaUrl,
full: true,
help: "A WebVTT (.vtt) file, for a video file; YouTube, Vimeo and Facebook show their own. Default: none.",
},
{ path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" },
{
path: "hero_event_id",
label: "Featured event",
widget: "select",
optionsFrom: "events",
blankLabel: "Default: the countdown's event",
full: true,
help: "For the Featured event feature. A pinned event that's over falls back to the countdown's",
},
],
},
{
legend: "Countdown",
fields: [
{
path: "countdown_event_id",
label: "Count down to",
widget: "select",
optionsFrom: "events",
blankLabel: "Default: the next upcoming event",
help: "Leave blank almost always. A pinned event that's over falls back to the next one",
},
{
path: "countdown_scope_id",
label: "Only this scope",
widget: "select",
optionsFrom: "event_scopes",
blankLabel: "Default: any scope",
help: "Narrows the next upcoming event. Ignored when an event is pinned above",
},
{
path: "countdown_event_type",
label: "Only this type",
widget: "select",
options: [
["retreat", "Retreat"],
["class", "Class"],
["workshop", "Workshop"],
["meeting", "Meeting"],
["other", "Other"],
],
blankLabel: "Default: any type",
help: "Combines with the scope: National + Retreat counts down to the next national retreat",
},
],
},
{
legend: "Featured Content",
note: "The cards themselves are under Featured cards below, each with its own Size.",
fields: [
{
path: "featured_columns",
label: "Columns",
widget: "select",
options: [
["2", "2 across"],
["3", "3 across"],
["4", "4 across"],
],
blankLabel: "Default: 3 across",
help: "On a wide screen. Tablets show 2, phones 1",
},
],
},
],
children: [
{
key: "sections",
label: "Page sections",
note: "Drag to reorder. Each section can appear once; leave one out to drop it.",
addLabel: "Add section",
title: (row) =>
FRONT_PAGE_SECTIONS.find(([key]) => key === row.section)?.[1] ?? "New section",
blank: { section: "", title: "", blurb: "" },
fields: [
{
path: "section",
label: "Section",
widget: "select",
options: FRONT_PAGE_SECTIONS,
required: true,
},
{ path: "title", label: "Heading", help: "Default: the band's own name. Up to about 60 characters fit." },
{ path: "blurb", label: "Blurb", full: true },
{ path: "is_hidden", label: "Hidden", widget: "checkbox", help: "Hide for now" },
],
},
{
key: "slides",
label: "Hero photos",
note: "Shown in Photos mode, in this order.",
addLabel: "Add photo",
title: (row) => row.caption || row.media || "New photo",
blank: { media: "", alt: "", caption: "" },
fields: [
{ path: "media", label: "Photo", required: true, widget: "image", crop: 16 / 9, resolve: mediaUrl, full: true },
{ path: "alt", label: "Description", help: "For screen readers" },
{ path: "caption", label: "Caption", full: true },
{ path: "link_url", label: "Link", help: "Optional; makes the caption a link" },
],
},
{
key: "stats",
label: "Numbers",
note: "Counts update themselves. A typed-in number with no value is left out.",
addLabel: "Add number",
title: (row) => row.label || "New number",
blank: { label: "", source: "", value: "" },
fields: [
{ path: "label", label: "Label", required: true },
{
path: "source",
label: "Number Source",
widget: "select",
options: STAT_SOURCES,
blankLabel: "Default: Print Value",
},
{ path: "value", label: "Value", help: "The number thats printed" },
{ path: "suffix", label: "Suffix", help: "+, k, % …" },
{ path: "note", label: "Note", full: true },
],
},
{
...featuredCardsChild,
fields: [
...featuredCardsChild.fields,
{
path: "size",
label: "Size",
widget: "select",
options: [
["normal", "Normal: one cell"],
["wide", "Wide: two columns"],
["tall", "Tall: two rows"],
["large", "Large: two columns, two rows"],
],
blankLabel: "Default: automatic (the first of three or more is large)",
help: "On a wide screen. Phones show one card per row",
},
],
},
{
key: "paths",
label: "Connect Nav",
note: "Each path is a choice a visitor can pick; its actions appear when they do.",
addLabel: "Add path",
title: (row) => row.label || "New path",
blank: { label: "", icon: "", blurb: "" },
fields: [
{ path: "label", label: "Label", required: true, help: "eg. Attend, Serve…" },
{
path: "icon",
label: "Icon",
widget: "select",
options: PATH_ICONS,
blankLabel: "Default: a dot",
},
{ path: "blurb", label: "Blurb", full: true },
],
children: [
{
key: "actions",
label: "Actions",
addLabel: "Add action",
title: (row) => row.label || "New action",
blank: { label: "", url: "" },
fields: [
{ path: "label", label: "Label", required: true },
{ path: "url", label: "Link", required: true },
{ path: "description", label: "Description", full: true },
],
},
],
},
],
};

View file

@ -83,6 +83,20 @@ export const people = {
note: "Unpublished people are invisible everywhere.",
fields: [PUBLISHED_FIELD, LISTED_FIELD],
},
{
legend: "Hidden on the site",
note: "Ticked parts stay here but don't show anywhere on the site. Someone with a profile account who has claimed this person sets these on their profile too (Data → Profile accounts).",
fields: [
["photo", "Photo"],
["pronouns", "Pronouns"],
["tagline", "Tagline"],
["bio", "Bio"],
["email", "Public email"],
["phone", "Public phone"],
["location", "Location"],
["links", "Links"],
].map(([key, label]) => ({ path: `hide_${key}`, label: `Hide ${label.toLowerCase()}`, widget: "checkbox" })),
},
],
children: [

View file

@ -346,6 +346,45 @@ export const HREF_HELP = {
video: "The video's page, eg. https://www.youtube.com/watch?v=…, or a video file",
};
/* Rotating words (084): text typed as {Next|Now|Rising} cycles
through its choices. These pick how, for a block or a hero; Site
settings → Animated words holds the defaults. */
export const WORD_MOTIONS = [
["slide", "Slide"],
["flip", "Flip, like a card"],
["fade", "Fade"],
["type", "Type, letter by letter"],
["mirror", "Mirror, turning round"],
];
export const WORD_DIRECTIONS = [
["bottom", "From the bottom"],
["top", "From the top"],
];
export const WORD_HELP = "Type choices in braces to rotate them, eg. {Next|Now|Rising} Generation of {Unity|New Thought}.";
/* The three fields, under `prefix` (eg. "hero."), shown `when`. */
export const wordFields = (prefix: string, label: string, when?: any) => [
{
path: `${prefix}word_motion`,
label: label ? `${label}rotating words` : "Rotating words",
widget: "select",
options: WORD_MOTIONS,
blankLabel: "Default: the site's (Site settings → Animated words)",
help: WORD_HELP,
when,
},
{
path: `${prefix}word_direction`,
label: label ? `${label}words come in` : "Words come in",
widget: "select",
options: WORD_DIRECTIONS,
blankLabel: "Default: the site's",
help: "For Slide and Flip",
when,
},
{ path: `${prefix}word_seconds`, label: label ? `${label}seconds per word` : "Seconds per word", widget: "number", help: "1 to 20. Default: the site's", when },
];
export const blocksChild = {
key: "content_blocks",
label: "Content blocks",
@ -441,6 +480,7 @@ export const blocksChild = {
help: "Shows the team's members as tiles, its leads first. People added as items show after it.",
when: { path: "type", value: "people" },
},
...wordFields("", "", { path: "type", value: ["heading", "subheading", "paragraph", "callout", "quote"] }),
],
children: [
{

View file

@ -0,0 +1,68 @@
/* ── Navigation (075_site_nav.sql) ───────────────────────────────
Pages → Navigation: the header's and footer's links. The pages
themselves (titles, intros, Hidden, Disabled) are Page
management's (sitePages.ts). Admins and up. Server side:
server/src/admin-schema/siteNav.js; the site reads it through
server/src/siteNav.js and src/lib/useSiteNav.ts. */
const PLACES: [string, string][] = [
["main", "Header: pages"],
["action", "Header: buttons"],
["footer", "Footer: Get in Touch"],
["legal", "Footer: bottom row"],
];
const placeLabel = (place) => PLACES.find(([key]) => key === place)?.[1];
export const siteNav = {
key: "navigation",
label: "Navigation",
singular: "navigation",
idLabel: "Navigation",
singleton: "site",
writeRole: "admin",
list: { columns: [], filters: [] },
groups: [],
children: [
{
key: "links",
label: "Links",
note: "Top to bottom, in the order each place shows them. A link to a hidden page is only shown to signed-in admin accounts, and one to a disabled page to no one. A header page lists its sections under it by itself (Pages → the page).",
addLabel: "Add link",
title: (row) => (row.label ? `${row.label} · ${placeLabel(row.place) ?? "No place"}` : "New link"),
blank: { place: "", label: "", path: "", parent_path: "", style: "", new_tab: 0 },
fields: [
{ path: "place", label: "Shows in", widget: "select", options: PLACES, required: true },
{ path: "label", label: "Label", required: true, help: "eg. Shop" },
{
path: "path",
label: "Link",
required: true,
full: true,
help: "A page on the site, a section of one, or an address elsewhere, eg. /shop, /organization#contact or https://www.bonfire.com/store/…",
},
{
path: "parent_path",
label: "Under page",
widget: "select",
optionsFrom: "site_pages",
blankLabel: "Default: its own place in the header",
help: "Lists it in that page's menu, after its sections, instead of in the header's row",
when: { path: "place", value: "main" },
},
{
path: "style",
label: "Style",
widget: "select",
options: [["filled", "Filled, like Give (also beside the footer's logo)"]],
blankLabel: "Default: outlined",
when: { path: "place", value: "action" },
},
{ path: "new_tab", label: "Opens in a new tab", widget: "checkbox" },
],
},
],
};

View file

@ -1,5 +1,6 @@
/* ── The site's own pages (056_site_pages.sql) ───────────────────
Pages → Community, Retreats, Resources, Organization, History:
/* ── The site's pages (056_site_pages.sql, 080_page_registry.sql) ──
Pages → Page management: every page, its address, title, intro,
Hidden and Disabled, and new pages made here.
each page is its sections, in order, and each section is its
heading and its own content blocks, then a preset if it has one
(a prebuilt part of the site, drawn under the blocks). Server
@ -7,9 +8,12 @@
src/pages/SitePage.tsx.
The preset values are the CHECK list on page_sections.preset;
each page offers the ones that belong on it. */
every page offers them all. The Community blog's settings show on
the Community page only (its id), for now. */
import { FEATURED_KINDS, featuredCardsChild, blocksChild } from "./shared.ts";
import { FEATURED_KINDS, featuredCardsChild, blocksChild, wordFields } from "./shared.ts";
import { mediaUrl } from "../media.ts";
import { PATH_ICONS } from "../../data/pathIcons.ts";
const PRESETS = {
community_blog: "Community blog (its settings are below)",
@ -18,7 +22,18 @@ const PRESETS = {
partner_list: "Organization cards (partners, ministries)",
events: "Event carousel or grid",
timeline: "Timeline",
people_directory: "People directory (a tag's people)",
people_directory: "People directory (tabs of people tags)",
feedback_form: "Website feedback form",
request_form: "Request form",
data_request_form: "Data request form (see, correct or delete)",
giving: "Giving button (Church Center)",
qr_maker: "QR code maker",
hero: "Hero (headline, photos, video, livestream or event)",
countdown: "Event countdown",
calendar: "Event calendar",
stats: "Numbers",
featured_cards: "Featured cards",
connect: "Connect nav (paths to choose from)",
};
const ACCENT_OPTIONS = [
@ -36,6 +51,273 @@ const EVENT_TYPES = [
["other", "Other"],
];
/* Gates on the section's type. */
const IS = (preset) => ({ path: "preset", value: preset });
const STAT_SOURCES = [
["manual", "Print Value Field"],
["years_since", "Years Since Value"],
["regions", "Count: regions"],
["groups", "Count: groups"],
["partners", "Count: partners"],
["events_held", "Count: past events"],
["retreats_held", "Count: past retreats"],
["people", "Count: people in database"],
["awards_given", "Count: public awards given"],
];
/* The settings of the section types that need them (083): each shows
only for its type. A band draws its own heading from the section's
title and blurb. */
const BAND_FIELDS = [
{
path: "hero.backdrop",
label: "Hero: background",
widget: "select",
options: [
["brand", "Brand: animated color and the dove"],
["photos", "Photos: cycles through the hero photos below"],
],
blankLabel: "Default: brand",
help: "Photos with none added shows the brand background",
when: IS("hero"),
},
{
path: "hero.feature",
label: "Hero: feature",
widget: "select",
options: [
["none", "Nothing: No additional overlay"],
["livestream", "Livestream: the stream, with a LIVE badge"],
["video", "Featured video: click to play"],
["event", "Featured event: an event's card"],
],
blankLabel: "Default: nothing",
help: "Switch to Livestream when you go live, and back when you're done",
when: IS("hero"),
},
{ path: "hero.eyebrow", label: "Hero: eyebrow", help: "Small line above the headline", when: IS("hero") },
{ path: "hero.headline", label: "Hero: headline", full: true, when: IS("hero") },
{ path: "hero.subhead", label: "Hero: subhead", widget: "textarea", full: true, when: IS("hero") },
{ path: "hero.primary_label", label: "Hero: main button label", when: IS("hero") },
{ path: "hero.primary_url", label: "Hero: main button link", help: "/page, #section-id or a full URL", when: IS("hero") },
{ path: "hero.secondary_label", label: "Hero: second button label", when: IS("hero") },
{ path: "hero.secondary_url", label: "Hero: second button link", when: IS("hero") },
{ path: "hero.slide_seconds", label: "Hero: seconds per photo", widget: "number", help: "Photos background. 3 to 60. Default: 7", when: IS("hero") },
{ path: "hero.livestream_url", label: "Hero: livestream link", full: true, help: "A YouTube, Facebook or Vimeo link, or any embed URL", when: IS("hero") },
{ path: "hero.livestream_title", label: "Hero: livestream title", full: true, when: IS("hero") },
{
path: "hero.video_url",
label: "Hero: featured video",
full: true,
help: "A YouTube, Vimeo or Facebook link, or a video file: a filename in the uploads folder, or a link ending in .mp4 or .webm",
when: IS("hero"),
},
{
path: "hero.video_still",
label: "Hero: video still",
widget: "image",
crop: 16 / 9,
resolve: mediaUrl,
full: true,
frameFrom: "hero.video_url",
help: "Shown before it plays. Default: YouTube's own thumbnail, or a video file's first frame. Frame at takes a still from a YouTube or Facebook video.",
when: IS("hero"),
},
{
path: "hero.video_captions",
label: "Hero: video captions",
widget: "image",
folder: "captions",
resolve: mediaUrl,
full: true,
help: "A WebVTT (.vtt) file, for a video file; YouTube, Vimeo and Facebook show their own. Default: none.",
when: IS("hero"),
},
{ path: "hero.video_title", label: "Hero: video title", full: true, help: "Shown after \"Featured video\" above the headline", when: IS("hero") },
{
path: "hero.event_id",
label: "Hero: featured event",
widget: "select",
optionsFrom: "events",
blankLabel: "Default: the page's countdown's event",
full: true,
help: "For the Featured event feature. A pinned event that's over falls back to the countdown's",
when: IS("hero"),
},
...wordFields("hero.", "Hero: ", IS("hero")),
{
path: "countdown.event_id",
label: "Count down to",
widget: "select",
optionsFrom: "events",
blankLabel: "Default: the next upcoming event",
help: "Leave blank almost always. A pinned event that's over falls back to the next one",
when: IS("countdown"),
},
{
path: "countdown.scope_id",
label: "Countdown: only this scope",
widget: "select",
optionsFrom: "event_scopes",
blankLabel: "Default: any scope",
help: "Narrows the next upcoming event. Ignored when an event is pinned above",
when: IS("countdown"),
},
{
path: "countdown.event_type",
label: "Countdown: only this type",
widget: "select",
options: [
["retreat", "Retreat"],
["class", "Class"],
["workshop", "Workshop"],
["meeting", "Meeting"],
["other", "Other"],
],
blankLabel: "Default: any type",
help: "Combines with the scope: National + Retreat counts down to the next national retreat",
when: IS("countdown"),
},
{
path: "featured.columns",
label: "Featured cards: columns",
widget: "select",
options: [
["2", "2 across"],
["3", "3 across"],
["4", "4 across"],
],
blankLabel: "Default: 3 across",
help: "On a wide screen. Tablets show 2, phones 1",
when: IS("featured_cards"),
},
{ path: "blog.internal_title", label: "Blog: our posts' heading", help: "Default: From NGU", when: IS("community_blog") },
{ path: "blog.internal_slots", label: "Blog: our posts' slots", widget: "number", help: "0 to 12. Pinned posts first, then the newest. Default: 3", when: IS("community_blog") },
{ path: "blog.external_title", label: "Blog: community posts' heading", help: "Default: From our community", when: IS("community_blog") },
{ path: "blog.external_slots", label: "Blog: community posts' slots", widget: "number", help: "0 to 12. Pinned cards first, then the feeds' newest. Default: 3", when: IS("community_blog") },
{ path: "blog.external_url", label: "Blog: button link", help: "eg. https://ngu.substack.com", full: true, when: IS("community_blog") },
{ path: "blog.external_label", label: "Blog: button text", help: "Default: Read more on Substack", when: IS("community_blog") },
];
const BAND_CHILDREN = [
{
key: "slides",
label: "Hero photos",
note: "Shown with the Photos background, in this order.",
addLabel: "Add photo",
when: IS("hero"),
title: (row) => row.caption || row.media || "New photo",
blank: { media: "", alt: "", caption: "" },
fields: [
{ path: "media", label: "Photo", required: true, widget: "image", crop: 16 / 9, resolve: mediaUrl, full: true },
{ path: "alt", label: "Description", help: "For screen readers" },
{ path: "caption", label: "Caption", full: true },
{ path: "link_url", label: "Link", help: "Optional; makes the caption a link" },
],
},
{
key: "stats",
label: "Numbers",
note: "Counts update themselves. A typed-in number with no value is left out.",
addLabel: "Add number",
when: IS("stats"),
title: (row) => row.label || "New number",
blank: { label: "", source: "", value: "" },
fields: [
{ path: "label", label: "Label", required: true },
{ path: "source", label: "Number Source", widget: "select", options: STAT_SOURCES, blankLabel: "Default: Print Value" },
{ path: "value", label: "Value", help: "The number that's printed" },
{ path: "suffix", label: "Suffix", help: "+, k, % …" },
{ path: "note", label: "Note", full: true },
],
},
{
...featuredCardsChild,
label: "Featured cards",
when: IS("featured_cards"),
fields: [
...featuredCardsChild.fields,
{
path: "size",
label: "Size",
widget: "select",
options: [
["normal", "Normal: one cell"],
["wide", "Wide: two columns"],
["tall", "Tall: two rows"],
["large", "Large: two columns, two rows"],
],
blankLabel: "Default: automatic (the first of three or more is large)",
help: "On a wide screen. Phones show one card per row",
},
],
},
{
...featuredCardsChild,
label: "Blog: pinned community posts",
note: "Always shown, before the feeds' newest. Paste a post's link and press Fetch preview.",
addLabel: "Pin a post",
when: IS("community_blog"),
blank: { kind: "", url: "", title: "" },
fields: featuredCardsChild.fields.map((field) =>
field.path === "kind" ? { ...field, options: FEATURED_KINDS.filter(([kind]) => kind !== "record") } : field,
),
},
{
key: "blog_posts",
label: "Blog: pinned posts (ours)",
note: "Always shown, before the newest.",
addLabel: "Pin a post",
when: IS("community_blog"),
title: (row, options) => options?.blog_posts?.find((p) => p.id === row.post_id)?.label ?? "New pin",
blank: { post_id: "" },
fields: [{ path: "post_id", label: "Post", widget: "select", optionsFrom: "blog_posts", required: true }],
},
{
key: "feeds",
label: "Blog: feeds",
note: "RSS or Atom feeds whose newest posts fill the community slots. Read about every 30 minutes.",
addLabel: "Add feed",
when: IS("community_blog"),
title: (row) => row.label || row.url || "New feed",
blank: { url: "", label: "" },
fields: [
{ path: "url", label: "Feed URL", required: true, full: true, help: "eg. https://ngu.substack.com/feed" },
{ path: "label", label: "Source name", help: "Shown on its cards. Default: the feed's own title" },
],
},
{
key: "paths",
label: "Connect nav: paths",
note: "Each path is a choice a visitor can pick; its actions appear when they do.",
addLabel: "Add path",
when: IS("connect"),
title: (row) => row.label || "New path",
blank: { label: "", icon: "", blurb: "" },
fields: [
{ path: "label", label: "Label", required: true, help: "eg. Attend, Serve…" },
{ path: "icon", label: "Icon", widget: "select", options: PATH_ICONS, blankLabel: "Default: a dot" },
{ path: "blurb", label: "Blurb", full: true },
],
children: [
{
key: "actions",
label: "Actions",
addLabel: "Add action",
title: (row) => row.label || "New action",
blank: { label: "", url: "" },
fields: [
{ path: "label", label: "Label", required: true },
{ path: "url", label: "Link", required: true },
{ path: "description", label: "Description", full: true },
],
},
],
},
];
const EVENTS = { path: "preset", value: "events" };
const CARDS = { path: "preset", value: "partner_list" };
@ -51,7 +333,7 @@ const sectionsChild = (presets: string[]) => ({
path: "title",
label: "Title",
required: true,
help: "Up to 30 characters, so it fits the side nav. eg. Mission, Vision & Values",
help: "Up to 30 characters, so it fits the side nav (60 on the front page). A band (hero, numbers...) draws it as its heading; the hero's isn't shown. eg. Mission, Vision & Values",
},
{
path: "anchor",
@ -61,6 +343,7 @@ const sectionsChild = (presets: string[]) => ({
},
{ path: "blurb", label: "Blurb", widget: "textarea", full: true, help: "A line under the title" },
{ path: "accent", label: "Accent", widget: "select", options: ACCENT_OPTIONS, blankLabel: "Default: Teal" },
{ path: "is_hidden", label: "Hidden", widget: "checkbox", help: "Left off the page for now, kept here." },
...(presets.length
? [
{
@ -101,19 +384,6 @@ 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("partner_list")
? [
{
@ -131,6 +401,19 @@ const sectionsChild = (presets: string[]) => ({
},
]
: []),
...(presets.includes("timeline")
? [
{
path: "view",
label: "Shows",
widget: "select",
options: [["carousel", "A rail of the featured moments (the front page's)"]],
blankLabel: "Default: the whole timeline",
when: { path: "preset", value: "timeline" },
},
]
: []),
...BAND_FIELDS,
...(presets.includes("group_map")
? [
{
@ -145,6 +428,17 @@ const sectionsChild = (presets: string[]) => ({
: []),
],
children: [
...BAND_CHILDREN,
{
key: "tags",
label: "Directory: tags",
note: "Each People tag is a tab, in this order, eg. Musicians, Authors, Creators: the first of its people, and a link to its full directory. One tag shows without tabs. Tags are made under Data → People tags.",
addLabel: "Add tag",
when: { path: "preset", value: "people_directory" },
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: "orgs",
label: "Cards: organizations",
@ -164,93 +458,64 @@ const sectionsChild = (presets: string[]) => ({
],
});
const sitePage = (id: string, label: string, presets: string[], more: Record<string, any> = {}) => ({
key: `${id}_page`,
label,
singular: label.toLowerCase(),
idLabel: "Page",
singleton: id,
const ALL_PRESETS = Object.keys(PRESETS);
list: { columns: [], filters: [] },
/* Pages the site's own code links to: their address stays
(server/src/admin-schema/sitePages.js, CORE_PAGES). */
const CORE_PAGE_IDS = ["home", "give", "feedback", "request", "qr", "privacy", "terms"];
groups: [],
...more,
children: [sectionsChild(presets), ...(more.children ?? [])],
});
export const pages = {
key: "pages",
label: "Page management",
singular: "page",
idLabel: "URL ID",
slugFrom: "title",
// The server refuses to delete these (CORE_PAGES); no Delete button.
undeletable: CORE_PAGE_IDS,
// Every page's address, title, intro and switches, then its own
// sections, the front page's included (its hero and bands).
list: {
columns: [
{ key: "title", label: "Page", primary: true },
{ key: "path", label: "Address" },
{ key: "is_hidden", label: "Hidden", widget: "bool" },
{ key: "is_disabled", label: "Disabled", widget: "bool" },
],
filters: [],
},
export const communityPage = sitePage(
"community",
"Community page",
["community_blog", "group_map", "region_list", "partner_list", "people_directory"],
{
groups: [
{
legend: "Community blog: our posts",
note: "For the Community blog preset. Pinned posts first, then the newest published, listed posts, up to the number of slots.",
legend: "The page",
fields: [
{ path: "blog.internal_title", label: "Heading", help: "Default: From NGU" },
{ path: "blog.internal_slots", label: "Slots", widget: "number", help: "0 to 12. Default: 3" },
],
},
{ path: "title", label: "Title", required: true, help: "The page's heading, and its title in search and the browser tab, eg. Library" },
{
legend: "Community blog: community posts",
note: "Pinned cards first, then the newest items from the feeds below, up to the number of slots.",
fields: [
{ path: "blog.external_title", label: "Heading", help: "Default: From our community" },
{ path: "blog.external_slots", label: "Slots", widget: "number", help: "0 to 12. Default: 3" },
{ path: "blog.external_url", label: "Button link", help: "eg. https://ngu.substack.com", full: true },
{ path: "blog.external_label", label: "Button text", help: "Default: Read more on Substack" },
],
},
],
children: [
{
key: "pinned_posts",
label: "Community blog: pinned posts (ours)",
note: "Always shown, before the newest.",
addLabel: "Pin a post",
title: (row, options) =>
options?.blog_posts?.find((p) => p.id === row.post_id)?.label ?? "New pin",
blank: { post_id: "" },
fields: [
{
path: "post_id",
label: "Post",
widget: "select",
optionsFrom: "blog_posts",
path: "path",
label: "Address",
required: true,
help: (row) =>
CORE_PAGE_IDS.includes(row?.id)
? "The site's own links point here, so this page's address stays."
: "Where it lives on the site, eg. /library. Lowercase letters, numbers, hyphens and /. Changing it breaks old links: update Navigation's too.",
readOnly: (row) => CORE_PAGE_IDS.includes(row?.id),
},
],
{ path: "description", label: "Intro", widget: "textarea", full: true, help: "The line under the title, and its description in search." },
{
path: "is_hidden",
label: "Hidden",
widget: "checkbox",
help: "Not found to everyone but signed-in admin accounts, eg. a page that isn't done. Out of the menus and the sitemap.",
},
{
...featuredCardsChild,
label: "Community blog: pinned community posts",
note: "Always shown, before the feeds' newest. Paste a post's link and press Fetch preview.",
addLabel: "Pin a post",
blank: { kind: "", url: "", title: "" },
fields: featuredCardsChild.fields.map((field) =>
field.path === "kind"
? { ...field, options: FEATURED_KINDS.filter(([kind]) => kind !== "record") }
: field,
),
path: "is_disabled",
label: "Disabled",
widget: "checkbox",
help: "Out of the menus, the sitemap and search; its address still works for anyone with the link.",
},
{
key: "feeds",
label: "Community blog: feeds",
note: "RSS or Atom feeds whose newest posts fill the community slots. Read about every 30 minutes.",
addLabel: "Add feed",
title: (row) => row.label || row.url || "New feed",
blank: { url: "", label: "" },
fields: [
{ path: "url", label: "Feed URL", required: true, full: true, help: "eg. https://ngu.substack.com/feed" },
{ path: "label", label: "Source name", help: "Shown on its cards. Default: the feed's own title" },
{ path: "sort_order", label: "Order", widget: "number", help: "Where its card sits on the admin home, lowest first. Default: 0" },
],
},
],
},
);
export const retreatsPage = sitePage("retreats", "Retreats page", ["events"]);
export const resourcesPage = sitePage("resources", "Resources page", ["people_directory"]);
export const organizationPage = sitePage("organization", "Organization page", ["people_directory"]);
export const historyPage = sitePage("history", "History page", ["timeline"]);
children: [sectionsChild(ALL_PRESETS)],
};

View file

@ -1,13 +1,12 @@
import siteConfiguration from "../../../site.json";
import { mediaUrl } from "../media.ts";
import { THEME_DEFAULTS } from "../../../server/src/themeDefaults.js";
import { WORD_DIRECTIONS, WORD_HELP, WORD_MOTIONS } from "./shared.ts";
/* ── Site settings (035_site_settings.sql) ───────────────────────
Overrides for site.json, superadmins only: every blank falls back
to what site.json says, which is shown as the default. */
const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).map(
([path, page]) => [path, `${page.title} (${path})`],
);
to what site.json says, which is shown as the default. Page titles
and intros are Pages → Navigation's (siteNav.ts). */
/* The palette an admin can change, in the order the dropdown lists
it: token and label. The defaults come from the server's list
@ -112,18 +111,6 @@ export const siteSettings = {
},
],
},
{
legend: "Privacy",
fields: [
{
path: "privacy_email",
label: "Privacy contact email",
help: `The Privacy page gives this for privacy questions and data requests, eg. privacy@nextgenerationofunity.org. ${
siteConfiguration.privacyEmail ? `Default: ${siteConfiguration.privacyEmail}` : "Default: none, the page offers its request form only"
}.`,
},
],
},
{
legend: "Access (Google groups)",
note: "Anyone in one of these Workspace groups can sign in to the admin with Google; their account is made at first sign-in, with the highest role their groups give. Their role follows the groups (checked at sign-in, hourly, and by Panel → Re-sync now); out of every group, the account is disabled. Superadmins and accounts made with admin-cli aren't affected. Needs GOOGLE_DIRECTORY_AS on the server (docs/google-sign-in.md).",
@ -172,6 +159,25 @@ export const siteSettings = {
},
],
},
{
legend: "Planning Center",
fields: [
{
path: "pco_list_id",
label: "People list",
help: "The Planning Center list Data → Planning Center brings in: its number, from the list's address in Planning Center People, eg. 1234567. Needs PCO_APP_ID and PCO_SECRET on the server (docs/planning-center.md).",
},
],
},
{
legend: "Animated words",
note: WORD_HELP + " Works in the hero's headline, section titles, headings and paragraphs. These are the defaults; a hero or a block can set its own. Visitors who ask for less motion see the first word, still.",
fields: [
{ path: "word_motion", label: "Motion", widget: "select", options: WORD_MOTIONS, blankLabel: "Default: Slide" },
{ path: "word_direction", label: "Words come in", widget: "select", options: WORD_DIRECTIONS, blankLabel: "Default: from the bottom", help: "For Slide and Flip" },
{ path: "word_seconds", label: "Seconds per word", widget: "number", help: "1 to 20. Default: 3" },
],
},
{
legend: "Notices",
fields: [
@ -218,28 +224,5 @@ export const siteSettings = {
},
],
},
{
key: "pages",
label: "Page titles and intros",
note: "Change a static page's heading and intro, which are also its search title and description. Blank fields keep site.json's.",
addLabel: "Change a page",
title: (row) => SITE_PAGES.find(([path]) => path === row.path)?.[1] ?? "New page",
blank: { path: "", title: "", description: "" },
fields: [
{ path: "path", label: "Page", widget: "select", options: SITE_PAGES, required: true },
{
path: "title",
label: "Title",
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.title ?? ""}` : undefined),
},
{
path: "description",
label: "Intro",
widget: "textarea",
full: true,
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.description ?? ""}` : undefined),
},
],
},
],
};

View file

@ -21,6 +21,36 @@ import { visionColor } from "./color.ts";
const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
const DEFAULT_TTL = 60_000;
/* A draft's preview (server/src/drafts.js): a tab opened from the
editor's Preview with ?preview=<entity>/<id> sends it with every
read of the site's data, for as long as the tab lasts, and the
server answers with that draft applied (to a signed-in viewer and
up; anyone else gets the live site). Never for the admin's own
reads. */
const PREVIEW_KEY = "site-draft-preview";
export const draftPreview: string | null = (() => {
if (typeof window === "undefined") return null;
try {
const asked = new URLSearchParams(window.location.search).get("preview");
if (asked) sessionStorage.setItem(PREVIEW_KEY, asked);
return asked ?? sessionStorage.getItem(PREVIEW_KEY);
} catch {
return null;
}
})();
export function stopPreview() {
try {
sessionStorage.removeItem(PREVIEW_KEY);
} catch {
// Nothing kept to clear.
}
const url = new URL(window.location.href);
url.searchParams.delete("preview");
window.location.replace(url.toString());
}
const cache = new Map(); // path → { at, promise }
const settled = new Map(); // path → the last body it answered with
@ -44,9 +74,11 @@ const NOT_THE_API: Record<number, string> = {
};
async function request(path, options: RequestInit = {}) {
const preview: Record<string, string> =
draftPreview && !String(path).startsWith("/admin") ? { "X-Draft-Preview": draftPreview } : {};
const response = await fetch(`${BASE}${path}`, {
...options,
headers: { Accept: "application/json", ...options.headers },
headers: { Accept: "application/json", ...preview, ...(options.headers as Record<string, string>) },
});
if (response.status === 204) return null;
@ -123,7 +155,7 @@ export function peek(path) {
return settled.get(path);
}
export function invalidate(path) {
export function invalidate(path?: string) {
if (path) {
cache.delete(path);
settled.delete(path);
@ -151,6 +183,14 @@ export function patch(path, data) {
});
}
export function put(path, data) {
return request(path, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
}
export function del(path) {
return request(path, { method: "DELETE" });
}

View file

@ -10,13 +10,19 @@
RequireAuth guards routes. Worth being clear about what that
does and doesn't do: it hides the interface, not the data. The
protection is the 401 from /api/admin, this only stops someone
staring at an empty table.
staring at an empty table. A profile account (member) is signed
in but has no admin, so it's sent to its page on the site.
The provider wraps the whole app, since the site shows a profile
link and hidden pages by who's signed in. Signing in or out drops
the API cache: the nav and hidden pages depend on it.
═══════════════════════════════════════════════════════════════ */
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";
import { get, post, ApiError } from "./api.ts";
import { get, invalidate, post, ApiError } from "./api.ts";
import { isStaff } from "./roles.ts";
const AuthContext = createContext<any>(null);
@ -45,6 +51,7 @@ export function AuthProvider({ children }) {
const login = useCallback(async (email, password) => {
const data = await post("/auth/login", { email, password });
invalidate();
setUser(data.user);
return data.user;
}, []);
@ -54,12 +61,19 @@ export function AuthProvider({ children }) {
await post("/auth/logout", {});
} finally {
// Whatever the server said, this browser is done.
invalidate();
setUser(null);
}
}, []);
// After a sign-in the server did itself (an invite's password).
const signedIn = useCallback((next) => {
invalidate();
setUser(next);
}, []);
return (
<AuthContext.Provider value={{ user, loading, login, logout }}>
<AuthContext.Provider value={{ user, loading, login, logout, signedIn }}>
{children}
</AuthContext.Provider>
);
@ -94,5 +108,7 @@ export function RequireAuth() {
return <Navigate to="/admin/login" state={{ from: location }} replace />;
}
if (!isStaff(user)) return <Navigate to="/account" replace />;
return <Outlet />;
}

View file

@ -25,8 +25,9 @@ const slug = (text: string) =>
.slice(0, 60) || 'section'
/* One entry per heading or subheading block, in order, and the id
for each block index that is one. */
export function headingAnchors(blocks?: ContentBlock[] | null): {
for each block index that is one. prefix keeps a blog post's tabs
apart (splitTabs): "Overview" in two tabs is two ids. */
export function headingAnchors(blocks?: ContentBlock[] | null, prefix = ''): {
entries: ContentsEntry[]
idAt: Map<number, string>
} {
@ -40,9 +41,39 @@ export function headingAnchors(blocks?: ContentBlock[] | null): {
const base = slug(text)
const n = (seen.get(base) ?? 0) + 1
seen.set(base, n)
const id = n === 1 ? base : `${base}-${n}`
const id = `${prefix}${n === 1 ? base : `${base}-${n}`}`
idAt.set(index, id)
entries.push({ id, text, level: block.type === 'heading' ? 1 : 2 })
})
return { entries, idAt }
}
/* ── A blog post's tabs (079) ──────────────────────────────────
A 'tab' block starts a tab, titled by its text, holding the
blocks after it up to the next; the blocks before the first are
the intro above the tabs. Each tab's heading ids start with its
own, so the same heading in two tabs is two ids; the intro's
keep their plain ids. */
export type PostTab = { id: string; title: string; prefix: string; blocks: ContentBlock[] }
export function splitTabs(blocks?: ContentBlock[] | null): { intro: ContentBlock[]; tabs: PostTab[] } {
const intro: ContentBlock[] = []
const tabs: PostTab[] = []
const seen = new Map<string, number>()
for (const block of blocks ?? []) {
if (block.type === 'tab') {
const title = (block.text ?? '').trim() || `Part ${tabs.length + 1}`
const base = `tab-${slug(title)}`
const n = (seen.get(base) ?? 0) + 1
seen.set(base, n)
const id = n === 1 ? base : `${base}-${n}`
tabs.push({ id, title, prefix: `${id}-`, blocks: [] })
} else if (tabs.length) {
tabs[tabs.length - 1].blocks.push(block)
} else {
intro.push(block)
}
}
return { intro, tabs }
}

72
src/lib/convertImage.ts Normal file
View file

@ -0,0 +1,72 @@
/* ═══════════════════════════════════════════════════════════════
IMAGE CONVERSION, in the browser
Tools → Image converter and the Media library's Download as: a
picture redrawn on a canvas and saved as another format. Nothing
is uploaded. Reads whatever this browser can show (JPEG, PNG,
WebP, GIF's first frame, AVIF, BMP, SVG; HEIC in Safari only).
JPEG has no transparency, so a JPEG's see-through parts are
filled white.
═══════════════════════════════════════════════════════════════ */
export const OUTPUT_FORMATS = [
{ type: 'image/jpeg', label: 'JPG', ext: 'jpg', lossy: true },
{ type: 'image/png', label: 'PNG', ext: 'png', lossy: false },
{ type: 'image/webp', label: 'WebP', ext: 'webp', lossy: true },
] as const
export type OutputType = (typeof OUTPUT_FORMATS)[number]['type']
/* An SVG with no size of its own is drawn this wide. */
const SVG_EDGE = 2048
function loadImage(blob: Blob): Promise<HTMLImageElement> {
const url = URL.createObjectURL(blob)
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject(new Error("This browser can't read that picture."))
img.src = url
}).finally(() => URL.revokeObjectURL(url)) as Promise<HTMLImageElement>
}
/** The picture as `type`; quality 0 to 1 for JPG and WebP. */
export async function convertImage(blob: Blob, type: OutputType, quality = 0.9): Promise<Blob> {
const img = await loadImage(blob)
const width = img.naturalWidth || SVG_EDGE
const height = img.naturalHeight || SVG_EDGE
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
if (!context) throw new Error("This browser can't draw the picture.")
if (type === 'image/jpeg') {
context.fillStyle = '#ffffff'
context.fillRect(0, 0, width, height)
}
context.drawImage(img, 0, 0, width, height)
const out = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, type, quality))
// A browser that can't write the format (old Safari and WebP)
// hands back a PNG, or nothing.
if (!out || out.type !== type) throw new Error(`This browser can't save ${type.split('/')[1].toUpperCase()}.`)
return out
}
/** A file name with the new format's extension. */
export function renamed(name: string, type: OutputType): string {
const ext = OUTPUT_FORMATS.find((f) => f.type === type)?.ext ?? 'img'
const stem = name.replace(/\.[^./]+$/, '') || 'image'
return `${stem}.${ext}`
}
/** Hands the browser a file to save. */
export function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
}

View file

@ -13,7 +13,7 @@
renders as its own name, so a CHECK is enough.
Adding a type is three edits: the CHECKs in a migration (on
events.event_type and front_page.countdown_event_type), the enums
events.event_type and section_countdown.event_type), the enums
in both descriptor halves (the event's type and the front page's
countdown type), and this list. Adding it here alone
means the site offers a filter the database will refuse to store.

View file

@ -1,38 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
FRONT PAGE BANDS
Each band the front page can show (front_page_sections.section):
the anchor it sits at, and the heading it gets when the admin gives
it none. Home.tsx draws the bands; the nav and footer list the ones
the front page is showing (navSections.ts). The countdown has no
anchor: it's a card under the hero, not a section to jump to.
═══════════════════════════════════════════════════════════════ */
import type { FrontPage, FrontPageSectionKey } from './useFrontPage.ts'
export const FRONT_PAGE_BANDS: Record<FrontPageSectionKey, { id: string | null; title: string }> = {
countdown: { id: null, title: 'Next up' },
retreats: { id: 'retreats', title: 'National Retreats' },
calendar: { id: 'calendar', title: 'What’s on' },
stats: { id: 'numbers', title: 'By the numbers' },
timeline: { id: 'story', title: 'Our story so far' },
connect: { id: 'connect', title: 'Find your way in' },
featured: { id: 'featured', title: 'Featured' },
}
/* Whether a band has anything to draw: Home.tsx leaves out a band
with nothing in it, and so does the nav. */
export function bandShows(page: FrontPage, key: FrontPageSectionKey): boolean {
switch (key) {
case 'countdown':
return Boolean(page.countdown)
case 'stats':
return page.stats.length > 0
case 'connect':
return page.paths.length > 0
case 'featured':
return page.featured.length > 0
default:
return true
}
}

View file

@ -13,7 +13,7 @@
table, so there is one answer to "where does an event live" and
changing it is changing EVENT_BASE below.
navConfig.ts stays the source of truth for the *nav*: these are
The nav is Pages → Navigation's (useSiteNav.ts): these are
record routes, which never appear in it.
── On missing ids ──

View file

@ -3,39 +3,28 @@
dropdowns, the mobile menu and the footer's site map
Every page's list comes from the page itself, so adding, moving
or renaming a section changes the menus too: the site pages'
sections (Pages → each page, GET /site-pages), and the front
page's bands it is showing, in the admin's order, each under its
heading (Front page → Sections).
or renaming a section changes the menus too (Pages → Page
management, GET /site-pages), the front page's included. The hero
and a countdown aren't listed: they're the top of a page, not a
place to jump to (sections/Bands.tsx).
═══════════════════════════════════════════════════════════════ */
import { useCallback } from 'react'
import { useSitePageHeadings } from './useSitePages.ts'
import { useFrontPage } from './useFrontPage.ts'
import { FRONT_PAGE_BANDS, bandShows } from './frontPageBands.ts'
import { UNLISTED_PRESETS } from '../pages/sections/Bands.tsx'
import { firstWords } from '../lib/words.ts'
export type NavSection = { label: string; hash: string }
export function useNavSections(): (path: string) => NavSection[] {
const { data: page } = useFrontPage()
const { data: sitePages } = useSitePageHeadings()
return useCallback(
(path: string) => {
if (path !== '/') {
return (sitePages?.[path.slice(1)] ?? []).map((section) => ({
label: section.title,
hash: `#${section.anchor}`,
}))
}
if (!page) return []
return page.sections.flatMap((section) => {
const band = FRONT_PAGE_BANDS[section.section]
if (!band?.id || !bandShows(page, section.section)) return []
return [{ label: section.title || band.title, hash: `#${band.id}` }]
})
},
[page, sitePages],
(path: string) =>
(sitePages?.[path] ?? [])
.filter((section) => !UNLISTED_PRESETS.includes(section.preset ?? ''))
.map((section) => ({ label: firstWords(section.title), hash: `#${section.anchor}` })),
[sitePages],
)
}

View file

@ -38,6 +38,7 @@
import { readableOn } from './color.ts'
import { PLATFORMS } from './platforms.ts'
import { firstWords } from '../lib/words.ts'
export type NewsletterItem = {
title: string
@ -186,7 +187,8 @@ const imageTag = (src: string, alt: string) =>
`<img src="${escape(src)}" width="552" alt="${escape(alt)}" style="display:block;margin:0 auto;width:100%;max-width:552px;height:auto;border:0;">`
function blockHtml(block: NewsletterPart, n: Newsletter): string {
const text = block.text?.trim() ?? ''
// An email can't animate: rotating words ({Next|Now}) are their first.
const text = firstWords(block.text).trim()
const href = block.href ? safeHref(block.href, n) : null
const items = block.items ?? []
const align = alignOf(block)
@ -412,7 +414,7 @@ export function newsletterHtml(n: Newsletter): string {
}
function blockText(block: NewsletterPart, n: Newsletter): string[] {
const text = block.text?.trim() ?? ''
const text = firstWords(block.text).trim()
const items = block.items ?? []
const link = (url: string) => safeHref(url, n) ?? url
switch (block.type) {

View file

@ -14,18 +14,22 @@
role to be added, and there's now a fourth.
═══════════════════════════════════════════════════════════════ */
export const ROLES = ["viewer", "editor", "admin", "superadmin"] as const;
/* member is a profile account (076): the site and their own profile,
never the admin. */
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"] as const;
export type Role = (typeof ROLES)[number];
export const ROLE_RANK: Record<Role, number> = {
viewer: 1,
editor: 2,
admin: 3,
superadmin: 4,
member: 1,
viewer: 2,
editor: 3,
admin: 4,
superadmin: 5,
};
export const ROLE_LABELS: Record<Role, string> = {
member: "Profile",
viewer: "Viewer",
editor: "Editor",
admin: "Admin",
@ -35,9 +39,10 @@ export const ROLE_LABELS: Record<Role, string> = {
/* Each line is what that role adds to the one above it in the
list. Read top to bottom, they describe the whole ladder. */
export const ROLE_NOTES: Record<Role, string> = {
member: "Signs in to the site to edit their own profile. No admin.",
viewer: "Can read everything in the CMS and change nothing.",
editor: "Can create and update records. Can't delete anything.",
admin: "Can delete records, including feedback.",
admin: "Can delete records, including feedback. Invites profile accounts and approves their claims.",
superadmin: "Can manage accounts, roles and sessions.",
};
@ -55,3 +60,5 @@ export function atLeast(user: MaybeUser, role: Role): boolean {
export const canWrite = (user: MaybeUser) => atLeast(user, "editor");
export const canDelete = (user: MaybeUser) => atLeast(user, "admin");
export const isSuper = (user: MaybeUser) => atLeast(user, "superadmin");
/* Uses the admin at all: a profile account (member) doesn't. */
export const isStaff = (user: MaybeUser) => atLeast(user, "viewer");

View file

@ -1,16 +1,11 @@
/* ═══════════════════════════════════════════════════════════════
FRONT PAGE DATA
SECTION TYPES' DATA
GET /front-page, as routes/home.js shapes it: the hero, the
visible sections in order, counted stats, paths with actions,
and the countdown's event. Edited in the admin under Front page.
No fallback content. If the request fails the page says so: a
plausible default home page would hide a broken server behind
something that looks fine.
What a band section's `data` holds (server/src/sectionData.js,
in GET /site-pages/:id): a hero, a countdown's event, stats, a
pathfinder's paths, featured cards. sections/Bands.tsx draws them.
═══════════════════════════════════════════════════════════════ */
import { useRecord, type Resource } from './useRecord.ts'
import type { EventSeries } from './eventSeries.ts'
import type { Link } from './useContent.ts'
@ -20,16 +15,6 @@ export type HeroBackdrop = 'brand' | 'photos'
/** What sits beside the words, over the backdrop. */
export type HeroFeature = 'none' | 'livestream' | 'video' | 'event'
/** The CHECK list on front_page_sections.section. */
export type FrontPageSectionKey =
| 'countdown'
| 'retreats'
| 'calendar'
| 'stats'
| 'timeline'
| 'connect'
| 'featured'
export type HeroButton = { label: string; url: string }
export type HeroSlide = {
@ -53,18 +38,13 @@ export type Hero = {
/** A link to embed or a video file; see videoSource in embeds.ts. */
/** `still` is shown before it plays; resolve it with mediaUrl. */
video: { url: string; title?: string | null; captions?: string | null; still?: string | null } | null
/** With the 'event' feature: the pinned event, else the countdown's. */
/** With the 'event' feature: the pinned event, else the page's countdown's. */
event: HeroEvent | null
/** Its rotating words' own motion (084), else the site's. */
words?: { motion?: any; direction?: any; seconds?: number | null } | null
}
export type FrontPageSection = {
section: FrontPageSectionKey
/** Null → the section's own heading. */
title?: string | null
blurb?: string | null
}
export type FrontPageStat = {
export type SectionStat = {
label: string
/** Already counted or typed; never null, since the API drops those. */
value: string
@ -74,7 +54,7 @@ export type FrontPageStat = {
export type PathAction = { label: string; description?: string | null; url: string }
export type FrontPagePath = {
export type SectionPath = {
label: string
icon?: string | null
blurb?: string | null
@ -122,17 +102,3 @@ export type HeroEvent = CountdownEvent & {
org_logo?: string | null
links: Link[]
}
export type FrontPage = {
hero: Hero
sections: FrontPageSection[]
stats: FrontPageStat[]
paths: FrontPagePath[]
featured: FeaturedCard[]
/** Columns across on a wide screen; null is the grid's default. */
featured_columns: FeaturedColumns | null
countdown: CountdownEvent | null
}
export const useFrontPage = (): Resource<FrontPage> =>
useRecord<FrontPage>('/front-page', 'front_page')

View file

@ -10,8 +10,9 @@
serves the plain index.html, it isn't there and site.json alone
applies.
A page's visible heading and intro and its search title and
description come from the same values, so they can't drift.
A page's heading and intro are its site_pages row's (Pages → Page
management), which also give its search title and description, so
they can't drift: useSiteNav and the page's own data carry them.
SITE_ORIGIN is the public address of the live site. It's used
where a URL has to leave the browser and still work: a printed QR
@ -22,9 +23,10 @@
import siteConfiguration from '../../site.json'
type PageText = { title: string; description: string }
/** How rotating words move (RotatingWords.tsx, 084). */
export type WordSettings = { motion: 'slide' | 'flip' | 'fade' | 'type' | 'mirror'; direction: 'top' | 'bottom'; seconds: number }
type SiteText = { title?: string; pages?: Record<string, PageText>; privacyEmail?: string; requestFiles?: boolean }
type SiteText = { title?: string; requestFiles?: boolean; words?: Partial<WordSettings> | null }
/* What the server wrote into the page, if it did. */
const fromServer: SiteText =
@ -34,9 +36,13 @@ export const SITE_NAME: string = fromServer.title || siteConfiguration.title
export const SITE_ORIGIN: string = siteConfiguration.url
/** Where privacy questions and data requests go (Panel → Site
* settings, else site.json). Blank: the Privacy page's form only. */
export const PRIVACY_EMAIL: string = fromServer.privacyEmail ?? siteConfiguration.privacyEmail
/** Rotating words' defaults: Site settings → Animated words, else
* sliding up from the bottom, three seconds a word. */
export const WORD_DEFAULTS: WordSettings = {
motion: fromServer.words?.motion || 'slide',
direction: fromServer.words?.direction || 'bottom',
seconds: fromServer.words?.seconds || 3,
}
/** Whether the Request form takes files (Google Drive is set up on
* the server). Unknown (the Vite dev server) offers them, and the
@ -46,18 +52,6 @@ export const REQUEST_FILES: boolean = fromServer.requestFiles ?? true
/** A site path as a full URL on the live site. */
export const siteUrl = (path: string): string => new URL(path, SITE_ORIGIN).href
const PAGES: Record<string, PageText> = { ...siteConfiguration.pages, ...fromServer.pages }
/* Every static page's path and text, for the not-found page's suggestions. */
export const SITE_PAGES: Readonly<Record<string, PageText>> = PAGES
/** A static page's title and intro, from site.json's "pages". */
export function sitePage(path: string): PageText {
const page = PAGES[path]
if (!page) throw new Error(`site.json has no "pages" entry for ${path}`)
return page
}
/** The browser tab's title for a page: "Retreats | Next Generation
* of Unity", or the site name alone for the home page. */
export const documentTitle = (title?: string | null): string =>

44
src/lib/useAccount.ts Normal file
View file

@ -0,0 +1,44 @@
/* A profile account's own page (server/src/routes/account.js): the
account, the People record it has (as its owner edits it), its
claim, and Discord. Not cached: it changes as they edit it. */
import { useRecord, type Resource } from './useRecord.ts'
/* What an owner can take off the site (people.hide_*), in the order
the profile page lists them. */
export const HIDE_FIELDS = [
['photo', 'Photo'],
['pronouns', 'Pronouns'],
['tagline', 'Tagline'],
['bio', 'Bio'],
['email', 'Public email'],
['phone', 'Public phone'],
['location', 'Location'],
['links', 'Links'],
] as const
export type HideField = (typeof HIDE_FIELDS)[number][0]
export type MyPerson = {
id: string
display_name: string
is_published: boolean
photo: string | null
pronouns: string | null
tagline: string | null
bio: string | null
public_email: string | null
public_phone: string | null
location_label: string | null
hidden: Record<HideField, boolean>
}
export type MyAccount = {
user: { id: number; email: string; name: string | null; role: string }
person: MyPerson | null
claim: { id: number; person_id: string; display_name: string; status: 'pending' | 'approved' | 'declined' } | null
discord: { enabled: boolean; id: string | null; name: string | null }
}
export const useMyAccount = (enabled: boolean): Resource<MyAccount> =>
useRecord(enabled ? '/account' : null, 'account')

View file

@ -1,15 +1,16 @@
/* ═══════════════════════════════════════════════════════════════
BLOG DATA
GET /blog/:id and GET /community-blog, as routes/blog.js shapes
them. The section's community posts arrive as featured cards, so
GET /blog/:id, as routes/blog.js shapes it, and what a Community
blog section shows (its `data`, server/src/sectionData.js). The
section's community posts arrive as featured cards, so
FeaturedCards.tsx draws them unchanged.
═══════════════════════════════════════════════════════════════ */
import { detailPath } from './hrefs.ts'
import { useRecord, type Resource } from './useRecord.ts'
import type { ContentBlock } from './useContent.ts'
import type { FeaturedCard } from './useFrontPage.ts'
import type { FeaturedCard } from './sectionTypes.ts'
export type BlogAuthor = {
id: string
@ -59,8 +60,6 @@ export type CommunityBlog = {
export const useBlogPost = (id?: string | null): Resource<BlogPostRecord> =>
useRecord<BlogPostRecord>(detailPath('/blog', id), 'post')
export const useCommunityBlog = (): Resource<CommunityBlog> =>
useRecord<CommunityBlog>('/community-blog', 'community_blog')
/** '2026-09-01' → 'September 1, 2026'. Parsed as a local date, so
* it can't slip a day in a timezone west of UTC. */

View file

@ -12,7 +12,7 @@
*/
import type { BlogPostSummary } from './useBlog.ts'
import type { FeaturedCard } from './useFrontPage.ts'
import type { FeaturedCard } from './sectionTypes.ts'
import { detailPath } from './hrefs.ts'
import { useRecord, type Resource } from './useRecord.ts'
import type { EventType } from './eventTypes.ts'
@ -24,6 +24,8 @@ import type { EventSeries } from './eventSeries.ts'
export type ContentBlock = {
id?: number | string
slot?: 'card' | 'body'
/** Its rotating words' own motion (084), else the site's. */
words?: { motion?: any; direction?: any; seconds?: number | null } | null
type:
| 'heading'
| 'subheading'
@ -38,6 +40,7 @@ export type ContentBlock = {
| 'callout'
| 'schedule'
| 'table'
| 'tab'
| 'cards'
| 'people'
text?: string | null

Some files were not shown because too many files have changed in this diff Show more