Compare commits

...

63 commits

Author SHA1 Message Date
13d8489fd4 Merge pull request 'v1.14.2-present: event schedules, venues and map blocks, Present mode and its phone remote' (#33) from event-schedule into main
Reviewed-on: #33
2026-11-21 23:02:04 +00:00
Zaldimmar
48b61e6cc7 Version v1.14.2-present
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:57:32 -06:00
Zaldimmar
2d354a35c1 Docs: an nginx /api/admin/ block with a 4m body limit, so big saves don't get a 413
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:57:32 -06:00
Aidan Dona
5eebc20c4e Present: a remote, a phone at /remote/<code> drives a presenting screen
The screen shows a code on its setup and with its controls. Anyone with
it can step, pause and jump through the slides, send the screen back to
its setup, or change the setup and play it there. Server-sent events,
held in memory (routes/present.js); X-Accel-Buffering: no, so nginx
needs no block of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:51:27 -06:00
Zaldimmar
3aef3b1c34 Present: dividers left off the slides
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:59:58 -06:00
Zaldimmar
b286cbddbf Present: a heading alone as a centered slide; just an events list
- A section left with only its heading and subheadings, and nothing
  after it to title, gets a centered slide of them
- Setup, per events block: A slide per event, so the list slide can
  show alone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:57:38 -06:00
Zaldimmar
b2ef692155 Present: featured events lit on the list slide; schedule row fixes
- An events list slide tints, bars and stars its featured events
- A schedule block's sub-items sit a little in, not under the title
- An entry with no place, person or tags no longer shows a stray 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:48:53 -06:00
Zaldimmar
7d31b3eea8 Present: Copy link for the setup's current choices
- addressFor builds the playing address from the choices, for Play
  and the new Copy link at the bottom of the setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:42:40 -06:00
Zaldimmar
f46deac3cc Image block: a dark theme picture; presented pictures centered
- media_dark (102): shown in place of the image while the site is
  dark, the block's alt text and caption shared
- Present: pictures beside text centered on the slide's height, and a
  section of only pictures centered both ways

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:40:40 -06:00
Zaldimmar
a59702b7f3 Present: a section's pictures left or right of its text, fitted
- Setup, per section with pictures and text: Pictures in the text,
  left of it or right of it (`pictures`), in a column beside the rest
- That slide shrinks to fit (Fit), measured again as pictures load

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:04:48 -06:00
Zaldimmar
a0eb9d7e49 Image block: a Size (small, medium, large), centered
- image_size (101): blank the column's full width, else up to 20, 32
  or 48rem, centered and never wider than the column

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:58:49 -06:00
Zaldimmar
c26e662406 Present: a callout slide without its tint and bar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:49:27 -06:00
Zaldimmar
c46a612226 Present: callout slides, Select all and Deselect all on the setup
- Setup, per callout block: a slide of its own, centered under the
  subheading above it (else the section's heading); Callouts seconds
- Select all and Deselect all over each list of the setup's checkboxes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:47:35 -06:00
Zaldimmar
afa95179ef Present: people roles picked on setup, an events list that fits
- Setup, per people block: each one's role or title under their name
  (`titles`)
- An events list slide: presenters under the titles, columns that
  flow, shrunk to fit rather than scrolled (Fit)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:32:09 -06:00
Zaldimmar
d58f630a8f Present: events picked on the setup screen, a titles list slide, people centered
- Setup, per events block: which events, and what's shown (list
  slide, picture, type and date, presenter, page content)
- An events block's list slide: titles and presenters as rows, not
  cards
- A slide of only people: title and photos centered both ways

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:20:42 -06:00
Zaldimmar
c4bb685bc0 Present: a list's slides picked on the setup screen, not the block
- Setup: Overview slide and A slide per item per list (`lists`), its
  items ticked on and off when either is picked
- The block's two fields and 098's columns go (100)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:02:06 -06:00
Zaldimmar
ae06cd2b4f Blocks: Shown on the page, in the presentation, or both
- present_show (099) replaces present_hide: only on the page, or only
  in the presentation, kept off the page and its contents list
- Blocks with the old Leave out ticked become Only on the page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:59:11 -06:00
Zaldimmar
2282bee23c Present: list slides, centered people
- A list block's Overview slide and A slide per item (098): its
  items' text on one slide, and each item with its detail, centered
- Setup ticks a list's overview and items on and off; List overview
  and List items seconds
- A presented people row is centered

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:57:08 -06:00
Zaldimmar
584340b0ee Present: the logo as a plain image, no dark mode plate, full size
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:40:19 -06:00
Zaldimmar
c35e65be63 Present: the logo in the screen's corner, not inset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:34:30 -06:00
Zaldimmar
b76f2a5707 Present: dark theme settings, a Theme pick, and a content inset
- Event Presentation, dark theme (096): background image and color,
  dim, accent, text color and logo for a dark screen; blank takes the
  light one
- Setup's Theme holds a screen light or dark while it plays (`theme=`)
- Inset top, right, bottom and left (097), percent of the screen, so
  the slides sit inside a frame drawn in the background image; with
  any set the image is stretched to the screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 04:14:14 -06:00
Zaldimmar
7e21a0dd40 Present: slide order, presentation settings, blocks drawn for a screen
- Setup's Order list: drag or move any slide; saved in the address
- A heading-only section titles the slides after it, no slide of its own
- Event Presentation settings (095): background image and color, dim,
  frame, accent, text color, logo
- Blocks: Presentation text and Leave out of the presentation; map
  blocks get a slide per section, map only, no details, location slides
- Presented, links are plain text, people a row of round photos and
  names, organizations their logos

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 03:41:06 -06:00
Zaldimmar
a79559d290 Admin preview: a map block's sections made as the API makes them
The preview handed MapBlock the form's sections (location_keys text),
so adding one crashed the page on section.keys. It now builds them as
shape.js does: keys the venue still has, empty ones dropped, the
venue cut to them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:45:43 -06:00
Zaldimmar
56a6e11655 Map block: sections of its own, shown one at a time
Migration 094 adds content_block_map_sections: a map block groups its
venue's locations for its page, eg. Main spaces, without changing the
venue. With sections the API cuts the block's venue to the locations
they hold, in their order; the list groups under their names, and
buttons (All, then each section) show one section's marks and rows.
A schedule's place links only when a map on the page shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:42:50 -06:00
Zaldimmar
06bf033448 Organizations block: its picker lists ministries too
The block picked from the `organizations` options, which leave
ministries out for pickers that link to a page. A card needs no page,
so the block has its own `block_orgs`, every kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:32:01 -06:00
Zaldimmar
bd271ef02d Organizations block: the Partners page's cards, picked one by one or every one of a kind
Migration 093 adds the 'organizations' block type (rebuilding
content_blocks for its CHECK, as 088 did), content_blocks.org_kind and
content_block_items.org_id. OrgListCards takes `nested` for a block:
no page gutter, names a level under the block's heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:23:58 -06:00
Zaldimmar
e9ea75a68d List block: bold text and a plain detail by default, with a Style to keep the old look
Migration 092 adds content_blocks.list_style: blank is bold text and
a detail in the body color, 'plain' the plain text and gray detail
lists had before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:20:00 -06:00
Zaldimmar
6a0271efd9 Map block: Google and Apple Maps buttons, a zoomable picture, links land at the map's top
Migration 091 adds google_maps_url and apple_maps_url to
venue_locations, shown as buttons at the right of each location's
row. The picture zooms (1x to 4x) and scrolls in its box. A link to a
location now scrolls to the top of the map block, not the mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:04:14 -06:00
Zaldimmar
8a79206998 Events block: featured events open in full above the cards, under a heading
Migration 090 adds heading and subheading to content_block_items. An
events block's item ticked Featured shows in full above the cards,
under its heading and subheading when set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:57:26 -06:00
Zaldimmar
a7495f09e5 Event page: the photo fills the column, as the blocks do
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:48:26 -06:00
Zaldimmar
b8a744cf41 Event page: a contents list, a links heading, full-width blocks; schedule tags in their own row
Migration 089 adds show_contents and links_heading to events (Page
group in the editor). The content blocks fill the column, beside the
contents list when it shows. A schedule's tag tabs sit in a row of
their own under the days, with a note on what they do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:44:57 -06:00
Zaldimmar
375c364861 Events block: a card opens the event in full, its own blocks too
An events block's events bring their own page's blocks (one level
deep, so events listing each other stop there), photo and place. A
card opens the event under the cards: photo, type and date, title,
place, person host, its blocks (else its card text) and a link to its
page. Reading mode shows them all in full, and the presentation's
event spotlight shows its blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 04:31:34 -06:00
Zaldimmar
df8052c75e Present: the whole event page, in sections at its headings
The presentation (now EventPresent) cuts the event's page into
sections at its Heading blocks: a section's text on one slide, then
its schedules' slides, a map block's map and each location lit up,
and an events block's grid and each event. One Present button on the
event page replaces the schedule's. Setup lists the sections, each
schedule's days and entries under its own; the address keys are now
skip and hide, numbered by schedule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 03:41:21 -06:00
Zaldimmar
818d648e91 Venues, map blocks and event blocks; schedule entries link to them
Data → Venues: a map picture with its locations marked as pins or
boxes (088). A Map block draws a venue with its locations listed;
a schedule names a venue and its entries pick a location, linking to
the map on the page with it lit up. Entries and sub-items can name
an event (a workshop) and take what they leave blank from it, and an
Events block shows event cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 03:21:18 -06:00
Zaldimmar
3d087da005 Present: scroll at seconds a screenful, the slide lengthened to fit
A long slide waits half its seconds, scrolls one screenful per Scroll seconds (setup, screen= in the address, default 8), then waits the other half. Pausing pauses the scroll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 03:41:47 -06:00
Zaldimmar
d17e2596ba Present: a slide with more than the screen holds scrolls through it
The day overview, tag and block lists and the spotlight text hold, scroll to the end over the slide's seconds, then hold. The spotlight description is no longer cut at six lines. Reduced motion keeps them at the top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 03:21:44 -06:00
Zaldimmar
b30f5f11fe Present: the tag filter's address key no longer collides with the tag slides' seconds
Both used 'tag', so on Play the seconds were read as the filter and every entry was cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 03:12:03 -06:00
Zaldimmar
edf0e0a177 Version: restore version.ts's characters, which the bump re-encoded
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:07:37 -06:00
Zaldimmar
d890efca2b Version v1.14.1-schedule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:07:14 -06:00
Zaldimmar
71d58318b6 Schedule tags: a block's own tags, tag tabs, chips, a tag filter and tag slides
A schedule block gets its own tags (content_block_tags, migration 087):
a name, a color and whether it's a tab. Entries and sub-items pick them
from a checklist. Each tag is a tab after the days, gathering what it's
on from every day under the day's name; a tagged entry comes whole and
an untagged block brings only its tagged sub-items. Rows show their tags
as chips. The presentation can show only one tag's entries and adds a
slide per tag after the days.

Entries name a tag by a key the admin makes when the tag is added, so a
rename keeps them, since the block's rows are rewritten on every save.
For that the admin engine gets a function blank (fresh values for every
new row and copy, with a `seeded` column that doesn't count as input),
`lends` (a row's options for the collections nested in it) and a
checklist widget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:04:06 -06:00
Zaldimmar
7885d10249 Schedule: entry types, picked times, striped rows, blocks in the presentation
Entries get a type (normal, block, break, heading) and a Featured tick.
Times are picked (start, optional end) and shown as 7:00pm or 9:00 to
10:30am; the typed time stays as the override, so existing entries look
the same. A block holds sub-items (content_block_subitems, migration 086),
each with every entry field. Rows alternate a faint tint. The presentation
gets a Blocks slide (its own seconds) before each sub-item's spotlight,
and sub-items get their own checkboxes on the setup page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:15:53 -06:00
274ffc26e0 Merge pull request 'v1.14.0-profiles: profile accounts, drafts, page management, Planning Center' (#32) from page-management into main 2026-10-28 07:00:09 +00:00
Zaldimmar
5ebc771272 Hero event card: photo always on top, words left and buttons stacked right from sm up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:59:35 -05:00
Zaldimmar
8b741676f3 Page management: list pages with their id, so the admin home's page cards link to them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 18:14:41 -05:00
Aidan Dona
54fc319d33 TODO: page management is part of v1.14.0-profiles
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 17:49:31 -05:00
Aidan Dona
e8aab4d7ec Planning Center: compare a People list with the site's people and apply what an admin picks
Migration 085 adds people.pco_id and Site settings' list. Data ->
Planning Center fetches the list, suggests matches (linked, same email,
same name), shows each field that would change (Planning Center wins),
and applies the chosen links, updates and new unpublished people in one
transaction. Needs PCO_APP_ID and PCO_SECRET.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:46:29 -05:00
Aidan Dona
a10ff6d75f Rotating words: {Next|Now} in titles and text cycles through its choices
Migration 084: site defaults for the motion (slide, flip, fade, type,
mirror), direction and seconds per word in Site settings, and a hero's
and a block's own. The hero's headline, section and band titles,
headings, paragraphs, callouts and quotes rotate; menus, tab titles,
search text and emails show the first word; less motion shows it still.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:43:59 -05:00
Aidan Dona
ab8dcdd608 Page management: no Delete button on the core pages the server won't delete
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:37:35 -05:00
Aidan Dona
f1a0b06ac2 Page management, step 3: section types with their own settings; the front page as sections
Migration 083 gives the section types that need more than blocks their
own tables (hero, slides, countdown, stats, paths, featured cards, the
Community blog's slots, pinned posts and feeds) and turns the front page
into Home's sections: the hero, then its bands in order. Any section can
be hidden. The Front page editor, its tables and the Community page's
are gone; /api/front-page and /api/community-blog fold into the page's
sections (sectionData.js). The admin engine reads and writes a child
collection's own side tables and gated nested collections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:34:56 -05:00
Aidan Dona
f33c0008fe Page management, step 2: the core pages as sections
Migrations 081 and 082: Feedback, Request, QR codes, Give, Privacy and
Terms become pages of sections. Their forms and embeds are section types
any page can use; Give's words and all of Privacy and Terms become blocks.
The privacy contact email is written into the policy and its setting goes.
Core pages keep their address and can't be deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:24:34 -05:00
Aidan Dona
1342691f49 Page management, step 1: every page in a registry, new pages, hidden and disabled
Migration 080 makes site_pages the list of every page: address, title,
intro, Hidden, Disabled (out of menus, sitemap and search) and card order.
site.json's pages and Navigation's page list move into it. Pages ->
Page management (one editor in place of six) makes new pages of sections
at any free address; the admin home opens Pages with a banner and a card
per page. A catch-all route draws whatever page is at an address; the
fixed pages take their words from the registry and can't be deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:19:54 -05:00
Aidan Dona
56acedf926 Featured event card beside the hero text; Word import: tabs, quotes, callouts, dividers, videos, buttons
From lg up the featured event's photo sits beside its words, so the card
is about as tall as the hero text. Word import turns a 'Tab:' line into a
tab, the Quote and Intense Quote styles into quotes and callouts, '---'
into a divider, a lone video link into a video and 'Button: label' into
a button; Blog posts shows the whole mapping beside Import from Word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:43:25 -05:00
Aidan Dona
3b034eb00e v1.14.0-profiles: bump SITE_VERSION
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:20:04 -05:00
Aidan Dona
31afa889d6 Page features: directory and blog post tabs, image converter, version names
- Featured event badge: above the event's card from lg up, left out on phones
- Version names from the tag (The Region Cards Update) in the site and admin footers
- Tools -> Image converter (JPG, PNG, WebP in the browser) and Download as in Media
- People directory sections take several tags, a tab each (migration 078)
- Tab blocks split a blog post into tabs; contents follow the open tab (migration 079)
- The side nav sun fades out as the page scrolls into the footer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:37:07 -05:00
Aidan Dona
a6c66d4607 Drafts of every record, previewed on the real page
Migration 077 keeps one draft per record of any entity. Saving a draft
checks it by applying it in a transaction that is rolled back; Preview
opens the record's page in a tab that sends X-Draft-Preview, and the
server answers those reads from a second connection holding the applied
draft, then rolls back, so nobody else sees it. Publish is the ordinary
save, which drops the draft. tx() now nests as a savepoint.

Also commits TODO.md: the answered questions, and parts 1 to 3 moved to
Done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:21:53 -05:00
Aidan Dona
e4c7e165d1 Profile accounts: invites, any-Google sign-in, claiming People, visibility, Discord
Migration 076 adds a member role below viewer (the site and its own
profile, never the admin: /api/admin now needs viewer), invites, person
claims, a Discord link on accounts and people.hide_* switches. Public reads
of people go through v_people_public, which nulls hidden fields, and the
views that read people are rebuilt over it.

Admins invite an email from Data -> Profile accounts (link shown once,
emailed on request). The invitee sets a password or signs in with any
Google account under that email, asks to claim their People record, and
once approved edits it and chooses what shows at /account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:14:30 -05:00
Aidan Dona
0cc2a3f721 Navigation in the admin: header and footer links, page titles, hidden pages, Shop
Pages -> Navigation (migration 075) edits the header's pages and buttons
and the footer's links; navConfig.ts is now only the defaults. Page titles
and intros move there from Site settings. A hidden page answers Not found
below viewer (server and app) and is out of the menus and sitemap; signed
in, it shows with a bar. Adds a /shop page of sections, hidden, with its
header button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 18:01:02 -05:00
b49497cc59 Merge pull request 'Cleanup: TODO.md, Claude settings and skills' (#31) from cleanup into main 2026-10-16 20:32:57 +01:00
Zaldimmar
5aad166054 TODO: the notes.txt items, each with questions to answer before building
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:29:40 -05:00
Zaldimmar
2b41b336f9 Skills: track design-taste-frontend once, in .agents, and add skills-lock.json
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:18:19 -05:00
Zaldimmar
bdec78010d Add TODO.md and the project's Claude settings and skills (graphify, design-taste-frontend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:17:46 -05:00
2e6c8b45e6 Merge pull request 'Region featured cards, featured grid, video stills, media naming (v1.13.2-region-cards)' (#30) from region-featured-cards into main
Reviewed-on: #30
2026-10-16 20:13:16 +01:00
1edc82fcf7 Merge pull request 'Feature updates: photo framing, group pages, schedule images, content block placement' (#29) from feature-updates into main 2026-10-07 22:52:58 +01:00
195 changed files with 17067 additions and 3313 deletions

File diff suppressed because it is too large Load diff

3
.claude/CLAUDE.md Normal file
View file

@ -0,0 +1,3 @@
# graphify
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.

34
.claude/settings.json Normal file
View file

@ -0,0 +1,34 @@
{
"permissions": {
"allow": [
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push origin:*)",
"Bash(tea pr create:*)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Grep",
"hooks": [
{
"type": "command",
"command": "graphify hook-guard search",
"timeout": 10
}
]
},
{
"matcher": "Read|Glob",
"hooks": [
{
"type": "command",
"command": "graphify hook-guard read",
"timeout": 10
}
]
}
]
}
}

View file

@ -0,0 +1 @@
0.9.71

View file

@ -0,0 +1,762 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
/graphify <path> # full pipeline on specific path
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
If no path was given, use `.` (current directory). Do not ask the user for a path.
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
Follow these steps in order. Do not skip steps.
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```powershell
# Detect Python with graphify — uv/pipx-aware (fixes #831)
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
$GRAPHIFY_PYTHON = $null
function Find-GraphifyPython {
# 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically
if (Get-Command uv -ErrorAction SilentlyContinue) {
$uvDir = (uv tool dir 2>$null).Trim()
if ($uvDir) {
$py = Join-Path $uvDir "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 2. pipx install — 'pipx environment' respects PIPX_HOME automatically
if (Get-Command pipx -ErrorAction SilentlyContinue) {
$venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim()
if ($venvs) {
$py = Join-Path $venvs "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 3. Active venv / conda / pip-into-current-env
$pyCmd = Get-Command python -ErrorAction SilentlyContinue
if ($pyCmd) {
& $pyCmd.Source -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) {
return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim()
}
}
return $null
}
# Try to find the right Python (uv → pipx → active env)
$GRAPHIFY_PYTHON = Find-GraphifyPython
# Not found — install then re-detect
if (-not $GRAPHIFY_PYTHON) {
if (Get-Command uv -ErrorAction SilentlyContinue) {
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
} else {
pip install graphifyy -q 2>&1 | Select-Object -Last 3
}
$GRAPHIFY_PYTHON = Find-GraphifyPython
}
# Save interpreter path — all subsequent steps read this.
# `Out-File -Encoding utf8` always writes a BOM on Windows PowerShell 5.1 (utf8NoBOM
# only exists from PowerShell 6), and that BOM rides into the saved path, so the hook
# rebuild fails with WinError 123 (#3028). WriteAllText with an explicit BOM-less
# encoding writes the bytes POSIX writes, and adds no trailing newline.
$Utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_python'), [string]$GRAPHIFY_PYTHON, $Utf8NoBom)
# Save scan root so `graphify update` (no args) knows where to look next time.
# INPUT_PATH is captured through a single-quoted (literal) here-string, never
# substituted directly into the command line: an unquoted bareword argument
# substituted here would let a malicious path (a stray `;`, `|`, or `$(...)`)
# execute as script code the moment this line runs.
$InputPathRaw = @'
INPUT_PATH
'@
[System.IO.File]::WriteAllText((Join-Path $PWD 'graphify-out\.graphify_root'), (Resolve-Path $InputPathRaw.Trim()).Path, $Utf8NoBom)
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent block, run Python through the saved interpreter — `& (Get-Content graphify-out\.graphify_python)` in place of a bare `python3` — so every step uses the interpreter that actually has graphify.**
### Step 2 - Detect files
```powershell
@'
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
print(f'Detected {result["total_files"]} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```powershell
@'
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('INPUT_PATH'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
print('No code files - skipping AST extraction')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
#### Part B - Semantic extraction (parallel subagents)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
```powershell
@'
import json
from pathlib import Path
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
```powershell
@'
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
# Only content files go to semantic extraction. Code is already covered structurally
# by the AST pass (Part A); flattening every category here makes subagents re-read
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
else:
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
**Step B2 - Dispatch ALL subagents in a single message**
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```powershell
$PROJECT_ROOT = (Get-Location).Path # cwd — where Part C globs graphify-out\ (NOT .graphify_root/scan dir, #1392)
# Then for chunk N: $CHUNK_PATH = Join-Path $PROJECT_ROOT "graphify-out\.graphify_chunk_0N.json"
```
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```powershell
@'
import json, glob
from pathlib import Path
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text(encoding="utf-8"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
```powershell
@'
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding="utf-8").splitlines() if line]
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH')
print(f'Cached {saved} files')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```powershell
@'
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Clean up temp files: `Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```powershell
@'
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
```powershell
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 4.5 - Graph health check (read-only integrity gate)
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
```powershell
@'
import json
from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
('missing_endpoint_edges', 'missing-endpoint edges'),
('self_loop_edges', 'self-loop edges'),
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
) if summary.get(k, 0)]
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```powershell
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
# Re-export so graph.json nodes carry the curated community_name (#2490).
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
# if it still refuses, surface the guard message - do not force past it.
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
print('Report updated with community labels')
'@ | & (Get-Content graphify-out\.graphify_python) -
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```powershell
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```powershell
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```powershell
@'
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
# so the on-disk manifest is portable across clones/machines and a later --update
# matches cached files instead of missing every one (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
# a detected file whose chunk failed or was omitted must stay unstamped so the
# next --update re-queues it, otherwise it is marked done and its content is lost
# forever (#2015). This mirrors the library extract path exactly
# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
# raw corpus. Code files are always stamped (AST is deterministic); only semantic
# types are gated on output.
from graphify.cli import _stamped_manifest_files
_corpus = detect.get('all_files') or detect['files']
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding="utf-8"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
'@ | & (Get-Content graphify-out\.graphify_python) -
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json
Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction SilentlyContinue | Remove-Item -Force
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```powershell
if (-not (Test-Path graphify-out\.graphify_python)) {
$GRAPHIFY_PYTHON = $null
$graphifyCmd = Get-Command graphify -ErrorAction SilentlyContinue
if ($graphifyCmd) {
# The interpreter that owns the graphify entry point sits next to it
# (<env>\Scripts\python.exe for uv tool, pipx, and venv installs).
$py = Join-Path (Split-Path $graphifyCmd.Source) "python.exe"
if (Test-Path $py) { $GRAPHIFY_PYTHON = $py }
}
if (-not $GRAPHIFY_PYTHON) { $GRAPHIFY_PYTHON = "python" }
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
& $GRAPHIFY_PYTHON -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
}
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```powershell
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
## Troubleshooting
### PowerShell 5.1: Vertical scrolling stops working
If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue:
1. **Upgrade graphify**: `pip install --upgrade graphifyy`
2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly
3. **Reset your terminal**: close and reopen PowerShell
4. **Skip Leiden**: uninstall its backend (`pip uninstall graspologic` on Python < 3.13, `pip uninstall graspologic-native` on Python 3.13+) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.

View file

@ -0,0 +1,56 @@
# graphify reference: add a URL and watch a folder
Load this when the user ran `/graphify add <url>` or passed `--watch`. Neither is part of the default build.
## For /graphify add
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
try:
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
print(f'Saved to {out}')
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
---
## For --watch
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
$(cat graphify-out/.graphify_python) -m graphify.watch "$(cat graphify-out/.graphify_root)" --debounce 3
```
This watches the same folder graphify extracted, read from the trusted `graphify-out/.graphify_root` that Step 1 resolved - there is no path to substitute, so a scan root containing shell metacharacters can never be re-interpreted here. Behavior depends on what changed:
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
Press Ctrl+C to stop.
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.

View file

@ -0,0 +1,87 @@
# graphify reference: extra exports and benchmark
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag.
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
graphify export neo4j
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
```
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag)
**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact:
```bash
graphify export falkordb
```
**If `--falkordb-push <uri>`** - push directly to a running FalkorDB instance. Credentials are optional; ask the user only if the instance requires auth:
```bash
graphify export falkordb --push falkordb://localhost:6379
```
Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
```bash
$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`:
```json
{
"mcpServers": {
"graphify": {
"command": "<absolute path from: cat graphify-out/.graphify_python>",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
graphify benchmark
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.

View file

@ -0,0 +1,70 @@
# graphify reference: extraction subagent prompt
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```

View file

@ -0,0 +1,46 @@
# graphify reference: GitHub clone and cross-repo merge
Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph.
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
**Single repo:**
```bash
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
# Use LOCAL_PATH as the target for all subsequent steps
```
**Multiple repos (cross-repo graph):**
```bash
# Clone each repo, run the full pipeline on each, then merge
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
# Run /graphify on each local path to produce their graph.json files
# Then merge:
graphify merge-graphs \
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
--out graphify-out/cross-repo-graph.json
```
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
**Multiple local subfolders (monorepo or multi-service layout):**
The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path:
```bash
graphify extract ./core/ # → ./core/graphify-out/graph.json
graphify extract ./service/ # → ./service/graphify-out/graph.json
graphify extract ./platform/ # → ./platform/graphify-out/graph.json
# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set
# Then merge at the project root:
graphify merge-graphs \
./core/graphify-out/graph.json \
./service/graphify-out/graph.json \
./platform/graphify-out/graph.json \
--out graphify-out/graph.json
```
Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate.

View file

@ -0,0 +1,33 @@
# graphify reference: commit hook and native CLAUDE.md integration
Load this when the user asked to install the post-commit hook or wire graphify into a project's CLAUDE.md.
## For git commit hook
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
```bash
graphify hook install # install
graphify hook uninstall # remove
graphify hook status # check
```
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
If a post-commit hook already exists, graphify appends to it rather than replacing it.
---
## For native CLAUDE.md integration
Run once per project to make graphify always-on in Claude Code sessions:
```bash
graphify claude install
```
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
```bash
graphify claude uninstall # remove the section
```

View file

@ -0,0 +1,311 @@
# graphify reference: query, path, explain
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
Two traversal modes - choose based on the question:
| Mode | Flag | Best for |
|------|------|----------|
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8')
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392)
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
subgraph_edges = []
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
subgraph_edges.append((node, neighbor))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_edges.append((n, neighbor))
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
"
```
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting):
- `useful` — the cited nodes answered the question well (they become *preferred sources*).
- `dead_end` — the question/path led nowhere; don't re-derive it next time.
- `corrected` — the saved answer was wrong; `--correction` records what was right.
At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing.
---
## For /graphify path
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```

View file

@ -0,0 +1,52 @@
# graphify reference: transcribe video and audio
Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command.
**Step 2 - Transcribe:**
```bash
export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported)
export GRAPHIFY_WHISPER_PROMPT="<the one-sentence domain hint you composed in Step 1>"
$(cat graphify-out/.graphify_python) -c "
import json, os, sys
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper
# print progress to stdout, which would otherwise corrupt the JSON file (#1392).
Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\")
print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr)
"
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, `export GRAPHIFY_WHISPER_MODEL=<name>` (it must be exported, not just assigned) before running the command above.

View file

@ -0,0 +1,210 @@
# graphify reference: incremental update and cluster-only
Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file.
## For --update (incremental re-extraction)
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
'files': r.get('new_files', {}),
'all_files': r.get('files', {}),
'total_files': r.get('new_total', 0),
'total_words': r.get('total_words', 0),
'skipped_sensitive': r.get('skipped_sensitive', []),
'needs_graph': True,
}, ensure_ascii=False), encoding=\"utf-8\")
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
"
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.build import build_merge
from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add `changed` here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else
# False. Without it a --directed --update silently rebuilds undirected and collapses
# reciprocal A<->B edges (#1392).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
merged_out = {
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
'edges': [
# Explicit source/target last so they win over any stale attrs in d.
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
for u, v, d in G.edges(data=True)
],
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
# and new_extraction (build_merge combines them). Falling back to
# new_extraction only would silently drop prior-run hyperedges (#801).
'hyperedges': list(G.graph.get('hyperedges', [])),
'input_tokens': new_extraction.get('input_tokens', 0),
'output_tokens': new_extraction.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest so next --update diffs against today's state, not the
# prior run's baseline (prevents ghost-node reports on subsequent updates).
# root= matches the build_merge call above so the manifest keys stay relative to
# the scan root — portable across clones/machines, so --update keeps matching
# cached files instead of missing every one after a move (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output
# THIS run (new_extraction is this run's fresh extraction, read above before the
# merge overwrote the file): a changed doc whose chunk failed must stay unstamped
# so the next --update re-queues it, otherwise it is marked done and its content
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
G_new = build_from_json(new_extract, directed=IS_DIRECTED)
if old_data:
G_old = json_graph.node_link_graph(old_data, edges='links')
diff = graph_diff(G_old, G_new)
print(diff['summary'])
if diff['new_nodes']:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
Clean up after: `rm -f graphify-out/.graphify_old.json`
---
## For --cluster-only
Skip Steps 1–3. Re-run clustering on the existing graph:
```bash
graphify cluster-only .
```
`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual.

4
.gitignore vendored
View file

@ -31,4 +31,6 @@ server/uploads/
server/clips/
# skills
graphify-out/
graphify-out/
# skill links into .agents/skills (installed from skills-lock.json)
.claude/skills/design-taste-frontend

View file

@ -35,11 +35,14 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. Short links `/go/<id>` (Data → Links/redirects, `server/src/routes/redirects.js`) count clicks, report each to Plausible as a pageview and add the link's UTM tags: `docs/redirects.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
- Present remote: a presenting screen (`/events/:id/present`) shows a code; a phone at `/remote/<code>` steps, pauses, jumps and changes its setup, anyone with the code (`server/src/routes/present.js`, `src/pages/PresentRemote.tsx`). Server-sent events held in memory (one process); the API sends `X-Accel-Buffering: no`, so nginx needs no block of its own.
- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`.
- Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`.
- 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 +64,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 +86,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.

380
TODO.md Normal file
View file

@ -0,0 +1,380 @@
# TODO
- Instructions for this document: update it as things are completed, moving items from TODO to Done under the same category. Develop content here based on conversations. Leave the categories blank in Part 1: TODO when you are moving items out of them to Done.
- Status: everything up to v1.8.3-video-mgmt is tested and deployed. PR #14 (branch `audit`, v1.9.0 to v1.9.4-audit) was merged into main on 2026-09-29 (adc88e5). Branch `content-display` was merged as PR #15 (v1.9.5 to v1.9.11, 2026-09-29) and PR #16 (v1.9.12 to v1.9.14, 2026-09-30, c76df02). All of it is deployed and checked in a browser (2026-09-30). The design overhaul (PR #18, v1.10.0 to v1.10.2) and the revised palette (PR #19, branch `palette-test`) were merged into main on 2026-09-30 (6f86a11); not deployed yet. Branch `page-updates` (v1.10.3 to v1.10.6) was merged into main as PR #20 on 2026-10-01 (3e4a725); not deployed yet. Branch `page-fixes` (v1.10.7 to v1.10.10) was merged as PR #21 on 2026-10-01 (0bb4b86); not deployed yet. Back up the database before deploying (migrations 056 to 059: 056 and 057 rebuild content_blocks, 058 page_sections, 059 recreates v_events). Branch `audit-3` (v1.11.0-audit) is open as PR #22; branch `audit-ui` (v1.11.1-audit, on top of it) as PR #23; branch `newsletter-layout` (v1.11.2-newsletter, on top of that, migration 060) as PR #24.
---
# Part 1: TODO
- Items from notes.txt (2026-10-16). Each has questions under it: tick one when it's settled, or write the answer after "Answer:".
## Pages
- [ ] **Resources page by audience**: frame the page as For Young Adults, For Ministries, For All.
- [ ] 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**: 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:
- [ ] Is the Metaphysical Bible Dictionary free to republish (public domain edition), or only linked? Answer:
- [ ] **The Acronym Dictionary**: a page of acronyms (Unity, New Thought, NGU).
- [ ] A page of its own, or a part of the Library? Answer:
- [ ] Each entry: acronym, meaning, a short description, a link? Anything else (category, related org)? Answer:
- [ ] Who adds entries: admins in Data, or anyone through the request form? Answer:
- [ ] Do you have a starting list to import? Answer:
- [ ] **Retreat content index**: ideas and content from retreats, which event each was featured at, tabs for the major pillars, a table of contents to fill out (borrowed from YOU history). Also retreat templates.
- [ ] What are the major pillars (the tab names)? Answer:
- [ ] What is one entry: a talk, an activity, a theme, a workshop? Its fields (title, description, files, presenter, event)? Answer:
- [ ] Where does the YOU history version live, so I can see what to borrow? Answer:
- [ ] Public, or for retreat teams only? Answer:
- [ ] How does the feedback form fit: a form per retreat linked to its entries, or feedback shown on entries? Answer:
- [ ] Retreat templates: documents to download (Drive files), or a "start a new retreat from this one" copy in the admin? Answer:
- [ ] **Centralized scholarship and donor giving page**: one page for scholarships and giving.
- [ ] Does giving stay on Church Center (embeds), with this page gathering them, or something else? Answer:
- [ ] What is "etc.": scholarships, the Catalyst Fund, general giving, per-event giving? Answer:
- [ ] Do scholarships need an application (a form like /request), or only a description and a link? Answer:
- [ ] Show donors or totals (eg. a goal bar), or none? Answer:
- [ ] **Website changelog**: the site's construction as an evolving blog post, tabs marking each update.
- [ ] One blog post with a tab per version, or a blog post per version under a "Website updates" tag? Answer:
- [ ] Written by hand, or started from the tags and TODO.md Done list (then edited)? Answer:
- [ ] Does it go back to v1.0, or start from now? Answer:
- [ ] Linked from the footer next to the version, or only in the blog? Answer:
## Sections
## Page Features
- [ ] **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:
- [ ] 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:
- [ ] **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.
- [ ] **Listen to a page**: a screen reader or compiled audio for certain pages.
- [ ] The browser's own voice (free, reads the Reading mode text, sounds robotic), or recorded/generated audio files (better voice, has to be made for each page and kept current)? Answer:
- [ ] Which pages: blog posts, History, Organization, all? Answer:
- [ ] A Listen button in the Accessibility panel, or on each page by its title? Answer:
## Mobile
## Page Editing
- [ ] **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
- [ ] **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
## Tools
## Content
- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post.
- [ ] A newsletter part of its own (picks organizations, shows logos), or a blog post the newsletter links to? Answer:
- [ ] **Blog posts to write** (content, not code):
- [ ] The Catalyst Fund.
- [ ] How churches can engage with young people, through social media: what tools they use.
- [ ] Aidan's ultimate guide: church management systems, donor engagement platforms, free tools for nonprofits, nonprofit technology, AI (its benefits, and using tools ethically).
- [ ] Should any of these come out as a series (a tag), or one at a time? Answer:
## Production cleanup
## Audits
## Future
- Timeline vine/tree SVG (you'll provide it); until then the timeline is solid teal dots on a teal rail, one color throughout.
- Legal check of the Privacy Policy and Terms for NGU's state and nonprofit status (wording read 2026-09-28, fine for now).
- Enforce the Content-Security-Policy after watching its reports on the server (`journalctl -u ngu-api | grep csp`, `docs/security-headers.md`).
- Potentially make new vertical nav circle a sun svg later on.
- Poetry Builder, need to import the metaphysical bible dictionary and virtue list.
---
# 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.
- [ ] Check in a browser: the partner cards with and without logos (light, dark); framing a portrait into a square and a wide photo into 16:9, Upload as is, Cancel, and a PNG keeping its transparency.
- [x] **Content blocks: Shown in** (migration 071): The page, The card only, or The card and the page. A card block used to show on the page too without saying so; every existing card block became "both", so nothing moved. Pages no longer print card paragraphs separately; a "both" block comes with the page's blocks, in its place in the list.
- [ ] Check in a browser: an event with a "both" paragraph (on its card and page) and one with "card only" (card, not page); an organization, team and person page still show their text.
- [x] **Group pages**: the facts at the top sit in a framed card (City, Part of <name> Region, Ministry, Meets, Since, tags); email buttons go to the link's URL, not its label (`splitLinks` took the label); every website and email row is listed with its own label, not only the first.
- [x] **Tags** (migration 070): Data → Tags (Online and In-Person to start) replace the Online checkbox on organizations and events. Records ticked Online got the Online tag (nothing got In-Person). The tag with URL ID `online` still makes an event online (calendar filter, place line, search data) through `v_events`. Tags show on the record's page and on group entries in the Community map list and grid; the map no longer keeps online groups off their state's tile.
- [ ] Check in a browser: a group page's facts card (light, dark, reading mode), two emails and two websites, tags on a group and an event, the Tags list in Data, and the calendar's Online filter still working.
- [x] **Schedule presentation** (digital signage): an event page's schedule block has a Present button (everyone) opening `/events/<id>/present` in a new tab. A setup screen picks the days and entries and the seconds for each kind of slide (day overview, entry spotlight with the person's photo and name beside the entry, graphics, map images; 0 leaves one out); Play goes full screen and loops, the parts of each slide animating in, a bar showing the time left. The settings are in the address (bookmark it on a signage screen; `play=1` skips setup). Arrows step, Space pauses, S returns to setup; the screen is kept awake where the browser allows. Not by the clock: it loops what was picked.
- [x] **Map image on schedule entries** (migration 069): an entry's own map picture, shown in its fold-out in place of the Google map (the "Open in Google Maps" link stays when a place is set) and as a slide in the presentation.
- [ ] Check in a browser: the Present button, setup, each slide kind (light and dark, a long day of 9+ entries in two columns), full screen on the signage device, and a map image in the fold-out.
- [x] **Group map** (Community): hovering a state outlines it in ink while its region stays lit; the list puts each region's groups under their state's subheading, each entry a raised card; the region's list of states is gone from the list (its map note stays); the list no longer scrolls on hover, only on click (a state goes to its subheading, or its region when it has no groups; a legend region to that region).
- [x] **Side nav pill** too tall when the window narrows (Community): the pill (straight sides, round ends) was sized as an ellipse, about three times the list's height; it's sized as the pill now.
- [x] The "Hide past events" button was clipped at the bottom when it grew on hover: the event cards' root wrapper was `overflow-hidden`; it is `overflow-x-clip` now (the carousel still can't spill sideways).
## v1.13.1-data (branch `data`, merged as PR #28, 2026-10-06, 970730d; migrations 065 and 066, the consolidated baseline, then 067 and 068, back up the database before deploying; not checked in a browser yet)
- [x] Newsletter: a new draft's Coming Up "Pick from" showed "events no longer exists". Events is that select's blank choice, so new drafts now leave the source blank and older drafts' `events` loads as blank.
- [x] **Frame from a video**: a video featured card's Image field has "Frame at" (a typed time, prefilled from the link's `t=`); the server takes that one frame with yt-dlp and ffmpeg and saves it to `/uploads/thumbnails/` as the card's picture (`POST /api/admin/video-frame`, editors and up). Choosing any other picture already worked through the same field. Not tested end to end yet: needs yt-dlp, which is on the VPS but not the dev machine.
- [x] **Plausible reports to Discord** (migration 065): daily (yesterday) and weekly (Mondays, last 7 days with the change from the week before), each switched on in Panel → Site settings → Reports; sent at 8:00 America/Chicago. Needs `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` on the ngu-api service (`PLAUSIBLE_URL` if Plausible isn't on 127.0.0.1:8000). Try it with `node src/analyticsReport.js daily`. Tested with a stubbed Plausible only.
- [x] **Captions for uploaded videos** (migration 066): video blocks have a Captions field and the hero a Video captions field, each taking a WebVTT (.vtt) upload (kept as is, in `/uploads/captions/`), drawn as `<track kind="captions" default>` on a video file (WCAG 1.2.2). Embeds bring their own. Needs `text/vtt vtt;` in nginx's mime.types if it isn't there (`docs/media-uploads.md`, step 5).
- [x] **Migrations consolidated** into `066_schema.sql` (generated from the live v66 schema, checked identical: 136 objects, every table's columns) and `066_seed.sql` (single rows, event scopes, home sections, the five site pages and their sections, the Musicians tag; the hero words, paths, stats and the Organization address and tax ID are no longer seeded). A database at v66 skips both; one below v66 is refused. **Deploy order:** production is below v66, so deploy 33be618 (the last commit with the old files) first, let it migrate to v66, then deploy this.
- [x] **Partners section picks its organizations** (migration 067): the organization cards preset (Community → Partners) has "Cards: list" (Partners by default, Ministries, or both, every published, listed one by name) and an optional hand-picked "Cards: organizations" list (partners or ministries, in order, published ones, listed or not) that replaces it. Ministry cards link to their website only (no page). `/organizations` now takes `kind=ministry` and `ids=`.
- [x] **Links/redirects** (migration 068): Data → Links/redirects makes short links, `/go/<URL ID>`, for the newsletter. Each click is counted (Clicks, Last click on the list), sent to Plausible as a pageview of `/go/<URL ID>`, and redirected with the link's optional UTM tags added. Editors and up. `docs/redirects.md`.
- [x] Newsletter: Save as a new draft beside Save draft; a Title color; every part color is a color picker (any hex, or none) instead of the palette dropdown.
- [x] Region pages no longer show the raw domestic/international scope.
- [x] Keywords question (2026-10-04): Google has ignored `<meta name="keywords">` since 2009, so nothing to add. What counts is the words on the page: titles, headings and descriptions, which `pageMeta.js` already fills per page. The Google side is Search Console, which shows the searches the pages appear for.
## Pages and Data (branch `data`, merged as PR #27, v1.13.0-data, 2026-10-04, 3b45944; migrations 062 to 064, back up the database before deploying; not checked in a browser yet)
- [x] **Musician directory, as people tags** (migration 062): Data → People tags lists what people can be tagged as (Musicians seeded); a person's Directories repeater tags them, and their new Specialty line ("Vocals, piano · Gospel, folk") shows on their tile in a directory, with their links in the details panel. A People directory section preset (Community, Resources, Organization) shows a tag's first 12 and links to its full page, `/directory/<tag>` (eg. `/directory/musician`), titled and indexed like any page. Another directory (Speakers) is a new tag, no code.
- [x] **Ministry organizations** (migration 063): a new organization kind for Unity ministries. A group picks its ministry (Group → Ministry), and its page says "Ministry: <name>", linked to the ministry's website link when it has one. Ministries have no page, list, sitemap entry, timeline entry or 404 suggestion on the public site, and aren't offered where a record links to its organization (event hosts, teams, awards, roles, home organization, featured cards, timeline).
- [x] **Organization contacts and the recipient export** (migration 064): Data → Contact types holds the roles you make (none seeded); each organization has a private Contacts repeater (type, name, email, phone; editors and up only). Tools → Newsletter → Recipients filters them by contact type, organization kind, region (the region and its groups) and published, previews the matches and downloads a CSV for Mailchimp (Email, First Name, Last Name, Phone, Organization, Kind, Region, Contact type). A type still in use can't be deleted.
- [ ] Check in a browser: tag a person, the directory section and page (light, dark, reading mode), a group's ministry line, contacts on an organization (as a viewer too), the export and its CSV.
## Accessibility, second round (branch `accessibility`, merged as PR #26, v1.12.1-accessibility, 2026-10-03, 07e56bf; not checked in a browser yet)
- [x] **Reading mode rebuilt** (`src/components/ReaderView.tsx`): the page as text only, headings, paragraphs, links and pictures with a description, in one column, with a line of links to the site's pages at the top. No header, footer, backdrop, buttons, cards or forms; the accessibility button stays, to turn it off. The real page still renders, hidden, and the reader writes out what it drew, again whenever it changes, so every page works without a version of its own. A card that is one link gives its heading the link; a button that opens something (a person's tile, a schedule row) keeps its words as a line; carousel copies and decorative pictures (empty alt) are left out.
- [x] **Color blind modes cover the whole site**: each mode now replaces all three color families (teal, green, amber), not just green, with sets picked by simulation (each family's darkness can differ, since a red-green color blind eye sees one blue to yellow line plus light and dark). The closest pair goes from 11.4 to 27.9 (protanopia), 19.5 to 24.7 (deuteranopia) and 6.4 to 21.1 (tritanopia); every theme token still meets 4.5:1 in light and dark mode. The theme tokens, the backdrop circles, the side nav circle, the header and menu, the hero, the stats band and data colors all follow (`--pal-*` variables in index.css, `SWAPS` in color.ts).
- [x] **Reading mode spacing and width**: words from parts the page draws on their own lines (a name above a title, a flex row's items) no longer run together; the column is 60rem (was 42rem) and headings are bold, in the display face.
- [x] **Front page in reading mode**: bands the reader can't read well draw a text version of their own (`useReadingMode()`): the numbers, one line each ("1,200+ Members"), no longer stuck at 0 (the count waited for the band to scroll into view, which the hidden page never does; reduced motion now shows them at once too); the calendar, the next six weeks from today as a list (date, linked title, time, type, place) on any page that has one; the featured cards, each a linked heading with its words, a video card linking to its video. The countdown is left out, since the retreats band shows that event.
- [x] **Reading mode, every page and section** (audited section by section): the reader itself now reads an icon-only link's aria-label, puts a card's link on its first line or picture when it has no heading, gives each item of a row of facts or link buttons its own line, keeps line breaks, skips what CSS hides (a blog post's print-only footer), turns a form into one line saying it can't be used there, shows empty table cells as "-", and keeps section and heading ids so #links land (side nav, a post's contents). What it can't read draws its own text version (`useReadingMode()`): the hero (its words, buttons, every slide's caption, livestream and video links), the pathfinder (every path and its actions), the front page history (linked entries), event lists (every event, past ones too, no carousel), the org lists and groups map (every region and all its groups, linked), the history timeline (every year open, upcoming too), schedules (every day, fold-outs included), people tiles (everyone, with their details) and videos (a link). Heading levels fixed where cards repeated their section's level; org names are linked headings; Team pages lose their doubled "Members"; Giving links the treasurer's email.
- [x] **Local groups map fits a phone**: it scales to the column's width instead of holding 34rem and scrolling sideways.
## Navigation (branch `accessibility`)
- [x] **No fixed back links on record pages**: a group, region or partner page no longer ends its facts line with "All groups" (and so on), and a team page no longer says "Back to <org>" (its "A team of" link stays); records are reached from many pages, so the browser's back is the right way back. Not-found pages keep their link, having nowhere else to send a visitor.
- [x] **Side nav label on its circle, dark mode**: the lit label was its accent mixed halfway to white, which for the deep teal (Unity Regions) left 4.2:1 on a circle of the same teal. Labels now use `--nav-text-mix` (30% in dark mode): 6.8:1 or better for every accent.
## Accessibility (branch `accessibility`, merged as PR #25, v1.12.0-accessibility, 2026-10-03; not checked in a browser yet)
- [x] **Plausible analytics**, self-hosted behind nginx at `/pa/`: the API adds its script to every page (`analyticsTag`, `server/src/pageMeta.js`), counting under site.json's url hostname, so dev and live report separately.
- [x] **Accessibility panel:** the switches' knob stays in its track (an absolute child of a `<button>` with no `left` started from the centered content). The panel comes after its button in the page, so Tab goes into it, and opens on its first switch; each switch reads its help line.
- [x] **Reading mode** is now the page as plain text: one 42rem column, ink on white (or white on near-black in dark mode), every color, background, border, shadow, picture, video, map and decoration gone, controls outlined, links underlined, no motion (JS scrolls, the hero slideshow and the stats count-up too, `src/lib/motion.ts`). A picture or video with a description leaves "Image: ..." in its place (`data-reading-alt`, set by the panel).
- [x] **Color blind mode** (Protanopia, Deuteranopia, Tritanopia, Monochrome), a select in the panel that reloads the page. Simulated with the Machado (2009) matrices, green and amber blur together for protanopia and tritanopia, so there the green family becomes violet (same contrasts; the closest pair of families goes from 11.4 to 17.4 and from 6.4 to 21.6 in CIELAB). For deuteranopia the palette already stays apart and is kept. In all three, a color picked off the palette snaps to the nearest palette shade. Colors from the database are swapped as they arrive (api.ts, never under /admin), colors from code through `visionColor` (color.ts), CSS through the `--green-*` variables (index.css). Monochrome is a grayscale filter on the root.
- [x] **Audit fixes:** the fixed header no longer covers what's focused or jumped to (`scroll-padding-top` from `--header-h`, now on the root; the per-section offsets it replaces are gone). A new page moves focus to its content; closing the phone menu returns focus to its button; Escape closes a desktop dropdown. In-page jumps (section nav, a post's contents, #links) move focus with the scroll (`jumpTo`, `src/lib/focus.ts`). Carousel arrows stay focusable at the ends. Calendar: canceled bars say so to screen readers; a day's list takes focus and gives it back to the day on Close. Thank-you messages, a started video, the livestream and a schedule map take focus (`focusOnMount`); closing a person's details returns to their tile. The countdown's ticking digits are out of its link name, and its title wraps instead of being cut. Wide tables scroll from the keyboard. Map tiles with groups are buttons for the keyboard. Request form radio errors and required fields are tied to their inputs. Admin: field errors, help and required marks reach screen readers; search boxes, the role select, the color picker and the two picker dialogs have names; the section nav's error dot says "needs attention".
- [x] **Calendar window** (from the third audit): the calendar asks `/events` for only the six weeks on screen (`?from=&to=`, undated events and open-ended series included), keeps the last month up while the next loads, and fetches from the month's end on only when a month is empty, to offer the jump to the next event. Carousels ask for only their 12 most recent past events (`?past=12`); the grid's past list still pages through them all.
- [x] **Event photo** (migration 061): events have two pictures. **Event photo** (16:9, with a description for screen readers) is shown whole at the top of the event's page, as the front page's featured event (its box is 16:9 now, was 16:7), on featured cards, in newsletter picks and as the share preview. **Card background** is only the faded background of the event's card again. Each event's photo starts as its card background, so nothing changes on screen until one is replaced. Sizes for both are in `Data Requirements.md`.
- [ ] Check in a browser, light and dark: the panel (Tab order, knobs, Escape), reading mode on the home page, a blog post and an event, each color blind mode (backdrop circles, side nav, footer links, event colors), the calendar paging months, the jump to the next event and the filters, a carousel's past events, keyboard focus after page changes and section jumps, the phone menu.
## Page fixes (branch `page-fixes`)
- [x] **Details & Contact is plain blocks** (migration 058): the address, tax ID and email preset is gone; Organization's Details & Contact section holds them as blocks (the address, the nonprofit line with the tax ID, an email button), edited like any section.
- [x] **Header dropdowns close after a click**: they opened on hover or on any focus inside, and a click leaves focus on the link, so the menu stayed open after the pointer left. Now only keyboard focus (:focus-visible) opens them besides hover.
- [x] **A circle behind the side nav**: a solid circle with a slight drop shadow in the light shade of the section being read (teal, green or amber; their darkest in dark mode), easing from one to the next as you scroll; each entry also takes its section's color when hovered or lit, centered on the list, which the nav's text reads on in both modes. It sticks with the nav as the page scrolls or grows, stays centered on the list however wide the screen, sits a little left of the list's center but never left of the "On this page" heading's center (centered on the whole list once its titles reach further right), shows above and below the list (clipped sideways only), keeps its right edge inside the nav column so it never covers content (a narrower window slides it off the screen's left edge instead), and, with the whole nav, sits in front of the section lines; "On this page" starts level with the first section's title (lower if the circle needs room to start a few pixels below the first line), and once scrolling the nav sticks just under the header, while its circle grows into a sun in the corner: centered on the header's bottom left, so a quarter of it shows, big enough to reach past the list (never wider than the nav column), easing between the two. Held narrower than that by the window, it stays centered on the header's edge (so below the header it only curves inward) and becomes a quarter ellipse, as tall as it takes to cover the list. At rest it keeps 16px clear of the section's edge and becomes an ellipse too for a tall list. Both cover the longest list a page may have, 10 sections of two-line titles; for that, the side nav now shows from 1536px (2xl) up instead of 1408px (narrower, the list is as wide as its column and nothing inside it can cover it).
- [x] **Side nav no longer shifts the sections**: it sits in the left margin beside the content instead of taking a column, so sections stay centered where they'd be without it. It shows on screens 1536px (2xl) wide and up, where the margin fits it and its circle (titles wrap onto a second line); narrower, the header's dropdowns list the sections.
## Page editors, navigation and tools (branch `page-updates`, after v1.10.5)
- [x] **Page editors with sections** (9daf7b1, migration 056): Pages → Retreats, Community, Resources, Organization, History. Each page is a list of sections, each with a title (30 characters at most, so it fits the side nav; the editor says so), URL ID, blurb, accent, its own content blocks, and an optional preset drawn under the blocks: Community blog, local groups map, Unity Regions list, partner cards (Community); event carousel or grid with scope, type and first view (Retreats); timeline (History); address, tax ID and email (Organization). Every page was seeded as it looked. Organization's Details & Contact is its third section; Volunteering became a heading, paragraph and link buttons at the end of Leadership. The Community blog's settings (slots, pinned posts, feeds) are in the Community editor; its heading and blurb are its section's. The header dropdowns, footer site map and side nav follow each page's sections. The admin engine now saves nested collections to any depth (page, sections, blocks, items).
- [x] **Timeline entries under Data** (4a1d6fd).
- [x] **Navigation** (4a1d6fd and this branch): the footer site map spans the full width; section divider lines run behind the side nav; the side nav fits 30-character titles; front page section headings fit about 60 (noted in its editor); Home has no dropdown in the header.
- [x] **Newsletter drafts** (migration 057): Tools → Newsletter saves drafts (title, intro, blocks, picks, footer) to open again later, adds content blocks written for the issue (those an email can show), an editable footer (blank: the site's name and address; no unsubscribe link, Mailchimp adds one), and Post as blog post, which makes an unpublished post (intro, blocks, then each section's picks as link cards) and opens it in the post editor.
## Entity pages and pages (branch `page-updates`)
- [x] **Cleanup** (43797f3): removed the old-data fixes, since nothing before them was public: the /leadership redirect, the "ngu-" browser key move, the boot-time image sorter, and emoji path icons (migration 055 turns the seeded emoji into named icons). Kept on purpose: OrganizationDetail's redirect from a wrong-kind URL (/groups/x for a region) to the right one, and the migrations' own data rewrites (they already ran).
- [x] **Organization page editor** (43797f3): Pages → Organization page. Mission blocks; Leadership heading, blurb and blocks (eg. a People block for the Board of Trustees, then one for the Retreat Team, in that order); Volunteering title, blurb and links under the leadership. The page reads only from this editor now (not the NGU organization record).
- [x] **Navigation** (ed0f120): the second strip is gone; each top link drops down its sections on hover or focus. Retreats, Community, Resources, Organization and History have a sticky "On this page" column from lg up (the admin editors' SectionNav). Home's sections everywhere follow the front page's visible bands, in order, under their headings. Resources now comes before Organization in the nav and footer.
- [x] **Mobile** (a907a47, 8d319bc): surveyed every public page at 320 to 430px and fixed what was cut off or hard to use. Menu scrolls to its top when tall; page titles and the hero headline size down and wrap; hero buttons stack, slide controls are 40px; the retreat carousel has phone-sized cards, arrows beside the dots, 40px dots and swipe; the narrow event card's logo row restored; people tile details stay on screen and tiles keep 60% of their width; the community map scrolls sideways at a readable size; group and org cards, schedule rows, stats numbers, timeline rail cards and the banner fit; long emails wrap; tap targets 40px; the accessibility panel sits above the privacy notice.
- [x] **Accessibility button** (177a650): a button at the bottom right of every public page opens two switches. Dyslexia-friendly font (OpenDyslexic, self-hosted, downloaded only when chosen); Reading mode (no background circles, motion or shadows, one column, larger text, underlined links). Remembered in the browser, applied before the first paint.
- [x] **Newsletter builder** (2a92697): Tools → Newsletter. Pick upcoming events, published blog posts and featured cards, add a title and intro, and copy email-ready HTML or plain text (or download it) for Mailchimp, Gmail or Church Center. Nothing is sent or stored. The header is the site name in type, since email clients don't show the SVG logo; a PNG logo could go there later.
- [x] **People tiles, one row** (01de627): a whole list (leads and members) shares one row when it fits with tiles at three quarters of full width or more, 10 at most; a board of 7 is one row at normal width.
- [x] **Privacy** (this branch): Giving links ngu.churchcenteronline.com (the address the site uses; the TODO said ngu.churchcenter.org) and says Church Center's script loads with the Giving page and may use Google Analytics in its form; Cookies says the site uses self-hosted, cookieless Plausible and not Google Analytics. Last updated September 30, 2026.
- [x] **People blocks** (7c7cdaa, migration 054): a "People" content block shows a team's members as people tiles, people picked one by one (each with a title), or both.
- [x] **Host teams** (7c7cdaa): an organization host can name a team (any organization's) to show in its place; the event page reads "Hosted by" the team, linked to its page.
- [x] **Organization page** (499662b): Leadership is now Organization, at /organization (/leadership 301s there). Mission, Vision & Values come from the NGU organization record's description and content blocks (Data → Organizations → NGU); Leadership is that record's teams with their people; Details & Contact has the address, nonprofit status, email and the record's contact links. Add the mission text and the teams (Board of Trustees, Retreat Team, Committees & Volunteers) on that record.
- [x] **404 page** (79c4b24): suggests the closest pages and records to the address (typos, old /chapters/ links), then the main pages.
- [x] **Request form wording** (this branch): short field titles with a help line; "Short description" for a post's card; the Files note says why to send a .docx.
- [x] **Cross-browser** (design): the backdrop parallax checked in Firefox and Chrome/Safari.
## Design (branch `design-overhaul`)
- [x] **Revised palette** (PR #19, 79f1d09): teal, green, amber and ink, four shades each (main, darkest, light, lightest), as the theme defaults in both modes; the old grid's literals mapped over, the hero's filled button amber. Every text pair passes 4.5:1.
- [x] **Overhaul fixes, third batch** (a397f3e to 2df908f, not yet tagged):
- Admin: header, strip and footer as wide as the content; white (surface) background in light mode, the page ink in dark; home cards alternate teal and green, with a shadow.
- `tint-soft` is a faint teal again (#e8fcfe / #00252b), not green; it's the hover and faint-panel color everywhere.
- Cards sit on a new raised surface (`bg-raised`: white, or a touch of tint in dark mode) with a shadow: featured cards, the connect block, people tile captions, the timeline's featured entries.
- Buttons: a small plain radius everywhere (superellipse removed).
- Video stills: YouTube's 16:9 frame (no black bars; the 4:3 one cropped as a fallback), small rounded corners, a round centered play button shown on hover or keyboard focus (always on touch screens).
- People tiles: rows balanced between 2 and 10 across, avoiding a lone tile on the last row where the width allows.
- Map tiles and region tags are solid, dimmed by color instead of transparency; map tiles are square.
- Backdrop: 16 circles in four parallax layers, all slower than the page, the back ones visibly moving on long pages; a different seeded arrangement per page; tone changes only at a new top-level section, easing over 2.4s. Text passes 4.5:1 however many overlap.
- Timeline: the rail is brown wood; decade numbers are tags off the rail on a short slanted branch, colored like their decade's leaves; featured entries and rosters are solid, not see-through.
- Cross-browser findings: the site needs Chrome/Edge 111+, Safari 16.4+, Firefox 128+ (Tailwind v4's own floor: color-mix, cascade layers). Everything else used (container queries, dialog, inert, line-clamp, ResizeObserver) is supported there. One gap: the backdrop's parallax uses scroll-driven animations, which Firefox doesn't have yet (Chrome/Edge 115+, Safari 26+); in Firefox the circles stay still, which is fine but flat. Done: option 2, a Firefox fallback (a passive scroll handler writing --pb-y once a frame, same motion as the scroll-driven version). Still possible: a dev-only Playwright check that screenshots key pages in Chromium, Firefox and WebKit, light and dark (a new dev dependency), for a repeatable browser pass.
- [x] **Overhaul fixes** (v1.10.1, f37c093):
- Backdrop: two slow circles fixed to the window drift up as you scroll (CSS scroll-driven animation, still in browsers without it and under reduced motion); three sit down the page and move with their sections. No sideways movement. Text stays 4.5:1 or better even where three circles overlap.
- Featured cards and the connect section: 4px rules; video frames inset from the card edge.
- Calendar: the weekday row is a solid dark bar with white Poppins labels.
- History: decade numerals are dark tags on the rail instead of a white box.
- Notices: two thick corner brackets (top left, bottom right), no box or fill.
- People tiles: the frame is around the whole list; details open right under the tile (flipping to the tile's right edge near the screen edge) and close on Escape or a click elsewhere.
- Community: "Request a region update" and "Request a partner listing"; the region list no longer shows a group count.
- Palette suggestion (not applied): the current grid has three near-duplicate pairs (#5ce7ff/#5cf4ff, #c2f6ff/#c2fbff, #004552/#004c52) and no mid-tone for secondary text or warm accent. Suggested grid, darkest to lightest per family, every 600 step usable as text and under white text: Teal #003a45 #00748a #5cd3e6 #d6f5fa; Green #23361a #4a7431 #9cc47c #e6f0dd; Amber #4a2e00 #8f5b00 #f0bd4f #fdf1d6; Ink #001011 #3b5456 #a3b8b9 #f5f9f8.
- [x] **Overhaul** (d81f7bd to dd33ee2), following design-taste-frontend with your notes first:
- **Palette:** the 16-color grid is the site's default colors, light and dark (`themeDefaults.js`, `index.css`, `PALETTE` in `src/lib/color.ts`); every text pair passes the admin's 4.5:1 check. #008fa8 is for borders and decoration (3.8:1 as text), text and buttons use the grid's dark shades.
- **Corners:** none anywhere; buttons share one `btn` utility (Poppins Bold, superellipse corners where the browser has `corner-shape`, a small radius elsewhere). Dots stay round.
- **Fonts:** Poppins Bold for titles, headings and buttons, subheadings Poppins regular, body Montserrat. The stat numbers keep their weight.
- **Front page:** hero buttons are one cell split by a slash (filled left, clear right); the brand backdrop is flat teal with the dove (no rings, blobs or glow); the countdown straddles the hero and the next band; featured cards and the connect section are one continuous block with a teal rule between cells, the first featured card large with the next two beside it; the calendar is square; stats unchanged except its blurred glow.
- **Page background:** `PageBackdrop` draws flat overlapping palette circles behind every public page, shifting tone as each section reaches the middle of the window; sections no longer paint their own bands.
- **Footer:** Give sits right of the logo.
- **People tiles:** square photos, a 2px frame, even heights (two lines of name and title, then an ellipsis and the down arrow, whose details show it whole); no photo shows the initials on a palette color picked by the name.
- **Notices:** empty sections and form notes use the `notice` style (tinted panel, solid left bar) instead of dashed borders.
- **Timeline:** each year is a leaf, green now and turning gold then autumn going back, fully turned before 2000 (History page and the front page rail).
- **Admin home:** each group of cards has its own palette color.
- **No glow** anywhere: blobs, rings, the live-dot pulse and the stats glow are gone.
- [ ] Check in a browser, light and dark: every page, the backdrop's tone shifts, the split hero buttons (and on a phone), featured cards with 1, 2 and 3+ cards, the connect tabs, people tiles with long titles, the timeline leaves, the admin home. Superellipse corners show in Chrome and Edge; other browsers get a small radius.
- [ ] Production: any colors saved in Panel → Site settings → Colors still override the new defaults; clear them to get the palette.
## Deployed and checked (2026-09-30)
- [x] **Groups and US spelling (PR #17, v1.9.15-groups):** database backed up; migrations 052 and 053 ran; Drive folder renamed Requests/Groups; old links, admin text and the showcase records handled.
- [x] **Main (PR #14):** Node 22.13+ on the VPS; production nginx has HSTS, gzip and HTTP/2; migrations 037 to 043 ran; 640px copies made; Connect Nav emoji icons replaced with named ones.
- [x] **Content display (PRs #15 and #16):** database and uploads backed up; migrations 044 to 051 ran; nginx blocks for `/api/requests`, `/api/admin/files` and `/api/admin/import/docx`; Google service account, shared drive, Gmail and access groups set up.
- [x] **After deploying:** request emails set in Notices and tested; a test request made into a post; a PDF uploaded to Files and used in a link card; groups checked in the Panel; privacy contact email set in Site settings.
- [x] **Browser checks** in light and dark mode: every page, logos on dark, the new icons, the nav between 768 and 1024px, anchors, the hero headline, empty sections, the loading skeleton, Privacy and Terms, the data request form, the privacy notice, click-to-load embeds, Site settings → Colours, the Panel, the Request buttons and form.
## Front-end pages
- [x] **Chapters are groups** (38aff34, migration 052): kind `group`, table `groups`, pages at `/groups/<id>`, Community `#groups`, the front page count, the Request form type and `Requests/Groups`; the site's own chapter links in records rewritten. Names and prose written in the admin left as written.
- [x] **US English** (2ad65cd, migration 053): color, center, canceled, labeled and the rest, in UI text, help, comments, docs and names. Kept: the stored event status `'cancelled'` (shown as canceled), `aria-labelledby`, schema.org's `EventCancelled`, old migrations.
- [x] **Front page: Featured Content section** (d4f65d9, migration 030): add it under Front page → Sections; draws Front page → Featured cards.
- Three card types: a record on the site (title, picture and link fill themselves, anything typed overrides), a link ("Fetch preview" reads the page's title, description and preview image into the library), and a video (thumbnail with a play button; the player loads only when pressed).
- Cards are shared: `featured_cards` is owned polymorphically and `FeaturedCards.tsx` draws them, so the Community blog reuses both.
- [x] **Front page: featured event hero** (migration 033): Front page → Feature → "Featured event". The event's card beside the headline (photo or colour, title, theme, dates or schedule, place, tagline, action buttons, "Event details") under a "Featured event" badge. Front page → Featured event picks one; blank uses the countdown's event, and a pinned event that's over falls back the same way.
- [x] **Community page: Community blog section** (d374f9a, migration 031): first on the Community page, heading and blurb from the admin. Two halves, each pinned first then newest up to its slots: our posts, and community posts (pinned link/video cards, then the newest items from RSS/Atom feeds, read about every 30 minutes).
- [x] **Blog posts:** pages at /blog/<id> (no index page), content-block body, cover image, excerpt, date, tags, authors as person tiles (People records and/or a guest name and photo). Drafts until published; Listed works as everywhere else. Also on the QR page.
- [x] **Blog post PDF** (5dceeb5): print layout with author information, cover as a banner, the post's link and a QR code.
- [x] **Request form** (migration 046): one form at `/request` (footer link too), a tile per kind: blog post (new only), event, chapter, region (update only), partner, team, award, person; then new or update, a name, details, up to 3 files (.docx, PDF, JPEG, PNG, 10 MB each) and an email. `?type=chapter` opens it on one.
- Buttons: Community blog section and the end of every blog post ("Write for the blog"), Retreats (first band) and the front page calendar ("Add or update an event"), Local Chapters, Unity Regions ("Update a region"), Partner Organizations. None for people, teams or awards.
- Each type asks for its main details (4b249c9, migration 049, `fields` in `src/data/requestTypes.ts`), stored as one JSON column.
- The message (and a request's name) is marked Required on the Request, feedback and data request forms, with a countdown of characters still needed (110b655).
- [x] **Privacy Policy and Terms** (ee61568): written from what the code does. Covers collected data, no data on minors displayed, AI use (builds the site's structure, no database access, data not ingested), third parties, cookie policy. Data deletion requests have their own form. Privacy contact email in Site settings (migration 039).
- [x] **Cookie notice:** a dismissible notice linking to the privacy page, since nothing third-party loads before a click. The hero video and the schedule map are click-to-load (ee61568).
- [x] **Community links** (c62dc84): nav and the org pages' "All regions" / "All chapters" pointed at #local and #virtual, which don't exist; now #chapters and #regions. "Virtual Community" renamed "Unity Regions".
## Content blocks and editing
- [x] **Showcase seed:** `DB_PATH=./dev.db node src/seed-showcase.js` (in server/) writes a fully filled record of every kind, ids starting `showcase-`: /regions/showcase-region, /chapters/showcase-chapter, /teams/showcase-team, /awards/showcase-award, /people/showcase-person, /events/showcase-event (upcoming retreat), /events/showcase-series (weekly), /events/showcase-past-event, /blog/content-block-showcase (every block type).
- Published but unlisted by default. `--listed` puts them in lists, the map, counts and History; rerun without it to take them out. Refuses /var/lib/ngu unless `--production` (back up first, leave `--listed` off on a live site).
- [x] **Block editor** (migration 032): each block type shows only its own fields, with a plain-English name and description; a live preview under each open block; insert-below and duplicate on every repeater row.
- Text formatting in paragraphs, callouts, quotes and list items: **bold**, *italic*, [text](url), line breaks, blank line for a new paragraph.
- Types added: video (click to play), button, callout. Quotes get an attribution, images alt text separate from the caption.
- [x] **Schedule block** (migration 034): entries have a day (the tab), time, title, detail, location, person and link, and fold out for a description, the person's photo and page link, a graphic, and a Google map. One tab per day in entry order; the tab for today's weekday opens first; entries with no day get their own tab; arrow keys, Home and End move between tabs.
- [x] **Table of contents** (92e7938, migration 043): Blog posts → Show contents (off by default). With two or more headings, a sticky "On this page" column, the heading being read lit; a fold-out on phones. Content-block headings carry anchor ids everywhere. Sticky fix merged with PR #14.
- [x] **Link cards block** (4e9b4e3, migration 045): link, title, description, picture; "Fetch preview" fills the rest. Smaller cards, a grid of up to three in a row (9ff1cd6). "Choose a file" picks from Media → Files, taking the file's name and Drive's first-page picture.
- [x] **Table block** (migration 044): a row per line, cells split by |; any page can use it.
- [x] **Import from Word** (7f12824): Blog posts → Import from Word turns a .docx into an unpublished post (title, date, headings, paragraphs, lists, tables, bold, italic, links; images don't come over, the editor says how many). PDFs: save as .docx first. `docs/importing.md`. Tested with the Church Management Systems comparison doc (untracked, not committed); imported, authored and published after deploying.
## Entities and data
- [x] **Listed flag** (cd393e4, migration 027): separate from Published (which stays the hard gate). Unlisted: own page works; left out of list routes, a region's chapters, an org's events/teams/awards, the QR page, front page counts and countdown. Still shown where attached by hand: rosters, hosts, billed people, award recipients, timeline, a pinned countdown.
- [x] **People pages list their blog posts** (7876e06): published and listed posts they're an author of, as Community blog cards.
- [x] **Event card background image** (eaff238, migration 029): Events → Appearance → "Card background", under a light veil (`CARD_IMAGE_VEIL` in `EventList-Cards.tsx`); card size unchanged. Gradients dropped (migration 040), colour borders kept.
- [x] **Create or update records from a request** (4b249c9): Forms → Content requests shows the requested details; "Create <type> from this" opens the New editor filled in (URL ID, links, a description paragraph); an update picks the record (closest name first) and shows each requested value beside the current one ("Use this" / "Add it"). Nothing saves until Save. Decided 2026-09-29.
- [x] **Every record image is an upload** (a67ca98): a bare filename resolves to `/uploads/<file>`; only the nav/footer/admin NGU logos are bundled from `src/assets/logos`. Missing files (eg. `ngu-logo-white-bg.svg`, old public/org-logos) copied to the server.
## Admin page
- [x] **Admin home three cards across** (175a189): the home asks for the wide admin column.
- [x] **Editor side nav:** sticky "On this page" left of every editor (field groups, then collections with row counts, current one lit, red dot on a section with a save error); "Jump to" dropdown below lg. Editor pages widen to fit (`src/lib/adminWidth.tsx`). Each collection has its own card; repeater rows start folded, with Expand all / Collapse all. Stays in view while scrolling (960c854).
- [x] **Nav groups:** header menus Data (Events, Organizations, Teams, Awards, People, Blog posts), Pages (Front page, Timeline, Community blog section), Forms, Tools (Media, QR code generator, Video clips), Panel. Hover or focus drops the group down; the strip under the header lists it (the touch path). The admin home shows the same groups as cards. One list: `adminNav.ts`. Tools on the admin home (99c3a87); blog posts moved to Data (c03914a).
- [x] **Forms split** (99d83eb): Website feedback and Data requests, a card each on the admin home and tabs with what's new in each. Content requests: same triage (status, notes, delete), files downloadable, "Make a blog post from it" on a .docx; deleting a request deletes its Drive files.
- [x] **Pickers:** both centred (Tailwind's reset had removed the dialog's auto margin). The image picker has folder tabs (All, Logos, Images, Previews) opening on the field's folder, and a From requests tab (6ccbc03: photos sent with requests, the one being edited first; picking one copies it into the library once). The file picker has a tab per Drive folder.
## Server (settings, auth, file management)
- [x] **Media uploads** (eaff238, migration 028): files in `/var/lib/ngu/uploads` served by nginx; editors and up upload, admins and up delete; resized and converted to WebP unless "Keep original". Every image field has Upload and "Choose from library"; Tools → Media. Production setup done (`docs/media-uploads.md`); `server/pnpm-lock.yaml` committed (be07bc1).
- [x] **Image folders:** `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (link and Drive previews); existing images sorted once at boot, records rewritten (`docs/media-uploads.md`, Folders).
- [x] **Google Drive and Gmail:** a service account (`server/src/googleService.js`, no library) uploads to, downloads from and trashes in a shared drive, a folder per use found or made by name; the same account sends mail as a Workspace user. `docs/google-drive-and-mail.md`.
- Request files go in `Requests/<type>` (migration 050). Tools → Media → Requests (by type folder, linked to its request) and Forms → Content requests mark files Drive no longer has as Missing from Drive; Remove (admins) trashes it and takes it off the request.
- **Files for pages** (migration 048): Tools → Media → Files uploads PDF, Office, MP3, M4A and zip (50 MB) to "Media", shared as anyone with the link (Drive's own sharing, decided 2026-09-29). Folders three deep, New folder, Rename, Delete when empty (admins), a Folder dropdown to move a file. Delete checks what links to a file first. Files and folders added in Drive by hand are picked up.
- [x] **Email notices** (v1.9.5 to v1.9.7): Site settings → Notices, "Email new requests to" (content and data requests), with a test button.
- [x] **Site settings** (migration 035): Panel → Site settings, superadmins only. Site name, description, preview image, favicon, home-screen icon, each static page's title and intro, search indexing on/off. A setting wins, a blank falls back to site.json. Colours (migration 041) and Access (migration 047) live here too.
- [x] **SEO and page previews:** the API fills in each page's title, description, preview image, canonical URL and structured data (Organization, Event, BlogPosting); serves /sitemap.xml and /robots.txt. Unlisted records are noindex; missing ones 404. site.json holds the site's name, address, default description and preview image. Deploy steps done (`docs/seo.md`), sitemap submitted.
- [x] **Google sign-in:** "Sign in with Google" above email and password. Server-side OAuth code flow with PKCE; checks issuer, audience, expiry, verified email and the Workspace domain. The first sign-in links an admin-cli account by email. OAuth client set up (`docs/google-sign-in.md`).
- [x] **Access groups** (migration 047): Site settings → Access names a group per role. Someone in one gets a Google-only account with their highest group's role, rechecked at sign-in, hourly and on Panel → Re-sync now. Out of every group: disabled and signed out, back on when they return. Superadmins and admin-cli accounts are untouched. Panel → Check their groups tests an email. Decided 2026-09-29.
- [x] **Security:** server-side auth, field allowlists, cookies, scrypt hashing, parameterized SQL, upload checks, escaping and trimmed responses were already right. Added: rate limits on the real client IP, CSRF check on /api writes, security headers (HSTS from nginx), 90-day session cap, `__Host-` session cookie, five wrong passwords lock an email for 15 minutes, CSP in Report-Only with /api/csp-report. Row-level security isn't a SQLite feature; route role checks, descriptor allowlists and published/listed filters do that job.
- [x] **Organization-agnostic names:** ngu-tl → site-tl, nguLogo → siteLogo, __NGU_SITE__ → __SITE__, browser keys ngu- → site-, cookies site_session / site_oauth, QR files qr-<page>. Kept on purpose: record ids (ngu-board), /var/lib/ngu, ngu.db, the ngu-api service, the logo file, NGU as the organization's name in text.
## Tools
- [x] **Video clips** (migration 036, admins and up): paste a YouTube or Facebook link; yt-dlp downloads it (up to 4 h / 4 GB). Cut clips by start and end, shaped as filmed, 16:9, square or 9:16 with a movable crop; MP4 or MP3. One job at a time with progress; everything swept after a day. VPS setup done (`docs/video-clips.md`).
- Save to library or Save to Drive (migration 051), with a folder picker (Videos or Audio chosen first), streamed with a resumable upload.
- A finished download can be saved whole (06a0e07); it stays on the server to cut from either way.
- [x] **QR code generator** (/qr): "In the centre" (nothing, NGU dove, or any SVG in `src/assets/qr`, embedded so SVG and PNG downloads carry it); "A link I type" (site path, full http(s) address, or bare domain); code, background and dove colours with a reset, warning under 4:1 contrast or when inverted.
## Design and accessibility
- [x] **Design system** (c74ad74): colour tokens in index.css, gradients gone (migration 040), data colours through `src/lib/color.ts`, one BRAND accent and ACCENTS family. One source for colour defaults with a build check (f934b1d).
- [x] **Dark mode:** follows the system with a header toggle. Fixed: the Church Center popup (7c1723b), the featured timeline background (048c759), a light plate behind every logo (048c759, f59ab31). Palette for both modes in Panel → Site settings → Colours; saving refuses text under 4.5:1 in either mode (`server/src/theme.js`).
- [x] **Accessibility** (185f983): contrast fixes, inert hidden carousel and past cards, keyboard links on admin rows, modal mobile menu, skip link, focus ring, reduced motion (JS smooth scrolls too), alt text for blog covers and schedule graphics (migration 038). Admin-chosen colours as text go through `accentText`/`readableOn`.
- [x] **Icons:** Phosphor everywhere; platform links show their brand icon (3c02eb8: `PLATFORMS` in `src/lib/platforms.ts`, icons in `PlatformIcon.tsx`, shared with the footer and event cards).
## Newsletter (branch `newsletter-layout`)
- [x] **Every part editable and movable** (migration 060): a draft is one list of parts, top to bottom, each moved, copied or removed like content blocks, and each aligned left or center: the header (words, a PNG or JPEG logo, its band color or no band; remove the part to leave it out), the title, any email block, picked items (upcoming events, blog posts or front page cards, picked one by one in order, with the section's heading, its underline, the cards' left bar and the button label), and the footer (its lines and the line above). Dividers take a color, thickness and space above. Colors are the palette or none. A new draft starts with the parts the email always had. 057's drafts (title, intro, picks, footer, blocks) are dropped: that migration never reached a live database.
- [x] **More parts and room** (this branch, after v1.11.2): the builder takes the whole window (the editor beside a 42rem preview; `useWideAdminPage('full')`). A **Social bar** part: a colored band (or none) of the site's platform icons, each linked; no links added shows the footer's (`src/data/socialLinks.ts`). Icons are white or ink PNGs in `public/email/` (made by `scripts/email-icons.mjs`), picked to read on the band. An **Event countdown** part: pick an upcoming dated event (not a series); the email shows a picture the API draws when it's opened (`/api/countdown/<id>.png`: days, hours and minutes to local midnight in America/Chicago on its start date, then "Happening now", then "Thanks for joining us"), with a fixed "10 days to go" line under it as of copying, for clients that block pictures. Gmail keeps the picture from its first open.
- [x] **Resizable builder**: a handle between the parts and the preview (from lg up) sets the preview's width, from 320px (as a phone shows the email) to all but 360px of the parts list; drag it, or focus it and use the arrow keys, Home and End. Remembered in the browser.
- [ ] Production: install Poppins on the VPS for the countdown picture (CLAUDE.md, Deployment), or it uses a plain sans.
- [ ] Check in a browser: build an issue with every part, move them, center some, turn off the band and the lines, pick items and reorder them, save and reopen the draft, Post as blog post, paste the HTML into Mailchimp and a Gmail test send.
## Navigation (branch `audit-ui`)
- [x] **Side nav over everything**: its column had no z-index, so later layers (the Retreats carousel arrows) drew over its circle; it's z-20 now, and its empty area lets clicks through.
- [x] **Request button**: the National Retreats band no longer shows "Add or update an event" (`NO_EVENT_REQUEST_SCOPES` in `src/lib/sections.tsx`); where a request button stays, it takes its section's accent (border, text, hover tint).
## Audits
- [x] **Third audit, UI half** (branch `audit-ui`, v1.11.1-audit, not checked in a browser yet):
- Event cards: the photo is a lazy `<img>` of the -640 copy under the veil (was a full-size CSS background); the carousel draws only slides within 2 of the current one; past 12 events the dots become a "7 / 200" counter; the past grid shows one row collapsed, then 12 at a time with Show more, newest first (was oldest first).
- Community map: a search box over the list and grid (name and place); each region's grid shows 12, then Show all; below lg the list scrolls in its own 36rem box; hovering a tile no longer redraws the list.
- People tiles: one clip check for the whole list (was an observer per tile); 30 tiles, then Show all.
- Person pages: 6 events and 6 posts, then Show all; blog excerpts load only each post's first paragraph.
- Admin: pickers and the QR page's record select get a filter box past 50 options (`src/components/OptionFilter.tsx`); `/admin/options?only=` sends only the lists a form uses; Media library thumbnails use the -640 copy, videos don't preload, search waits 250 ms and drops stale answers (Drive files too), and says when the newest 500 are shown.
- Coming back to a page after the 60 s cache shows its last data while it refreshes (api.ts `peek`), instead of the skeleton.
- [ ] Check in a browser, light and dark: the Retreats carousel with many events (counter, swipe, height between cards), the past grid, the side nav over the carousel arrow, request buttons' colors, Community search and Show all (and the phone list box), people tiles Show all and cut-off titles, a person page, admin pickers' filter, an editor's dropdowns all filled, the Media library.
- [x] **Third audit** (2026-10-01, branch `audit-3`): security after the Drive integration and in general, and scalability at hundreds of records. Fixed: a zip bomb through the request form's .docx (each part unpacked once); request files must be named for what they are (a PDF named .html is refused); a team's roster hidden with its unpublished organization; `/people?ids=` no longer names a draft organization, and takes 200 ids (was 50, which dropped people from big people blocks); v_events takes the first published host (a draft partner's name and logo leaked into an event's preview) and reads event_hosts directly, about 18 times faster per lookup (migration 059, with an index on person_awards.event_id); group accounts can't sign in while access groups are off, and a sync can't undo a superadmin's disable; 64 KB body limit on login, feedback and csp-report; Drive pick-up races no longer 500; random upload boundary. Scalability: /events filters by scope, host, status and type on the server (each band fetches only its own; Home no longer prefetches every event); /organizations leaves out bodies and leadership (the map's group panel fetches its group); admin lists page with "Show more" and a real count; Content requests "find the record" searches by name; the newsletter asks for published posts only. Kept: viewers see Forms (decided 2026-09-28).
- [x] **First audit** (v1.9.0-audit, 2026-09-28): security (4066e9e), bugs (693dd84), cleanup (5274e09: no em-dashes, import extensions, dead code, shared helpers, hooks moved to src/lib), accessibility (185f983), leftovers (e4a9c96: one mediaUrl, orgPath on orgHref, one Logo component, adminSchema split per entity), more cleanup (d1a6332: url column type refusing unsafe schemes).
- [x] **Second audit** (2026-09-29, after v1.9.3-audit): bugs and security (be7e924: Panel role changes, hostile feed markup, SSRF ranges, prototype keys), speed (f72a960: lazy pages, preloads, 640px copies, gzip and HTTP/2), dark mode and design (048c759), structure (f934b1d).
## Decided / left as they are
- `noImplicitAny` stays off (about 480 errors); decided 2026-09-29, noted in CLAUDE.md.
- Viewers may see feedback emails, including data requests (2026-09-28).
- Left alone: the two date-range formatters and the two findOr404 helpers (different, not duplicates); content.js as one file; the chapter grid in OrgList-Map; unused `export` keywords on internal helpers; RetreatsBand's name.

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`. |
@ -111,6 +111,18 @@ with it off it blocks everything.
client_max_body_size 26m;
proxy_read_timeout 60s;
}
# The admin's saves send a record whole (every content block,
# schedule entry and sub-item), well over 64k for a big page or
# event: nginx answers 413 "Too large for the web server" without
# this. A longer prefix than /api/, so it wins; the exact and
# longer admin blocks (media, files, import, clips) still win over
# it. Same proxy_set_header lines as /api/.
location /api/admin/ {
proxy_pass http://127.0.0.1:3001;
client_max_body_size 4m;
proxy_read_timeout 30s;
}
```
Keep the existing `/api/` and `/uploads/` blocks; they're more

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
@ -179,20 +181,26 @@ also in `server/src/admin-schema/` and a CHECK):
| Links → Kind (on organizations, events, people, teams) | action, social, website, email | no | `splitLinks` in `server/src/shape.js` |
| Links → Platform | instagram, facebook, discord, youtube, tiktok, x, substack, spotify, linkedin | **yes**, `PLATFORMS` | `PlatformIcon.tsx` draws the icon on the button. **No CHECK and no `enumeration`**: the column is plain text, so adding one is an entry in `PLATFORMS` (`src/lib/platforms.ts`) and its icon in `src/components/PlatformIcon.tsx`, no migration. |
| Content blocks → Shown in (slot) | card, body | **yes** | `paragraphs()` in `server/src/shape.js` (card), `ContentBlocks.tsx` (body) |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule, table | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema/shared.ts`). |
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule, table, cards, people, map, events, organizations | **yes**, `BLOCK_TYPES` (with each type's description) | `ContentBlocks.tsx` (one renderer per type). Which fields each type shows is `when` on the fields in `blocksChild` (`src/lib/adminSchema/shared.ts`). |
| Content blocks → Schedule items → Type | (blank: normal entry), block, break, heading | **yes**, migration 086 | `SCHEDULE_KINDS` in `src/lib/adminSchema/shared.ts`; drawn by `ScheduleBlock.tsx` and `EventPresent.tsx` (which slides each kind gets; the presentation cuts the event's page into sections at its Heading blocks). A block's sub-items are `content_block_subitems`. A schedule's own tags (087) are `content_block_tags`, rows of the block typed in the admin (not a fixed list); entries name them by `tag_key`, made in the admin as the tag is added. A schedule's Venue (088) lends its locations (Data → Venues, `venue_locations`) to its entries' Map location, named by `location_key` the same way; an entry's Event (a workshop) fills what it leaves blank in `shape.js` (`attachEvents`). |
| Content blocks → Image → Size | (blank: the column's full width), small (20rem), medium (32rem), large (48rem) | **yes**, migration 101 | The `image_size` field in `src/lib/adminSchema/shared.ts`; `IMAGE_SIZE` in `ContentBlocks.tsx` sets the widths |
| Content blocks → List → Style | (blank: bold text, normal detail), plain (plain text, gray detail) | **yes**, migration 092 | The Style field in `src/lib/adminSchema/shared.ts`; drawn by the `list` case in `ContentBlocks.tsx`. |
| Content blocks (an event's) → Shown | (blank: the page and the presentation), page, presentation | **yes**, migration 099 | `PRESENT_BLOCK_FIELDS` in `src/lib/adminSchema/shared.ts`; `ContentBlocks.tsx` leaves out a presentation-only block on the page and a page-only one presented, `sectionsOf` in `src/pages/EventPresent.tsx` too |
| Content blocks (an event's) → Map → Location slides | (blank: each marked location), picked (the Locations with a slide), none | **yes**, migration 095 | `PRESENT_BLOCK_FIELDS` in `src/lib/adminSchema/shared.ts`; read by `mapSlides` in `src/pages/EventPresent.tsx` |
| Events → Presentation → Frame | (blank: the accent bar, title line and timer), border, none | **yes**, migration 095 | The `present_frame` field in `src/lib/adminSchema/events.ts`; drawn by `Player` in `src/pages/EventPresent.tsx` |
| Content blocks → Organizations → List | (blank: only the picked ones), partner, region, group, ministry | **yes**, migration 093 | The `org_kind` field in `src/lib/adminSchema/shared.ts`; the `organizations` case in `ContentBlocks.tsx` passes it as the kind to `OrgListCards` (`nested`); items picked by `org_id` replace it |
| 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 +217,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 +268,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. |
| 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, map block (its list alone), 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 | 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 +294,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);
@ -482,6 +494,8 @@ function isBlankChildRow(child, raw) {
if (!raw || typeof raw !== "object") return true;
for (const column of child.columns) {
// A value the admin seeds every new row with (`seeded`), not input.
if (column.seeded) continue;
const value = raw[column.name];
if (value === undefined || value === null || value === "") continue;
// An unchecked box is the default state of a new row, not input.
@ -584,8 +598,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,16 @@ 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";
import { venues } from "./admin-schema/venues.js";
export const ENTITIES = {
organizations,
@ -74,16 +74,13 @@ export const ENTITIES = {
tags,
contact_types: contactTypes,
redirects,
venues,
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,
};
@ -103,6 +100,10 @@ export const OPTION_QUERIES = {
// What an organization cards section can hand-pick (067).
card_orgs:
"SELECT id, name || ' (' || kind || ')' AS label FROM organizations WHERE kind IN ('partner', 'ministry') ORDER BY kind, name",
// What an organizations content block can pick (093): every kind,
// a card needing no page of its own.
block_orgs:
"SELECT id, name || ' (' || kind || ')' AS label FROM organizations ORDER BY kind, name",
event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order",
events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title",
people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name",
@ -111,7 +112,18 @@ export const OPTION_QUERIES = {
contact_types: "SELECT id, name AS label FROM contact_types ORDER BY sort_order, name",
// Link fields with `redirects: true` pick from these (068).
redirects: "SELECT id, id || ' (' || target_url || ')' AS label FROM redirects ORDER BY id",
// A map block's venue; its locations ride along (as JSON) for a
// schedule's entries to pick from and for the block's preview.
venues: `
SELECT v.id, v.name AS label, v.map_image, v.map_alt,
(SELECT json_group_array(json_object('key', l.location_key, 'name', l.name, 'detail', l.detail,
'x', l.x, 'y', l.y, 'w', l.w, 'h', l.h))
FROM (SELECT * FROM venue_locations WHERE venue_id = v.id ORDER BY sort_order) l) AS locations
FROM venues v
ORDER BY v.name`,
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,18 +152,48 @@ export const blocksChild = (ownerKind) => ({
"table",
"cards",
"people",
// A blog post's tab (079): its text is the tab's title.
"tab",
// A venue's map, and event cards (088).
"map",
"events",
// Organization cards (093).
"organizations",
],
{ required: true },
),
text("text"),
text("media"),
// Image blocks (102): shown in place of media in the dark theme.
text("media_dark"),
url("href"),
text("alt"),
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"),
// Map and schedule blocks (088): whose map and locations.
text("venue_id"),
// List blocks (092): null bold text, 'plain' the old look.
enumeration("list_style", ["plain"]),
// Image blocks (101): null full width, else a narrower size.
enumeration("image_size", ["small", "medium", "large"]),
// Organizations blocks (093): the kind listed when none are picked.
enumeration("org_kind", ["region", "group", "partner", "ministry"]),
// How it's presented (095): EventPresent.tsx.
// Where it shows (099): null both, the page or the presentation.
enumeration("present_show", ["page", "presentation"]),
text("present_text"),
bool("present_map_split"),
bool("present_map_no_list"),
bool("present_map_no_details"),
enumeration("present_places", ["picked", "none"]),
text("present_place_keys"),
],
children: [
{
@ -185,7 +215,76 @@ export const blocksChild = (ownerKind) => ({
text("media_alt"),
text("map"),
text("map_image"),
// Its kind, picked times and Featured tick (086).
enumeration("kind", ["block", "break", "heading"]),
time("start_time"),
time("end_time"),
bool("featured"),
// The block's tags it has, by key, comma-separated (087).
text("tags"),
// A workshop or other event it is, and its place on the
// block's venue map (088).
text("event_id"),
text("location_key"),
// A featured event's heading and subheading (090).
text("heading"),
text("subheading"),
// An organizations block's organization (093).
text("org_id"),
],
children: [
{
// A block entry's sub-items (086).
key: "items",
table: "content_block_subitems",
owner: { column: "item_id" },
order: "sort_order",
when: { column: "kind", value: "block" },
columns: [
text("text", { required: true }),
text("detail"),
url("url"),
time("start_time"),
time("end_time"),
text("time"),
text("location"),
text("person_id"),
text("description"),
text("media"),
text("media_alt"),
text("map"),
text("map_image"),
bool("featured"),
text("tags"),
text("event_id"),
text("location_key"),
],
},
],
},
{
// A schedule's own tags (087).
key: "tags",
table: "content_block_tags",
owner: { column: "block_id" },
order: "sort_order",
when: { column: "type", value: "schedule" },
columns: [
// Made by the admin as the row is added, so it isn't input.
text("tag_key", { required: true, seeded: true }),
text("name", { required: true }),
text("color"),
bool("no_tab"),
],
},
{
// A map block's own sections of its venue's locations (094).
key: "map_sections",
table: "content_block_map_sections",
owner: { column: "block_id" },
order: "sort_order",
when: { column: "type", value: "map" },
columns: [text("name", { required: true }), text("location_keys")],
},
],
});

View file

@ -1,4 +1,4 @@
import { text, int, bool, date, time, enumeration, placeColumns, timelineExtension, linksChild, blocksChild, hostsChild } from "./columns.js";
import { text, int, real, bool, date, time, enumeration, placeColumns, timelineExtension, linksChild, blocksChild, hostsChild } from "./columns.js";
import { tagsChild } from "./tags.js";
/* ── Events ──────────────────────────────────────────────────── */
@ -67,6 +67,28 @@ export const events = {
bool("is_published"),
bool("is_listed"),
bool("in_timeline"),
bool("show_contents"),
text("links_heading"),
// Its page presented (095).
text("present_background"),
text("present_background_color"),
int("present_dim"),
enumeration("present_frame", ["border", "none"]),
text("present_accent"),
text("present_text_color"),
text("present_logo"),
// The same in the dark theme (096), null the above.
text("present_background_dark"),
text("present_background_color_dark"),
int("present_dim_dark"),
text("present_accent_dark"),
text("present_text_color_dark"),
text("present_logo_dark"),
// Room clear at each edge, eg. inside a frame picture (097).
real("present_inset_top"),
real("present_inset_right"),
real("present_inset_bottom"),
real("present_inset_left"),
// A repeating schedule. Columns rather than a side table: the
// schedule is always exactly one per event, and the public view

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, the account pages and the remote. */
const RESERVED = [
"admin", "api", "uploads", "assets", "pa", "go",
"events", "regions", "groups", "partners", "organizations", "teams", "awards", "people", "blog", "directory",
"sign-in", "account", "remote", "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

@ -0,0 +1,47 @@
import { text, real, url } from "./columns.js";
/* ── Venues (088_venues.sql) ─────────────────────────────────────
A place we gather, with its map picture and the locations marked
on it. Map blocks draw it, and schedule entries link to its
locations. Its own entity because content_blocks.venue_id points
at it; nothing points at a location's row, entries name one by
location_key, so the locations can be replaced wholesale. */
export const venues = {
key: "venues",
table: "venues",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "name", "address"],
filters: [],
search: ["name", "id", "address"],
order: "name",
},
columns: [text("name", { required: true }), text("address"), text("map_image"), text("map_alt")],
children: [
{
key: "locations",
table: "venue_locations",
owner: { column: "venue_id" },
order: "sort_order",
columns: [
// Made by the admin as the row is added, so it isn't input.
text("location_key", { required: true, seeded: true }),
text("name", { required: true }),
text("detail"),
real("x"),
real("y"),
real("w"),
real("h"),
// The place in Google and Apple Maps (091).
url("google_maps_url"),
url("apple_maps_url"),
],
},
],
};

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";
@ -41,13 +43,15 @@ import imports from "./routes/import.js";
import files from "./routes/files.js";
import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import present from "./routes/present.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 +138,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", "/api/present/*"]) 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 +182,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 +193,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);
@ -196,6 +203,11 @@ app.use("/api/countdown/*", rateLimit({ windowMs: 60_000, max: 600 }));
app.route("/api", countdown);
// Tighter limit on the write path than anything else gets.
// A presenting screen and its remotes, by the screen's code
// (routes/present.js): a cap far above tapping, far below guessing.
app.use("/api/present/*", rateLimit({ windowMs: 60_000, max: 300 }));
app.route("/api", present);
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback);
// Requests carry files: fewer again.
@ -206,9 +218,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

@ -0,0 +1,47 @@
-- ═══════════════════════════════════════════════════════════════
-- 086 SCHEDULE ENTRY TYPES
--
-- A schedule entry gets a kind:
-- null a normal entry
-- block a time frame holding several things, its sub-items
-- (content_block_subitems below), each with its own time
-- break a meal or free time: a quieter row, no spotlight slide
-- heading a label across the day, eg. Evening sessions
-- and `featured`, which makes the row stand out.
--
-- Times are picked (start_time, end_time, HH:MM 24-hour) and shown
-- as 7:00pm or 9:00 to 10:30am (shape.js). The old typed `time`
-- stays as the override: when it's filled it shows instead, so the
-- entries typed before this look the same.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_block_items ADD COLUMN kind TEXT
CHECK (kind IN ('block', 'break', 'heading'));
ALTER TABLE content_block_items ADD COLUMN start_time TEXT;
ALTER TABLE content_block_items ADD COLUMN end_time TEXT;
ALTER TABLE content_block_items ADD COLUMN featured INTEGER NOT NULL DEFAULT 0
CHECK (featured IN (0, 1));
-- A block entry's sub-items: every field an entry has but day and
-- kind (they're under their block's day, and don't nest further).
CREATE TABLE content_block_subitems (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id INTEGER NOT NULL REFERENCES content_block_items (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
text TEXT NOT NULL,
detail TEXT,
url TEXT,
start_time TEXT,
end_time TEXT,
time TEXT, -- the override, as on an entry
location TEXT,
person_id TEXT REFERENCES people (id) ON DELETE SET NULL,
description TEXT,
media TEXT,
media_alt TEXT,
map TEXT,
map_image TEXT,
featured INTEGER NOT NULL DEFAULT 0 CHECK (featured IN (0, 1))
) STRICT;
CREATE INDEX content_block_subitems_item_idx
ON content_block_subitems (item_id, sort_order);

View file

@ -0,0 +1,28 @@
-- ═══════════════════════════════════════════════════════════════
-- 087 SCHEDULE TAGS
--
-- A schedule block's own tags, eg. Youth or Worship: entries and
-- sub-items are tagged with them, a tag can be a tab of its own
-- gathering every entry it's on (across the days), and the schedule
-- presentation can show only one tag's entries and a slide per tag.
--
-- These are the block's, not Data → Tags (070). The block's rows are
-- rewritten on every save, so entries name a tag by `tag_key` (made
-- in the admin when the tag is added, kept when it's renamed), not
-- by its row id. An entry's `tags` is its keys, comma-separated; a
-- key no tag has any more is skipped.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_block_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
block_id INTEGER NOT NULL REFERENCES content_blocks (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
tag_key TEXT NOT NULL,
name TEXT NOT NULL,
color TEXT, -- null: the event's accent
no_tab INTEGER NOT NULL DEFAULT 0 CHECK (no_tab IN (0, 1)),
UNIQUE (block_id, tag_key)
) STRICT;
ALTER TABLE content_block_items ADD COLUMN tags TEXT;
ALTER TABLE content_block_subitems ADD COLUMN tags TEXT;

View file

@ -0,0 +1,125 @@
-- ═══════════════════════════════════════════════════════════════
-- 088 VENUES, MAP BLOCKS AND EVENT BLOCKS
--
-- Data → Venues: a place we gather (a camp, a church), with one map
-- picture and its marked locations, each a pin (x, y) or a box
-- (x, y, w, h), in percent of the picture from its top left.
--
-- A 'map' content block draws a venue's map with its locations
-- listed beside it; a schedule block names a venue too, and its
-- entries and sub-items pick one of its locations (location_key),
-- which links to the map block on the same page, the location
-- lit up. The venue's locations are rewritten on every save, so an
-- entry names one by `location_key` (made in the admin when the
-- location is added), as schedule tags do (087).
--
-- An 'events' content block shows events as cards, an item each
-- (event_id); a schedule entry or sub-item can name an event too
-- (a workshop), and takes what it leaves blank from it.
--
-- content_blocks.type's CHECK can't change in place, so the table
-- is rebuilt (as in 079), then its index and owner trigger made
-- again.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE venues (
id TEXT PRIMARY KEY
CONSTRAINT "A venue's URL ID can use only lowercase letters, numbers and hyphens, eg. camp-hebron."
CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'),
name TEXT NOT NULL,
address TEXT,
map_image TEXT, -- an upload
map_alt TEXT
) STRICT;
CREATE TABLE venue_locations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
venue_id TEXT NOT NULL REFERENCES venues (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
location_key TEXT NOT NULL,
name TEXT NOT NULL,
detail TEXT,
x REAL CHECK (x BETWEEN 0 AND 100),
y REAL CHECK (y BETWEEN 0 AND 100),
w REAL CHECK (w > 0 AND w <= 100), -- null: a pin
h REAL CHECK (h > 0 AND h <= 100),
UNIQUE (venue_id, location_key)
) STRICT;
ALTER TABLE content_block_items ADD COLUMN event_id TEXT
REFERENCES events (id) ON DELETE SET NULL;
ALTER TABLE content_block_items ADD COLUMN location_key TEXT;
ALTER TABLE content_block_subitems ADD COLUMN event_id TEXT
REFERENCES events (id) ON DELETE SET NULL;
ALTER TABLE content_block_subitems ADD COLUMN location_key TEXT;
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', 'map', 'events')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT,
team_id TEXT REFERENCES teams (id) ON DELETE SET NULL,
captions TEXT,
word_motion TEXT CHECK (word_motion IN ('slide', 'flip', 'fade', 'type', 'mirror')),
word_direction TEXT CHECK (word_direction IN ('top', 'bottom')),
word_seconds INTEGER CHECK (word_seconds BETWEEN 1 AND 20),
-- Map and schedule blocks: whose map, and whose locations.
venue_id TEXT REFERENCES venues (id) ON DELETE SET NULL
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions,
word_motion, word_direction, word_seconds)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions,
word_motion, word_direction, word_seconds
FROM content_blocks;
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,14 @@
-- ═══════════════════════════════════════════════════════════════
-- 089 EVENT PAGE OPTIONS
--
-- show_contents the page's headings listed beside its content
-- blocks, as a blog post's are (PostContents.tsx)
-- links_heading a heading above the event's link buttons; null
-- shows none
--
-- v_events is SELECT e.*, so it carries both with no rebuild.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN show_contents INTEGER NOT NULL DEFAULT 0
CHECK (show_contents IN (0, 1));
ALTER TABLE events ADD COLUMN links_heading TEXT;

View file

@ -0,0 +1,15 @@
-- ═══════════════════════════════════════════════════════════════
-- 090 FEATURED EVENTS IN AN EVENTS BLOCK
--
-- An events block's item ticked Featured (086's `featured`) shows
-- opened in full above the cards, under its own heading and
-- subheading, both optional:
--
-- heading eg. This year's keynote
-- subheading a line under it
--
-- Other item kinds ignore both.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_block_items ADD COLUMN heading TEXT;
ALTER TABLE content_block_items ADD COLUMN subheading TEXT;

View file

@ -0,0 +1,10 @@
-- ═══════════════════════════════════════════════════════════════
-- 091 A VENUE LOCATION'S MAP LINKS
--
-- Each location on a venue's map can link to the same place in
-- Google Maps and Apple Maps, shown as buttons beside it in a map
-- block's list. Null shows no button.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE venue_locations ADD COLUMN google_maps_url TEXT;
ALTER TABLE venue_locations ADD COLUMN apple_maps_url TEXT;

View file

@ -0,0 +1,13 @@
-- ═══════════════════════════════════════════════════════════════
-- 092 A LIST BLOCK'S STYLE
--
-- How a list block's items read:
--
-- null the item's text bold, its detail in the body color
-- plain the text plain, the detail gray (the look before 092)
--
-- Other block types ignore it.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_blocks ADD COLUMN list_style TEXT
CHECK (list_style IN ('plain'));

View file

@ -0,0 +1,91 @@
-- ═══════════════════════════════════════════════════════════════
-- 093 ORGANIZATIONS BLOCK
--
-- An 'organizations' content block shows organizations as the
-- Partners page's cards (OrgList-Card.tsx): the ones picked as its
-- items, in their order (content_block_items.org_id), else every
-- published, listed one of its kind (content_blocks.org_kind), by
-- name.
--
-- content_blocks.type's CHECK can't change in place, so the table
-- is rebuilt (as in 088), then its index and owner trigger made
-- again.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_block_items ADD COLUMN org_id TEXT
REFERENCES organizations (id) ON DELETE SET NULL;
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', 'map', 'events', 'organizations')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT,
team_id TEXT REFERENCES teams (id) ON DELETE SET NULL,
captions TEXT,
word_motion TEXT CHECK (word_motion IN ('slide', 'flip', 'fade', 'type', 'mirror')),
word_direction TEXT CHECK (word_direction IN ('top', 'bottom')),
word_seconds INTEGER CHECK (word_seconds BETWEEN 1 AND 20),
-- Map and schedule blocks: whose map, and whose locations.
venue_id TEXT REFERENCES venues (id) ON DELETE SET NULL,
-- List blocks (092): null bold text, 'plain' the old look.
list_style TEXT CHECK (list_style IN ('plain')),
-- Organizations blocks: the kind listed when none are picked.
org_kind TEXT CHECK (org_kind IN ('region', 'group', 'partner', 'ministry'))
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions,
word_motion, word_direction, word_seconds, venue_id, list_style)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions,
word_motion, word_direction, word_seconds, venue_id, list_style
FROM content_blocks;
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,27 @@
-- ═══════════════════════════════════════════════════════════════
-- 094 A MAP BLOCK'S SECTIONS
--
-- A map content block can group its venue's locations into
-- sections of its own, eg. Main spaces, Small group spaces: the
-- block's list shows them under those names, and a visitor can pick
-- one to see only its locations on the map. They're the block's,
-- not the venue's, so each event groups the same venue its own way.
--
-- With sections, the block shows only the locations they name (in
-- the sections' order); without, every location, as before.
--
-- location_keys the venue's location_keys (088) it holds,
-- comma-separated, as schedule tags are (087). A
-- key the venue no longer has is skipped.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_block_map_sections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
block_id INTEGER NOT NULL REFERENCES content_blocks (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
name TEXT NOT NULL,
location_keys TEXT
) STRICT;
CREATE INDEX content_block_map_sections_block_idx
ON content_block_map_sections (block_id, sort_order);

View file

@ -0,0 +1,56 @@
-- ═══════════════════════════════════════════════════════════════
-- 095 PRESENTATION SETTINGS
--
-- How an event's page looks presented (EventPresent.tsx), set on
-- the event; nothing here changes the page itself.
--
-- On events (v_events is SELECT e.*, so no rebuild):
-- present_background an image behind every slide
-- present_background_color the slides' background color; with an
-- image, laid over it at present_dim
-- present_dim percent of the color over the image,
-- 0 to 90; null 60
-- present_frame null the accent bar, title line and
-- timer; 'border' an accent border around
-- the slide; 'none' the slide alone
-- present_accent in place of the event's color
-- present_text_color the slides' text; null the background
-- color's readable one, else the site's
-- present_logo in the slide's bottom-right corner
--
-- On content blocks (any owner's; only an event's are presented):
-- present_hide left out of the presentation
-- present_text shown presented in place of its text,
-- eg. a shorter heading
-- present_map_split a map: a slide per map section (094)
-- present_map_no_list a map: no locations list beside it
-- present_map_no_details a map: no location detail lines
-- present_places a map: which locations get a slide of
-- their own; null every marked one,
-- 'picked' present_place_keys, 'none'
-- present_place_keys the venue's location_keys (088),
-- comma-separated
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN present_background TEXT;
ALTER TABLE events ADD COLUMN present_background_color TEXT;
ALTER TABLE events ADD COLUMN present_dim INTEGER
CHECK (present_dim BETWEEN 0 AND 90);
ALTER TABLE events ADD COLUMN present_frame TEXT
CHECK (present_frame IN ('border', 'none'));
ALTER TABLE events ADD COLUMN present_accent TEXT;
ALTER TABLE events ADD COLUMN present_text_color TEXT;
ALTER TABLE events ADD COLUMN present_logo TEXT;
ALTER TABLE content_blocks ADD COLUMN present_hide INTEGER NOT NULL DEFAULT 0
CHECK (present_hide IN (0, 1));
ALTER TABLE content_blocks ADD COLUMN present_text TEXT;
ALTER TABLE content_blocks ADD COLUMN present_map_split INTEGER NOT NULL DEFAULT 0
CHECK (present_map_split IN (0, 1));
ALTER TABLE content_blocks ADD COLUMN present_map_no_list INTEGER NOT NULL DEFAULT 0
CHECK (present_map_no_list IN (0, 1));
ALTER TABLE content_blocks ADD COLUMN present_map_no_details INTEGER NOT NULL DEFAULT 0
CHECK (present_map_no_details IN (0, 1));
ALTER TABLE content_blocks ADD COLUMN present_places TEXT
CHECK (present_places IN ('picked', 'none'));
ALTER TABLE content_blocks ADD COLUMN present_place_keys TEXT;

View file

@ -0,0 +1,24 @@
-- ═══════════════════════════════════════════════════════════════
-- 096 PRESENTATION SETTINGS IN THE DARK THEME
--
-- The same as 095's, for a screen in the dark theme (the device's
-- setting, or the setup's Theme pick). Each one null takes the
-- light theme's (095), so only what differs needs setting.
--
-- present_background_dark the image behind every slide
-- present_background_color_dark the slides' background color
-- present_dim_dark percent of the color over the
-- image, 0 to 90
-- present_accent_dark in place of the accent
-- present_text_color_dark the slides' text
-- present_logo_dark the bottom-right logo, eg. a
-- light version
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN present_background_dark TEXT;
ALTER TABLE events ADD COLUMN present_background_color_dark TEXT;
ALTER TABLE events ADD COLUMN present_dim_dark INTEGER
CHECK (present_dim_dark BETWEEN 0 AND 90);
ALTER TABLE events ADD COLUMN present_accent_dark TEXT;
ALTER TABLE events ADD COLUMN present_text_color_dark TEXT;
ALTER TABLE events ADD COLUMN present_logo_dark TEXT;

View file

@ -0,0 +1,20 @@
-- ═══════════════════════════════════════════════════════════════
-- 097 PRESENTATION CONTENT INSET
--
-- Room kept clear at each edge of a presented slide, so its content
-- sits inside a background image that is a frame (eg. a 1920x1080
-- picture with a border drawn in it). Percent of the screen: top
-- and bottom of its height, left and right of its width, 0 to 45.
-- Null is 0. With any set, the background image is stretched to the
-- screen rather than cropped, so the frame stays where the inset
-- expects it. Both themes share them.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN present_inset_top REAL
CHECK (present_inset_top BETWEEN 0 AND 45);
ALTER TABLE events ADD COLUMN present_inset_right REAL
CHECK (present_inset_right BETWEEN 0 AND 45);
ALTER TABLE events ADD COLUMN present_inset_bottom REAL
CHECK (present_inset_bottom BETWEEN 0 AND 45);
ALTER TABLE events ADD COLUMN present_inset_left REAL
CHECK (present_inset_left BETWEEN 0 AND 45);

View file

@ -0,0 +1,18 @@
-- ═══════════════════════════════════════════════════════════════
-- 098 A LIST BLOCK'S PRESENTATION SLIDES
--
-- A list block presented (EventPresent.tsx) is a section's text,
-- unless it has slides of its own:
--
-- present_list_overview one slide of every item's text, without
-- the detail, centered
-- present_list_items a slide per item: its text the heading,
-- its detail under it, centered
--
-- Either or both. Other block types ignore them.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_blocks ADD COLUMN present_list_overview INTEGER NOT NULL DEFAULT 0
CHECK (present_list_overview IN (0, 1));
ALTER TABLE content_blocks ADD COLUMN present_list_items INTEGER NOT NULL DEFAULT 0
CHECK (present_list_items IN (0, 1));

View file

@ -0,0 +1,20 @@
-- ═══════════════════════════════════════════════════════════════
-- 099 WHERE A BLOCK SHOWS: THE PAGE, THE PRESENTATION OR BOTH
--
-- present_hide (095) could only leave a block out of the
-- presentation. present_show says where it shows instead:
--
-- null the page and the presentation
-- 'page' only on the page (was present_hide = 1)
-- 'presentation' only in the presentation (EventPresent.tsx), eg.
-- a slide's welcome line the page doesn't need
--
-- present_hide is copied over, then dropped.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_blocks ADD COLUMN present_show TEXT
CHECK (present_show IN ('page', 'presentation'));
UPDATE content_blocks SET present_show = 'page' WHERE present_hide = 1;
ALTER TABLE content_blocks DROP COLUMN present_hide;

View file

@ -0,0 +1,10 @@
-- ═══════════════════════════════════════════════════════════════
-- 100 A LIST'S SLIDES PICKED WHEN PRESENTING
--
-- A list block's Overview slide and A slide per item (098) are
-- picked on the Present setup screen (EventPresent.tsx, `lists` in
-- its address) rather than on the block, so 098's columns go.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_blocks DROP COLUMN present_list_overview;
ALTER TABLE content_blocks DROP COLUMN present_list_items;

View file

@ -0,0 +1,15 @@
-- ═══════════════════════════════════════════════════════════════
-- 101 AN IMAGE BLOCK'S SIZE
--
-- How wide an image block shows, centered in the column:
--
-- null the column's full width (as before)
-- small up to 20rem
-- medium up to 32rem
-- large up to 48rem
--
-- Never wider than the column. Other block types ignore it.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_blocks ADD COLUMN image_size TEXT
CHECK (image_size IN ('small', 'medium', 'large'));

View file

@ -0,0 +1,13 @@
-- ═══════════════════════════════════════════════════════════════
-- 102 AN IMAGE BLOCK'S DARK THEME PICTURE
--
-- media_dark shown in place of media while the site is in its
-- dark theme (the visitor's setting, or a presentation
-- held dark), eg. a chart or a logo drawn light on
-- dark. Null shows media in both themes.
--
-- Image blocks only; other types ignore it. Its alt text and caption
-- are the block's, so it should show the same thing.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE content_blocks ADD COLUMN media_dark 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,12 +409,27 @@ 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 presenting screen's remote (src/pages/PresentRemote.tsx).
if (/^\/remote(\/|$)/.test(pathname)) return { ...meta, title: titled(site, "Remote"), 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
// An event page's presentation (EventPresent.tsx): the
// event's own title and preview, kept out of search, pointing
// search engines at the event page.
const present = pathname.match(/^\/events\/([^/]+)\/present$/);
@ -520,7 +549,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 +574,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)`,
)
@ -591,7 +591,42 @@ content.get("/events/:id", (c) => {
citation: r.citation,
}));
const event = { ...shapeEvent(row, links, cards, hosts), blocks: body, people, awards };
const event = {
...shapeEvent(row, links, cards, hosts),
show_contents: row.show_contents === 1,
links_heading: row.links_heading,
// Its page presented (095).
present: {
background: row.present_background,
background_color: row.present_background_color,
dim: row.present_dim,
frame: row.present_frame,
accent: row.present_accent,
text_color: row.present_text_color,
logo: row.present_logo,
// Room clear at each edge, percent of the screen (097).
inset: [row.present_inset_top, row.present_inset_right, row.present_inset_bottom, row.present_inset_left].some((n) => n)
? {
top: row.present_inset_top ?? 0,
right: row.present_inset_right ?? 0,
bottom: row.present_inset_bottom ?? 0,
left: row.present_inset_left ?? 0,
}
: null,
// In the dark theme (096); null takes the above.
dark: {
background: row.present_background_dark,
background_color: row.present_background_color_dark,
dim: row.present_dim_dark,
accent: row.present_accent_dark,
text_color: row.present_text_color_dark,
logo: row.present_logo_dark,
},
},
blocks: body,
people,
awards,
};
attachTags(db, "event", [event]);
return json(c, { event });
@ -774,7 +809,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 +853,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,151 @@
/* ═══════════════════════════════════════════════════════════════
PRESENT REMOTE: a phone drives a presenting screen by its code
A screen (src/pages/EventPresent.tsx) opens /present/screen, a
stream that first says its code and key, then carries commands.
It posts what it shows (state) with the key. A remote
(src/pages/PresentRemote.tsx) opens /present/:code, a stream of
that state, and posts commands. Anyone with the code can drive
the screen: the code is the only lock, so it's long enough not to
guess at the rate limit set where this is mounted.
In memory only: one process, and a restart only makes each screen
reconnect (keeping its code when no one took it) and post its
state again. A screen gone for SWEEP_AFTER is forgotten.
═══════════════════════════════════════════════════════════════ */
import { randomBytes, randomInt } from "node:crypto";
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
const present = new Hono();
// No 0/O, 1/I/L: read off a screen across a room.
const LETTERS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
const CODE = /^[A-Z0-9]{6}$/;
const PING_EVERY = 25_000; // under nginx's 60 second read timeout
const SWEEP_AFTER = 10 * 60_000;
const COMMANDS = ["next", "prev", "pause", "resume", "go", "setup", "start"];
// A screen's state before it first says.
const NOTHING_YET = { event: "", title: "", query: "", playing: false, paused: false, index: 0, slides: [] };
// code → { key, state, screen (its stream, or null), gone (ms), remotes (streams) }
const screens = new Map();
setInterval(() => {
const now = Date.now();
for (const [code, s] of screens) {
if (!s.screen && s.remotes.size === 0 && now - s.gone > SWEEP_AFTER) screens.delete(code);
}
}, 60_000).unref();
function newCode() {
for (;;) {
const code = Array.from({ length: 6 }, () => LETTERS[randomInt(LETTERS.length)]).join("");
// SCREEN would be the screen's own stream's address.
if (!screens.has(code) && code !== "SCREEN") return code;
}
}
const send = (stream, event, data) => stream.writeSSE({ event, data: JSON.stringify(data) }).catch(() => {});
function tellRemotes(s) {
for (const remote of s.remotes) send(remote, "state", { connected: !!s.screen, ...s.state });
}
// Holds a stream open, pinging, until the other end goes.
function hold(stream, onGone) {
return new Promise((resolve) => {
const ping = setInterval(() => stream.write(": ping\n\n").catch(() => {}), PING_EVERY);
stream.onAbort(() => {
clearInterval(ping);
onGone();
resolve();
});
});
}
/* A screen's stream. It asks for the code it had (code and key) and
gets it back unless that's wrong or another screen holds it now. */
present.get("/present/screen", (c) => {
let code = c.req.query("code");
const key = c.req.query("key");
let s = screens.get(code);
if (!s || s.key !== key || s.screen) {
code = newCode();
s = { key: randomBytes(16).toString("hex"), state: NOTHING_YET, screen: null, gone: 0, remotes: new Set() };
screens.set(code, s);
}
// Tells nginx to pass each event on as it's written.
c.header("X-Accel-Buffering", "no");
return streamSSE(c, async (stream) => {
s.screen = stream;
await send(stream, "hello", { code, key: s.key });
tellRemotes(s);
await hold(stream, () => {
if (s.screen !== stream) return;
s.screen = null;
s.gone = Date.now();
tellRemotes(s);
});
});
});
/* What the screen shows, for its remotes: shown as text there, so
only capped here. */
present.post("/present/:code/state", async (c) => {
const s = screens.get(c.req.param("code"));
const body = await c.req.json().catch(() => null);
if (!s || !body || body.key !== s.key) return c.json({ error: "Not found" }, 404);
const text = (v, max) => (typeof v === "string" ? v.slice(0, max) : "");
const count = (v) => (Number.isInteger(v) && v >= 0 ? v : 0);
s.state = {
event: text(body.event, 200),
title: text(body.title, 300),
query: text(body.query, 4000),
playing: body.playing === true,
paused: body.paused === true,
index: count(body.index),
slides: Array.isArray(body.slides) ? body.slides.slice(0, 500).map((name) => text(name, 150)) : [],
};
tellRemotes(s);
return c.body(null, 204);
});
// A remote's stream: the screen's state now and each time it changes.
present.get("/present/:code", (c) => {
const s = screens.get(c.req.param("code").toUpperCase());
if (!s) return c.json({ error: "No screen has that code." }, 404);
c.header("X-Accel-Buffering", "no");
return streamSSE(c, async (stream) => {
s.remotes.add(stream);
await send(stream, "state", { connected: !!s.screen, ...s.state });
await hold(stream, () => s.remotes.delete(stream));
});
});
/* A command for the screen: next, prev, pause, resume, go (to
`index`), setup (back to its setup) or start (playing `query`, the
setup's choices as EventPresent's address reads them). */
present.post("/present/:code/command", async (c) => {
const code = c.req.param("code").toUpperCase();
const s = CODE.test(code) ? screens.get(code) : null;
if (!s) return c.json({ error: "No screen has that code." }, 404);
if (!s.screen) return c.json({ error: "The screen isn't connected right now." }, 409);
const body = await c.req.json().catch(() => null);
if (!body || !COMMANDS.includes(body.do)) return c.json({ error: "Unknown command." }, 400);
const command = { do: body.do };
if (body.do === "go") {
if (!Number.isInteger(body.index) || body.index < 0) return c.json({ error: "Which slide?" }, 400);
command.index = body.index;
}
if (body.do === "start") {
if (typeof body.query !== "string" || body.query.length > 4000) return c.json({ error: "That setup is too long." }, 400);
command.query = body.query;
}
await send(s.screen, "command", command);
return c.body(null, 204);
});
export default present;

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

@ -79,24 +79,40 @@ const MEMBERS = ["showcase-member-1", "showcase-member-2", "showcase-member-3"];
const EVENT = "showcase-event";
const SERIES = "showcase-series";
const PAST = "showcase-past-event";
const VENUE = "showcase-venue";
/* ── Content ───────────────────────────────────────────────── */
/* A schedule over three days, using every entry field: a plain
entry, one with a location and person, one folding out with a
description, graphic and map, one linked, and one with no day
(it lands in a tab of its own). */
/* A schedule over three days, using every entry field and kind: a
plain entry, one with a location and person, one folding out with
a description, graphic and map, one linked, a heading, a featured
entry, a block with sub-items, a break, typed and picked times,
tags (one a tab of its own in its color, one with No tab), and one
with no day (it lands in a tab of its own). Its venue's locations
(088) are picked on some entries, one with no typed Location, and
one sub-item is the showcase workshop, filled in from it. */
const SCHEDULE = [
"schedule",
{ text: "The weekend at a glance. Tap an entry for more." },
{ text: "The weekend at a glance. Tap an entry for more.", venue_id: VENUE },
[
{ day: "Friday", time: "4:00pm", text: "Arrivals and check-in", location: "Front desk" },
{ day: "Friday", time: "7:00 to 8:30pm", text: "Opening session", location: "Main Hall", person_id: "showcase-person", detail: "Welcome and worship", description: "The **opening session** sets the theme for the weekend.\n\nBring a notebook.", media: "/uploads/showcase.jpg", map: "Camp Hebron, Halifax PA", map_image: "/uploads/showcase.jpg" },
{ day: "Saturday", time: "9:00am", text: "Workshops", location: "Classrooms", person_id: "showcase-member-2", detail: "Pick one of three", url: "/blog/content-block-showcase" },
{ day: "Saturday", time: "7:00pm", text: "Talent night", location: "Main Hall", person_id: "showcase-member-3", description: "Sign up at the front desk by noon." },
{ day: "Friday", start_time: "16:00", text: "Arrivals and check-in", location: "Front desk", tags: "showcase-youth,showcase-all" },
{ day: "Friday", kind: "heading", text: "Evening", detail: "A heading across the day" },
{ day: "Friday", time: "7:00 to 8:30pm", text: "Opening session", location_key: "hall", person_id: "showcase-person", detail: "Welcome and worship", description: "The **opening session** sets the theme for the weekend.\n\nBring a notebook.", media: "/uploads/showcase.jpg", map: "Camp Hebron, Halifax PA", map_image: "/uploads/showcase.jpg" },
{ day: "Saturday", start_time: "08:00", end_time: "09:00", kind: "break", text: "Breakfast", location: "Dining hall" },
{ day: "Saturday", start_time: "09:00", end_time: "10:30", kind: "block", text: "Workshops", location: "Classrooms", detail: "Pick one of three", items: [
{ start_time: "09:00", end_time: "09:45", text: "Leading worship", location: "Room A", location_key: "rooma", person_id: "showcase-member-2", url: "/blog/content-block-showcase" },
{ start_time: "09:00", end_time: "09:45", text: "Showcase Past Workshop", event_id: PAST, location_key: "rooma" },
{ start_time: "09:00", end_time: "09:45", text: "Speaking with confidence", location: "Room B", featured: 1, tags: "showcase-youth", description: "A featured sub-item that folds out." },
{ time: "After the first round", text: "Open questions", location: "Room C" },
] },
{ day: "Saturday", start_time: "19:00", featured: 1, tags: "showcase-youth", text: "Talent night", location: "Main Hall", location_key: "hall", person_id: "showcase-member-3", description: "Sign up at the front desk by noon." },
{ day: "Sunday", time: "10:00am", text: "Closing service", location: "Chapel", map: "Main Street, Halifax PA" },
{ time: "Any time", text: "Quiet room open", location: "Library", detail: "An entry with no day" },
],
[
{ tag_key: "showcase-youth", name: "Youth", color: "#00748a" },
{ tag_key: "showcase-all", name: "Everyone", no_tab: 1 },
],
];
/* Every block type, for the blog showcase. [type, fields, items?] */
@ -129,6 +145,13 @@ const ALL_BLOCKS = [
["image", { media: IMAGE, alt: "The same picture, linked", href: "/history" }],
["subheading", { text: "Schedule" }],
SCHEDULE,
["subheading", { text: "Map" }],
["map", { venue_id: VENUE }],
["subheading", { text: "Events" }],
["events", {}, [
{ event_id: PAST, text: "Showcase Past Workshop" },
{ event_id: "showcase-event", text: "A card with its own title", detail: "And its own text in place of the event's." },
]],
["subheading", { text: "Video" }],
["video", { href: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", text: "A YouTube video, with its own thumbnail" }],
["video", { href: "https://vimeo.com/76979871", media: IMAGE, text: "A Vimeo video with an uploaded still" }],
@ -201,7 +224,7 @@ function insert(table, row) {
}
function blocks(ownerKind, ownerId, slot, list) {
list.forEach(([type, f, items = []], order) => {
list.forEach(([type, f, items = [], tags = []], order) => {
const { lastInsertRowid } = insert("content_blocks", {
owner_kind: ownerKind,
owner_id: ownerId,
@ -210,7 +233,11 @@ function blocks(ownerKind, ownerId, slot, list) {
type,
...f,
});
items.forEach((item, i) => insert("content_block_items", { block_id: lastInsertRowid, sort_order: i, ...item }));
items.forEach(({ items: subitems = [], ...item }, i) => {
const entry = insert("content_block_items", { block_id: lastInsertRowid, sort_order: i, ...item });
subitems.forEach((sub, j) => insert("content_block_subitems", { item_id: entry.lastInsertRowid, sort_order: j, ...sub }));
});
tags.forEach((tag, i) => insert("content_block_tags", { block_id: lastInsertRowid, sort_order: i, ...tag }));
});
}
@ -239,6 +266,7 @@ tx(db, () => {
db.prepare(`DELETE FROM awards WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM affiliations WHERE person_id LIKE 'showcase-%' OR org_id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM teams WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM venues WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM people WHERE id LIKE 'showcase-%'`).run();
db.prepare(`DELETE FROM organizations WHERE id = ?`).run(GROUP);
db.prepare(`DELETE FROM organizations WHERE id LIKE 'showcase-%'`).run();
@ -396,7 +424,6 @@ tx(db, () => {
{ kind: "social", platform: "instagram", label: "@showcaseretreat", url: "https://instagram.com/showcaseretreat" },
]);
blocks("event", EVENT, "both", cardText("event"));
blocks("event", EVENT, "body", [...pageBody("event"), ["heading", { text: "Schedule" }], SCHEDULE]);
insert("events", {
id: SERIES,
@ -442,6 +469,23 @@ tx(db, () => {
insert("event_people", { event_id: PAST, person_id: PERSON, role: "host", is_public: 1, sort_order: 0 });
blocks("event", PAST, "card", cardText("past event"));
/* ── Venue (088): a pin, a box and an unmarked location ── */
insert("venues", { id: VENUE, name: "Showcase Retreat Center", address: "123 Example Road, Exampletown PA", map_image: IMAGE });
[
{ location_key: "hall", name: "Main Hall", detail: "Sessions and talent night", x: 30, y: 40 },
{ location_key: "rooma", name: "Room A", detail: "Workshops", x: 55, y: 20, w: 25, h: 30 },
{ location_key: "desk", name: "Front desk", detail: "Not marked on the map" },
].forEach((location, i) => insert("venue_locations", { venue_id: VENUE, sort_order: i, ...location }));
// The retreat's page, after the workshop and venue its schedule names.
blocks("event", EVENT, "body", [
...pageBody("event"),
["heading", { text: "Schedule" }],
SCHEDULE,
["heading", { text: "Map" }],
["map", { venue_id: VENUE }],
]);
/* ── Award ── */
insert("awards", {
id: AWARD,

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);
@ -61,13 +64,32 @@ export function loadLinks(db, ownerKind, ids) {
rather than no key, so the renderer never has to check.
───────────────────────────────────────────────────────────── */
export function loadBlocks(db, ownerKind, ids, slot = "body") {
/* A block's presentation settings (095), or null with none set. */
function presentOf(row) {
const present = {
// Where it shows (099).
hide: row.present_show === "page",
only: row.present_show === "presentation",
text: row.present_text,
map_split: row.present_map_split === 1,
map_no_list: row.present_map_no_list === 1,
map_no_details: row.present_map_no_details === 1,
places: row.present_places,
place_keys: row.present_place_keys ? row.present_place_keys.split(",").filter(Boolean) : [],
};
return Object.values(present).some((value) => (Array.isArray(value) ? value.length : value)) ? present : null;
}
export function loadBlocks(db, ownerKind, ids, slot = "body", depth = 0) {
const out = new Map();
if (ids.length === 0) return out;
const blockRows = db
.prepare(
`SELECT id, owner_id, type, text, media, href, alt, cite, captions, team_id
`SELECT id, owner_id, type, text, media, media_dark, href, alt, cite, captions, team_id, venue_id,
word_motion, word_direction, word_seconds, list_style, image_size, org_kind,
present_show, present_text, present_map_split, present_map_no_list,
present_map_no_details, present_places, present_place_keys
FROM content_blocks
WHERE owner_kind = ? AND slot IN (?, 'both') AND owner_id IN (${placeholders(ids.length)})
ORDER BY owner_id, sort_order`,
@ -83,11 +105,22 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
type: row.type,
text: row.text,
media: row.media,
media_dark: row.media_dark,
href: row.href,
alt: row.alt,
cite: row.cite,
captions: row.captions,
team_id: row.team_id,
venue_id: row.venue_id,
list_style: row.list_style,
image_size: row.image_size,
org_kind: row.org_kind,
// 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,
// How it's presented (095), when anything is set.
present: presentOf(row),
items: [],
};
byId.set(row.id, block);
@ -99,14 +132,17 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
const blockIds = [...byId.keys()];
const ENTRY_FIELDS = `i.text, i.detail, i.url, i.start_time, i.end_time, i.time, i.location,
i.description, i.media, i.media_alt, i.map, i.map_image, i.featured, i.tags,
i.event_id, i.location_key,
p.id AS person_id, p.display_name AS person_name,
p.photo AS person_photo, p.tagline AS person_tagline`;
const itemRows = db
.prepare(
`SELECT i.block_id, i.text, i.detail, i.url,
i.day, i.time, i.location, i.description, i.media, i.media_alt, i.map, i.map_image,
p.id AS person_id, p.display_name AS person_name,
p.photo AS person_photo, p.tagline AS person_tagline
`SELECT i.id, i.block_id, i.day, i.kind, i.heading, i.subheading, i.org_id, ${ENTRY_FIELDS}
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`,
)
@ -114,34 +150,248 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
// The schedule fields are null on a list or link-row item; they
// ride along anyway rather than branching on the block's type.
// An unpublished person comes back as no person.
const itemsById = new Map();
for (const row of itemRows) {
byId.get(row.block_id)?.items.push({
text: row.text,
detail: row.detail,
url: row.url,
const item = {
...scheduleEntry(row),
day: row.day,
time: row.time,
location: row.location,
description: row.description,
media: row.media,
media_alt: row.media_alt,
map: row.map,
map_image: row.map_image,
person: row.person_id
? {
id: row.person_id,
name: row.person_name,
photo: row.person_photo,
tagline: row.person_tagline,
}
: null,
});
kind: row.kind ?? "entry",
heading: row.heading,
subheading: row.subheading,
org_id: row.org_id,
items: [],
};
itemsById.set(row.id, item);
byId.get(row.block_id)?.items.push(item);
}
// A block entry's sub-items (086).
const blockEntryIds = itemRows.filter((row) => row.kind === "block").map((row) => row.id);
if (blockEntryIds.length) {
const subRows = db
.prepare(
`SELECT i.item_id, ${ENTRY_FIELDS}
FROM content_block_subitems i
LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
WHERE i.item_id IN (${placeholders(blockEntryIds.length)})
ORDER BY i.item_id, i.sort_order`,
)
.all(...blockEntryIds);
for (const row of subRows) itemsById.get(row.item_id)?.items.push(scheduleEntry(row));
}
// A schedule's own tags (087), and each entry's cut to the ones
// the block still has.
const tagRows = db
.prepare(
`SELECT block_id, tag_key, name, color, no_tab
FROM content_block_tags
WHERE block_id IN (${placeholders(blockIds.length)})
ORDER BY block_id, sort_order`,
)
.all(...blockIds);
for (const row of tagRows) {
const block = byId.get(row.block_id);
if (!block) continue;
block.tags ??= [];
block.tags.push({ key: row.tag_key, name: row.name, color: row.color, tab: row.no_tab === 0 });
}
for (const block of byId.values()) {
if (block.type !== "schedule") continue;
const known = new Set((block.tags ??= []).map((tag) => tag.key));
const cut = (entry) => {
entry.tags = entry.tags.filter((key) => known.has(key));
entry.items?.forEach(cut);
};
block.items.forEach(cut);
}
attachVenues(db, [...byId.values()]);
attachEvents(db, [...byId.values()], depth);
// A map block's sections (094): each names some of its venue's
// locations. With any, the block's venue is cut to the locations
// they name, in their order, so the page, its schedule's links
// and the presentation all see the same places, numbered alike.
const sectionRows = db
.prepare(
`SELECT block_id, name, location_keys
FROM content_block_map_sections
WHERE block_id IN (${placeholders(blockIds.length)})
ORDER BY block_id, sort_order`,
)
.all(...blockIds);
for (const row of sectionRows) {
const block = byId.get(row.block_id);
if (!block?.venue) continue;
const known = new Set(block.venue.locations.map((location) => location.key));
const keys = (row.location_keys ?? "").split(",").filter((key) => known.has(key));
if (keys.length) (block.map_sections ??= []).push({ name: row.name, keys });
}
for (const block of byId.values()) {
if (!block.map_sections) continue;
const byKey = new Map(block.venue.locations.map((location) => [location.key, location]));
const shown = [...new Set(block.map_sections.flatMap((section) => section.keys))];
block.venue = { ...block.venue, locations: shown.map((key) => byKey.get(key)) };
}
return out;
}
/* A map or schedule block's venue (088), its locations in order,
and each entry's location_key made its place on it: `place` is
the location, and the location's name stands in for a blank
typed Location. A key the venue no longer has is dropped. */
function attachVenues(db, blocks) {
const ids = [...new Set(blocks.map((block) => block.venue_id).filter(Boolean))];
if (ids.length === 0) return;
const venues = new Map(
db
.prepare(`SELECT id, name, address, map_image, map_alt FROM venues WHERE id IN (${placeholders(ids.length)})`)
.all(...ids)
.map((row) => [row.id, { ...row, locations: [] }]),
);
const locationRows = db
.prepare(
`SELECT venue_id, location_key AS key, name, detail, x, y, w, h, google_maps_url, apple_maps_url
FROM venue_locations
WHERE venue_id IN (${placeholders(ids.length)})
ORDER BY venue_id, sort_order`,
)
.all(...ids);
for (const { venue_id, ...location } of locationRows) venues.get(venue_id)?.locations.push(location);
for (const block of blocks) {
const venue = venues.get(block.venue_id);
block.venue = venue ?? null;
const place = (entry) => {
const location = venue?.locations.find((l) => l.key === entry.location_key) ?? null;
entry.place = location ? { venue_id: venue.id, key: location.key, name: location.name } : null;
if (location && !entry.location) entry.location = location.name;
entry.items?.forEach(place);
};
block.items.forEach(place);
}
}
/* The events named by items (088): an events block's cards, and a
schedule entry or sub-item that is a workshop, which takes what
it leaves blank from its event: the link, the description (its
card text), the graphic (its photo) and the person (a person
host). An unpublished event is no event.
An events block's event also brings its own page's blocks
(`blocks`), drawn when its card is opened. Only at the top
(`depth` 0): a workshop's blocks don't bring theirs, so two
events listing each other can't go round forever. */
function attachEvents(db, blocks, depth = 0) {
const entries = [];
const walk = (entry) => {
entries.push(entry);
entry.items?.forEach(walk);
};
blocks.forEach((block) => block.items.forEach(walk));
const ids = [...new Set(entries.map((entry) => entry.event_id).filter(Boolean))];
if (ids.length === 0) return;
const rows = db
.prepare(
`SELECT e.id, e.title, e.tagline, e.event_type, e.starts_on, e.ends_on, e.date_label,
e.effective_color AS color, COALESCE(e.card_image, e.photo) AS image, e.photo, e.photo_alt,
e.location_label,
p.id AS person_id, p.display_name AS person_name, p.photo AS person_photo,
p.tagline AS person_tagline
FROM v_events e
LEFT JOIN v_people_public p ON e.host_kind = 'person' AND p.id = e.host_id AND p.is_published = 1
WHERE e.is_published = 1 AND e.id IN (${placeholders(ids.length)})`,
)
.all(...ids);
const cards = loadBlocks(db, "event", rows.map((row) => row.id), "card");
const events = new Map(rows.map((row) => [row.id, row]));
const shown = blocks.filter((block) => block.type === "events").flatMap((block) => block.items);
const shownIds = [...new Set(shown.map((item) => item.event_id).filter((id) => events.has(id)))];
const bodies = depth === 0 && shownIds.length ? loadBlocks(db, "event", shownIds, "body", depth + 1) : new Map();
for (const entry of entries) {
const row = events.get(entry.event_id);
if (!row) {
entry.event = null;
continue;
}
const blurb = paragraphs(cards.get(row.id) ?? []).join("\n\n") || row.tagline || null;
entry.event = {
id: row.id,
title: row.title,
event_type: row.event_type,
starts_on: row.starts_on,
ends_on: row.ends_on,
date_label: row.date_label,
color: row.color,
image: row.image,
photo: row.photo,
photo_alt: row.photo_alt,
location_label: row.location_label,
blurb,
};
if (shown.includes(entry)) entry.event.blocks = bodies.get(row.id) ?? [];
entry.url ||= `/events/${row.id}`;
entry.description ||= blurb;
if (!entry.media && row.image) {
entry.media = row.image;
entry.media_alt = row.photo_alt;
}
if (!entry.person && row.person_id) {
entry.person = { id: row.person_id, name: row.person_name, photo: row.person_photo, tagline: row.person_tagline };
}
}
}
/* A schedule entry or sub-item as the page gets it. `time` is what
to show: the typed override, else the picked times (086). An
unpublished person comes back as no person. */
function scheduleEntry(row) {
return {
text: row.text,
detail: row.detail,
url: row.url,
time: row.time || clockRange(row.start_time, row.end_time),
start_time: row.start_time,
end_time: row.end_time,
location: row.location,
description: row.description,
media: row.media,
media_alt: row.media_alt,
map: row.map,
map_image: row.map_image,
featured: row.featured === 1,
tags: row.tags ? row.tags.split(",").filter(Boolean) : [],
event_id: row.event_id,
location_key: row.location_key,
person: row.person_id
? {
id: row.person_id,
name: row.person_name,
photo: row.person_photo,
tagline: row.person_tagline,
}
: null,
};
}
/* "19:00" → 7:00pm, and a range as 9:00 to 10:30am, or 11:30am to
1:00pm when it crosses noon. */
export function clockRange(start, end) {
if (!start) return null;
const clock = (hhmm) => {
const [h, m] = hhmm.split(":").map(Number);
return { text: `${h % 12 || 12}:${String(m).padStart(2, "0")}`, half: h < 12 ? "am" : "pm" };
};
const from = clock(start);
if (!end) return from.text + from.half;
const to = clock(end);
return `${from.text}${from.half === to.half ? "" : from.half} to ${to.text}${to.half}`;
}
/* ── Card description ──────────────────────────────────────────
The card slot is paragraphs by convention, so it collapses to
an array of strings, desc_a and desc_b become description[0]
@ -209,7 +459,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 +516,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."
}
}
}

11
skills-lock.json Normal file
View file

@ -0,0 +1,11 @@
{
"version": 1,
"skills": {
"design-taste-frontend": {
"source": "Leonxlnx/taste-skill",
"sourceType": "github",
"skillPath": "skills/taste-skill/SKILL.md",
"computedHash": "899b84384f74f540ea5284d9b2e9234e050998b42eacc805410b518d4226c0b3"
}
}
}

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"))
@ -70,7 +67,8 @@ const AwardDetail = lazyPage(() => import("./pages/AwardDetail.tsx"))
const PersonDetail = lazyPage(() => import("./pages/PersonDetail.tsx"))
const BlogPost = lazyPage(() => import("./pages/BlogPost.tsx"))
const DirectoryPage = lazyPage(() => import("./pages/DirectoryPage.tsx"))
const SchedulePresent = lazyPage(() => import("./pages/SchedulePresent.tsx"))
const EventPresent = lazyPage(() => import("./pages/EventPresent.tsx"))
const PresentRemote = lazyPage(() => import("./pages/PresentRemote.tsx"))
/*Admin Pages*/
const AdminLayout = lazyPage(() => import("./pages/admin/AdminLayout.tsx"))
@ -82,19 +80,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,33 +105,35 @@ 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. */}
{/* An event page as a slideshow for a screen: full screen, no Layout. */}
<Route
path="/events/:id/present"
element={
<Suspense fallback={null}>
<SchedulePresent />
<EventPresent />
</Suspense>
}
/>
{/* A phone driving a presenting screen, by its code. */}
<Route
path="/remote/:code?"
element={
<Suspense fallback={null}>
<PresentRemote />
</Suspense>
}
/>
<Route
element={
<AuthProvider>
<Suspense fallback={null}>
<Outlet />
</Suspense>
</AuthProvider>
<Suspense fallback={null}>
<Outlet />
</Suspense>
}
>
<Route path="/admin/login" element={<AdminLogin />} />
@ -146,11 +149,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 +164,7 @@ export default function App() {
</Route>
</Route>
</Routes>
</AuthProvider>
</BrowserRouter>
)
}

View file

@ -30,6 +30,14 @@
people team_id's members as people tiles, then
items as more tiles: person, text their
title (an unpublished person is left out)
map venue: its map, locations marked and
listed (MapBlock); a schedule's places
link to it
events items as event cards: event (from
event_id), text the title shown, detail
in place of the event's card text; a card
opens the event in full under them, its
own page's blocks too (EventsBlock)
divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
@ -44,37 +52,62 @@
visible even if the renderer hasn't caught up with it.
═══════════════════════════════════════════════════════════════ */
import { CaretDown } from '@phosphor-icons/react'
import { useEffect, useId, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { mediaUrl } from '../lib/media.ts'
import PeopleTiles from './PeopleTiles.tsx'
import type { ContentBlock, ContentBlockItem } from '../lib/useContent.ts'
import type { ContentBlock, ContentBlockItem, ItemEvent } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs, isExternalUrl } from './InlineText.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import ScheduleBlock from './ScheduleBlock.tsx'
import ScheduleBlock, { Avatar } from './ScheduleBlock.tsx'
import MapBlock, { PageMaps, mapAnchor } from './MapBlock.tsx'
import { eventHref, personHref } from '../lib/hrefs.ts'
import { occurrenceLabel } from '../lib/eventSeries.ts'
import { accentText, BRAND } from '../lib/color.ts'
import { headingAnchors } from '../lib/contents.ts'
import { SITE_NAME } from '../lib/site.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
import { useReadingMode } from '../lib/readingMode.ts'
import { WordMotion, Words } from './RotatingWords.tsx'
import OrgListCards, { OrgLogoRow } from '../pages/sections/OrgList-Card.tsx'
import { usePresenting } from '../lib/presenting.ts'
import { useDarkTheme } from '../lib/darkTheme.ts'
const BODY = 'var(--color-muted)'
/* An image block's Size (101): its widest, centered. */
const IMAGE_SIZE = { small: 'max-w-[20rem]', medium: 'max-w-[32rem]', large: 'max-w-[48rem]' } as const
export default function ContentBlocks({
blocks,
accent = BRAND,
className = '',
presentAt,
anchorPrefix = '',
}: {
blocks?: ContentBlock[] | null
accent?: string
className?: string
/** An event page's presentation route: each schedule gets a Present
* button to it, `?block=<n>` naming which schedule (from 0). */
presentAt?: string
/** Put before each heading's id: a blog post's tab (contents.ts, splitTabs). */
anchorPrefix?: string
}) {
const presenting = usePresenting()
// Presented, a block shown only on the page is left out, so is a
// divider (a slide has its own edges), and the rest take their
// Presentation text (095, 099); on the page, a block shown only in
// the presentation is.
if (blocks) {
blocks = presenting
? blocks
.filter((block) => !block.present?.hide && block.type !== 'divider')
.map((block) => (block.present?.text ? { ...block, text: block.present.text } : block))
: blocks.filter((block) => !block.present?.only)
}
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
@ -85,24 +118,32 @@ export default function ContentBlocks({
return level
})
let schedules = 0
const presentHrefs = blocks.map((block) =>
presentAt && block.type === 'schedule' ? `${presentAt}?block=${schedules++}` : undefined,
// The places mapped here, for a schedule's places to link to: a
// map block's venue's locations (only those its sections show).
const maps = new Set(
blocks.flatMap((block) =>
block.type === 'map' && block.venue
? block.venue.locations.map((location) => mapAnchor(block.venue!.id, location.key))
: [],
),
)
return (
<PageMaps.Provider value={maps}>
<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>
</PageMaps.Provider>
)
}
@ -139,6 +180,182 @@ function LinkCard({ item }: { item: ContentBlockItem }) {
)
}
/* One event card (088): the event's picture, its type and date,
its title (or the item's text) and card text (or the item's
detail); the whole card links to the event. */
/* An event's type and date, eg. workshop · June 14, 2025 (shown
capitalized), or null with neither. */
export function eventLine(event: ItemEvent): string | null {
const when = event.date_label || (event.starts_on ? occurrenceLabel(event.starts_on) : null)
const kind = event.event_type && event.event_type !== 'other' ? event.event_type : null
return [kind, when].filter(Boolean).join(' · ') || null
}
function EventCard({
item,
accent,
open,
panelId,
onToggle,
}: {
item: ContentBlockItem
accent: string
open: boolean
panelId: string
onToggle: () => void
}) {
const event = item.event!
const img = useSmallImage(mediaUrl(event.image))
const color = event.color || accent
const line = eventLine(event)
return (
<button
type="button"
onClick={onToggle}
aria-expanded={open}
aria-controls={panelId}
className="group flex h-full w-full flex-col overflow-hidden border bg-raised text-left shadow-sm transition-shadow hover:shadow-lg"
style={{
borderColor: open ? accent : 'color-mix(in srgb, var(--color-brand) 15%, transparent)',
boxShadow: open ? `inset 0 -4px 0 ${accent}` : undefined,
}}
>
{!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)}
<span className="flex flex-1 flex-col gap-1 p-4">
{line && (
<span className="text-xs font-semibold capitalize" style={{ color: accentText(color) }}>
{line}
</span>
)}
<span className="font-display text-base font-bold leading-snug text-ink group-hover:text-link">
{item.text || event.title}
</span>
{(item.detail || event.blurb) && (
<span className="line-clamp-3 text-sm leading-snug text-body">{item.detail || event.blurb}</span>
)}
<span className="mt-auto inline-flex items-center gap-1 pt-2 text-sm font-semibold" style={{ color: accentText(color) }}>
{open ? 'Close' : 'More'}
<CaretDown aria-hidden="true" weight="bold" className={`h-4 w-4 transition-transform ${open ? 'rotate-180' : ''}`} />
</span>
</span>
</button>
)
}
/* An event in full (088): its photo, type and date, title, place and
person host, then its own page's blocks (else its card text), and
a link to its page. */
function EventInFull({ item, accent, level }: { item: ContentBlockItem; accent: string; level: 3 | 4 | 5 }) {
const event = item.event!
const color = event.color || accent
const photo = mediaUrl(event.photo || event.image)
const line = eventLine(event)
const Title = `h${level}` as 'h3'
const blurb = item.detail || event.blurb
return (
<section aria-label={item.text || event.title} className="space-y-6 bg-raised p-6 shadow-md">
{photo && <img src={photo} alt={event.photo_alt ?? ''} loading="lazy" className="aspect-video w-full object-cover" />}
<div>
{line && (
<p className="text-sm font-semibold capitalize" style={{ color: accentText(color) }}>
{line}
</p>
)}
<Title className="text-2xl font-bold text-ink">{item.text || event.title}</Title>
{(event.location_label || item.person) && (
<p className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-muted">
{event.location_label && <span>{event.location_label}</span>}
{item.person && (
<Link to={personHref(item.person.id)} className="inline-flex items-center gap-2 hover:underline">
<Avatar person={item.person} size="h-8 w-8" />
{item.person.name}
</Link>
)}
</p>
)}
</div>
{event.blocks?.length ? (
<ContentBlocks blocks={event.blocks} accent={color} anchorPrefix={`${event.id}-`} />
) : blurb ? (
<div className="space-y-3 leading-relaxed" style={{ color: BODY }}>
<Paragraphs text={blurb} accent={color} />
</div>
) : null}
<Anchor href={eventHref(event.id)} className="inline-block text-sm font-semibold underline" style={{ color: accentText(color) }}>
{event.title}: the event's page
</Anchor>
</section>
)
}
/* An events block (088): its events as cards; one opened shows in
full under them, scrolled into view. A featured one (090) is
already open, above the cards, under its own heading and
subheading. Reading mode has them all in full. */
function EventsBlock({ items, accent, level }: { items: ContentBlockItem[]; accent: string; level: 3 | 4 | 5 }) {
const [open, setOpen] = useState<number | null>(null)
const panelId = useId()
const panel = useRef<HTMLDivElement>(null)
const reading = useReadingMode()
useEffect(() => {
if (open != null) panel.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}, [open])
const featured = reading ? items : items.filter((item) => item.featured)
const cards = reading ? [] : items.filter((item) => !item.featured)
return (
<div className="space-y-6">
{featured.map((item, i) => (
<FeaturedEvent key={i} item={item} accent={accent} level={level} />
))}
{cards.length > 0 && (
<>
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{cards.map((item, i) => (
<li key={i}>
<EventCard
item={item}
accent={accent}
open={open === i}
panelId={panelId}
onToggle={() => setOpen(open === i ? null : i)}
/>
</li>
))}
</ul>
<div ref={panel} id={panelId}>
{open != null && cards[open] && <EventInFull item={cards[open]} accent={accent} level={level} />}
</div>
</>
)}
</div>
)
}
/* A featured event: its heading and subheading, if set, then the
event in full, its title a level under the heading. */
function FeaturedEvent({ item, accent, level }: { item: ContentBlockItem; accent: string; level: 3 | 4 | 5 }) {
if (!item.heading && !item.subheading) return <EventInFull item={item} accent={accent} level={level} />
const Heading = `h${level}` as 'h3'
const color = item.event?.color || accent
return (
<div className="space-y-4">
<div>
{item.heading && (
<Heading className="text-2xl font-bold" style={{ color: accentText(color) }}>
{item.heading}
</Heading>
)}
{item.subheading && <p className="mt-1 text-lg text-body">{item.subheading}</p>}
</div>
<EventInFull item={item} accent={accent} level={item.heading ? (Math.min(level + 1, 5) as 3 | 4 | 5) : level} />
</div>
)
}
/* A table block's text as rows of cells: one row per line, cells
split by "|" (a literal bar is "\|"), blank lines skipped. A
leading and trailing bar, as in Markdown, is allowed. */
@ -170,33 +387,42 @@ function Block({
accent,
anchor,
level,
presentHref,
}: {
block: ContentBlock
accent: string
anchor?: string
level: 3 | 4 | 5
presentHref?: string
}) {
const text = block.text ?? ''
const reading = useReadingMode()
// On a screen: links are their text, people and organizations
// just pictures and names (095).
const presenting = usePresenting()
// An image block's dark theme picture (102).
const dark = useDarkTheme()
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>
)
case 'list':
case 'list': {
// Bold text and a plain detail, unless the block is set Plain
// (092): plain text, gray detail.
const plain = block.list_style === 'plain'
return (
<ul className="space-y-2">
{(block.items ?? []).map((item, index) => (
@ -204,20 +430,23 @@ function Block({
<span aria-hidden="true" style={{ color: accentText(accent) }}>
•
</span>
<span style={{ color: BODY }}>
{item.url ? (
<Anchor href={item.url} className="underline" style={{ color: accentText(accent) }}>
{item.text}
</Anchor>
) : (
<Inline text={item.text} accent={accent} />
)}
{item.detail && <span className="opacity-70">: {item.detail}</span>}
<span style={{ color: plain ? BODY : 'var(--color-body)' }}>
<span className={plain ? undefined : 'font-bold'}>
{item.url && !presenting ? (
<Anchor href={item.url} className="underline" style={{ color: accentText(accent) }}>
{item.text}
</Anchor>
) : (
<Inline text={item.text} accent={accent} />
)}
</span>
{item.detail && <span className={plain ? 'opacity-70' : undefined}>: {item.detail}</span>}
</span>
</li>
))}
</ul>
)
}
case 'links':
return (
@ -335,7 +564,7 @@ function Block({
)
case 'image': {
const src = mediaUrl(block.media)
const src = mediaUrl((dark && block.media_dark) || block.media)
if (!src) return null
// The reader leaves out a picture with no alt, and its link with it.
if (reading && block.href && !block.alt) {
@ -357,7 +586,7 @@ function Block({
/>
)
return (
<figure>
<figure className={block.image_size ? `mx-auto ${IMAGE_SIZE[block.image_size]}` : undefined}>
{block.href ? <Anchor href={block.href}>{img}</Anchor> : img}
<Caption text={text} />
</figure>
@ -377,7 +606,41 @@ function Block({
case 'schedule':
if (!block.items?.length) return null
return <ScheduleBlock items={block.items} intro={block.text} accent={accent} presentHref={presentHref} />
return (
<ScheduleBlock
items={block.items}
tags={block.tags}
intro={block.text}
accent={accent}
/>
)
case 'map':
if (!block.venue) return null
return <MapBlock venue={block.venue} sections={block.map_sections} accent={accent} />
case 'events': {
const events = (block.items ?? []).filter((item) => item.event)
if (events.length === 0) return null
return <EventsBlock items={events} accent={accent} level={level} />
}
case 'organizations': {
// Picked ones in their order, else every listed one of its kind.
const ids = (block.items ?? []).map((item) => item.org_id).filter((id): id is string => Boolean(id))
if (ids.length === 0 && !block.org_kind) return null
if (presenting) return <OrgLogoRow kind={block.org_kind} ids={ids} accent={accent} />
return (
<OrgListCards
kind={block.org_kind}
ids={ids}
accent={accent}
pageLabel="Their page"
empty="Organizations coming soon."
nested
/>
)
}
case 'people': {
const picked = (block.items ?? [])
@ -386,8 +649,8 @@ function Block({
if (!block.team_id && picked.length === 0) return null
return (
<div className="space-y-6">
{block.team_id && <PeopleTiles size="lg" teams={block.team_id} accent={accent} headingLevel={level} />}
{picked.length > 0 && <PeopleTiles size="lg" people={picked} accent={accent} headingLevel={level} />}
{block.team_id && <PeopleTiles size="lg" teams={block.team_id} accent={accent} headingLevel={level} row={presenting} titles={block.present?.titles} />}
{picked.length > 0 && <PeopleTiles size="lg" people={picked} accent={accent} headingLevel={level} row={presenting} titles={block.present?.titles} />}
</div>
)
}
@ -398,7 +661,7 @@ function Block({
case 'paragraph':
default:
if (!text) return null
return block.href ? (
return block.href && !presenting ? (
<p className="leading-relaxed" style={{ color: BODY }}>
<Anchor href={block.href} className="underline" style={{ color: accentText(accent) }}>
{text}

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"
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>
)}
{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)" }}
>
{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}
>
{link.label}
</a>
) : (
<Link to={link.to} className={pageLinkClass}>
{link.label}
</Link>
)}
{nav.footer.map((link) => (
<li key={`${link.label}${link.path}`}>
<SiteLink link={link} className={pageLinkClass}>
{link.label}
</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">
<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}>
<div className="text-center md:text-left">
<p className="text-white/65 text-sm">© 2026 Next Generation of Unity. All rights reserved.</p>
<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,10 @@
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'
import { usePresenting } from '../lib/presenting.ts'
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
@ -76,17 +78,20 @@ export function Anchor({
)
}
function line(text: string, accent: string, key: string): ReactNode[] {
/* `plain`: a link's text alone, presented (095). */
function line(text: string, accent: string, key: string, plain = false): ReactNode[] {
const out: ReactNode[] = []
let last = 0
let n = 0
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 && plain) out.push(label)
else if (label != null && SAFE_URL.test(url)) {
out.push(
<Anchor key={k} href={url} className="underline underline-offset-2" style={{ color: accentText(accent) }}>
@ -102,13 +107,14 @@ function line(text: string, accent: string, key: string): ReactNode[] {
/** Text inside another element: formatting and line breaks. */
export function Inline({ text, accent }: { text?: string | null; accent: string }) {
const plain = usePresenting()
const lines = (text ?? '').split('\n')
return (
<>
{lines.map((part, i) => (
<Fragment key={i}>
{i > 0 && <br />}
{line(part, accent, `l${i}`)}
{line(part, accent, `l${i}`, plain)}
</Fragment>
))}
</>

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