Feature fixes: admin nav, hero event, schedule block, SEO, site settings, Google sign-in, QR tool #12
|
|
@ -32,6 +32,8 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service.
|
||||
- Never run commands against the production server or database unless explicitly asked.
|
||||
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
|
||||
- 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`.
|
||||
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Only existing accounts (made by admin-cli) get in; passwords still work. Setup: `docs/google-sign-in.md`.
|
||||
|
||||
## Git workflow
|
||||
- Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`.
|
||||
|
|
@ -55,7 +57,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
|
||||
- `api.ts` is the shared caching client used by frontend data hooks.
|
||||
- `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content.
|
||||
- Logos: org logos in `public/org-logos/` (served at `/org-logos/`), event logos in `public/event-logos/`. The `<Logo>` component hides itself on load error.
|
||||
- Images: every record image (logos, photos, backgrounds, block images) is an upload. 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/`. The `<Logo>` component hides itself on load error.
|
||||
|
||||
## 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.
|
||||
|
|
|
|||
75
docs/google-sign-in.md
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
# Google sign-in
|
||||
|
||||
The admin login offers "Sign in with Google" for
|
||||
@nextgenerationofunity.org accounts, alongside email and password. It's
|
||||
off until the service has an OAuth client ID and secret.
|
||||
|
||||
## Who gets in
|
||||
|
||||
Only accounts that already exist. Create them as before with
|
||||
`admin-cli.js add <email>` (the password it asks for stays as a way in
|
||||
if Google is ever unavailable). The first time that person signs in with
|
||||
Google, their Google account is linked to the admin account with the
|
||||
same email; after that it matches by the link, even if the email later
|
||||
changes. `admin-cli.js list` shows which accounts are linked.
|
||||
|
||||
Refused, with a message on the login page: no admin account for that
|
||||
email, 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.
|
||||
|
||||
Code: `server/src/googleAuth.js` (the Google side) and
|
||||
`server/src/routes/auth.js` (matching and linking accounts).
|
||||
|
||||
## Setting up the OAuth client
|
||||
|
||||
In [Google Cloud Console](https://console.cloud.google.com/), signed in
|
||||
as a Workspace admin for nextgenerationofunity.org:
|
||||
|
||||
1. **Create or pick a project**, eg. "NGU Website".
|
||||
2. **APIs & Services → OAuth consent screen** (Google Auth Platform →
|
||||
Branding / Audience):
|
||||
- User type / audience: **Internal**. Only accounts in the Workspace
|
||||
can use it, and Google doesn't need to review the app.
|
||||
- App name: NGU Admin. Support email: yours.
|
||||
- Scopes: `openid`, `email`, `profile` (nothing else is needed).
|
||||
3. **APIs & Services → Credentials → Create credentials → OAuth client
|
||||
ID** (Google Auth Platform → Clients):
|
||||
- Application type: **Web application**. Name: NGU admin.
|
||||
- Authorized redirect URIs:
|
||||
- `https://nextgenerationofunity.org/api/auth/google/callback`
|
||||
- for local work, also the dev address, eg.
|
||||
`http://localhost:5174/api/auth/google/callback`
|
||||
- No JavaScript origins are needed: the browser never talks to Google
|
||||
directly.
|
||||
4. Copy the **Client ID** and **Client secret**.
|
||||
|
||||
## Turning it on
|
||||
|
||||
On the server, add them to the `ngu-api` unit (`systemctl edit ngu-api`)
|
||||
and restart. Never commit the secret or paste it into the repo:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
Environment=GOOGLE_CLIENT_ID=<client id>
|
||||
Environment=GOOGLE_CLIENT_SECRET=<client secret>
|
||||
Environment=GOOGLE_REDIRECT_URI=https://nextgenerationofunity.org/api/auth/google/callback
|
||||
```
|
||||
|
||||
`GOOGLE_REDIRECT_URI` must match the redirect URI in step 3 exactly.
|
||||
Without it the API builds it from `site.json`'s `url`, which the API only
|
||||
finds if `site.json` is deployed with it and `SITE_CONFIG` points at it
|
||||
(the deploy copies `server/` into `/srv/ngu-api`, and `site.json` lives
|
||||
at the repo root, so it isn't there by default). If neither is set,
|
||||
sign-in fails and the log says so.
|
||||
|
||||
Optional:
|
||||
|
||||
| Variable | Default |
|
||||
| --- | --- |
|
||||
| `GOOGLE_REDIRECT_URI` | `<site.json url>/api/auth/google/callback`. Set it for local work, eg. `http://localhost:5174/api/auth/google/callback`, and add the same URI in step 3. |
|
||||
| `GOOGLE_ALLOWED_DOMAIN` | `nextgenerationofunity.org` |
|
||||
|
||||
The login page asks `/api/auth/providers` whether Google is set up, so
|
||||
the button appears as soon as the service restarts with both values.
|
||||
Locally, also set `COOKIE_SECURE=false` when working over plain http.
|
||||
|
|
@ -23,6 +23,17 @@ in the `media` table (`server/src/migrations/028_media.sql`).
|
|||
|
||||
Limits and sizes are constants at the top of `server/src/media.js`.
|
||||
|
||||
## Files copied in by hand
|
||||
|
||||
A file put straight into the uploads directory (with `scp`, say) shows
|
||||
up in the library the next time the Media page or an image picker opens:
|
||||
the server registers any image it finds there without a record, under
|
||||
the file's own name, kept as it is (not resized). Anything that isn't a
|
||||
JPEG, PNG, GIF, WebP or SVG is ignored. A record can name such a file by
|
||||
its bare filename (eg. `fall-retreat-logo.svg`), which resolves to
|
||||
`/uploads/<file>`, and the delete check counts those uses too. Keep the
|
||||
files readable by the `ngu-api` user.
|
||||
|
||||
## Local development
|
||||
|
||||
The API reads `UPLOADS_DIR` (default `./uploads`, so `server/uploads/`,
|
||||
|
|
|
|||
128
docs/seo.md
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
# Search and link previews
|
||||
|
||||
Each page's HTML carries its own title, description, preview image,
|
||||
canonical address and, where it fits, structured data, so a link shared
|
||||
on Facebook, iMessage, Slack, Discord or X shows that page, and search
|
||||
engines see the right title before any JavaScript runs.
|
||||
|
||||
The API does this: nginx sends page requests to it, and it fills the
|
||||
built `index.html` in for that path (`server/src/routes/pages.js`, rules
|
||||
in `server/src/pageMeta.js`). It also serves `/sitemap.xml`.
|
||||
|
||||
## Where the words come from
|
||||
|
||||
Everything below can also be set in the admin, under **Panel → Site
|
||||
settings** (superadmins only): the site's name, description, preview
|
||||
image, favicon and home-screen icon, each static page's title and intro,
|
||||
and whether search engines may list the site. A setting there wins; a
|
||||
blank one falls back to `site.json`. The indexing switch is per
|
||||
database, so the dev server can be off while production is on, from the
|
||||
same build.
|
||||
|
||||
| What | Where |
|
||||
| --- | --- |
|
||||
| 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. |
|
||||
| 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`. |
|
||||
|
||||
Structured data: Organization on the home page, Event on event pages,
|
||||
BlogPosting on posts.
|
||||
|
||||
`robots.txt` is written by the build (`vite.config.ts`): with indexing
|
||||
on it allows everything but `/admin` and `/api` and names the sitemap;
|
||||
with it off it blocks everything.
|
||||
|
||||
## Production setup
|
||||
|
||||
1. The API needs to find two files. Both default to the repo layout
|
||||
(`site.json` at the root, the build in `dist/`), which isn't how the
|
||||
server is deployed: the deploy copies `server/` into `/srv/ngu-api`,
|
||||
so neither file is next to it. Copy `site.json` there with each
|
||||
deploy (eg. rsync it to `/srv/ngu-api/site.json`) and set both on the
|
||||
`ngu-api` unit:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
Environment=SITE_CONFIG=/srv/ngu-api/site.json
|
||||
Environment=SITE_INDEX=/path/to/the/built/site/index.html
|
||||
```
|
||||
|
||||
`index.html` is reread when it changes, so a frontend deploy doesn't
|
||||
need an API restart.
|
||||
|
||||
2. In the nginx site, serve files that exist, send everything else to
|
||||
the API, and fall back to the plain `index.html` if the API is down,
|
||||
so the site still loads (with default previews) during a restart:
|
||||
|
||||
```nginx
|
||||
# Shared by every block that sends a page to the API.
|
||||
# (Or repeat these lines in each block, as nginx-dev does.)
|
||||
# proxy_http_version 1.1;
|
||||
# proxy_set_header Host $host;
|
||||
# proxy_set_header X-Real-IP $remote_addr;
|
||||
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
# proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
location = /sitemap.xml {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
}
|
||||
|
||||
# The home page needs its own block: try_files would otherwise find
|
||||
# the site's folder and serve index.html without asking the API.
|
||||
location = / {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
proxy_intercept_errors on;
|
||||
error_page 500 502 503 504 = @static;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri @page;
|
||||
}
|
||||
|
||||
location @page {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
proxy_intercept_errors on;
|
||||
error_page 500 502 503 504 = @static;
|
||||
}
|
||||
|
||||
location @static {
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
# From the API, so Site settings' indexing switch applies; the
|
||||
# build's own robots.txt if the API is down.
|
||||
location = /robots.txt {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
proxy_intercept_errors on;
|
||||
error_page 500 502 503 504 = @file;
|
||||
}
|
||||
|
||||
location @file {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# Uploads are bigger than the /api/ block's 64k limit allows.
|
||||
location = /api/admin/media {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
client_max_body_size 26m;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
```
|
||||
|
||||
Keep the existing `/api/` and `/uploads/` blocks; they're more
|
||||
specific and still win. Use the port the API listens on. A 404
|
||||
from the API (a record that doesn't exist) goes through as it is;
|
||||
500 to 504 fall back to the plain page.
|
||||
|
||||
A dev or test server should also send `X-Robots-Tag: noindex,
|
||||
nofollow` and its own blocking `robots.txt`, since it shares the
|
||||
production build's settings: see `nginx-dev` in the repo root.
|
||||
|
||||
3. Check it: `curl -s https://nextgenerationofunity.org/events/<id> | grep og:title`
|
||||
should show the event's name, and Facebook's Sharing Debugger or
|
||||
`https://www.opengraph.xyz` will show the preview.
|
||||
|
||||
4. Tell Google: add the site in Google Search Console and submit
|
||||
`https://nextgenerationofunity.org/sitemap.xml`.
|
||||
|
|
@ -28,12 +28,13 @@ what a dropdown in the admin editor says.
|
|||
| If it's… | It lives in… | Change it by… |
|
||||
| ------------------------------------------------------------ | ---------------- | ------------------------------------ |
|
||||
| A record: an event, organization, person, team, award, timeline entry | the database | editing it in the admin |
|
||||
| The front page's words, photos, bands, stats and paths | the database | Admin → Front page |
|
||||
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Blog |
|
||||
| The front page's words, photos, bands, stats and paths | the database | Admin → Pages → Front page |
|
||||
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Pages → Blog posts, and Community blog section |
|
||||
| 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, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) |
|
||||
| Uploaded images | disk + the `media` table | Admin → Media, or any image field. See `docs/media-uploads.md` |
|
||||
| A static page's title and intro (also its search title and description), the site's name, description, preview image, icons, search indexing | 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` |
|
||||
| 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,
|
||||
presentation belongs in code. A dropdown's *values* are data the
|
||||
|
|
@ -175,16 +176,16 @@ also in `admin-schema.js` 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 | **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.ts`). |
|
||||
| Content blocks → Type | heading, subheading, paragraph, list, links, quote, image, divider, video, button, callout, schedule | **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.ts`). |
|
||||
| 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 | **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 (Blog → Community section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
|
||||
| Front page → Featured cards → Card type (Community blog section → Pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
|
||||
| Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` |
|
||||
| Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a |
|
||||
|
||||
|
|
@ -200,11 +201,11 @@ code):
|
|||
| Event → Scope (+ list filter); Front page → Countdown → Only this scope | `event_scopes` | the `event_scopes` table (migration only) |
|
||||
| Event hosts → Organization; affiliations; team and award "Organization" / "Awarded by"; person → Home organization | `organizations` | organizations, labelled by name |
|
||||
| Event hosts / event people / team members / timeline people → Person | `people` | people |
|
||||
| Blog → Community section → Pinned posts → Post | `blog_posts` | blog posts, newest first |
|
||||
| Community blog section → Pinned posts → Post | `blog_posts` | blog posts, newest first |
|
||||
| Timeline → Record; Featured cards → Record | `record_refs` | every event, organization, award, person and team, narrowed by the type picked beside it |
|
||||
| Affiliations → Team | `teams` | teams, filtered to the chosen organization |
|
||||
| Person awards → Award | `awards` | awards, labelled "Award (Organization)" |
|
||||
| Person awards → Presented at; Front page → Count down to | `events` | events |
|
||||
| Person awards → Presented at; Front page → Count down to; Front page → Featured event | `events` | events |
|
||||
| Timeline → Record | `timeline_refs` | all five kinds, filtered by "Points at" |
|
||||
|
||||
---
|
||||
|
|
@ -216,7 +217,7 @@ each is changed in a different place:
|
|||
|
||||
| What you see | Where it's set |
|
||||
| --- | --- |
|
||||
| **The heading on the page** ("National Retreats", "What's on") | **Admin → Front page → Page sections → Heading.** Blank uses the default below. |
|
||||
| **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.ts` |
|
||||
| The subnav links under the header ("#Retreats", "#Calendar") | `PAGE_SECTIONS["/"]` in `src/navConfig.ts` |
|
||||
|
|
@ -271,7 +272,7 @@ The numbers band's "Number Source" dropdown works the same way:
|
|||
| Section titles, blurbs and colours on Retreats, Community, Leadership, Resources, Feedback, Privacy, Terms | the page file in `src/pages/` | the `SECTIONS` array at the top. A section's `id` must match its subnav `hash`. |
|
||||
| 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. |
|
||||
| Chapter 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 → Organizations → a region → Map areas). |
|
||||
| Chapter 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. |
|
||||
| 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` | |
|
||||
|
|
|
|||
|
|
@ -209,6 +209,7 @@ function list(db) {
|
|||
const rows = db
|
||||
.prepare(
|
||||
`SELECT u.email, u.name, u.role, u.is_active, u.last_login_at,
|
||||
u.google_sub IS NOT NULL AS google,
|
||||
(SELECT COUNT(*) FROM sessions s
|
||||
WHERE s.user_id = u.id AND s.expires_at > datetime('now')) AS sessions
|
||||
FROM admin_users u
|
||||
|
|
@ -228,7 +229,8 @@ function list(db) {
|
|||
const state = r.is_active ? r.role : `${r.role} (disabled)`;
|
||||
const seen = r.last_login_at ?? "never";
|
||||
console.log(
|
||||
`${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)`,
|
||||
`${r.email.padEnd(32)} ${state.padEnd(22)} last login ${seen.padEnd(20)} ${r.sessions} session(s)` +
|
||||
(r.google ? " google linked" : ""),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -179,6 +179,7 @@ const blocksChild = (ownerKind) => ({
|
|||
"video",
|
||||
"button",
|
||||
"callout",
|
||||
"schedule",
|
||||
],
|
||||
{ required: true },
|
||||
),
|
||||
|
|
@ -198,6 +199,14 @@ const blocksChild = (ownerKind) => ({
|
|||
text("text", { required: true }),
|
||||
text("detail"),
|
||||
text("url"),
|
||||
// Schedule entries only (034_schedule_block.sql).
|
||||
text("day"),
|
||||
text("time"),
|
||||
text("location"),
|
||||
text("person_id"),
|
||||
text("description"),
|
||||
text("media"),
|
||||
text("map"),
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
@ -710,7 +719,8 @@ const frontPage = {
|
|||
|
||||
columns: [
|
||||
enumeration("hero_backdrop", ["brand", "photos"]),
|
||||
enumeration("hero_feature", ["none", "livestream", "video"]),
|
||||
enumeration("hero_feature", ["none", "livestream", "video", "event"]),
|
||||
text("hero_event_id"),
|
||||
text("eyebrow"),
|
||||
text("headline"),
|
||||
text("subhead"),
|
||||
|
|
@ -894,6 +904,47 @@ const communityPage = {
|
|||
],
|
||||
};
|
||||
|
||||
/* ── 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
|
||||
over site.json. */
|
||||
const siteSettings = {
|
||||
key: "site_settings",
|
||||
table: "site_settings",
|
||||
idColumn: "id",
|
||||
idKind: "slug",
|
||||
singleton: "site",
|
||||
concurrency: "updated_at",
|
||||
writeRole: "superadmin",
|
||||
|
||||
list: {
|
||||
columns: ["id", "site_name", "updated_at"],
|
||||
filters: [],
|
||||
search: [],
|
||||
order: "id",
|
||||
},
|
||||
|
||||
columns: [
|
||||
text("site_name"),
|
||||
text("description"),
|
||||
text("preview_image"),
|
||||
text("favicon"),
|
||||
text("apple_touch_icon"),
|
||||
enumeration("indexing", ["on", "off"]),
|
||||
],
|
||||
|
||||
children: [
|
||||
{
|
||||
key: "pages",
|
||||
table: "site_setting_pages",
|
||||
owner: { column: "settings_id" },
|
||||
order: "sort_order",
|
||||
columns: [text("path", { required: true }), text("title"), text("description")],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const ENTITIES = {
|
||||
organizations,
|
||||
events,
|
||||
|
|
@ -904,6 +955,7 @@ export const ENTITIES = {
|
|||
front_page: frontPage,
|
||||
blog_posts: blogPosts,
|
||||
community_page: communityPage,
|
||||
site_settings: siteSettings,
|
||||
};
|
||||
|
||||
/* ── Options for the form's select inputs ────────────────────── */
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ const SESSION_DAYS = 30;
|
|||
const REFRESH_WITHIN_DAYS = 7;
|
||||
|
||||
// Off only for plain-http local work. Production is behind TLS.
|
||||
const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
|
||||
export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
|
||||
|
||||
const IP_SALT = process.env.IP_SALT ?? randomBytes(16).toString("hex");
|
||||
|
||||
|
|
@ -201,6 +201,11 @@ export async function requireAuth(c, next) {
|
|||
export const ROLES = ["viewer", "editor", "admin", "superadmin"];
|
||||
const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
|
||||
|
||||
/* 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);
|
||||
}
|
||||
|
||||
export function requireRole(...roles) {
|
||||
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
|
||||
return async (c, next) => {
|
||||
|
|
|
|||
153
server/src/googleAuth.js
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
GOOGLE SIGN-IN
|
||||
|
||||
The OAuth 2.0 authorization-code flow with PKCE, done on the
|
||||
server, for @nextgenerationofunity.org accounts. The routes are
|
||||
in routes/auth.js; this is the part that talks to Google and
|
||||
decides whether an answer is good enough.
|
||||
|
||||
Configured by the service environment:
|
||||
|
||||
GOOGLE_CLIENT_ID from Google Cloud Console
|
||||
GOOGLE_CLIENT_SECRET the same; never in the repo
|
||||
GOOGLE_REDIRECT_URI default <site.json url>/api/auth/google/callback;
|
||||
set it when the server is deployed
|
||||
without site.json (SITE_CONFIG)
|
||||
GOOGLE_ALLOWED_DOMAIN default nextgenerationofunity.org
|
||||
|
||||
With no client id or secret it's off: the login page doesn't
|
||||
offer it and the routes answer 404. Setup: docs/google-sign-in.md.
|
||||
|
||||
── Why the ID token isn't signature-checked ──
|
||||
The token comes straight from Google's token endpoint, over TLS,
|
||||
in answer to a request this server made with its own secret.
|
||||
Google's documentation says a token received that way can be
|
||||
trusted without verifying its signature. Everything else is
|
||||
checked: issuer, audience (our client id), expiry, a verified
|
||||
email, and the Workspace domain in the `hd` claim, which only
|
||||
Google sets, not just the email's suffix.
|
||||
|
||||
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.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
import { loadSite } from "./pageMeta.js";
|
||||
|
||||
const AUTHORIZE = "https://accounts.google.com/o/oauth2/v2/auth";
|
||||
const TOKEN = "https://oauth2.googleapis.com/token";
|
||||
const ISSUERS = new Set(["accounts.google.com", "https://accounts.google.com"]);
|
||||
|
||||
const base64url = (buf) => buf.toString("base64url");
|
||||
|
||||
export function googleConfig() {
|
||||
const clientId = process.env.GOOGLE_CLIENT_ID;
|
||||
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
|
||||
if (!clientId || !clientSecret) return null;
|
||||
|
||||
// Whether Google is on depends only on the id and secret. The
|
||||
// return address can come from site.json, which a deploy of the
|
||||
// server alone may not have; that's reported where it's needed
|
||||
// (the sign-in routes), rather than hiding the button.
|
||||
let redirectUri = process.env.GOOGLE_REDIRECT_URI ?? null;
|
||||
if (!redirectUri) {
|
||||
try {
|
||||
const origin = (loadSite().url ?? "").replace(/\/$/, "");
|
||||
if (origin) redirectUri = `${origin}/api/auth/google/callback`;
|
||||
} catch {
|
||||
redirectUri = null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri,
|
||||
domain: (process.env.GOOGLE_ALLOWED_DOMAIN ?? "nextgenerationofunity.org").toLowerCase(),
|
||||
};
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
const state = base64url(randomBytes(24));
|
||||
const verifier = base64url(randomBytes(48));
|
||||
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
||||
|
||||
const url = new URL(AUTHORIZE);
|
||||
url.search = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: config.redirectUri,
|
||||
response_type: "code",
|
||||
scope: "openid email profile",
|
||||
state,
|
||||
code_challenge: challenge,
|
||||
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,
|
||||
prompt: "select_account",
|
||||
});
|
||||
|
||||
return { url: url.toString(), state, verifier };
|
||||
}
|
||||
|
||||
export class GoogleLoginError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message);
|
||||
this.code = code; // shown to the login page as ?error=<code>
|
||||
}
|
||||
}
|
||||
|
||||
/* The second leg: trade the code for tokens and check the identity.
|
||||
Returns { sub, email, name } or throws GoogleLoginError. */
|
||||
export async function finishLogin(config, code, verifier) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(TOKEN, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
code,
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
redirect_uri: config.redirectUri,
|
||||
grant_type: "authorization_code",
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
} catch {
|
||||
throw new GoogleLoginError("google_unreachable", "Couldn't reach Google.");
|
||||
}
|
||||
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !body.id_token) {
|
||||
console.warn(`google token exchange failed: ${res.status} ${body.error ?? ""}`);
|
||||
throw new GoogleLoginError("google_failed", "Google didn't accept the sign-in.");
|
||||
}
|
||||
|
||||
let claims;
|
||||
try {
|
||||
claims = JSON.parse(Buffer.from(body.id_token.split(".")[1], "base64url").toString("utf8"));
|
||||
} catch {
|
||||
throw new GoogleLoginError("google_failed", "Google's answer couldn't be read.");
|
||||
}
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
if (!ISSUERS.has(claims.iss) || claims.aud !== config.clientId || !(claims.exp > now)) {
|
||||
throw new GoogleLoginError("google_failed", "Google's answer didn't check out.");
|
||||
}
|
||||
|
||||
const email = String(claims.email ?? "").toLowerCase();
|
||||
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.`);
|
||||
}
|
||||
|
||||
return { sub: String(claims.sub), email, name: claims.name ?? null };
|
||||
}
|
||||
|
|
@ -23,6 +23,7 @@ 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 pages from "./routes/pages.js";
|
||||
import feedback from "./routes/feedback.js";
|
||||
import auth from "./routes/auth.js";
|
||||
import admin from "./routes/admin.js";
|
||||
|
|
@ -75,6 +76,9 @@ app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
|
|||
app.route("/api/feedback", feedback);
|
||||
|
||||
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 }));
|
||||
app.route("/api/admin/panel", panel);
|
||||
app.route("/api/auth", auth);
|
||||
app.route("/api/admin", admin);
|
||||
|
|
@ -102,6 +106,10 @@ app.use(
|
|||
}),
|
||||
);
|
||||
|
||||
// Last: every other GET that isn't /api is a page of the site, sent
|
||||
// with its metadata filled in (routes/pages.js).
|
||||
app.route("/", pages);
|
||||
|
||||
startSessionSweeper(db);
|
||||
|
||||
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
||||
|
|
|
|||
|
|
@ -29,10 +29,19 @@
|
|||
|
||||
Names are random, so two uploads of "logo.png" can't collide
|
||||
and a filename says nothing about what's in it.
|
||||
|
||||
── Files copied in by hand ──
|
||||
A file put straight into UPLOADS_DIR has no media row, so the
|
||||
library wouldn't know it. registerLooseFiles() gives each image
|
||||
it finds one, under the file's own name, unprocessed, uploaded by
|
||||
nobody. The Media routes call it when the library is listed. Only
|
||||
images are registered (by their bytes, as for an upload); anything
|
||||
else, dotfiles and the temporary names store() writes through
|
||||
are left alone.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
|
||||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import sharp from "sharp";
|
||||
|
|
@ -182,3 +191,82 @@ export async function remove(filename) {
|
|||
if (err.code !== "ENOENT") throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Files copied in by hand ─────────────────────────────────── */
|
||||
|
||||
/* What a file already on disk is: the fields a media row needs, or
|
||||
null when it isn't an image this library takes. */
|
||||
async function describe(filename) {
|
||||
const full = path.join(UPLOADS_DIR, filename);
|
||||
const info = await stat(full);
|
||||
if (!info.isFile() || info.size === 0 || info.size > MAX_UPLOAD_BYTES) return null;
|
||||
|
||||
const buf = await readFile(full);
|
||||
const kind = sniff(buf);
|
||||
if (!kind) return null;
|
||||
|
||||
let width = null;
|
||||
let height = null;
|
||||
if (kind !== "svg") {
|
||||
try {
|
||||
const meta = await sharp(buf).metadata();
|
||||
width = meta.width ?? null;
|
||||
height = meta.pageHeight ?? meta.height ?? null;
|
||||
} catch {
|
||||
return null; // looks like an image, won't open as one
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
filename,
|
||||
content_type: TYPES[kind].mime,
|
||||
bytes: info.size,
|
||||
width,
|
||||
height,
|
||||
processed: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/* Gives every image in UPLOADS_DIR without a media row one. Returns
|
||||
how many it added. Safe to run often: it only reads the folder
|
||||
and the table, and inserts nothing twice (filename is UNIQUE). */
|
||||
export async function registerLooseFiles(db) {
|
||||
let names;
|
||||
try {
|
||||
names = await readdir(UPLOADS_DIR);
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") return 0;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const known = new Set(db.prepare(`SELECT filename FROM media`).all().map((row) => row.filename));
|
||||
const insert = db.prepare(
|
||||
`INSERT OR IGNORE INTO media
|
||||
(filename, original_name, content_type, bytes, width, height, processed, uploaded_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,
|
||||
);
|
||||
|
||||
let added = 0;
|
||||
for (const name of names) {
|
||||
if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue;
|
||||
let row;
|
||||
try {
|
||||
row = await describe(name);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!row) continue;
|
||||
const result = insert.run(
|
||||
row.filename,
|
||||
row.filename,
|
||||
row.content_type,
|
||||
row.bytes,
|
||||
row.width,
|
||||
row.height,
|
||||
row.processed,
|
||||
);
|
||||
added += result.changes;
|
||||
}
|
||||
if (added) console.log(`media: registered ${added} file(s) found in ${UPLOADS_DIR}`);
|
||||
return added;
|
||||
}
|
||||
|
|
|
|||
34
server/src/migrations/033_hero_event.sql
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 033 HERO: A FEATURED EVENT
|
||||
--
|
||||
-- A fourth hero feature, 'event': an event's card beside the
|
||||
-- headline, over whichever backdrop is chosen.
|
||||
--
|
||||
-- hero_event_id the event to feature. Null means the event the
|
||||
-- countdown shows (its pin, or the next one that
|
||||
-- hasn't ended, narrowed by its scope and type),
|
||||
-- so the hero and the countdown can't disagree.
|
||||
-- A pinned event that is over, unpublished or
|
||||
-- deleted falls back the same way; ON DELETE SET
|
||||
-- NULL does the last one.
|
||||
--
|
||||
-- hero_feature's CHECK gains 'event'. A CHECK can't be altered in
|
||||
-- place, so the column is replaced the way 025 did it: a new column
|
||||
-- with the new CHECK, the values copied across, the old one dropped
|
||||
-- and the new one renamed into its place. Nothing else names the
|
||||
-- column, so front_page itself needn't be rebuilt.
|
||||
--
|
||||
-- PRAGMA user_version; -- reads 32 before this file
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
ALTER TABLE front_page ADD COLUMN hero_feature_new TEXT NOT NULL DEFAULT 'none'
|
||||
CHECK (hero_feature_new IN ('none', 'livestream', 'video', 'event'));
|
||||
|
||||
UPDATE front_page SET hero_feature_new = hero_feature;
|
||||
|
||||
ALTER TABLE front_page DROP COLUMN hero_feature;
|
||||
|
||||
ALTER TABLE front_page RENAME COLUMN hero_feature_new TO hero_feature;
|
||||
|
||||
ALTER TABLE front_page ADD COLUMN hero_event_id TEXT
|
||||
REFERENCES events (id) ON DELETE SET NULL;
|
||||
99
server/src/migrations/034_schedule_block.sql
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 034 CONTENT BLOCKS: SCHEDULE
|
||||
--
|
||||
-- A 'schedule' block: the block's items are its entries, grouped
|
||||
-- into one tab per day. Each entry says when, what and where, and
|
||||
-- folds out for more. The block's own text is an optional intro.
|
||||
--
|
||||
-- content_block_items gains the entry's fields. A list or link-row
|
||||
-- block leaves them empty:
|
||||
--
|
||||
-- day the tab it sits under, eg. 'Friday'. Tabs follow
|
||||
-- the order entries are in; blank means one untitled
|
||||
-- day, and a schedule of one day draws no tabs
|
||||
-- time '7:00pm', '9:00 to 10:30am': shown as typed
|
||||
-- location where it happens, eg. 'Main Hall'
|
||||
-- person_id who hosts or speaks: a people row, drawn with its
|
||||
-- photo and linked to its page. ON DELETE SET NULL,
|
||||
-- and an unpublished person isn't shown
|
||||
-- description the fold-out text, formatted like a paragraph
|
||||
-- media a graphic in the fold-out: '/uploads/…' or a URL
|
||||
-- map a place or address to show on a Google map in the
|
||||
-- fold-out, eg. 'Camp Hebron, Halifax PA'
|
||||
--
|
||||
-- text is the entry's title, detail a line under it, url a link on
|
||||
-- the title, as for list items.
|
||||
--
|
||||
-- The type list is a CHECK, so content_blocks is rebuilt the way
|
||||
-- 031 and 032 did it (legacy_alter_table around the rename, then
|
||||
-- the index and the owner trigger again). The item columns are
|
||||
-- plain ADD COLUMNs.
|
||||
--
|
||||
-- PRAGMA user_version; -- reads 33 before this file
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
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')),
|
||||
owner_id TEXT NOT NULL,
|
||||
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
|
||||
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')),
|
||||
text TEXT,
|
||||
media TEXT,
|
||||
href TEXT,
|
||||
alt TEXT,
|
||||
cite TEXT
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO content_blocks_new
|
||||
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
|
||||
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
|
||||
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);
|
||||
|
||||
ALTER TABLE content_block_items ADD COLUMN day TEXT;
|
||||
ALTER TABLE content_block_items ADD COLUMN time TEXT;
|
||||
ALTER TABLE content_block_items ADD COLUMN location TEXT;
|
||||
ALTER TABLE content_block_items ADD COLUMN person_id TEXT
|
||||
REFERENCES people (id) ON DELETE SET NULL;
|
||||
ALTER TABLE content_block_items ADD COLUMN description TEXT;
|
||||
ALTER TABLE content_block_items ADD COLUMN media TEXT;
|
||||
ALTER TABLE content_block_items ADD COLUMN map TEXT;
|
||||
|
||||
|
||||
-- ── Triggers last (see CLAUDE.md, Migrations) ──
|
||||
|
||||
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')
|
||||
END;
|
||||
END;
|
||||
62
server/src/migrations/035_site_settings.sql
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 035 SITE SETTINGS
|
||||
--
|
||||
-- What the site says about itself, editable in the admin (Panel →
|
||||
-- Site settings, superadmins only) instead of only in site.json.
|
||||
-- Every column is an override: null means "whatever site.json
|
||||
-- says", so a fresh database behaves exactly as before and the
|
||||
-- built index.html (made from site.json) stays a true fallback for
|
||||
-- when the API is down.
|
||||
--
|
||||
-- site_name the site's name, in every title
|
||||
-- description the default search description
|
||||
-- preview_image the default link-preview image
|
||||
-- favicon the browser-tab icon ('/uploads/…', PNG or SVG)
|
||||
-- apple_touch_icon the home-screen icon on iPhones (PNG, 180px)
|
||||
-- indexing 'on' or 'off': whether search engines may list
|
||||
-- the site. Per database, so the dev server can
|
||||
-- say off while production says on, from one
|
||||
-- build. Null follows site.json's robots.index.
|
||||
--
|
||||
-- site_setting_pages overrides a static page's title and intro
|
||||
-- (site.json's "pages"), one row per page that differs. The path
|
||||
-- must be one of site.json's pages; the admin only offers those.
|
||||
--
|
||||
-- A singleton like front_page: one row, made here, which the admin
|
||||
-- edits and can't delete.
|
||||
--
|
||||
-- PRAGMA user_version; -- reads 34 before this file
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE site_settings (
|
||||
id TEXT PRIMARY KEY CHECK (id = 'site'),
|
||||
site_name TEXT,
|
||||
description TEXT,
|
||||
preview_image TEXT,
|
||||
favicon TEXT,
|
||||
apple_touch_icon TEXT,
|
||||
indexing TEXT CHECK (indexing IN ('on', 'off')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO site_settings (id) VALUES ('site');
|
||||
|
||||
CREATE TABLE site_setting_pages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
path TEXT NOT NULL, -- '/retreats'
|
||||
title TEXT,
|
||||
description TEXT,
|
||||
UNIQUE (settings_id, path)
|
||||
) STRICT;
|
||||
|
||||
|
||||
-- ── Triggers last (see CLAUDE.md, Migrations) ──
|
||||
|
||||
CREATE TRIGGER site_settings_touch
|
||||
AFTER UPDATE ON site_settings
|
||||
FOR EACH ROW WHEN new.updated_at = old.updated_at
|
||||
BEGIN
|
||||
UPDATE site_settings SET updated_at = datetime('now') WHERE id = new.id;
|
||||
END;
|
||||
506
server/src/pageMeta.js
Normal file
|
|
@ -0,0 +1,506 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PAGE METADATA
|
||||
|
||||
What a page's HTML should say about it before any JavaScript
|
||||
runs: title, description, preview image, canonical address,
|
||||
whether search engines may index it, and structured data. Link
|
||||
previews (Facebook, iMessage, Slack, Discord, X) never run the
|
||||
app's JavaScript, so this is the only way a shared event shows
|
||||
the event rather than the site's defaults.
|
||||
|
||||
routes/pages.js puts it into the built index.html for each
|
||||
request, and serves /sitemap.xml from the same rules.
|
||||
|
||||
── 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
|
||||
pages read the same merged values (renderPage writes them into
|
||||
the HTML as window.__NGU_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.
|
||||
|
||||
── 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
|
||||
/admin noindex
|
||||
|
||||
Image paths resolve like src/lib/media.ts does: a bare filename
|
||||
is in the uploads directory, anything starting with / or a scheme
|
||||
is used as it is.
|
||||
An SVG isn't used as a preview image (the big sites won't show
|
||||
one), so it falls back to the site default.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { loadBlocks, paragraphs } from "./shape.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const SITE_CONFIG = path.resolve(process.env.SITE_CONFIG ?? path.join(here, "../../site.json"));
|
||||
|
||||
const DESCRIPTION_CHARS = 160;
|
||||
|
||||
/* Where a bare filename lives: record images are uploads, whatever
|
||||
kind they are. Mirrors src/lib/media.ts. */
|
||||
const UPLOADS = "/uploads";
|
||||
|
||||
/* ── site.json, reread when it changes ─────────────────────── */
|
||||
|
||||
let cached = { mtime: 0, site: null };
|
||||
|
||||
export function loadSite() {
|
||||
const mtime = statSync(SITE_CONFIG).mtimeMs;
|
||||
if (cached.site && cached.mtime === mtime) return cached.site;
|
||||
const site = JSON.parse(readFileSync(SITE_CONFIG, "utf8"));
|
||||
cached = { mtime, site };
|
||||
return site;
|
||||
}
|
||||
|
||||
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. */
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
title: row.site_name || base.title,
|
||||
description: row.description || base.description,
|
||||
openGraph: { ...base.openGraph, image: row.preview_image || base.openGraph?.image },
|
||||
icons: {
|
||||
...base.icons,
|
||||
icon: row.favicon || base.icons?.icon,
|
||||
apple: row.apple_touch_icon || base.icons?.apple,
|
||||
},
|
||||
robots: {
|
||||
...base.robots,
|
||||
index: row.indexing ? row.indexing === "on" : base.robots?.index !== false,
|
||||
},
|
||||
pages,
|
||||
};
|
||||
}
|
||||
|
||||
/* What the browser app reads for headings and titles. */
|
||||
const forBrowser = (site) => ({ title: site.title, pages: site.pages });
|
||||
|
||||
/* robots.txt for this database's setting, as the build writes it. */
|
||||
export function robotsTxt(site) {
|
||||
if (site.robots?.index === false) return "User-agent: *\nDisallow: /\n";
|
||||
return (
|
||||
"User-agent: *\nDisallow: /admin\nDisallow: /api\n" +
|
||||
(site.url ? `\nSitemap: ${origin(site)}/sitemap.xml\n` : "")
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Helpers ───────────────────────────────────────────────── */
|
||||
|
||||
/* Text as a description: the formatting marks content blocks allow
|
||||
(**bold**, *italic*, [text](url)) taken out, whitespace folded,
|
||||
cut on a word near DESCRIPTION_CHARS. */
|
||||
export function plainText(text) {
|
||||
if (!text) return null;
|
||||
const flat = String(text)
|
||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
||||
.replace(/\*\*(.+?)\*\*/g, "$1")
|
||||
.replace(/\*(.+?)\*/g, "$1")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
if (!flat) return null;
|
||||
if (flat.length <= DESCRIPTION_CHARS) return flat;
|
||||
const cut = flat.slice(0, DESCRIPTION_CHARS);
|
||||
const space = cut.lastIndexOf(" ");
|
||||
return `${(space > DESCRIPTION_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
|
||||
}
|
||||
|
||||
const first = (...values) => values.find((v) => v != null && String(v).trim() !== "") ?? null;
|
||||
|
||||
function imageUrl(site, file, kind) {
|
||||
if (!file || /\.svg(\?|#|$)/i.test(file)) return null;
|
||||
// A record's bare filename is an upload; the site's own default
|
||||
// image (kind null) is a path from the site's root.
|
||||
const pathOrUrl = /^(https?:|\/)/.test(file) ? file : kind ? `${UPLOADS}/${file}` : `/${file}`;
|
||||
return /^https?:/.test(pathOrUrl) ? pathOrUrl : `${origin(site)}${pathOrUrl}`;
|
||||
}
|
||||
|
||||
function firstParagraph(db, ownerKind, id, slot) {
|
||||
return paragraphs(loadBlocks(db, ownerKind, [id], slot).get(id) ?? [])[0] ?? null;
|
||||
}
|
||||
|
||||
/* ── One page ──────────────────────────────────────────────── */
|
||||
|
||||
const ORG_ROUTES = { region: "/regions", chapter: "/chapters", partner: "/partners", national: "/organizations" };
|
||||
|
||||
function defaults(site, db, pathname) {
|
||||
const home = db.prepare(`SELECT headline, subhead FROM front_page WHERE id = 'home'`).get();
|
||||
return {
|
||||
status: 200,
|
||||
title: site.title,
|
||||
description: plainText(first(site.description, home?.subhead)),
|
||||
image: imageUrl(site, site.openGraph?.image, null),
|
||||
canonical: `${origin(site)}${pathname === "/" ? "/" : pathname}`,
|
||||
type: "website",
|
||||
noindex: false,
|
||||
jsonLd: null,
|
||||
site,
|
||||
};
|
||||
}
|
||||
|
||||
function notFound(meta) {
|
||||
return { ...meta, status: 404, noindex: true, title: `Page not found | ${meta.title}` };
|
||||
}
|
||||
|
||||
/* Title for a record page: "Name | Site". */
|
||||
const titled = (site, name) => `${name} | ${site.title}`;
|
||||
|
||||
function eventMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM v_events WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
|
||||
const when = [row.date_label, row.location_label].filter(Boolean).join(" · ");
|
||||
const image =
|
||||
imageUrl(site, row.card_image, "eventBackground") ??
|
||||
imageUrl(site, row.event_logo, "eventLogo") ??
|
||||
imageUrl(site, row.effective_org_logo, "organization") ??
|
||||
meta.image;
|
||||
const description = plainText(first(row.tagline, firstParagraph(db, "event", id, "card"), when, row.theme));
|
||||
|
||||
const place = row.is_online
|
||||
? { "@type": "VirtualLocation", url: meta.canonical }
|
||||
: {
|
||||
"@type": "Place",
|
||||
name: first(row.venue, row.location_label, row.locality),
|
||||
address: {
|
||||
"@type": "PostalAddress",
|
||||
streetAddress: row.address ?? undefined,
|
||||
addressLocality: row.locality ?? undefined,
|
||||
addressRegion: row.state_code ?? undefined,
|
||||
addressCountry: row.country ?? undefined,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.title),
|
||||
description,
|
||||
image,
|
||||
noindex: row.is_listed !== 1,
|
||||
jsonLd: row.starts_on
|
||||
? {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Event",
|
||||
name: row.title,
|
||||
description: description ?? undefined,
|
||||
startDate: row.starts_on,
|
||||
endDate: row.ends_on ?? undefined,
|
||||
eventStatus:
|
||||
row.effective_status === "cancelled"
|
||||
? "https://schema.org/EventCancelled"
|
||||
: "https://schema.org/EventScheduled",
|
||||
eventAttendanceMode: row.is_online
|
||||
? "https://schema.org/OnlineEventAttendanceMode"
|
||||
: "https://schema.org/OfflineEventAttendanceMode",
|
||||
location: place,
|
||||
image: image ? [image] : undefined,
|
||||
organizer: row.host_name ? { "@type": "Organization", name: row.host_name } : undefined,
|
||||
url: meta.canonical,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function organizationMeta(site, db, id, kind, meta) {
|
||||
const row = db.prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1`).get(id);
|
||||
// /regions/x must be a region: the same slug under the wrong route
|
||||
// is a page the site doesn't have.
|
||||
if (!row || (kind && row.kind !== kind)) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.name),
|
||||
description: plainText(first(row.tagline, firstParagraph(db, "organization", id, "card"))),
|
||||
image: imageUrl(site, row.logo, "organization") ?? meta.image,
|
||||
canonical: `${origin(site)}${ORG_ROUTES[row.kind] ?? "/organizations"}/${row.id}`,
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function teamMeta(site, db, id, meta) {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT t.* FROM teams t
|
||||
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
|
||||
WHERE t.id = ? AND t.is_published = 1`,
|
||||
)
|
||||
.get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.name),
|
||||
description: plainText(first(row.tagline, firstParagraph(db, "team", id, "card"))),
|
||||
image: imageUrl(site, row.logo, "team") ?? meta.image,
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function awardMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM awards WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.name),
|
||||
description: plainText(row.description),
|
||||
image: imageUrl(site, row.logo, "award") ?? meta.image,
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function personMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.display_name),
|
||||
description: plainText(first(row.tagline, row.bio, firstParagraph(db, "person", id, "card"))),
|
||||
image: imageUrl(site, row.photo, "person") ?? meta.image,
|
||||
type: "profile",
|
||||
noindex: row.is_listed !== 1,
|
||||
};
|
||||
}
|
||||
|
||||
function blogMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
const authors = db
|
||||
.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
|
||||
WHERE a.post_id = ? ORDER BY a.sort_order`,
|
||||
)
|
||||
.all(id)
|
||||
.map((a) => a.name);
|
||||
if (row.guest_author) authors.push(row.guest_author);
|
||||
|
||||
const description = plainText(first(row.excerpt, firstParagraph(db, "blog_post", id, "body")));
|
||||
const image = imageUrl(site, row.cover_image, "blog") ?? meta.image;
|
||||
|
||||
return {
|
||||
...meta,
|
||||
title: titled(site, row.title),
|
||||
description,
|
||||
image,
|
||||
type: "article",
|
||||
noindex: row.is_listed !== 1,
|
||||
jsonLd: {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BlogPosting",
|
||||
headline: row.title,
|
||||
description: description ?? undefined,
|
||||
datePublished: row.published_on ?? undefined,
|
||||
dateModified: row.updated_at ? row.updated_at.replace(" ", "T") + "Z" : undefined,
|
||||
author: authors.length ? authors.map((name) => ({ "@type": "Person", name })) : undefined,
|
||||
image: image ? [image] : undefined,
|
||||
publisher: { "@type": "Organization", name: site.title, url: `${origin(site)}/` },
|
||||
mainEntityOfPage: meta.canonical,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/* The metadata for one request path. */
|
||||
export function metaFor(db, rawPath) {
|
||||
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);
|
||||
|
||||
if (pathname === "/") {
|
||||
return {
|
||||
...meta,
|
||||
jsonLd: {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
name: site.title,
|
||||
url: `${origin(site)}/`,
|
||||
logo: meta.image ?? undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
|
||||
|
||||
const page = site.pages?.[pathname];
|
||||
if (page) {
|
||||
return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description };
|
||||
}
|
||||
|
||||
const match = pathname.match(/^\/(events|regions|chapters|partners|organizations|teams|awards|people|blog)\/([^/]+)$/);
|
||||
if (!match) return notFound(meta);
|
||||
|
||||
const [, base, rawId] = match;
|
||||
let id;
|
||||
try {
|
||||
id = decodeURIComponent(rawId);
|
||||
} catch {
|
||||
return notFound(meta);
|
||||
}
|
||||
|
||||
switch (base) {
|
||||
case "events":
|
||||
return eventMeta(site, db, id, meta);
|
||||
case "regions":
|
||||
return organizationMeta(site, db, id, "region", meta);
|
||||
case "chapters":
|
||||
return organizationMeta(site, db, id, "chapter", meta);
|
||||
case "partners":
|
||||
return organizationMeta(site, db, id, "partner", meta);
|
||||
case "organizations":
|
||||
return organizationMeta(site, db, id, null, meta);
|
||||
case "teams":
|
||||
return teamMeta(site, db, id, meta);
|
||||
case "awards":
|
||||
return awardMeta(site, db, id, meta);
|
||||
case "people":
|
||||
return personMeta(site, db, id, meta);
|
||||
case "blog":
|
||||
return blogMeta(site, db, id, meta);
|
||||
}
|
||||
return notFound(meta);
|
||||
}
|
||||
|
||||
/* ── Into the HTML ─────────────────────────────────────────── */
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
String(value)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
|
||||
/* The tags the build put in (vite.config.ts's site plugin) that this
|
||||
replaces, so a page never says two different things. */
|
||||
const REPLACED = [
|
||||
/<title>[\s\S]*?<\/title>\s*/i,
|
||||
/<meta\s+(?:name|property)="(?:description|robots|og:[^"]+|twitter:[^"]+)"[^>]*>\s*/gi,
|
||||
/<link\s+rel="canonical"[^>]*>\s*/gi,
|
||||
/<script\s+type="application\/ld\+json"[^>]*>[\s\S]*?<\/script>\s*/gi,
|
||||
/<link\s+rel="(?:icon|apple-touch-icon)"[^>]*>\s*/gi,
|
||||
];
|
||||
|
||||
/* A value for a <script>: JSON with "<" escaped, so nothing in it
|
||||
can end the element early. */
|
||||
const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
|
||||
|
||||
export function renderPage(html, meta) {
|
||||
const site = meta.site;
|
||||
let out = html;
|
||||
for (const pattern of REPLACED) out = out.replace(pattern, "");
|
||||
|
||||
const tags = [
|
||||
`<title>${escapeHtml(meta.title)}</title>`,
|
||||
meta.description && `<meta name="description" content="${escapeHtml(meta.description)}">`,
|
||||
meta.noindex && `<meta name="robots" content="noindex">`,
|
||||
meta.status === 200 && `<link rel="canonical" href="${escapeHtml(meta.canonical)}">`,
|
||||
`<meta property="og:site_name" content="${escapeHtml(site.title)}">`,
|
||||
`<meta property="og:type" content="${meta.type}">`,
|
||||
`<meta property="og:title" content="${escapeHtml(meta.title)}">`,
|
||||
meta.description && `<meta property="og:description" content="${escapeHtml(meta.description)}">`,
|
||||
meta.status === 200 && `<meta property="og:url" content="${escapeHtml(meta.canonical)}">`,
|
||||
meta.image && `<meta property="og:image" content="${escapeHtml(meta.image)}">`,
|
||||
`<meta name="twitter:card" content="${meta.image ? "summary_large_image" : "summary"}">`,
|
||||
meta.image && `<meta name="twitter:image" content="${escapeHtml(meta.image)}">`,
|
||||
// "</" can't appear inside the script, or the browser would
|
||||
// end the element there.
|
||||
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
|
||||
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
|
||||
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
|
||||
// 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.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,
|
||||
].filter(Boolean);
|
||||
|
||||
// A blocked site (Site settings indexing off, or site.json's
|
||||
// robots.index false) stays blocked on every page, whatever the
|
||||
// record says.
|
||||
if (site.robots?.index === false && !meta.noindex) {
|
||||
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
|
||||
}
|
||||
|
||||
return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n </head>`);
|
||||
}
|
||||
|
||||
/* ── Sitemap ───────────────────────────────────────────────── */
|
||||
|
||||
export function sitemap(db) {
|
||||
const site = siteFor(db);
|
||||
const base = origin(site);
|
||||
const day = (value) => (value ? String(value).slice(0, 10) : null);
|
||||
|
||||
const entries = [
|
||||
{ loc: "/" },
|
||||
...Object.keys(site.pages ?? {}).map((loc) => ({ loc })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM events WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/events/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(`SELECT id, kind, updated_at FROM organizations WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `${ORG_ROUTES[r.kind] ?? "/organizations"}/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(
|
||||
`SELECT t.id, t.updated_at FROM teams t
|
||||
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
|
||||
WHERE t.is_published = 1 AND t.is_listed = 1`,
|
||||
)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/teams/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(`SELECT id FROM awards WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/awards/${r.id}` })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM people WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/people/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM blog_posts WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
.map((r) => ({ loc: `/blog/${r.id}`, lastmod: day(r.updated_at) })),
|
||||
];
|
||||
|
||||
const xml = entries
|
||||
.map(
|
||||
(e) =>
|
||||
` <url><loc>${escapeHtml(base + e.loc.split("/").map(encodeURIComponent).join("/"))}</loc>` +
|
||||
(e.lastmod ? `<lastmod>${e.lastmod}</lastmod>` : "") +
|
||||
`</url>`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${xml}\n</urlset>\n`;
|
||||
}
|
||||
|
|
@ -18,7 +18,7 @@
|
|||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { requireAuth, requireRole } from "../auth.js";
|
||||
import { hasRole, requireAuth, requireRole } from "../auth.js";
|
||||
import { ENTITIES, OPTION_QUERIES } from "../admin-schema.js";
|
||||
import {
|
||||
HttpError,
|
||||
|
|
@ -41,6 +41,17 @@ function entityOr404(c) {
|
|||
return entity;
|
||||
}
|
||||
|
||||
/* Saving needs editor, unless the descriptor asks for more
|
||||
(writeRole): site settings are superadmin-only. requireRole on the
|
||||
route is the floor; this is the entity's own bar on top. */
|
||||
function entityForWrite(c) {
|
||||
const entity = entityOr404(c);
|
||||
if (entity.writeRole && !hasRole(c.get("user"), entity.writeRole)) {
|
||||
throw new HttpError(403, "Not allowed.");
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
/* Everything the select inputs need, in one request. Small enough
|
||||
that paging it would cost more than it saves. */
|
||||
entities.get("/options", (c) => {
|
||||
|
|
@ -64,14 +75,14 @@ entities.get("/:entity/:id", (c) => {
|
|||
});
|
||||
|
||||
entities.post("/:entity", requireRole("editor"), async (c) => {
|
||||
const entity = entityOr404(c);
|
||||
const entity = entityForWrite(c);
|
||||
const row = createRow(c.get("db"), entity, await json(c));
|
||||
console.log(`${entity.key} ${row[entity.idColumn]} created by ${c.get("user").email}`);
|
||||
return c.json({ row }, 201, NO_STORE);
|
||||
});
|
||||
|
||||
entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
|
||||
const entity = entityOr404(c);
|
||||
const entity = entityForWrite(c);
|
||||
const id = c.req.param("id");
|
||||
const row = updateRow(c.get("db"), entity, id, await json(c));
|
||||
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@
|
|||
POST /api/auth/login email + password → session cookie
|
||||
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/callback back from it: sign in, or
|
||||
back to the login page with ?error=
|
||||
|
||||
Three deliberate choices:
|
||||
|
||||
|
|
@ -14,18 +18,27 @@
|
|||
A failed login still runs a hash. Otherwise the response time
|
||||
itself says whether the account exists.
|
||||
|
||||
Nothing here creates accounts. See admin-cli.js.
|
||||
Nothing here creates accounts. See admin-cli.js. Google sign-in
|
||||
only lets in an account that already exists: matched by its
|
||||
linked Google id, or on first use by its 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.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
||||
|
||||
import {
|
||||
SECURE_COOKIE,
|
||||
createSession,
|
||||
destroySession,
|
||||
currentUser,
|
||||
hashPassword,
|
||||
verifyPassword,
|
||||
} from "../auth.js";
|
||||
import { GoogleLoginError, finishLogin, googleConfig, startLogin } from "../googleAuth.js";
|
||||
|
||||
const auth = new Hono();
|
||||
|
||||
|
|
@ -96,4 +109,111 @@ auth.get("/me", (c) => {
|
|||
return c.json({ user }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
|
||||
/* ── Google ──────────────────────────────────────────────────── */
|
||||
|
||||
// The state and PKCE verifier between the two legs. Scoped to the
|
||||
// Google routes and gone in ten minutes; Lax so it comes back on
|
||||
// the redirect from Google, which is a top-level navigation.
|
||||
const OAUTH_COOKIE = "ngu_oauth";
|
||||
const OAUTH_COOKIE_OPTIONS = {
|
||||
httpOnly: true,
|
||||
secure: SECURE_COOKIE,
|
||||
sameSite: "Lax",
|
||||
path: "/api/auth/google",
|
||||
};
|
||||
|
||||
// Where to land afterwards: an admin page, never anywhere else.
|
||||
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);
|
||||
|
||||
auth.get("/providers", (c) =>
|
||||
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
|
||||
);
|
||||
|
||||
auth.get("/google", (c) => {
|
||||
const config = googleConfig();
|
||||
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
|
||||
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");
|
||||
}
|
||||
|
||||
const { url, state, verifier } = startLogin(config);
|
||||
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
|
||||
...OAUTH_COOKIE_OPTIONS,
|
||||
maxAge: 600,
|
||||
});
|
||||
return c.redirect(url, 302);
|
||||
});
|
||||
|
||||
auth.get("/google/callback", async (c) => {
|
||||
const config = googleConfig();
|
||||
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
|
||||
|
||||
let saved = null;
|
||||
try {
|
||||
saved = JSON.parse(getCookie(c, OAUTH_COOKIE) ?? "null");
|
||||
} catch {
|
||||
saved = null;
|
||||
}
|
||||
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
|
||||
|
||||
// Pressing Cancel on Google's screen comes back as ?error=.
|
||||
if (c.req.query("error")) return backToLogin(c, "cancelled");
|
||||
|
||||
const code = c.req.query("code");
|
||||
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
|
||||
return backToLogin(c, "expired");
|
||||
}
|
||||
|
||||
let identity;
|
||||
try {
|
||||
identity = await finishLogin(config, code, saved.verifier);
|
||||
} catch (err) {
|
||||
if (err instanceof GoogleLoginError) {
|
||||
console.warn(`google login refused: ${err.code}`);
|
||||
return backToLogin(c, err.code);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const db = c.get("db");
|
||||
const columns = `id, email, name, role, is_active, google_sub`;
|
||||
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
|
||||
|
||||
if (!user) {
|
||||
const byEmail = db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
|
||||
if (!byEmail) {
|
||||
console.warn(`google login: no account for ${identity.email}`);
|
||||
return backToLogin(c, "no_account");
|
||||
}
|
||||
if (byEmail.google_sub) {
|
||||
console.warn(`google login: ${identity.email} is linked to another Google account`);
|
||||
return backToLogin(c, "linked_elsewhere");
|
||||
}
|
||||
// Before linking: a refused sign-in mustn't change the account.
|
||||
if (byEmail.is_active !== 1) return backToLogin(c, "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;
|
||||
}
|
||||
|
||||
if (user.is_active !== 1) return backToLogin(c, "disabled");
|
||||
|
||||
createSession(db, c, user.id);
|
||||
db.prepare(
|
||||
`UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
|
||||
).run(identity.name, user.id);
|
||||
console.log(`login ${user.email} (google)`);
|
||||
|
||||
return c.redirect(saved.next ?? "/admin/home", 302);
|
||||
});
|
||||
|
||||
export default auth;
|
||||
|
|
|
|||
|
|
@ -34,6 +34,12 @@
|
|||
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
|
||||
|
|
@ -42,7 +48,7 @@
|
|||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { asBool, loadFeaturedCards, shapeSeries } from "../shape.js";
|
||||
import { asBool, loadFeaturedCards, loadLinks, shapeSeries, splitLinks } from "../shape.js";
|
||||
|
||||
const home = new Hono();
|
||||
|
||||
|
|
@ -84,6 +90,20 @@ function statValue(db, row) {
|
|||
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, card background 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,
|
||||
card_image: row.card_image,
|
||||
org_logo: row.effective_org_logo,
|
||||
links: actions,
|
||||
};
|
||||
}
|
||||
|
||||
function shapeCountdown(row) {
|
||||
if (!row) return null;
|
||||
return {
|
||||
|
|
@ -179,6 +199,15 @@ home.get("/front-page", (c) => {
|
|||
)
|
||||
.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: {
|
||||
|
|
@ -201,6 +230,7 @@ home.get("/front-page", (c) => {
|
|||
video: page.video_url
|
||||
? { url: page.video_url, title: page.video_title }
|
||||
: null,
|
||||
event: shapeHeroEvent(db, heroEvent),
|
||||
},
|
||||
sections,
|
||||
stats,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,11 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
MEDIA ROUTES: mounted under /api/admin
|
||||
|
||||
GET /media the library, newest first, ?q=name
|
||||
GET /media the library, newest first, ?q=name.
|
||||
Picks up images copied into the
|
||||
uploads folder by hand first
|
||||
(registerLooseFiles, at most every
|
||||
SCAN_EVERY_MS)
|
||||
POST /media upload one image (multipart: file,
|
||||
keep_original)
|
||||
GET /media/:id/uses which records name this file
|
||||
|
|
@ -23,7 +27,14 @@ import { Hono } from "hono";
|
|||
import { bodyLimit } from "hono/body-limit";
|
||||
|
||||
import { requireAuth, requireRole } from "../auth.js";
|
||||
import { MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, remove, store } from "../media.js";
|
||||
import {
|
||||
MAX_UPLOAD_BYTES,
|
||||
MediaError,
|
||||
PUBLIC_PREFIX,
|
||||
registerLooseFiles,
|
||||
remove,
|
||||
store,
|
||||
} from "../media.js";
|
||||
import { fetchImage, previewLink } from "../linkPreview.js";
|
||||
|
||||
const media = new Hono();
|
||||
|
|
@ -34,13 +45,20 @@ const NO_STORE = { "Cache-Control": "no-store" };
|
|||
|
||||
const MAX_LIST = 500;
|
||||
|
||||
/* How often listing the library looks in the uploads folder for
|
||||
files copied there by hand. */
|
||||
const SCAN_EVERY_MS = 30_000;
|
||||
let lastScan = 0;
|
||||
|
||||
/* Tables that can't hold an image path, or mustn't be searched. */
|
||||
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "sqlite_sequence"]);
|
||||
|
||||
function shape(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
url: `${PUBLIC_PREFIX}${row.filename}`,
|
||||
// A hand-copied file keeps its own name, which may need escaping
|
||||
// in a URL (a space, say); uploads' random names never do.
|
||||
url: `${PUBLIC_PREFIX}${encodeURIComponent(row.filename)}`,
|
||||
original_name: row.original_name,
|
||||
content_type: row.content_type,
|
||||
bytes: row.bytes,
|
||||
|
|
@ -84,7 +102,12 @@ async function addToLibrary(db, buf, { originalName, keepOriginal, userId }) {
|
|||
}
|
||||
}
|
||||
|
||||
media.get("/media", (c) => {
|
||||
media.get("/media", async (c) => {
|
||||
if (Date.now() - lastScan > SCAN_EVERY_MS) {
|
||||
lastScan = Date.now();
|
||||
await registerLooseFiles(c.get("db"));
|
||||
}
|
||||
|
||||
const q = (c.req.query("q") ?? "").trim().slice(0, 100);
|
||||
const rows = c
|
||||
.get("db")
|
||||
|
|
@ -168,10 +191,20 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
|
|||
);
|
||||
});
|
||||
|
||||
/* Every TEXT column of every content table, searched for the exact
|
||||
path. Read from the live schema rather than a list of image
|
||||
/* Every TEXT column of every content table, searched for any of the
|
||||
exact values a record can use to name the file: its /uploads/
|
||||
path, that path escaped, or (for a file copied in by hand and
|
||||
typed into a field) its bare name, which media.ts resolves to the
|
||||
same place. Read from the live schema rather than a list of image
|
||||
columns, so a new image field is covered the day it's added. */
|
||||
function usesOf(db, url) {
|
||||
function usesOf(db, filename) {
|
||||
const values = [
|
||||
...new Set([
|
||||
`${PUBLIC_PREFIX}${filename}`,
|
||||
`${PUBLIC_PREFIX}${encodeURIComponent(filename)}`,
|
||||
filename,
|
||||
]),
|
||||
];
|
||||
const tables = db
|
||||
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
|
||||
.all()
|
||||
|
|
@ -188,10 +221,11 @@ function usesOf(db, url) {
|
|||
if (columns.length === 0) continue;
|
||||
|
||||
// Names come from the schema, not the request; quoted anyway.
|
||||
const where = columns.map((col) => `"${col}" = ?`).join(" OR ");
|
||||
const marks = values.map(() => "?").join(", ");
|
||||
const where = columns.map((col) => `"${col}" IN (${marks})`).join(" OR ");
|
||||
const { n } = db
|
||||
.prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`)
|
||||
.get(...columns.map(() => url));
|
||||
.get(...columns.flatMap(() => values));
|
||||
if (n > 0) uses.push({ table, count: n });
|
||||
}
|
||||
return uses;
|
||||
|
|
@ -208,7 +242,7 @@ function findOr404(c) {
|
|||
|
||||
media.get("/media/:id/uses", (c) => {
|
||||
const row = findOr404(c);
|
||||
return c.json({ uses: usesOf(c.get("db"), `${PUBLIC_PREFIX}${row.filename}`) }, 200, NO_STORE);
|
||||
return c.json({ uses: usesOf(c.get("db"), row.filename) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
media.delete("/media/:id", requireRole("admin"), async (c) => {
|
||||
|
|
|
|||
129
server/src/routes/pages.js
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PAGE ROUTES: the site's HTML, with each page's metadata
|
||||
|
||||
GET /sitemap.xml every public, listed page
|
||||
GET /robots.txt this database's indexing setting (Site
|
||||
settings, else site.json), so a dev server
|
||||
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)
|
||||
|
||||
In production nginx serves files that exist (the JS, CSS,
|
||||
uploads) itself and sends everything else here, so a shared link
|
||||
carries the right preview; see docs/seo.md for the block. The app
|
||||
in the page then takes over as usual. In development Vite serves
|
||||
index.html itself and this is never reached.
|
||||
|
||||
SITE_INDEX is the built index.html (default: dist/ at the repo
|
||||
root). It's reread when the file changes, so a deploy needs no
|
||||
restart for the page to update. A record that doesn't exist gets
|
||||
the app's own not-found page with a 404 status, so search engines
|
||||
drop it.
|
||||
|
||||
If the metadata can't be built (no site.json at SITE_CONFIG, say),
|
||||
the page is still served, as built, and the cause is logged once:
|
||||
a preview is never worth a page that won't load.
|
||||
|
||||
Mounted last, after every /api and /uploads route; an unknown
|
||||
/api path is still the API's JSON 404.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { metaFor, renderPage, robotsTxt, siteFor, sitemap } from "../pageMeta.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const SITE_INDEX = path.resolve(
|
||||
process.env.SITE_INDEX ?? path.join(here, "../../../dist/index.html"),
|
||||
);
|
||||
|
||||
const CACHE = "public, max-age=60, stale-while-revalidate=300";
|
||||
|
||||
let cached = { mtime: 0, html: null };
|
||||
|
||||
function indexHtml() {
|
||||
const mtime = statSync(SITE_INDEX).mtimeMs;
|
||||
if (cached.html && cached.mtime === mtime) return cached.html;
|
||||
cached = { mtime, html: readFileSync(SITE_INDEX, "utf8") };
|
||||
return cached.html;
|
||||
}
|
||||
|
||||
const pages = new Hono();
|
||||
|
||||
/* Warned once per cause rather than on every request, so a missing
|
||||
site.json doesn't bury the log. */
|
||||
const warned = new Set();
|
||||
function warnOnce(key, message) {
|
||||
if (warned.has(key)) return;
|
||||
warned.add(key);
|
||||
console.error(message);
|
||||
}
|
||||
|
||||
pages.get("/robots.txt", (c) => {
|
||||
let text;
|
||||
try {
|
||||
text = robotsTxt(siteFor(c.get("db")));
|
||||
} catch (err) {
|
||||
warnOnce(`robots:${err.message}`, `pages: can't build robots.txt: ${err.message}`);
|
||||
return c.text("robots.txt isn't available.", 503);
|
||||
}
|
||||
return c.text(text, 200, { "Cache-Control": CACHE });
|
||||
});
|
||||
|
||||
pages.get("/sitemap.xml", (c) => {
|
||||
let xml;
|
||||
try {
|
||||
xml = sitemap(c.get("db"));
|
||||
} catch (err) {
|
||||
warnOnce(`sitemap:${err.message}`, `pages: can't build the sitemap: ${err.message}`);
|
||||
return c.text("The sitemap isn't available.", 503);
|
||||
}
|
||||
return c.body(xml, 200, {
|
||||
"Content-Type": "application/xml; charset=utf-8",
|
||||
"Cache-Control": CACHE,
|
||||
});
|
||||
});
|
||||
|
||||
pages.get("*", (c, next) => {
|
||||
const pathname = c.req.path;
|
||||
// The API's own paths, and an upload that isn't there, stay plain
|
||||
// 404s rather than becoming a page.
|
||||
if (/^\/(api|uploads)(\/|$)/.test(pathname)) return next();
|
||||
|
||||
let html;
|
||||
try {
|
||||
html = indexHtml();
|
||||
} catch (err) {
|
||||
console.error(`pages: can't read ${SITE_INDEX}: ${err.message}`);
|
||||
return c.text("The site hasn't been built.", 503);
|
||||
}
|
||||
|
||||
// The metadata is an extra. If it can't be built (site.json
|
||||
// missing, a query failing), the page goes out as it was built,
|
||||
// with the site's default tags, rather than not at all.
|
||||
let meta;
|
||||
let page;
|
||||
try {
|
||||
meta = metaFor(c.get("db"), pathname);
|
||||
page = renderPage(html, meta);
|
||||
} catch (err) {
|
||||
warnOnce(
|
||||
`meta:${err.message}`,
|
||||
`pages: serving ${pathname} without its metadata: ${err.message}` +
|
||||
(err.code === "ENOENT" ? " (set SITE_CONFIG to the deployed site.json)" : ""),
|
||||
);
|
||||
return c.html(html, 200, { "Cache-Control": "no-store" });
|
||||
}
|
||||
|
||||
return c.html(page, meta.status, {
|
||||
"Cache-Control": meta.status === 200 ? CACHE : "no-store",
|
||||
});
|
||||
});
|
||||
|
||||
export default pages;
|
||||
|
|
@ -16,7 +16,8 @@
|
|||
/people/showcase-person person: bio, links, roles past and
|
||||
current, events, awards, private data
|
||||
/events/showcase-event upcoming retreat: hosts, billed
|
||||
people, links, blocks, background
|
||||
people, links, blocks, background,
|
||||
a three-day schedule
|
||||
/events/showcase-series weekly series with times
|
||||
/events/showcase-past-event past event where the award was given
|
||||
/blog/content-block-showcase every content block type
|
||||
|
|
@ -37,7 +38,7 @@
|
|||
Run without it again to take them back out.
|
||||
|
||||
Images point at /uploads/showcase.jpg. Upload any photo in
|
||||
Admin → Media and copy it to that name in the uploads directory,
|
||||
Admin → Tools → Media and copy it to that name in the uploads directory,
|
||||
or leave it missing to check how each page copes without one.
|
||||
|
||||
A database under /var/lib/ngu (where the deployed service keeps
|
||||
|
|
@ -81,6 +82,23 @@ const PAST = "showcase-past-event";
|
|||
|
||||
/* ── 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). */
|
||||
const SCHEDULE = [
|
||||
"schedule",
|
||||
{ text: "The weekend at a glance. Tap an entry for more." },
|
||||
[
|
||||
{ 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" },
|
||||
{ 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: "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" },
|
||||
],
|
||||
];
|
||||
|
||||
/* Every block type, for the blog showcase. [type, fields, items?] */
|
||||
const ALL_BLOCKS = [
|
||||
["paragraph", { text: "Every content block type, top to bottom, with each of its options. Use it to check the page after changing how blocks draw." }],
|
||||
|
|
@ -109,6 +127,8 @@ const ALL_BLOCKS = [
|
|||
["subheading", { text: "Images" }],
|
||||
["image", { media: IMAGE, alt: "Describe the picture here", text: "An image with a caption and alt text" }],
|
||||
["image", { media: IMAGE, alt: "The same picture, linked", href: "/history" }],
|
||||
["subheading", { text: "Schedule" }],
|
||||
SCHEDULE,
|
||||
["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" }],
|
||||
|
|
@ -354,7 +374,7 @@ tx(db, () => {
|
|||
{ kind: "social", platform: "instagram", label: "@showcaseretreat", url: "https://instagram.com/showcaseretreat" },
|
||||
]);
|
||||
blocks("event", EVENT, "card", cardText("event"));
|
||||
blocks("event", EVENT, "body", pageBody("event"));
|
||||
blocks("event", EVENT, "body", [...pageBody("event"), ["heading", { text: "Schedule" }], SCHEDULE]);
|
||||
|
||||
insert("events", {
|
||||
id: SERIES,
|
||||
|
|
|
|||
|
|
@ -98,18 +98,39 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
|
|||
|
||||
const itemRows = db
|
||||
.prepare(
|
||||
`SELECT block_id, text, detail, url
|
||||
FROM content_block_items
|
||||
WHERE block_id IN (${placeholders(blockIds.length)})
|
||||
ORDER BY block_id, sort_order`,
|
||||
`SELECT i.block_id, i.text, i.detail, i.url,
|
||||
i.day, i.time, i.location, i.description, i.media, i.map,
|
||||
p.id AS person_id, p.display_name AS person_name,
|
||||
p.photo AS person_photo, p.tagline AS person_tagline
|
||||
FROM content_block_items i
|
||||
LEFT JOIN people p ON p.id = i.person_id AND p.is_published = 1
|
||||
WHERE i.block_id IN (${placeholders(blockIds.length)})
|
||||
ORDER BY i.block_id, i.sort_order`,
|
||||
)
|
||||
.all(...blockIds);
|
||||
|
||||
// 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.
|
||||
for (const row of itemRows) {
|
||||
byId.get(row.block_id)?.items.push({
|
||||
text: row.text,
|
||||
detail: row.detail,
|
||||
url: row.url,
|
||||
day: row.day,
|
||||
time: row.time,
|
||||
location: row.location,
|
||||
description: row.description,
|
||||
media: row.media,
|
||||
map: row.map,
|
||||
person: row.person_id
|
||||
? {
|
||||
id: row.person_id,
|
||||
name: row.person_name,
|
||||
photo: row.person_photo,
|
||||
tagline: row.person_tagline,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
48
site.json
|
|
@ -1,11 +1,57 @@
|
|||
{
|
||||
"title": "Next Generation of Unity",
|
||||
"url": "https://nextgenerationofunity.org",
|
||||
"description": "",
|
||||
"robots": {
|
||||
"index": false
|
||||
"index": true
|
||||
},
|
||||
"openGraph": {
|
||||
"image": ""
|
||||
},
|
||||
"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": "Chapters, regions and the people who make up Next Generation of Unity."
|
||||
},
|
||||
"/leadership": {
|
||||
"title": "Leadership",
|
||||
"description": "The board, staff, and volunteers who keep Next Generation of Unity running."
|
||||
},
|
||||
"/resources": {
|
||||
"title": "Resources",
|
||||
"description": "Teachings, brand assets, and material for chapters 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."
|
||||
},
|
||||
"/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 colours."
|
||||
},
|
||||
"/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."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 221 KiB |
|
Before Width: | Height: | Size: 221 KiB |
|
|
@ -1,82 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="403.64276mm"
|
||||
height="86.755943mm"
|
||||
viewBox="0 0 403.64273 86.755943"
|
||||
version="1.1"
|
||||
id="svg5"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs2" />
|
||||
<g
|
||||
id="layer10"
|
||||
style="display:inline"
|
||||
transform="translate(-344.28592,167.60401)">
|
||||
<g
|
||||
id="g3">
|
||||
<circle
|
||||
style="display:inline;fill:#008da9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:0.634488;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
id="path205602-8-3-1"
|
||||
cx="403.82111"
|
||||
cy="-121.75806"
|
||||
r="40.889923" />
|
||||
<path
|
||||
id="path1887-1-3-7-7-6-2"
|
||||
style="color:#000000;display:inline;fill:#008da9;fill-opacity:1;stroke:none;stroke-width:2.284;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 443.45159,-167.57122 c -8.63995,3.71591 -17.05927,7.97953 -25.85742,11.27148 -3.76442,1.391 -7.68514,2.52606 -11.12305,4.64648 -3.58916,2.42042 -5.95825,6.25942 -7.35135,10.29228 -1.23335,3.0863 -2.32136,6.17712 -3.84982,9.11983 -3.67393,-2.17848 -7.69746,-4.08371 -12.04108,-4.24843 -4.09333,-0.39358 -8.26381,0.55262 -11.85512,2.53592 -6.41916,3.13465 -11.92468,7.82515 -18.56868,10.51862 -2.73797,1.21486 -5.51687,2.3331 -8.27926,3.49077 -0.88252,2.47734 0.77854,5.31191 3.20508,6.10351 4.27199,1.7128 8.98018,1.56772 13.49433,1.35771 4.71612,-0.31488 9.32779,-1.47771 13.7933,-2.98449 4.28568,-1.20657 8.61172,-2.23873 13.00143,-3.03728 -2.64145,2.85774 -6.27041,4.39222 -9.272,6.78523 -0.9862,0.76271 -1.85771,1.89939 -1.64657,3.21845 0.1709,1.85512 1.7211,3.08775 2.9593,4.29677 2.6421,2.35246 5.95831,4.07918 9.49722,4.487017 1.35103,0.106385 2.71085,-0.642417 3.25697,-1.900747 1.43582,-2.68121 2.25426,-5.67671 4.35603,-7.93655 1.20099,-1.4152 3.08751,-1.77888 4.83141,-2.01081 3.79664,-0.62592 7.50391,-2.47133 9.93534,-5.50938 1.37471,-1.65305 2.10201,-3.71602 2.52235,-5.79656 0.1379,-0.6722 1.04486,-0.68506 1.58622,-0.85974 1.78218,-0.35339 3.91283,-0.77776 4.83392,-2.54366 0.89776,-1.84635 -0.0715,-4.04503 -1.61189,-5.21854 -2.41639,-1.86664 -5.65021,-3.01579 -8.63111,-2.61499 2.2258,-1.54005 4.74178,-2.58917 7.19752,-3.70372 6.31792,-2.71081 13.11161,-4.94567 18.40937,-9.54069 3.73885,-3.20962 6.79577,-7.24801 8.78271,-11.76096 0.80138,-2.0522 1.44232,-4.33553 0.95805,-6.5376 -0.3398,-1.04637 -1.34059,-2.15906 -2.5332,-1.91992 z" />
|
||||
<path
|
||||
id="path92116-3-2-7-1-4"
|
||||
style="display:inline;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.222835;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 401.4397,-85.357733 -5.07733,3.7999 c 1.40469,0.28813 3.37038,0.49431 4.1477,0.56482 0,0 13.4726,-8.14749 21.27399,-14.00284 7.80139,-5.855347 13.28514,-13.045137 15.64699,-18.030857 4.23462,-8.93904 5.76755,-17.18121 4.93866,-21.94278 -2.3532,12.13055 -6.84548,20.1394 -8.91525,22.66728 -2.77658,3.39114 -7.3818,10.79482 -14.1263,15.035397 -8.02485,5.04559 -16.87157,10.25674 -17.88846,11.90908 z" />
|
||||
<path
|
||||
fill="#519259"
|
||||
d="m 401.25566,-85.224563 c 2.11431,-7.90893 7.29014,-19.728807 13.53049,-25.077287 3.15174,-2.74769 6.75532,-5.34691 11.45401,-7.64618 4.36158,-2.05194 6.70709,-3.73973 9.19688,-6.81027 3.40267,-3.94053 5.90574,-7.35199 6.96383,-10.47421 0.22347,8.84634 -6.48806,19.37766 -9.02864,23.54668 -6.2265,9.41606 -10.0147,12.608287 -17.50625,17.196147 -4.38236,2.60687 -9.65678,5.68615 -14.61032,9.26512 z"
|
||||
fill-opacity="1"
|
||||
fill-rule="nonzero"
|
||||
id="path184-6-7-6-9-3-2"
|
||||
style="display:inline;fill:#358a0d;fill-opacity:1;stroke:none;stroke-width:0.625031;stroke-opacity:1" />
|
||||
<path
|
||||
style="color:#000000;display:inline;fill:#ffffff;stroke:none;stroke-width:2.284;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 358.52422,-123.11955 c 3.13369,-1.59928 7.04147,-4.49077 10.29591,-6.33595 3.25443,-1.84519 6.30899,-3.58417 9.61426,-4.20523 2.65302,-0.4889 6.37319,-0.18817 9.07211,0.58357 2.69896,0.77175 5.57299,2.70484 7.16593,3.40762 1.59295,0.70275 2.24655,0.19006 2.82855,-0.77494 0.582,-0.96504 2.81839,-6.05064 3.84362,-8.9293 1.02519,-2.87864 2.26409,-5.72337 4.14553,-7.76121 1.88144,-2.03782 2.31893,-2.07776 4.06202,-3.15865 1.74307,-1.08086 10.24244,-3.71628 14.53403,-5.61581 4.29158,-1.89953 8.11957,-3.58996 12.24067,-5.48028 4.12109,-1.89033 6.08861,-2.79441 7.30709,-3.29554 0.273,0.73801 -0.2034,3.06663 -1.16031,5.22317 -0.95691,2.15654 -2.9569,5.04357 -4.86279,7.26365 -1.90589,2.22009 -4.28775,4.10342 -6.82223,5.66812 -2.53448,1.56467 -4.53981,2.45823 -7.60439,3.71266 -3.06457,1.25446 -11.88915,4.7102 -14.64698,7.12005 -2.75786,2.40984 -4.18313,6.63212 -3.64772,7.60115 0.5354,0.96902 2.51391,-1.48598 3.81084,-2.34867 1.29694,-0.8627 1.95172,-1.05814 3.14897,-1.09198 1.17765,-0.0172 2.77532,0.40067 3.29849,0.63293 1.48441,0.659 3.97438,2.00122 3.54176,3.36038 -0.16368,0.51434 -0.19462,0.56904 -3.05611,1.25841 -2.86151,0.68935 -3.48508,1.29579 -3.81533,3.74861 -0.22097,1.47094 -1.44719,3.88743 -3.13317,5.28015 -1.68596,1.39274 -4.55099,2.93627 -8.41717,3.35482 -3.86617,0.41855 -6.17544,3.97192 -6.93256,5.37259 -0.75713,1.40064 -2.66104,5.90506 -2.99685,6.15238 -0.3358,0.24732 -2.76998,-0.36582 -3.79458,-0.82517 -1.02463,-0.45935 -2.612,-1.39111 -3.63624,-2.16132 -1.02425,-0.7702 -3.457,-2.975 -3.0018,-3.64018 0.45519,-0.66516 1.56543,-1.35445 2.73515,-2.12254 1.16972,-0.76811 3.86984,-2.33631 5.3456,-3.59002 1.47576,-1.25372 2.7334,-2.47754 3.4042,-3.48323 0.67079,-1.00567 0.9358,-2.14286 -0.28206,-2.7388 -1.21786,-0.59597 -1.84092,-0.39835 -4.4486,0.0225 -2.60769,0.42097 -4.8218,1.10142 -8.46858,1.9005 -3.64678,0.79905 -7.82786,2.49393 -10.97221,3.07304 -3.14439,0.5791 -4.3363,0.83756 -8.5197,0.95691 -4.1834,0.11935 -7.15938,-0.35864 -8.95468,-0.91763 -1.7953,-0.55899 -2.64147,-1.55556 -2.60415,-2.17667 3.90737,-1.58574 7.9469,-3.2841 11.38348,-5.04009 z"
|
||||
id="path1887-1-3-7-7-6" />
|
||||
<path
|
||||
fill="#519259"
|
||||
d="m 412.95849,-81.884143 c 4.58067,-1.05723 7.7275,-1.9948 13.67931,-5.91343 5.95181,-3.91863 10.62995,-9.54813 13.02992,-14.097387 2.39997,-4.54926 4.34384,-10.28218 4.83384,-15.81643 0.49,-5.53425 0.14775,-11.25197 -2.10696,-17.66367 0.15927,9.10203 -2.7414,15.06092 -4.17879,18.80503 -1.43739,3.74411 -4.80196,9.50687 -8.2717,13.57264 -3.46184,4.223207 -7.82036,7.647487 -12.67981,10.383567 -5.38026,3.05578 -13.21504,8.4585 -16.7484,11.61577 4.01135,0.4226 9.12694,-0.10316 12.44259,-0.88609 z"
|
||||
fill-opacity="1"
|
||||
fill-rule="nonzero"
|
||||
id="path182-2-6-6-7-2-2"
|
||||
style="display:inline;fill:#358a0d;fill-opacity:1;stroke:none;stroke-width:0.717458;stroke-opacity:1" />
|
||||
</g>
|
||||
<g
|
||||
id="g40616-9"
|
||||
transform="translate(13.096206,-216.39844)"
|
||||
style="display:inline">
|
||||
<g
|
||||
id="g2-4">
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-size:34.109px;line-height:1.25;font-family:Impact;-inkscape-font-specification:Impact;letter-spacing:0px;word-spacing:0px;display:inline;stroke-width:0.852729"
|
||||
x="451.59149"
|
||||
y="89.758339"
|
||||
id="text156858-3-8"><tspan
|
||||
id="tspan156856-8-82"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:34.109px;font-family:Poppins;-inkscape-font-specification:'Poppins, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:#008da9;fill-opacity:1;stroke-width:0.852729"
|
||||
x="451.59149"
|
||||
y="89.758339">Next Generation</tspan></text>
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-size:33.8136px;line-height:1.25;font-family:Impact;-inkscape-font-specification:Impact;letter-spacing:0px;word-spacing:0px;display:inline;stroke-width:0.845345"
|
||||
x="469.26224"
|
||||
y="119.08144"
|
||||
id="text156858-3-1-4"><tspan
|
||||
id="tspan156856-8-8-5"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:33.8136px;font-family:Poppins;-inkscape-font-specification:'Poppins, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;fill:#008da9;fill-opacity:1;stroke-width:0.845345"
|
||||
x="469.26224"
|
||||
y="119.08144">of Unity</tspan></text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 8.4 KiB |
|
|
@ -19,6 +19,10 @@
|
|||
image media, alt, text is the caption, href
|
||||
video href is the video, media a still, text
|
||||
the caption; click to play
|
||||
schedule items as entries in day tabs (day, time,
|
||||
text, detail, url, location, person, and
|
||||
a fold-out of description, media, map);
|
||||
text is an optional intro. ScheduleBlock
|
||||
divider nothing
|
||||
|
||||
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
|
||||
|
|
@ -33,6 +37,7 @@ import { blockMedia } from '../lib/media.ts'
|
|||
import type { ContentBlock } from '../lib/useContent.ts'
|
||||
import { Anchor, Inline, Paragraphs } from './InlineText.tsx'
|
||||
import VideoPlayer from './VideoPlayer.tsx'
|
||||
import ScheduleBlock from './ScheduleBlock.tsx'
|
||||
|
||||
const BODY = '#4a6b72'
|
||||
|
||||
|
|
@ -196,6 +201,10 @@ function Block({ block, accent }: { block: ContentBlock; accent: string }) {
|
|||
</figure>
|
||||
)
|
||||
|
||||
case 'schedule':
|
||||
if (!block.items?.length) return null
|
||||
return <ScheduleBlock items={block.items} intro={block.text} accent={accent} />
|
||||
|
||||
case 'divider':
|
||||
return <hr className="border-0 h-px" style={{ background: accent, opacity: 0.3 }} />
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Link } from "react-router-dom";
|
||||
import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts";
|
||||
import nguLogo from "../assets/NGU_Logo.svg";
|
||||
import nguLogo from "../assets/logos/NGU_Logo.svg";
|
||||
import PlatformIcon from "./PlatformIcon.tsx";
|
||||
|
||||
const Social_Links = [
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { useState, useEffect, useRef } from "react";
|
|||
import { NavLink, Link, Outlet, useLocation } from "react-router-dom";
|
||||
import { PAGE_LINKS, PAGE_SECTIONS, NAV_ACTIONS } from "../navConfig.ts";
|
||||
import Banner from "./Banner.jsx";
|
||||
import nguLogo from "../assets/NGU_Logo.svg";
|
||||
import nguLogo from "../assets/logos/NGU_Logo.svg";
|
||||
import Footer from "./Footer.tsx";
|
||||
|
||||
/* ── Right-side nav actions ──────────────────────────────── */
|
||||
|
|
|
|||
|
|
@ -29,7 +29,9 @@
|
|||
/>
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
|
||||
import { documentTitle } from "../lib/site.ts";
|
||||
|
||||
const TEAL = "#138ba0";
|
||||
|
||||
|
|
@ -89,6 +91,13 @@ export function Section({ section }: { section: ShellSection }) {
|
|||
}
|
||||
|
||||
export default function PageShell({ title, intro, sections }: PageShellProps) {
|
||||
// The tab's title as the visitor moves around. The first load's
|
||||
// comes from the server (pageMeta.js), which also sets the page's
|
||||
// description and preview for search and link sharing.
|
||||
useEffect(() => {
|
||||
if (typeof title === "string") document.title = documentTitle(title);
|
||||
}, [title]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Page header */}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,25 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
QR CODE
|
||||
|
||||
A QR code as an <svg>, sized by its container. With `dove`, the
|
||||
NGU dove sits on a white badge over the centre; the code switches
|
||||
to high error correction so the modules under the badge are
|
||||
recovered when it's scanned (see lib/qr.ts). The badge covers
|
||||
under 6% of the code, well inside what 'H' repairs, and never
|
||||
reaches the three corner finder patterns.
|
||||
A QR code as an <svg>, sized by its container.
|
||||
|
||||
Everything is drawn in the SVG itself (no CSS, no external
|
||||
references), so the element serialises to a file that looks the
|
||||
same outside the page. `ref` reaches the <svg> for exactly that.
|
||||
`centre` puts something on a badge over the middle: the NGU dove,
|
||||
or an image (an SVG from src/assets/qr, passed as a data: URL).
|
||||
With anything there, the code switches to high error correction
|
||||
so the modules under the badge are recovered when it's scanned
|
||||
(see lib/qr.ts). The badge covers under 6% of the code, well
|
||||
inside what 'H' repairs, and never reaches the three corner
|
||||
finder patterns.
|
||||
|
||||
`ink` is the modules and the badge's outline, `paper` the
|
||||
background and the badge. A code should stay dark on light with
|
||||
strong contrast to scan reliably; QrCodeMaker warns when it
|
||||
doesn't, this just draws what it's given.
|
||||
|
||||
Everything is drawn in the SVG itself (no CSS, and an image is
|
||||
embedded rather than linked), so the element serialises to a
|
||||
file that looks the same outside the page. `ref` reaches the
|
||||
<svg> for exactly that.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useMemo, type Ref } from 'react'
|
||||
|
|
@ -23,8 +32,9 @@ import { qrMatrix, qrPath } from '../lib/qr.ts'
|
|||
const MARGIN = 4
|
||||
|
||||
/* Dark enough to scan as black; the site's deep teal. */
|
||||
const INK = '#04262e'
|
||||
const TEAL = '#138ba0'
|
||||
export const QR_INK = '#04262e'
|
||||
export const QR_PAPER = '#ffffff'
|
||||
export const QR_DOVE = '#138ba0'
|
||||
|
||||
/* Badge side as a share of the code's width. */
|
||||
const BADGE = 0.24
|
||||
|
|
@ -32,21 +42,28 @@ const BADGE = 0.24
|
|||
/* DoveMark's own viewBox is 72.87 × 48.57. */
|
||||
const DOVE_ASPECT = 72.867699 / 48.568241
|
||||
|
||||
export type QrCentre = { kind: 'dove'; color?: string } | { kind: 'image'; src: string } | null
|
||||
|
||||
export default function QrCode({
|
||||
value,
|
||||
dove = false,
|
||||
centre = null,
|
||||
ink = QR_INK,
|
||||
paper = QR_PAPER,
|
||||
label,
|
||||
ref,
|
||||
className,
|
||||
}: {
|
||||
value: string
|
||||
dove?: boolean
|
||||
centre?: QrCentre
|
||||
ink?: string
|
||||
paper?: string
|
||||
/** Accessible name for the image, e.g. "QR code for /retreats". */
|
||||
label: string
|
||||
ref?: Ref<SVGSVGElement>
|
||||
className?: string
|
||||
}) {
|
||||
const matrix = useMemo(() => qrMatrix(value, dove ? 'H' : 'M'), [value, dove])
|
||||
const level = centre ? 'H' : 'M'
|
||||
const matrix = useMemo(() => qrMatrix(value, level), [value, level])
|
||||
const path = useMemo(() => qrPath(matrix, MARGIN), [matrix])
|
||||
|
||||
const total = matrix.size + MARGIN * 2
|
||||
|
|
@ -54,6 +71,7 @@ export default function QrCode({
|
|||
const badgeAt = (total - badge) / 2
|
||||
const doveWidth = badge * 0.78
|
||||
const doveHeight = doveWidth / DOVE_ASPECT
|
||||
const imageSize = badge * 0.8
|
||||
|
||||
return (
|
||||
<svg
|
||||
|
|
@ -65,10 +83,10 @@ export default function QrCode({
|
|||
className={className}
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<rect width={total} height={total} fill="#ffffff" />
|
||||
<path d={path} fill={INK} />
|
||||
<rect width={total} height={total} fill={paper} />
|
||||
<path d={path} fill={ink} />
|
||||
|
||||
{dove && (
|
||||
{centre && (
|
||||
<g shapeRendering="auto">
|
||||
<rect
|
||||
x={badgeAt}
|
||||
|
|
@ -76,17 +94,28 @@ export default function QrCode({
|
|||
width={badge}
|
||||
height={badge}
|
||||
rx={badge * 0.22}
|
||||
fill="#ffffff"
|
||||
stroke={INK}
|
||||
fill={paper}
|
||||
stroke={ink}
|
||||
strokeWidth={0.35}
|
||||
/>
|
||||
<DoveMark
|
||||
x={(total - doveWidth) / 2}
|
||||
y={(total - doveHeight) / 2}
|
||||
width={doveWidth}
|
||||
height={doveHeight}
|
||||
style={{ color: TEAL }}
|
||||
/>
|
||||
{centre.kind === 'dove' ? (
|
||||
<DoveMark
|
||||
x={(total - doveWidth) / 2}
|
||||
y={(total - doveHeight) / 2}
|
||||
width={doveWidth}
|
||||
height={doveHeight}
|
||||
style={{ color: centre.color ?? QR_DOVE }}
|
||||
/>
|
||||
) : (
|
||||
<image
|
||||
href={centre.src}
|
||||
x={(total - imageSize) / 2}
|
||||
y={(total - imageSize) / 2}
|
||||
width={imageSize}
|
||||
height={imageSize}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
/>
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
|
|
|
|||
270
src/components/ScheduleBlock.tsx
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SCHEDULE BLOCK
|
||||
|
||||
The 'schedule' content block (034_schedule_block.sql): entries
|
||||
in one tab per day, each a row of time, title, place and person,
|
||||
folding out for the rest.
|
||||
|
||||
Tabs are the entries' `day` values in the order they first
|
||||
appear, so the admin's order is the page's. An entry with no day
|
||||
joins an untitled group; a schedule of one day draws no tabs. The
|
||||
tab whose name starts with today's weekday opens first ("Friday",
|
||||
"Fri", "Friday, June 6"), so on the day of an event the visitor
|
||||
lands on today; otherwise the first tab.
|
||||
|
||||
A row folds out when it has anything more to show: a
|
||||
description, a graphic, a map, or a person (their photo, tagline
|
||||
and a link to their page). The map is Google's key-free embed of
|
||||
the place typed in, with a link out to the full map.
|
||||
|
||||
Tabs follow the ARIA tab pattern: arrow keys move between them.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useId, useState, type KeyboardEvent } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import { personHref } from '../lib/hrefs.ts'
|
||||
import { blockMedia, initials, personPhoto } from '../lib/media.ts'
|
||||
import type { ContentBlockItem } from '../lib/useContent.ts'
|
||||
import { Anchor, Paragraphs } from './InlineText.tsx'
|
||||
|
||||
const BODY = '#4a6b72'
|
||||
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
|
||||
|
||||
type Day = { name: string; entries: ContentBlockItem[] }
|
||||
|
||||
function groupByDay(items: ContentBlockItem[]): Day[] {
|
||||
const days: Day[] = []
|
||||
for (const item of items) {
|
||||
const name = item.day?.trim() ?? ''
|
||||
let day = days.find((d) => d.name === name)
|
||||
if (!day) {
|
||||
day = { name, entries: [] }
|
||||
days.push(day)
|
||||
}
|
||||
day.entries.push(item)
|
||||
}
|
||||
return days
|
||||
}
|
||||
|
||||
/* The tab to open with: today's weekday if a tab starts with it (or
|
||||
its three-letter form), else the first. */
|
||||
function todayIndex(days: Day[]): number {
|
||||
const today = WEEKDAYS[new Date().getDay()]
|
||||
const found = days.findIndex((day) => {
|
||||
const name = day.name.toLowerCase()
|
||||
return name.startsWith(today) || name.startsWith(today.slice(0, 3))
|
||||
})
|
||||
return found >= 0 ? found : 0
|
||||
}
|
||||
|
||||
const mapEmbed = (place: string) =>
|
||||
`https://maps.google.com/maps?q=${encodeURIComponent(place)}&output=embed&maptype=satellite`
|
||||
const mapLink = (place: string) =>
|
||||
`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(place)}`
|
||||
|
||||
function Avatar({ person, size }: { person: NonNullable<ContentBlockItem['person']>; size: string }) {
|
||||
const [failed, setFailed] = useState(false)
|
||||
const src = personPhoto(person.photo)
|
||||
return src && !failed ? (
|
||||
<img src={src} alt="" onError={() => setFailed(true)} className={`${size} shrink-0 rounded-full object-cover`} />
|
||||
) : (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`${size} flex shrink-0 items-center justify-center rounded-full bg-[#eef9fb] text-xs font-bold text-[#138ba0]`}
|
||||
>
|
||||
{initials(person.name)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function Entry({ entry, accent }: { entry: ContentBlockItem; accent: string }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const panelId = useId()
|
||||
const graphic = blockMedia(entry.media)
|
||||
const place = entry.map?.trim()
|
||||
const more = Boolean(entry.description || graphic || place || entry.person)
|
||||
|
||||
const title = entry.url ? (
|
||||
<Anchor href={entry.url} className="underline-offset-2 hover:underline" style={{ color: accent }}>
|
||||
{entry.text}
|
||||
</Anchor>
|
||||
) : (
|
||||
entry.text
|
||||
)
|
||||
|
||||
return (
|
||||
<li className="border-b border-[#138ba0]/10 last:border-b-0">
|
||||
<div className="flex gap-4 py-4 sm:gap-6">
|
||||
<p className="w-24 shrink-0 pt-0.5 text-sm font-semibold sm:w-32" style={{ color: accent }}>
|
||||
{entry.time}
|
||||
</p>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-semibold text-[#26454c]">{title}</p>
|
||||
{(entry.location || entry.person) && (
|
||||
<p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm" style={{ color: BODY }}>
|
||||
{entry.location && <span>{entry.location}</span>}
|
||||
{entry.person && (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Avatar person={entry.person} size="h-6 w-6" />
|
||||
{entry.person.name}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{entry.detail && (
|
||||
<p className="mt-1 text-sm" style={{ color: BODY }}>
|
||||
{entry.detail}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{more && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-expanded={open}
|
||||
aria-controls={panelId}
|
||||
aria-label={open ? `Less about ${entry.text}` : `More about ${entry.text}`}
|
||||
className="h-8 w-8 shrink-0 rounded-full border text-sm transition-colors hover:bg-[#eef9fb]"
|
||||
style={{ borderColor: `${accent}55`, color: accent }}
|
||||
>
|
||||
<span aria-hidden="true" className={`inline-block transition-transform ${open ? 'rotate-180' : ''}`}>
|
||||
▾
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{more && open && (
|
||||
<div id={panelId} className="mb-5 space-y-5 rounded-2xl bg-[#f6fbfc] p-5 sm:ml-38">
|
||||
{entry.person && (
|
||||
<div className="flex items-center gap-4">
|
||||
<Avatar person={entry.person} size="h-16 w-16" />
|
||||
<div>
|
||||
<Link
|
||||
to={personHref(entry.person.id)}
|
||||
className="font-semibold hover:underline"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{entry.person.name}
|
||||
</Link>
|
||||
{entry.person.tagline && (
|
||||
<p className="text-sm" style={{ color: BODY }}>
|
||||
{entry.person.tagline}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{entry.description && (
|
||||
<div className="space-y-3 leading-relaxed" style={{ color: BODY }}>
|
||||
<Paragraphs text={entry.description} accent={accent} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{graphic && <img src={graphic} alt="" loading="lazy" className="w-full rounded-lg" />}
|
||||
|
||||
{place && (
|
||||
<div>
|
||||
<iframe
|
||||
src={mapEmbed(place)}
|
||||
title={`Map: ${place}`}
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer-when-downgrade"
|
||||
className="aspect-video w-full rounded-lg border-0"
|
||||
/>
|
||||
<a
|
||||
href={mapLink(place)}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="mt-2 inline-block text-sm underline"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
Open in Google Maps
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ScheduleBlock({
|
||||
items,
|
||||
intro,
|
||||
accent,
|
||||
}: {
|
||||
items: ContentBlockItem[]
|
||||
intro?: string | null
|
||||
accent: string
|
||||
}) {
|
||||
const days = groupByDay(items)
|
||||
const [active, setActive] = useState(() => todayIndex(days))
|
||||
const baseId = useId()
|
||||
|
||||
if (days.length === 0) return null
|
||||
const current = days[Math.min(active, days.length - 1)]
|
||||
|
||||
const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
|
||||
const step = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0
|
||||
if (!step) return
|
||||
e.preventDefault()
|
||||
const next = (active + step + days.length) % days.length
|
||||
setActive(next)
|
||||
document.getElementById(`${baseId}-tab-${next}`)?.focus()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{intro && (
|
||||
<div className="space-y-3 leading-relaxed" style={{ color: BODY }}>
|
||||
<Paragraphs text={intro} accent={accent} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{days.length > 1 && (
|
||||
<div role="tablist" aria-label="Days" className="flex flex-wrap gap-2">
|
||||
{days.map((day, index) => {
|
||||
const selected = day === current
|
||||
return (
|
||||
<button
|
||||
key={day.name || index}
|
||||
id={`${baseId}-tab-${index}`}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={selected}
|
||||
aria-controls={`${baseId}-panel`}
|
||||
tabIndex={selected ? 0 : -1}
|
||||
onClick={() => setActive(index)}
|
||||
onKeyDown={onKey}
|
||||
className="rounded-full border px-5 py-2 text-sm font-semibold transition-colors"
|
||||
style={
|
||||
selected
|
||||
? { background: accent, borderColor: accent, color: '#ffffff' }
|
||||
: { borderColor: `${accent}55`, color: accent }
|
||||
}
|
||||
>
|
||||
{day.name || 'Schedule'}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ul
|
||||
id={`${baseId}-panel`}
|
||||
role={days.length > 1 ? 'tabpanel' : undefined}
|
||||
aria-labelledby={days.length > 1 ? `${baseId}-tab-${days.indexOf(current)}` : undefined}
|
||||
className="rounded-2xl border border-[#138ba0]/15 bg-white px-5"
|
||||
>
|
||||
{current.entries.map((entry, index) => (
|
||||
<Entry key={`${current.name}-${index}`} entry={entry} accent={accent} />
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -32,12 +32,17 @@
|
|||
can't keep a value for a choice it no longer makes: a featured
|
||||
card switched from "record" to "link" drops its record.
|
||||
|
||||
`when: { scope: "parent", path, value }` looks at the row this
|
||||
collection belongs to instead: a schedule entry shows its day and
|
||||
time only while the block above it is a schedule.
|
||||
|
||||
A nested collection takes `when` the same way, and one that goes
|
||||
hidden is emptied: a list block turned into a paragraph drops its
|
||||
items.
|
||||
|
||||
`help` may be a function of the row, for help that depends on
|
||||
another field (a content block's type says what its text is).
|
||||
`help` and `label` may be functions of the row, for wording that
|
||||
depends on another field (a content block's type says what its
|
||||
text is).
|
||||
|
||||
`preview` on a collection names an entry in PREVIEWS below; each
|
||||
open row then shows how it will look on the site, drawn by the
|
||||
|
|
@ -78,7 +83,24 @@ import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
|
|||
/* Live previews a collection can name with `preview`. Each gets the
|
||||
row as the form holds it, which is the API's shape. */
|
||||
const PREVIEWS = {
|
||||
contentBlock: (row) => <ContentBlocks blocks={[row]} />,
|
||||
// The form holds an entry's person as person_id; the renderer wants
|
||||
// the person, so it's looked up in the select options (a name, no
|
||||
// photo: the options carry no more).
|
||||
contentBlock: (row, options) => (
|
||||
<ContentBlocks
|
||||
blocks={[
|
||||
{
|
||||
...row,
|
||||
items: (row.items ?? []).map((item) => {
|
||||
const person = item.person_id
|
||||
? options?.people?.find((p) => p.id === item.person_id)
|
||||
: null;
|
||||
return { ...item, person: person ? { id: person.id, name: person.label } : null };
|
||||
}),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
),
|
||||
};
|
||||
|
||||
const input =
|
||||
|
|
@ -118,25 +140,33 @@ export function setPath(object, path, value) {
|
|||
|
||||
/* ── Conditional fields ──────────────────────────────────────── */
|
||||
|
||||
export function fieldShown(field, row) {
|
||||
export function fieldShown(field, row, parent?) {
|
||||
if (!field.when) return true;
|
||||
const want = Array.isArray(field.when.value) ? field.when.value : [field.when.value];
|
||||
return want.includes(row?.[field.when.path]);
|
||||
const source = field.when.scope === "parent" ? parent : row;
|
||||
return want.includes(source?.[field.when.path]);
|
||||
}
|
||||
|
||||
/* A row after an edit, with any field the edit hid cleared. "" is
|
||||
the engine's deliberate clear, so it saves as NULL. */
|
||||
function withHiddenCleared(spec, row) {
|
||||
function withHiddenCleared(spec, row, parent?) {
|
||||
let next = row;
|
||||
for (const field of spec.fields) {
|
||||
const value = next[field.path];
|
||||
if (!fieldShown(field, next) && value != null && value !== "") {
|
||||
if (!fieldShown(field, next, parent) && value != null && value !== "") {
|
||||
next = { ...next, [field.path]: "" };
|
||||
}
|
||||
}
|
||||
for (const nested of spec.children ?? []) {
|
||||
if (!fieldShown(nested, next) && next[nested.key]?.length) {
|
||||
const rows = next[nested.key];
|
||||
if (!rows?.length) continue;
|
||||
if (!fieldShown(nested, next, parent)) {
|
||||
next = { ...next, [nested.key]: [] };
|
||||
} else {
|
||||
// Its rows may have fields that follow this row (scope
|
||||
// "parent"), which this edit may just have hidden.
|
||||
const cleared = rows.map((child) => withHiddenCleared(nested, child, next));
|
||||
if (cleared.some((child, i) => child !== rows[i])) next = { ...next, [nested.key]: cleared };
|
||||
}
|
||||
}
|
||||
return next;
|
||||
|
|
@ -197,7 +227,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
|
|||
return (
|
||||
<div className={field.full ? "sm:col-span-2" : ""}>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-[#26454c]">
|
||||
{field.label}
|
||||
{typeof field.label === "function" ? field.label(row) : field.label}
|
||||
{field.required && !locked && <span className="ml-1 text-[#b3261e]">*</span>}
|
||||
</label>
|
||||
|
||||
|
|
@ -357,6 +387,7 @@ export function Repeater({
|
|||
errorPrefix,
|
||||
onChange,
|
||||
className = "mt-8",
|
||||
parentRow = undefined,
|
||||
}: any) {
|
||||
const list = rows ?? [];
|
||||
|
||||
|
|
@ -382,7 +413,7 @@ export function Repeater({
|
|||
const rowRefs = useRef<any[]>([]);
|
||||
|
||||
const update = (index, next) =>
|
||||
onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec, next) : row)));
|
||||
onChange(list.map((row, i) => (i === index ? withHiddenCleared(spec, next, parentRow) : row)));
|
||||
|
||||
const move = (index, delta) => {
|
||||
const target = index + delta;
|
||||
|
|
@ -593,7 +624,7 @@ export function Repeater({
|
|||
<>
|
||||
<FieldGrid>
|
||||
{spec.fields
|
||||
.filter((field) => fieldShown(field, row))
|
||||
.filter((field) => fieldShown(field, row, parentRow))
|
||||
.map((field) => (
|
||||
<Field
|
||||
key={field.path}
|
||||
|
|
@ -609,7 +640,7 @@ export function Repeater({
|
|||
</FieldGrid>
|
||||
|
||||
{(spec.children ?? [])
|
||||
.filter((nested) => fieldShown(nested, row))
|
||||
.filter((nested) => fieldShown(nested, row, parentRow))
|
||||
.map((nested) => (
|
||||
<div key={nested.key} className="mt-4 border-t border-[#4a6b72]/15 pt-4">
|
||||
<Repeater
|
||||
|
|
@ -618,6 +649,7 @@ export function Repeater({
|
|||
options={options}
|
||||
errors={errors}
|
||||
errorPrefix={`${errorPrefix}${index}.${nested.key}.`}
|
||||
parentRow={row}
|
||||
className=""
|
||||
onChange={(value) => update(index, { ...row, [nested.key]: value })}
|
||||
/>
|
||||
|
|
@ -629,7 +661,7 @@ export function Repeater({
|
|||
<p className="mb-3 text-xs font-semibold uppercase tracking-wider text-[#4a6b72]/70">
|
||||
Preview
|
||||
</p>
|
||||
{PREVIEWS[spec.preview](row)}
|
||||
{PREVIEWS[spec.preview](row, options)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@
|
|||
import { preview } from "./text.ts";
|
||||
import { PLATFORMS } from "./platforms.ts";
|
||||
import { FORMATTING_HELP } from "../components/InlineText.tsx";
|
||||
import siteConfiguration from "../../site.json";
|
||||
import {
|
||||
awardLogo,
|
||||
blockMedia,
|
||||
|
|
@ -302,12 +303,16 @@ const BLOCK_TYPES = [
|
|||
["button", "Button", "One filled call-to-action button, eg. Register, Donate."],
|
||||
["image", "Image", "A picture, with alt text and an optional caption and link."],
|
||||
["video", "Video", "A YouTube, Vimeo or Facebook video, or a video file, played in place."],
|
||||
["schedule", "Schedule", "Entries in one tab per day, each folding out for more. The text is an optional intro."],
|
||||
["divider", "Divider", "A thin line between parts."],
|
||||
];
|
||||
|
||||
/* An item field that only a schedule's entries have. */
|
||||
const SCHEDULE_ENTRY = { scope: "parent", path: "type", value: "schedule" };
|
||||
|
||||
const blockTypeLabel = (type) => BLOCK_TYPES.find(([value]) => value === type)?.[1] ?? type;
|
||||
|
||||
const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video"];
|
||||
const TEXT_TYPES = ["paragraph", "heading", "subheading", "callout", "quote", "button", "image", "video", "schedule"];
|
||||
|
||||
const TEXT_HELP = {
|
||||
paragraph: FORMATTING_HELP,
|
||||
|
|
@ -316,9 +321,10 @@ const TEXT_HELP = {
|
|||
button: "The button's label, eg. Register now",
|
||||
image: "Caption shown under the image. Optional.",
|
||||
video: "Caption shown under the video. Optional.",
|
||||
schedule: "Optional intro above the tabs. " + FORMATTING_HELP,
|
||||
};
|
||||
|
||||
const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption" };
|
||||
const TEXT_LABEL = { button: "Label", image: "Caption", video: "Caption", schedule: "Intro" };
|
||||
|
||||
const HREF_HELP = {
|
||||
paragraph: "Optional. Makes the whole paragraph one link. For a link inside the text, use [text](url).",
|
||||
|
|
@ -357,7 +363,7 @@ const blocksChild = {
|
|||
},
|
||||
{
|
||||
path: "text",
|
||||
label: "Text",
|
||||
label: (row) => TEXT_LABEL[row?.type] ?? "Text",
|
||||
widget: "textarea",
|
||||
full: true,
|
||||
when: { path: "type", value: TEXT_TYPES },
|
||||
|
|
@ -400,13 +406,59 @@ const blocksChild = {
|
|||
key: "items",
|
||||
label: "Items",
|
||||
addLabel: "Add item",
|
||||
when: { path: "type", value: ["list", "links"] },
|
||||
title: (row) => row.text || "New item",
|
||||
when: { path: "type", value: ["list", "links", "schedule"] },
|
||||
title: (row) => [row.day, row.time, row.text].filter(Boolean).join(" · ") || "New item",
|
||||
blank: { text: "" },
|
||||
fields: [
|
||||
{ path: "text", label: "Text", required: true },
|
||||
{ path: "detail", label: "Detail", help: "Lists only: shown after the text" },
|
||||
{ path: "url", label: "URL", help: "Blank for a plain list item. Link buttons need one." },
|
||||
{
|
||||
path: "day",
|
||||
label: "Day",
|
||||
help: "The tab it's under, eg. Friday. Entries with the same day share a tab, in this order.",
|
||||
when: SCHEDULE_ENTRY,
|
||||
},
|
||||
{ path: "time", label: "Time", help: "eg. 7:00pm, or 9:00 to 10:30am", when: SCHEDULE_ENTRY },
|
||||
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title" },
|
||||
{
|
||||
path: "location",
|
||||
label: "Location",
|
||||
help: "eg. Main Hall",
|
||||
when: SCHEDULE_ENTRY,
|
||||
},
|
||||
{
|
||||
path: "person_id",
|
||||
label: "Person",
|
||||
widget: "select",
|
||||
optionsFrom: "people",
|
||||
blankLabel: "Default: none",
|
||||
help: "Who hosts or speaks: shown with their photo, linked to their page",
|
||||
when: SCHEDULE_ENTRY,
|
||||
},
|
||||
{ path: "detail", label: "Detail", help: "A line under the text. Lists: shown after the text" },
|
||||
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one." },
|
||||
{
|
||||
path: "description",
|
||||
label: "More",
|
||||
widget: "textarea",
|
||||
full: true,
|
||||
help: "Shown when the entry is folded out. " + FORMATTING_HELP,
|
||||
when: SCHEDULE_ENTRY,
|
||||
},
|
||||
{
|
||||
path: "media",
|
||||
label: "Graphic",
|
||||
widget: "image",
|
||||
resolve: blockMedia,
|
||||
full: true,
|
||||
help: "Optional, in the fold-out: a map of the site, a slide, a poster",
|
||||
when: SCHEDULE_ENTRY,
|
||||
},
|
||||
{
|
||||
path: "map",
|
||||
label: "Map",
|
||||
full: true,
|
||||
help: "Optional, in the fold-out: a place or address for a Google map, eg. Camp Hebron, Halifax PA",
|
||||
when: SCHEDULE_ENTRY,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
@ -1218,6 +1270,7 @@ const frontPage = {
|
|||
["none", "Nothing: No additional overlay"],
|
||||
["livestream", "Livestream: the stream, with a LIVE badge"],
|
||||
["video", "Featured video: click to play"],
|
||||
["event", "Featured event: an event's card"],
|
||||
],
|
||||
blankLabel: "Default: nothing",
|
||||
help: "Switch to Livestream when you go live, and back when you're done",
|
||||
|
|
@ -1232,7 +1285,7 @@ const frontPage = {
|
|||
],
|
||||
},
|
||||
{
|
||||
legend: "Photos, livestream and video",
|
||||
legend: "Photos, livestream, video and event",
|
||||
fields: [
|
||||
{
|
||||
path: "slide_seconds",
|
||||
|
|
@ -1253,9 +1306,18 @@ const frontPage = {
|
|||
full: true,
|
||||
help:
|
||||
"A YouTube, Vimeo or Facebook link, or a video file: a filename in " +
|
||||
"/front-page/ or a link ending in .mp4 or .webm",
|
||||
"the uploads folder, or a link ending in .mp4 or .webm",
|
||||
},
|
||||
{ path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" },
|
||||
{
|
||||
path: "hero_event_id",
|
||||
label: "Featured event",
|
||||
widget: "select",
|
||||
optionsFrom: "events",
|
||||
blankLabel: "Default: the countdown's event",
|
||||
full: true,
|
||||
help: "For the Featured event feature. A pinned event that's over falls back to the countdown's",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
@ -1558,6 +1620,112 @@ const communityPage = {
|
|||
],
|
||||
};
|
||||
|
||||
/* ── Site settings (035_site_settings.sql) ───────────────────────
|
||||
Overrides for site.json, superadmins only: every blank falls back
|
||||
to what site.json says, which is shown as the default. */
|
||||
const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).map(
|
||||
([path, page]) => [path, `${page.title} (${path})`],
|
||||
);
|
||||
|
||||
const siteSettings = {
|
||||
key: "site_settings",
|
||||
label: "Site settings",
|
||||
singular: "site settings",
|
||||
idLabel: "Settings",
|
||||
singleton: "site",
|
||||
writeRole: "superadmin",
|
||||
|
||||
list: { columns: [], filters: [] },
|
||||
|
||||
groups: [
|
||||
{
|
||||
legend: "The site",
|
||||
note: "Anything left blank uses site.json, so the build and these settings agree until you change one.",
|
||||
fields: [
|
||||
{ path: "site_name", label: "Site name", help: `Default: ${siteConfiguration.title}` },
|
||||
{
|
||||
path: "description",
|
||||
label: "Description",
|
||||
widget: "textarea",
|
||||
full: true,
|
||||
help: "Search engines and link previews show this for pages without their own. Default: site.json's, or the front page's subhead.",
|
||||
},
|
||||
{
|
||||
path: "preview_image",
|
||||
label: "Preview image",
|
||||
widget: "image",
|
||||
resolve: blogImage,
|
||||
full: true,
|
||||
help: "Shown when a page without its own image is shared. 1200 × 630 works everywhere.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
legend: "Icons",
|
||||
fields: [
|
||||
{
|
||||
path: "favicon",
|
||||
label: "Favicon",
|
||||
widget: "image",
|
||||
resolve: blogImage,
|
||||
full: true,
|
||||
help: "The browser-tab icon: a square PNG (512px) or an SVG. Keep original when uploading an SVG.",
|
||||
},
|
||||
{
|
||||
path: "apple_touch_icon",
|
||||
label: "Home-screen icon",
|
||||
widget: "image",
|
||||
resolve: blogImage,
|
||||
full: true,
|
||||
help: "For iPhones saving the site to their home screen: a square PNG, 180px, no transparency.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
legend: "Search engines",
|
||||
fields: [
|
||||
{
|
||||
path: "indexing",
|
||||
label: "Let search engines list this site",
|
||||
widget: "select",
|
||||
options: [
|
||||
["on", "On: pages can appear in Google"],
|
||||
["off", "Off: hidden from search (use on the dev server)"],
|
||||
],
|
||||
blankLabel: `Default: site.json (${siteConfiguration.robots?.index === false ? "off" : "on"})`,
|
||||
help: "Applies to this server's database only, so dev can be off while production is on.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
children: [
|
||||
{
|
||||
key: "pages",
|
||||
label: "Page titles and intros",
|
||||
note: "Change a static page's heading and intro, which are also its search title and description. Blank fields keep site.json's.",
|
||||
addLabel: "Change a page",
|
||||
title: (row) => SITE_PAGES.find(([path]) => path === row.path)?.[1] ?? "New page",
|
||||
blank: { path: "", title: "", description: "" },
|
||||
fields: [
|
||||
{ path: "path", label: "Page", widget: "select", options: SITE_PAGES, required: true },
|
||||
{
|
||||
path: "title",
|
||||
label: "Title",
|
||||
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.title ?? ""}` : undefined),
|
||||
},
|
||||
{
|
||||
path: "description",
|
||||
label: "Intro",
|
||||
widget: "textarea",
|
||||
full: true,
|
||||
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.description ?? ""}` : undefined),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const ADMIN_ENTITIES: Record<string, any> = {
|
||||
organizations,
|
||||
events,
|
||||
|
|
@ -1568,6 +1736,7 @@ export const ADMIN_ENTITIES: Record<string, any> = {
|
|||
front_page: frontPage,
|
||||
blog_posts: blogPosts,
|
||||
community_page: communityPage,
|
||||
site_settings: siteSettings,
|
||||
};
|
||||
|
||||
export function slugify(value) {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
so the visitor presses play.
|
||||
|
||||
A featured video can also be a file rather than a link: a
|
||||
filename in public/front-page/, a /path, or an https URL ending
|
||||
filename in the uploads directory, a /path, or an https URL ending
|
||||
in a video extension. videoSource() says which, so the hero can
|
||||
hand a file to <video> and a link to an <iframe>.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
|
|
|||
|
|
@ -1,18 +1,25 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
MEDIA PATHS
|
||||
|
||||
Every image field in the API is a bare filename — "where the
|
||||
images live is the component's business", as history.js puts it.
|
||||
This is that business, in one file, so moving a directory is one
|
||||
edit rather than a grep.
|
||||
Every image field in the API is a filename or a path, and where a
|
||||
bare filename lives is decided here, in one file.
|
||||
|
||||
⚠ Only two of these directories are confirmed by the admin help
|
||||
text: people/ and event-logos/. The other three are a guess at
|
||||
your convention. Check public/ and fix them here — nothing else
|
||||
references the paths.
|
||||
One rule: record images are uploads. A value from the media
|
||||
library is already '/uploads/<file>'; a bare filename is a file
|
||||
copied into the uploads directory by hand (fall-retreat-logo.svg
|
||||
was), so it resolves to /uploads/<file> too. That covers logos,
|
||||
photos, backgrounds, hero slides, block images: everything an
|
||||
editor picks.
|
||||
|
||||
The site's own chosen assets (the NGU logos in the nav, footer
|
||||
and admin) are the exception: they're bundled from
|
||||
src/assets/logos and imported where they're used, not resolved
|
||||
here.
|
||||
|
||||
A value that already looks like a path or a URL is returned
|
||||
untouched, so a hand-written entry can point anywhere.
|
||||
server/src/pageMeta.js resolves images for link previews by the
|
||||
same rule; keep the two in step.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
const ABSOLUTE = /^(https?:|\/|data:)/
|
||||
|
|
@ -29,40 +36,42 @@ function inDir(dir: string) {
|
|||
}
|
||||
}
|
||||
|
||||
export const personPhoto = inDir('/people') // confirmed
|
||||
export const eventLogo = inDir('/event-logos') // confirmed
|
||||
export const eventBackground = inDir('/event-backgrounds')
|
||||
export const orgLogo = inDir('/org-logos') // ⚠ guess
|
||||
export const teamLogo = inDir('/team-logos') // ⚠ guess
|
||||
export const awardLogo = inDir('/award-logos') // ⚠ guess
|
||||
export const UPLOADS = '/uploads'
|
||||
|
||||
/* front_page_slides.media — the home page hero's photos. New with
|
||||
the Front page editor, which names the directory in its help. */
|
||||
export const heroPhoto = inDir('/front-page')
|
||||
const inUploads = inDir(UPLOADS)
|
||||
|
||||
/* front_page.video_url when it names a file rather than a link:
|
||||
same directory as the photos. */
|
||||
export const heroVideo = inDir('/front-page')
|
||||
/* One helper per field, all the same rule, so a caller says what the
|
||||
image is and a future exception is one line here. */
|
||||
export const personPhoto = inUploads
|
||||
export const eventLogo = inUploads
|
||||
export const eventBackground = inUploads
|
||||
export const orgLogo = inUploads
|
||||
export const teamLogo = inUploads
|
||||
export const awardLogo = inUploads
|
||||
|
||||
/* content_blocks.media, which can be an image on any owner's page,
|
||||
so it can't share a per-entity directory. */
|
||||
export const blockMedia = inDir('/media') // ⚠ guess
|
||||
/* front_page_slides.media, the hero's photos. */
|
||||
export const heroPhoto = inUploads
|
||||
|
||||
/* featured_cards.image, a card's own picture. Normally an upload
|
||||
('/uploads/…'); a bare filename looks here. */
|
||||
export const featuredImage = inDir('/featured')
|
||||
/* front_page.video_url when it names a file rather than a link.
|
||||
Videos can't be uploaded through the media library, so a file is
|
||||
one copied into the uploads directory by hand. */
|
||||
export const heroVideo = inUploads
|
||||
|
||||
/* blog_posts.cover_image and guest_photo. Normally uploads. */
|
||||
export const blogImage = inDir('/blog')
|
||||
/* content_blocks.media and content_block_items.media. */
|
||||
export const blockMedia = inUploads
|
||||
|
||||
/* featured_cards.image. */
|
||||
export const featuredImage = inUploads
|
||||
|
||||
/* blog_posts.cover_image and guest_photo. */
|
||||
export const blogImage = inUploads
|
||||
|
||||
/* ── By record kind ────────────────────────────────────────────
|
||||
The timeline sends `logo: { file, kind }` rather than a path,
|
||||
because v_timeline COALESCEs across five tables and only the
|
||||
ref_kind says which one the filename came from.
|
||||
|
||||
⚠ Three of these directories are the guesses above. Your current
|
||||
timelineRefs.ts already has the real ones — timeline logos render
|
||||
today — so copy them into the map above and delete this note.
|
||||
ref_kind says which one the filename came from. Featured cards
|
||||
send the same shape. Every kind resolves to the uploads directory
|
||||
today; the map is what lets one kind differ later.
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
||||
const BY_KIND: Record<string, (file?: string | null) => string | null> = {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,55 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SITE
|
||||
|
||||
The public address of the live site. Used where a URL has to
|
||||
leave the browser and still work: a printed QR code made on
|
||||
localhost or a preview has to point here, not at wherever it was
|
||||
generated. Everything inside the site links by path, not this.
|
||||
What the site says about itself, for the browser: /site.json, with
|
||||
the admin's Site settings (Panel) laid over it. The server merges
|
||||
the two and writes the result into each page's HTML as
|
||||
window.__NGU_SITE__ (server/src/pageMeta.js), which is read here
|
||||
before the app renders, so there's no request and no flash of the
|
||||
old wording. In development, or if the API is down and nginx
|
||||
serves the plain index.html, it isn't there and site.json alone
|
||||
applies.
|
||||
|
||||
A page's visible heading and intro and its search title and
|
||||
description come from the same values, so they can't drift.
|
||||
|
||||
SITE_ORIGIN is the public address of the live site. It's used
|
||||
where a URL has to leave the browser and still work: a printed QR
|
||||
code made on localhost or a preview has to point here, not at
|
||||
wherever it was generated. Everything inside the site links by
|
||||
path, not this.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export const SITE_ORIGIN = 'https://nextgenerationofunity.org'
|
||||
import siteConfiguration from '../../site.json'
|
||||
|
||||
type PageText = { title: string; description: string }
|
||||
|
||||
type SiteText = { title?: string; pages?: Record<string, PageText> }
|
||||
|
||||
/* What the server wrote into the page, if it did. */
|
||||
const fromServer: SiteText =
|
||||
(typeof window !== 'undefined' && (window as unknown as { __NGU_SITE__?: SiteText }).__NGU_SITE__) || {}
|
||||
|
||||
export const SITE_NAME: string = fromServer.title || siteConfiguration.title
|
||||
|
||||
export const SITE_ORIGIN: string = siteConfiguration.url
|
||||
|
||||
/** A site path as a full URL on the live site. */
|
||||
export const siteUrl = (path: string): string => new URL(path, SITE_ORIGIN).href
|
||||
|
||||
const PAGES: Record<string, PageText> = { ...siteConfiguration.pages, ...fromServer.pages }
|
||||
|
||||
/** The static pages site.json knows, for the admin's page list. */
|
||||
export const SITE_PAGE_PATHS: string[] = Object.keys(siteConfiguration.pages)
|
||||
|
||||
/** A static page's title and intro, from site.json's "pages". */
|
||||
export function sitePage(path: string): PageText {
|
||||
const page = PAGES[path]
|
||||
if (!page) throw new Error(`site.json has no "pages" entry for ${path}`)
|
||||
return page
|
||||
}
|
||||
|
||||
/** The browser tab's title for a page: "Retreats | Next Generation
|
||||
* of Unity", or the site name alone for the home page. */
|
||||
export const documentTitle = (title?: string | null): string =>
|
||||
title ? `${title} | ${SITE_NAME}` : SITE_NAME
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ export type ContentBlock = {
|
|||
| 'video'
|
||||
| 'button'
|
||||
| 'callout'
|
||||
| 'schedule'
|
||||
text?: string | null
|
||||
media?: string | null
|
||||
href?: string | null
|
||||
|
|
@ -41,7 +42,22 @@ export type ContentBlock = {
|
|||
alt?: string | null
|
||||
/** Who a quote is by. */
|
||||
cite?: string | null
|
||||
items?: Array<{ text: string; detail?: string | null; url?: string | null }>
|
||||
items?: ContentBlockItem[]
|
||||
}
|
||||
|
||||
/** A list, link-row or schedule entry. The schedule fields are
|
||||
* empty on the other two (034_schedule_block.sql). */
|
||||
export type ContentBlockItem = {
|
||||
text: string
|
||||
detail?: string | null
|
||||
url?: string | null
|
||||
day?: string | null
|
||||
time?: string | null
|
||||
location?: string | null
|
||||
description?: string | null
|
||||
media?: string | null
|
||||
map?: string | null
|
||||
person?: { id: string; name: string; photo?: string | null; tagline?: string | null } | null
|
||||
}
|
||||
|
||||
export type Link = {
|
||||
|
|
|
|||
|
|
@ -12,12 +12,13 @@
|
|||
|
||||
import { useRecord, type Resource } from './useRecord.ts'
|
||||
import type { EventSeries } from './eventSeries.ts'
|
||||
import type { Link } from './useContent.ts'
|
||||
|
||||
/** What fills the hero's background. */
|
||||
export type HeroBackdrop = 'brand' | 'photos'
|
||||
|
||||
/** What sits beside the words, over the backdrop. */
|
||||
export type HeroFeature = 'none' | 'livestream' | 'video'
|
||||
export type HeroFeature = 'none' | 'livestream' | 'video' | 'event'
|
||||
|
||||
/** The CHECK list on front_page_sections.section. */
|
||||
export type FrontPageSectionKey =
|
||||
|
|
@ -51,6 +52,8 @@ export type Hero = {
|
|||
livestream: { url: string; title?: string | null } | null
|
||||
/** A link to embed or a video file; see videoSource in embeds.ts. */
|
||||
video: { url: string; title?: string | null } | null
|
||||
/** With the 'event' feature: the pinned event, else the countdown's. */
|
||||
event: HeroEvent | null
|
||||
}
|
||||
|
||||
export type FrontPageSection = {
|
||||
|
|
@ -105,6 +108,14 @@ export type FeaturedCard = {
|
|||
image: { file: string; kind: string } | null
|
||||
}
|
||||
|
||||
/** The countdown's event plus what the hero's event card draws. */
|
||||
export type HeroEvent = CountdownEvent & {
|
||||
tagline?: string | null
|
||||
card_image?: string | null
|
||||
org_logo?: string | null
|
||||
links: Link[]
|
||||
}
|
||||
|
||||
export type FrontPage = {
|
||||
hero: Hero
|
||||
sections: FrontPageSection[]
|
||||
|
|
|
|||
|
|
@ -7,4 +7,4 @@
|
|||
box or a build banner can read the same value later.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export const SITE_VERSION = "NGU-Web.v1.7.4-feature-updates";
|
||||
export const SITE_VERSION = "NGU-Web.v1.8.0-feature-fixes";
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import PageShell from "../components/PageShell.tsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
import { useSectionManifest } from "../lib/sections.tsx";
|
||||
import OrgListMap, { OrgMapToggle } from "./sections/OrgList-Map.tsx";
|
||||
import OrgListVertical from "./sections/OrgList-Vertical.tsx";
|
||||
|
|
@ -6,6 +7,9 @@ import OrgListCards from "./sections/OrgList-Card.tsx";
|
|||
import CommunityBlog from "./sections/CommunityBlog.tsx";
|
||||
import { useCommunityBlog } from "../lib/useBlog.ts";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/community");
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
COMMUNITY PAGE
|
||||
|
||||
|
|
@ -13,7 +17,7 @@ import { useCommunityBlog } from "../lib/useBlog.ts";
|
|||
map is filtered to chapters; the vertical list is filtered to
|
||||
regions. Same rows, same endpoint, different shape on the page.
|
||||
|
||||
The blog's heading and blurb are the admin's (Blog → Community
|
||||
The blog's heading and blurb are the admin's (Pages → Community blog
|
||||
section), so that one entry is built here from the same cached
|
||||
request CommunityBlog makes for its posts.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
|
@ -82,8 +86,8 @@ export default function CommunityPage() {
|
|||
|
||||
return (
|
||||
<PageShell
|
||||
title="Community"
|
||||
intro="Chapters, regions and the people who make up Next Generation of Unity."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={sections}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import PageShell from "../components/PageShell";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
import FeedbackForm from "./sections/FeedbackForm";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/feedback");
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
Feedback page.
|
||||
|
||||
|
|
@ -36,8 +40,8 @@ const SECTIONS = [
|
|||
export default function Feedback() {
|
||||
return (
|
||||
<PageShell
|
||||
title="Feedback"
|
||||
intro="Tell us what's working, what isn't, and what you'd like to see next."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={SECTIONS}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import { useEffect } from "react";
|
||||
import PageShell from "../components/PageShell.tsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/give");
|
||||
|
||||
const GIVING_URL =
|
||||
"https://ngu.churchcenteronline.com/giving?open-in-church-center-modal=true";
|
||||
|
|
@ -81,8 +85,8 @@ export default function GivingPage() {
|
|||
|
||||
return (
|
||||
<PageShell
|
||||
title="Giving"
|
||||
intro="Support the work of Next Generation of Unity."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={sections}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
import PageShell from "../components/PageShell";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
import HistoryTimeline from "./sections/history/HistoryTimeline";
|
||||
import { HISTORY_DECADES } from "../data/historyDecades";
|
||||
import { useHistory } from "../lib/useHistory";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/history");
|
||||
|
||||
/**
|
||||
* Year the program starts. Decades ending before this render with the
|
||||
* pre-program treatment, so the gap moves if the founding date is ever
|
||||
|
|
@ -66,8 +70,8 @@ export default function History() {
|
|||
|
||||
return (
|
||||
<PageShell
|
||||
title="History"
|
||||
intro="A near-complete timeline of Next Generation of Unity (NGU), and other Unity Young Adult programs."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={[
|
||||
{
|
||||
id: "timeline",
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
broken server.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
|
||||
import HeroStage from './sections/home/HeroStage.tsx'
|
||||
import NextEventCountdown from './sections/home/NextEventCountdown.tsx'
|
||||
|
|
@ -33,6 +33,7 @@ import StatsBand from './sections/home/StatsBand.tsx'
|
|||
import FeaturedBand from './sections/home/FeaturedBand.tsx'
|
||||
import FeaturedTimelineRail from './sections/home/FeaturedTimelineRail.tsx'
|
||||
import Pathfinder from './sections/home/Pathfinder.tsx'
|
||||
import { documentTitle } from '../lib/site.ts'
|
||||
import {
|
||||
useFrontPage,
|
||||
type FrontPage,
|
||||
|
|
@ -104,6 +105,11 @@ const SECTIONS: Record<
|
|||
export default function Home() {
|
||||
const { data: page, error, reload } = useFrontPage()
|
||||
|
||||
// Back to the site name when a visitor returns here from a page.
|
||||
useEffect(() => {
|
||||
document.title = documentTitle()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<>
|
||||
<HeroStage hero={page?.hero ?? null} />
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import PageShell from "../components/PageShell.tsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
import PeopleTiles from "../components/PeopleTiles.tsx";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/leadership");
|
||||
|
||||
const SECTIONS = [
|
||||
{
|
||||
id: "board-staff",
|
||||
|
|
@ -61,8 +65,8 @@ const SECTIONS = [
|
|||
export default function Leadership() {
|
||||
return (
|
||||
<PageShell
|
||||
title="Leadership"
|
||||
intro="The board, staff, and volunteers who keep Next Generation of Unity running."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={SECTIONS}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import PageShell from "../components/PageShell.jsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/privacy");
|
||||
|
||||
const SECTIONS = [
|
||||
{
|
||||
|
|
@ -18,8 +22,8 @@ const SECTIONS = [
|
|||
export default function PrivacyPage() {
|
||||
return (
|
||||
<PageShell
|
||||
title="Privacy Policy"
|
||||
intro="How Next Generation of Unity collects, uses, and protects your information."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={SECTIONS}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import PageShell from '../components/PageShell.tsx'
|
||||
import { sitePage } from '../lib/site.ts'
|
||||
import QrCodeMaker from './sections/QrCodeMaker.tsx'
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage('/qr')
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
QR CODES PAGE: /qr
|
||||
|
||||
|
|
@ -15,7 +19,7 @@ const SECTIONS = [
|
|||
id: 'make',
|
||||
title: 'Make a QR code',
|
||||
blurb:
|
||||
'Pick a page from the main navigation, or any event, organization, team, award, person or blog post on the site. The code always points at the live site.',
|
||||
'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 centre and the colours; a warning shows if the code might not scan.',
|
||||
accent: '#138ba0',
|
||||
background: '#eef9fb',
|
||||
content: (
|
||||
|
|
@ -29,8 +33,8 @@ const SECTIONS = [
|
|||
export default function QrCodes() {
|
||||
return (
|
||||
<PageShell
|
||||
title="QR Codes"
|
||||
intro="Codes for flyers, slides and signs, pointing at any page on the site."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={SECTIONS}
|
||||
/>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import PageShell from "../components/PageShell.jsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/resources");
|
||||
|
||||
const SECTIONS = [
|
||||
{
|
||||
|
|
@ -42,8 +46,8 @@ const SECTIONS = [
|
|||
export default function ResourcesPage() {
|
||||
return (
|
||||
<PageShell
|
||||
title="Resources"
|
||||
intro="Teachings, brand assets, and material for chapters and partners."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={SECTIONS}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,11 @@
|
|||
import PageShell from "../components/PageShell.tsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
import { useSectionManifest } from "../lib/sections.tsx";
|
||||
import EventListCards, { EventCardsToggle } from "./sections/EventList-Cards.tsx";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/retreats");
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
RETREATS PAGE
|
||||
|
||||
|
|
@ -112,8 +116,8 @@ export default function RetreatsPage() {
|
|||
|
||||
return (
|
||||
<PageShell
|
||||
title="Retreats"
|
||||
intro="Retreats hosted by Next Generation of Unity, our regions, and our partners throughout the year."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={sections}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import PageShell from "../components/PageShell.jsx";
|
||||
import { sitePage } from "../lib/site.ts";
|
||||
|
||||
/* Title and intro: site.json, which also gives the search metadata. */
|
||||
const PAGE = sitePage("/terms");
|
||||
|
||||
const SECTIONS = [
|
||||
{
|
||||
|
|
@ -18,8 +22,8 @@ const SECTIONS = [
|
|||
export default function TermsPage() {
|
||||
return (
|
||||
<PageShell
|
||||
title="Terms of Service"
|
||||
intro="The terms that apply when you use this site and our programs."
|
||||
title={PAGE.title}
|
||||
intro={PAGE.description}
|
||||
sections={SECTIONS}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -7,10 +7,8 @@
|
|||
|
||||
The cards come from adminNav.ts, the same list the CMS header
|
||||
reads, so a new entity shows up here the moment it's registered.
|
||||
Forms sit in their own block below: they're submissions coming
|
||||
in rather than content going out, and there'll be more of them
|
||||
than the feedback queue eventually. Tools come next, and the
|
||||
Panel block below that only exists for superadmins.
|
||||
One block per header group, in the same order: Data, Pages,
|
||||
Forms, Tools, and Panel, which only exists for superadmins.
|
||||
|
||||
The right-hand panel is deliberately inert. Nothing here
|
||||
fetches, so the landing page can't be slow or half-broken on
|
||||
|
|
@ -22,7 +20,7 @@ import { Link } from "react-router-dom";
|
|||
import { useAuth } from "../../lib/auth.tsx";
|
||||
import { SITE_VERSION } from "../../lib/version.ts";
|
||||
import { ROLE_LABELS, isSuper } from "../../lib/roles.ts";
|
||||
import { CMS_NAV, FORMS_NAV, PANEL_NAV, TOOLS_NAV, target } from "./adminNav.ts";
|
||||
import { DATA_NAV, FORMS_NAV, PAGES_NAV, PANEL_NAV, TOOLS_NAV, target } from "./adminNav.ts";
|
||||
|
||||
/* One card. The title link is stretched over the whole card with
|
||||
`after:absolute`, which makes the card clickable without nesting
|
||||
|
|
@ -98,6 +96,10 @@ function PanelSection({ title, children }) {
|
|||
);
|
||||
}
|
||||
|
||||
/* The header's groups, in its order. Panel is drawn separately
|
||||
below, since only superadmins get it. */
|
||||
const GROUPS = [DATA_NAV, PAGES_NAV, FORMS_NAV, TOOLS_NAV];
|
||||
|
||||
const QUICK_ADD = [
|
||||
{ to: "/admin/events/new", label: "New event" },
|
||||
{ to: "/admin/people/new", label: "New person" },
|
||||
|
|
@ -117,27 +119,19 @@ export default function AdminHome() {
|
|||
</h1>
|
||||
<p className="mt-1 text-[#4a6b72]">Pick a section to work in.</p>
|
||||
|
||||
<div className="mt-6 grid gap-4 sm:grid-cols-2">
|
||||
{CMS_NAV.map((item) => (
|
||||
<NavCard key={item.label} item={item} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
<CardBlock title={FORMS_NAV.label} blurb={FORMS_NAV.blurb}>
|
||||
{FORMS_NAV.children.map((form) => (
|
||||
<NavCard key={form.to} item={form} />
|
||||
))}
|
||||
</CardBlock>
|
||||
|
||||
<CardBlock title={TOOLS_NAV.label} blurb={TOOLS_NAV.blurb}>
|
||||
{TOOLS_NAV.children.map((tool) => (
|
||||
<NavCard key={tool.to} item={tool} />
|
||||
))}
|
||||
</CardBlock>
|
||||
{GROUPS.map((group) => (
|
||||
<CardBlock key={group.label} title={group.label} blurb={group.blurb}>
|
||||
{group.children.map((item) => (
|
||||
<NavCard key={item.to} item={item} />
|
||||
))}
|
||||
</CardBlock>
|
||||
))}
|
||||
|
||||
{isSuper(user) && (
|
||||
<CardBlock title="Superadmin" blurb="Only superadmins see this block.">
|
||||
<NavCard item={PANEL_NAV} />
|
||||
<CardBlock title={PANEL_NAV.label} blurb={PANEL_NAV.blurb}>
|
||||
{PANEL_NAV.children.map((item) => (
|
||||
<NavCard key={item.to} item={item} />
|
||||
))}
|
||||
</CardBlock>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -9,10 +9,14 @@
|
|||
wordmark names whichever one you're in, and from anywhere but
|
||||
Home it's the way back to Home.
|
||||
|
||||
The tab row is drawn everywhere except Home, where the card grid
|
||||
is the navigation and drawing both would say the same thing
|
||||
twice. Which tabs appear depends on the signed-in user
|
||||
(navFor() drops the superadmin-only ones), but that's cosmetics.
|
||||
The group menus (Data, Pages, Forms, Tools, Panel: adminNav.ts)
|
||||
are drawn everywhere except Home, where the card grid is the
|
||||
navigation and drawing both would say the same thing twice. Each
|
||||
group's name opens its first item and hovering it lists the rest;
|
||||
the strip under the header lists the open group's items, which is
|
||||
also the way around on a touch screen. Which groups appear depends
|
||||
on the signed-in user (navFor() drops the superadmin-only ones),
|
||||
but that's cosmetics.
|
||||
The route guard and the API are what actually say no.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
|
|
@ -23,7 +27,7 @@ import { AdminTitleContext } from "../../lib/adminTitle.tsx";
|
|||
import { AdminWidthContext } from "../../lib/adminWidth.tsx";
|
||||
import { SITE_VERSION } from "../../lib/version.ts";
|
||||
import { ROLE_LABELS, isSuper } from "../../lib/roles.ts";
|
||||
import nguLogo from "../../assets/NGU_Logo.svg";
|
||||
import nguLogo from "../../assets/logos/NGU_Logo.svg";
|
||||
import {
|
||||
ADMIN_HOME,
|
||||
AREA_TITLES,
|
||||
|
|
@ -33,6 +37,52 @@ import {
|
|||
target,
|
||||
} from "./adminNav.ts";
|
||||
|
||||
/* One group in the header. The name opens the group's first item;
|
||||
hovering it, or tabbing into it, drops down the rest. The menu is
|
||||
CSS only (group-hover, group-focus-within), so it can't get stuck
|
||||
open, and a keyboard reaches every item by tabbing on from the
|
||||
name. A group of one has nothing to drop down. */
|
||||
function GroupMenu({ item, lit, pathname }) {
|
||||
const children = item.children ?? [];
|
||||
const link = lit
|
||||
? "font-semibold text-[#138ba0]"
|
||||
: "text-[#4a6b72] transition-colors hover:text-[#138ba0]";
|
||||
|
||||
return (
|
||||
<div className="group relative">
|
||||
<NavLink to={target(item)} className={`flex items-center gap-1 ${link}`}>
|
||||
{item.label}
|
||||
{children.length > 1 && (
|
||||
<span aria-hidden="true" className="text-[10px] opacity-60">
|
||||
▾
|
||||
</span>
|
||||
)}
|
||||
</NavLink>
|
||||
|
||||
{children.length > 1 && (
|
||||
<div className="invisible absolute left-0 top-full z-30 pt-2 opacity-0 transition-opacity group-focus-within:visible group-focus-within:opacity-100 group-hover:visible group-hover:opacity-100">
|
||||
<ul className="min-w-52 rounded-xl border border-[#138ba0]/20 bg-white p-1.5 shadow-lg">
|
||||
{children.map((child) => (
|
||||
<li key={child.to}>
|
||||
<NavLink
|
||||
to={child.to}
|
||||
className={`block rounded-lg px-3 py-2 text-sm transition-colors hover:bg-[#eef9fb] ${
|
||||
matches(pathname, child.to)
|
||||
? "font-semibold text-[#138ba0]"
|
||||
: "text-[#26454c]"
|
||||
}`}
|
||||
>
|
||||
{child.label}
|
||||
</NavLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminLayout() {
|
||||
const { user, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -109,16 +159,7 @@ export default function AdminLayout() {
|
|||
className="h-4 w-px bg-[#4a6b72]/25"
|
||||
/>
|
||||
)}
|
||||
<NavLink
|
||||
to={target(item)}
|
||||
className={
|
||||
item === active
|
||||
? "font-semibold text-[#138ba0]"
|
||||
: "text-[#4a6b72] transition-colors hover:text-[#138ba0]"
|
||||
}
|
||||
>
|
||||
{item.label}
|
||||
</NavLink>
|
||||
<GroupMenu item={item} lit={item === active} pathname={pathname} />
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
|
|
|||
|
|
@ -5,18 +5,35 @@
|
|||
page of the website; it's the door to the back office, and it
|
||||
shouldn't carry a banner, a subnav, or a footer site map.
|
||||
|
||||
The Google button is stubbed and disabled until the OAuth
|
||||
routes exist. It's here so the layout doesn't change when it
|
||||
starts working.
|
||||
Google first, when the server has it set up (/auth/providers
|
||||
says so; it's off until GOOGLE_CLIENT_ID and _SECRET are on the
|
||||
service). It's a plain link: the server sends the browser to
|
||||
Google and back, and a refusal comes back here as ?error=<code>,
|
||||
worded below. Email and password stay underneath as the way in
|
||||
if Google is ever unavailable.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
|
||||
|
||||
import { useAuth } from "../../lib/auth.tsx";
|
||||
import { ApiError } from "../../lib/api.ts";
|
||||
import { ApiError, get } from "../../lib/api.ts";
|
||||
|
||||
const GOOGLE_ENABLED = false;
|
||||
/* What a ?error= from the Google callback means, in the words the
|
||||
person at the login page needs. */
|
||||
const GOOGLE_ERRORS: Record<string, string> = {
|
||||
cancelled: "Google sign-in was cancelled.",
|
||||
expired: "That sign-in took too long or was already used. Try again.",
|
||||
no_account:
|
||||
"There's no admin account for that Google account. Ask a superadmin to add your email.",
|
||||
linked_elsewhere:
|
||||
"That email's admin account is linked to a different Google account.",
|
||||
disabled: "That account has been disabled.",
|
||||
wrong_domain: "Use your @nextgenerationofunity.org Google account.",
|
||||
unverified: "That Google account's email isn't verified.",
|
||||
google_unreachable: "Couldn't reach Google. Try again in a moment.",
|
||||
google_failed: "Google sign-in didn't work. Try again, or use your password.",
|
||||
};
|
||||
|
||||
const fieldClass =
|
||||
"w-full rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 text-[#26454c] " +
|
||||
|
|
@ -27,9 +44,21 @@ export default function AdminLogin() {
|
|||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
const googleError = searchParams.get("error");
|
||||
const [google, setGoogle] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
get("/auth/providers", { ttl: 0 })
|
||||
.then((data) => setGoogle(Boolean(data.google)))
|
||||
.catch(() => setGoogle(false));
|
||||
}, []);
|
||||
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<any>(null);
|
||||
const [error, setError] = useState<any>(
|
||||
googleError ? (GOOGLE_ERRORS[googleError] ?? GOOGLE_ERRORS.google_failed) : null,
|
||||
);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const destination = location.state?.from?.pathname ?? "/admin/home";
|
||||
|
|
@ -60,7 +89,7 @@ export default function AdminLogin() {
|
|||
<div className="w-full max-w-sm">
|
||||
<h1 className="text-3xl font-bold text-[#138ba0]">NGU admin</h1>
|
||||
<p className="mt-2 text-sm text-[#4a6b72]">
|
||||
Sign in to read and triage site feedback.
|
||||
Sign in to edit the site.
|
||||
</p>
|
||||
|
||||
<form
|
||||
|
|
@ -68,6 +97,28 @@ export default function AdminLogin() {
|
|||
noValidate
|
||||
className="mt-8 rounded-2xl border border-[#138ba0]/20 bg-white p-6"
|
||||
>
|
||||
{google && (
|
||||
<>
|
||||
<a
|
||||
href={`/api/auth/google?next=${encodeURIComponent(destination)}`}
|
||||
className="flex items-center justify-center gap-3 rounded-full border border-[#4a6b72]/30 px-6 py-3 font-semibold text-[#26454c] transition-colors hover:bg-[#eef9fb]"
|
||||
>
|
||||
<svg viewBox="0 0 48 48" className="h-5 w-5" 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>
|
||||
Sign in with Google
|
||||
</a>
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-[#4a6b72]">
|
||||
<span className="h-px flex-1 bg-[#4a6b72]/20" />
|
||||
or with a password
|
||||
<span className="h-px flex-1 bg-[#4a6b72]/20" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<label
|
||||
htmlFor="admin-email"
|
||||
className="block text-sm font-medium text-[#26454c]"
|
||||
|
|
@ -78,7 +129,7 @@ export default function AdminLogin() {
|
|||
id="admin-email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
autoFocus={!google}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
|
|
@ -116,21 +167,6 @@ export default function AdminLogin() {
|
|||
{busy ? "Signing in…" : "Sign in"}
|
||||
</button>
|
||||
|
||||
{GOOGLE_ENABLED && (
|
||||
<>
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-[#4a6b72]">
|
||||
<span className="h-px flex-1 bg-[#4a6b72]/20" />
|
||||
or
|
||||
<span className="h-px flex-1 bg-[#4a6b72]/20" />
|
||||
</div>
|
||||
<a
|
||||
href="/api/auth/google"
|
||||
className="block rounded-full border border-[#4a6b72]/30 px-6 py-3 text-center font-semibold text-[#26454c] transition-colors hover:bg-[#eef9fb]"
|
||||
>
|
||||
Continue with Google
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
|
||||
<p className="mt-6 text-center text-xs text-[#4a6b72]">
|
||||
|
|
|
|||
|
|
@ -87,7 +87,9 @@ export default function EntityEdit() {
|
|||
useWideAdminPage();
|
||||
|
||||
const isNew = id === "new";
|
||||
const canWrite = atLeast(user, "editor");
|
||||
// Editor, unless the entity asks for more (site settings:
|
||||
// superadmin), matching the server's writeRole.
|
||||
const canWrite = atLeast(user, manifest?.writeRole ?? "editor");
|
||||
const canDelete = atLeast(user, "admin");
|
||||
|
||||
// Some entities have no slug: the table assigns an integer id, so
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ export default function EntityList() {
|
|||
// equality test this replaced hid the button from superadmins as
|
||||
// well as editors, which is the failure mode an == against a
|
||||
// ladder always produces once a rank is added above it.
|
||||
const canWrite = atLeast(user, "editor");
|
||||
const canWrite = atLeast(user, manifest?.writeRole ?? "editor");
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!manifest || manifest.singleton) return;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,26 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ADMIN NAVIGATION: src/pages/admin/adminNav.ts
|
||||
|
||||
Lifted out of AdminLayout because two things read it now: the
|
||||
header tabs and the card grid on the home page. Adding an entity
|
||||
stays one entry here plus a descriptor; there's still no second
|
||||
list to keep in step, it just isn't inside the layout file
|
||||
any more.
|
||||
One list, read by two things: the header (a menu per group, its
|
||||
items on hover or focus, and the open group's items in the strip
|
||||
below) and the admin home page (a block of cards per group).
|
||||
Adding an entity stays one entry here plus a descriptor; there's
|
||||
no second list to keep in step.
|
||||
|
||||
Five groups, each a menu in the header and a block on the home
|
||||
page:
|
||||
|
||||
Data the records: events, organizations, teams, awards, people
|
||||
Pages what edits a page rather than a record type: the front
|
||||
page, the history timeline, the blog and its Community
|
||||
section
|
||||
Forms what the public site has sent us
|
||||
Tools pages that make something: the media library, QR codes
|
||||
Panel accounts and the server (superadmins only)
|
||||
|
||||
Clicking a group's name opens its first item. That's also the
|
||||
touch path, where hover doesn't exist: the strip under the header
|
||||
lists the rest of the open group.
|
||||
|
||||
`blurb` is only read by the home cards. The header ignores it.
|
||||
|
||||
|
|
@ -31,73 +46,72 @@ export const AREA_TITLES = {
|
|||
panel: "NGU Admin Panel",
|
||||
};
|
||||
|
||||
/* The CMS tabs. Teams and Awards live under Organizations because
|
||||
that's where they belong conceptually (a team is part of an org,
|
||||
an award is given by one), even though each is its own table and
|
||||
its own page. */
|
||||
export const CMS_NAV = [
|
||||
{
|
||||
to: "/admin/events",
|
||||
label: "Events",
|
||||
blurb: "Retreats, conferences and gatherings, with their sections and rosters.",
|
||||
},
|
||||
{
|
||||
to: "/admin/organizations",
|
||||
label: "Organizations",
|
||||
blurb: "Regions, chapters and partners, plus the teams and awards they own.",
|
||||
children: [
|
||||
{ to: "/admin/organizations", label: "All organizations" },
|
||||
{ to: "/admin/teams", label: "Teams" },
|
||||
{ to: "/admin/awards", label: "Awards" },
|
||||
],
|
||||
},
|
||||
{
|
||||
to: "/admin/people",
|
||||
label: "People",
|
||||
blurb: "Bios, contact details, affiliations and awards received.",
|
||||
},
|
||||
// Its own tab rather than a child of anything: a timeline entry can
|
||||
// point at an event, an organization, an award, a person or a team,
|
||||
// so filing it under one of them would be arbitrary.
|
||||
{
|
||||
to: "/admin/timeline",
|
||||
label: "Timeline",
|
||||
blurb: "What the history page shows, and the order it shows it in.",
|
||||
},
|
||||
// One record, not a list: the tab opens it directly.
|
||||
{
|
||||
to: "/admin/front_page",
|
||||
label: "Front page",
|
||||
blurb: "The hero, its photos or livestream, and which bands the home page draws.",
|
||||
},
|
||||
// Posts, and the Community page section that lists them. Two
|
||||
// entities, one tab, like Organizations with Teams and Awards.
|
||||
{
|
||||
to: "/admin/blog_posts",
|
||||
label: "Blog",
|
||||
blurb: "Posts of our own, and the Community page's blog section.",
|
||||
children: [
|
||||
{ to: "/admin/blog_posts", label: "Posts" },
|
||||
{ to: "/admin/community_page", label: "Community section" },
|
||||
],
|
||||
},
|
||||
// Not an entity: the uploaded-image library every image field
|
||||
// picks from. Its own page, AdminMedia.tsx.
|
||||
{
|
||||
to: "/admin/media",
|
||||
label: "Media",
|
||||
blurb: "Uploaded images: logos, photos and backgrounds, ready to reuse.",
|
||||
},
|
||||
];
|
||||
export const DATA_NAV = {
|
||||
label: "Data",
|
||||
blurb: "The records the site is built from.",
|
||||
children: [
|
||||
{
|
||||
to: "/admin/events",
|
||||
label: "Events",
|
||||
blurb: "Retreats, conferences and gatherings, with their sections and rosters.",
|
||||
},
|
||||
{
|
||||
to: "/admin/organizations",
|
||||
label: "Organizations",
|
||||
blurb: "The national organization, regions, chapters and partners.",
|
||||
},
|
||||
{
|
||||
to: "/admin/teams",
|
||||
label: "Teams",
|
||||
blurb: "Boards, committees and leadership teams within an organization.",
|
||||
},
|
||||
{
|
||||
to: "/admin/awards",
|
||||
label: "Awards",
|
||||
blurb: "Awards an organization gives. Who received one is edited on the person.",
|
||||
},
|
||||
{
|
||||
to: "/admin/people",
|
||||
label: "People",
|
||||
blurb: "Bios, contact details, affiliations and awards received.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/* Forms are submissions coming in rather than content going out, so
|
||||
they get their own group in the header and their own block on the
|
||||
home page. A group with no `to` of its own opens its first child,
|
||||
so clicking the word Forms goes somewhere rather than nowhere. */
|
||||
export const PAGES_NAV = {
|
||||
label: "Pages",
|
||||
blurb: "What a page shows and in what order.",
|
||||
children: [
|
||||
// One record, not a list: the item opens it directly.
|
||||
{
|
||||
to: "/admin/front_page",
|
||||
label: "Front page",
|
||||
blurb: "The hero, its photos or livestream, and which bands the home page draws.",
|
||||
},
|
||||
// A timeline entry can point at an event, an organization, an
|
||||
// award, a person or a team, so it isn't filed under any of them.
|
||||
{
|
||||
to: "/admin/timeline",
|
||||
label: "Timeline",
|
||||
blurb: "What the history page shows, and the order it shows it in.",
|
||||
},
|
||||
{
|
||||
to: "/admin/blog_posts",
|
||||
label: "Blog posts",
|
||||
blurb: "Posts of our own, each at /blog/…",
|
||||
},
|
||||
{
|
||||
to: "/admin/community_page",
|
||||
label: "Community blog section",
|
||||
blurb: "The Community page's blog: headings, pinned posts and feeds.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/* Submissions coming in rather than content going out. */
|
||||
export const FORMS_NAV = {
|
||||
label: "Forms",
|
||||
blurb: "Whatever the public site has sent us.",
|
||||
separated: true,
|
||||
children: [
|
||||
{
|
||||
to: "/admin/feedback",
|
||||
|
|
@ -107,47 +121,65 @@ export const FORMS_NAV = {
|
|||
],
|
||||
};
|
||||
|
||||
/* Tools are pages that make something rather than edit a record.
|
||||
They live on the public site, so they're on the home page only:
|
||||
a header tab would leave the admin area. */
|
||||
/* Pages that make something rather than edit a record. The QR page
|
||||
lives on the public site, so opening it leaves the admin. */
|
||||
export const TOOLS_NAV = {
|
||||
label: "Tools",
|
||||
blurb: "Handy pages for making things.",
|
||||
children: [
|
||||
{
|
||||
to: "/admin/media",
|
||||
label: "Media",
|
||||
blurb: "Uploaded images: logos, photos and backgrounds, ready to reuse.",
|
||||
},
|
||||
{
|
||||
to: "/qr",
|
||||
label: "QR code generator",
|
||||
blurb: "Codes for flyers, slides and signs, pointing at any page on the site.",
|
||||
blurb: "Codes for flyers, slides and signs: any page or link, in your choice of colours.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/* Accounts and server state, not content, which is why it sits
|
||||
outside the CMS rather than as another tab within it. */
|
||||
/* Accounts, server state and what the site says about itself: the
|
||||
superadmin's area, its own area rather than a group of CMS pages. */
|
||||
export const SITE_SETTINGS = "/admin/site_settings";
|
||||
|
||||
export const PANEL_NAV = {
|
||||
to: ADMIN_PANEL,
|
||||
label: "Panel",
|
||||
blurb: "Accounts, sessions and the state of the server.",
|
||||
blurb: "Only superadmins see this.",
|
||||
separated: true,
|
||||
superOnly: true,
|
||||
children: [
|
||||
{
|
||||
to: ADMIN_PANEL,
|
||||
label: "Accounts and server",
|
||||
blurb: "Accounts, sessions and the state of the server.",
|
||||
},
|
||||
{
|
||||
to: SITE_SETTINGS,
|
||||
label: "Site settings",
|
||||
blurb: "The site's name, description, preview image, icons, page titles and search indexing.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const NAV: any[] = [...CMS_NAV, FORMS_NAV, PANEL_NAV];
|
||||
export const NAV: any[] = [DATA_NAV, PAGES_NAV, FORMS_NAV, TOOLS_NAV, PANEL_NAV];
|
||||
|
||||
/* What this user may see. Call it with the user from useAuth. */
|
||||
export function navFor(user) {
|
||||
return NAV.filter((item) => !item.superOnly || isSuper(user));
|
||||
}
|
||||
|
||||
/* A tab owns its own page and everything below it, so editing
|
||||
/* An item owns its own page and everything below it, so editing
|
||||
/admin/teams/ngu-board keeps Teams lit. */
|
||||
export const matches = (pathname, to) =>
|
||||
Boolean(to) && (pathname === to || pathname.startsWith(`${to}/`));
|
||||
|
||||
/* Where a group's name goes: its own page, else its first item. */
|
||||
export const target = (item) => item.to ?? item.children?.[0]?.to;
|
||||
|
||||
export function areaFor(pathname) {
|
||||
if (matches(pathname, ADMIN_HOME)) return "home";
|
||||
if (matches(pathname, ADMIN_PANEL)) return "panel";
|
||||
if (matches(pathname, ADMIN_PANEL) || matches(pathname, SITE_SETTINGS)) return "panel";
|
||||
return "cms";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
COMMUNITY BLOG
|
||||
|
||||
The Community page's blog section (Admin → Blog → Community
|
||||
The Community page's blog section (Admin → Pages → Community blog
|
||||
section). Two halves, each pinned first and then newest, as
|
||||
routes/blog.js decides:
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { eventHref } from "../../lib/hrefs.ts";
|
|||
import { EVENT_TYPES, eventTypeLabel } from "../../lib/eventTypes.ts";
|
||||
import { seriesLabel } from "../../lib/eventSeries.ts";
|
||||
import PlatformIcon from "../../components/PlatformIcon.tsx";
|
||||
import { eventBackground, isAbsoluteMedia } from "../../lib/media.ts";
|
||||
import { eventBackground, eventLogo as eventLogoSrc, orgLogo as orgLogoSrc } from "../../lib/media.ts";
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
EVENT LIST — CARDS
|
||||
|
|
@ -27,28 +27,17 @@ import { eventBackground, isAbsoluteMedia } from "../../lib/media.ts";
|
|||
nothing but retreats shows no control at all.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
const LOGO_FILES = import.meta.glob("../../assets/event-logos/*.svg", {
|
||||
eager: true,
|
||||
import: "default",
|
||||
});
|
||||
|
||||
const LOGOS = Object.fromEntries(
|
||||
Object.entries(LOGO_FILES).map(([path, src]) => [path.split("/").pop(), src])
|
||||
);
|
||||
|
||||
/* A bundled logo by filename, or an upload or URL as it is. */
|
||||
const logoSrc = file =>
|
||||
(file && LOGOS[file]) || (isAbsoluteMedia(file) ? file : null);
|
||||
|
||||
/* Last resort only. The API already falls back to the host
|
||||
organization's logo when an event doesn't name its own, so this
|
||||
fires only for an event with no host at all. */
|
||||
const DEFAULT_ORG_LOGO = null;
|
||||
|
||||
/* An <img> that removes itself if the file 404s. */
|
||||
function Logo({ file, alt = "", className }) {
|
||||
/* An <img> that removes itself if the file 404s. `src` is already
|
||||
resolved by media.ts: a bare filename from the uploads directory,
|
||||
anything with a path or URL as it is. */
|
||||
function Logo({ src, alt = "", className }) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
const src = logoSrc(file);
|
||||
if (!src || failed) return null;
|
||||
return (
|
||||
<img
|
||||
|
|
@ -165,8 +154,8 @@ export function Card({
|
|||
}) {
|
||||
const past = ev.status === "past";
|
||||
const color = ev.color || defaultColor;
|
||||
const orgLogo = ev.org_logo || DEFAULT_ORG_LOGO;
|
||||
const eventLogo = ev.event_logo;
|
||||
const orgLogo = orgLogoSrc(ev.org_logo) || DEFAULT_ORG_LOGO;
|
||||
const eventLogo = eventLogoSrc(ev.event_logo);
|
||||
const schedule = seriesLabel(ev.series, ev.starts_on);
|
||||
const links = ev.links ?? [];
|
||||
const igHandle = ev.instagram || null;
|
||||
|
|
@ -216,7 +205,7 @@ export function Card({
|
|||
{compact ? (
|
||||
/* ── GRID CARD: layout driven by .ev-grid container queries ── */
|
||||
<div className="ev-grid mb-2">
|
||||
<Logo file={orgLogo} className="ev-ngu h-11 w-auto mb-4" />
|
||||
<Logo src={orgLogo} className="ev-ngu h-11 w-auto mb-4" />
|
||||
<div className="ev-info">
|
||||
{typeBadge}
|
||||
<h3 className="text-3xl font-900 leading-tight">
|
||||
|
|
@ -234,7 +223,7 @@ export function Card({
|
|||
)}
|
||||
</div>
|
||||
<Logo
|
||||
file={eventLogo}
|
||||
src={eventLogo}
|
||||
alt={ev.title}
|
||||
className="ev-image w-full h-auto object-contain"
|
||||
/>
|
||||
|
|
@ -245,7 +234,7 @@ export function Card({
|
|||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-x-8 mb-4">
|
||||
<div className="md:col-span-2">
|
||||
<Logo file={orgLogo} className="h-15 w-auto mb-6" />
|
||||
<Logo src={orgLogo} className="h-15 w-auto mb-6" />
|
||||
{typeBadge}
|
||||
<h3 className="text-4xl font-900">
|
||||
<TitleLink ev={ev} linked={linked}>
|
||||
|
|
@ -263,7 +252,7 @@ export function Card({
|
|||
</div>
|
||||
<div className="md:col-span-1 flex items-center justify-end">
|
||||
<Logo
|
||||
file={eventLogo}
|
||||
src={eventLogo}
|
||||
alt={ev.title}
|
||||
className="w-full h-auto max-h-72 object-contain"
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,23 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
QR CODE MAKER
|
||||
|
||||
Pick a page, get a QR code for it on the live site.
|
||||
Pick a page, or type a link, and get a QR code for it.
|
||||
|
||||
What main navigation, or one kind of record
|
||||
What main navigation, one kind of record, or a link
|
||||
typed in
|
||||
Which the page or record itself
|
||||
Section for a main page with a subnav, optionally one of
|
||||
its #sections
|
||||
Centre nothing, the NGU dove, or any SVG in
|
||||
src/assets/qr (drop a file there and it's offered;
|
||||
it's embedded in the code, so downloads carry it)
|
||||
Colours the code, its background, and the dove. A warning
|
||||
appears when the pair is unlikely to scan: too
|
||||
little contrast, or a light code on a dark ground
|
||||
|
||||
A typed link can be a site path (/retreats, which goes to the live
|
||||
site like every other choice), a full http(s) address, or a bare
|
||||
domain, which gets https:// in front.
|
||||
|
||||
The main pages come from navConfig.ts, the same list the header
|
||||
draws; records come from GET /directory, which lists only what's
|
||||
|
|
@ -22,7 +33,7 @@
|
|||
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
|
||||
import QrCode from '../../components/QrCode.tsx'
|
||||
import QrCode, { QR_DOVE, QR_INK, QR_PAPER, type QrCentre } from '../../components/QrCode.tsx'
|
||||
import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts'
|
||||
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
|
||||
import { siteUrl } from '../../lib/site.ts'
|
||||
|
|
@ -35,7 +46,7 @@ const MUTED = '#4a6b72'
|
|||
anything bigger should use the SVG. */
|
||||
const PNG_SIZE = 1024
|
||||
|
||||
type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts'
|
||||
type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts' | 'custom'
|
||||
|
||||
const KINDS: Array<[Kind, string]> = [
|
||||
['pages', 'Main navigation'],
|
||||
|
|
@ -45,8 +56,81 @@ const KINDS: Array<[Kind, string]> = [
|
|||
['awards', 'Awards'],
|
||||
['people', 'People'],
|
||||
['blog_posts', 'Blog posts'],
|
||||
['custom', 'A link I type'],
|
||||
]
|
||||
|
||||
/* The centres on offer: the dove, then every SVG in src/assets/qr,
|
||||
named after its file ("ngu-circle.svg" → "Ngu circle"). Read as
|
||||
text and turned into data: URLs so they sit inside the code's own
|
||||
SVG. */
|
||||
const CENTRE_FILES = import.meta.glob<string>('../../assets/qr/*.svg', {
|
||||
eager: true,
|
||||
query: '?raw',
|
||||
import: 'default',
|
||||
})
|
||||
|
||||
type CentreOption = { id: string; label: string; centre: (dove: string) => QrCentre }
|
||||
|
||||
const toDataUrl = (svg: string) =>
|
||||
`data:image/svg+xml;base64,${btoa(String.fromCharCode(...new TextEncoder().encode(svg)))}`
|
||||
|
||||
const CENTRES: CentreOption[] = [
|
||||
{ id: 'none', label: 'Nothing', centre: () => null },
|
||||
{ id: 'dove', label: 'NGU dove', centre: (color) => ({ kind: 'dove', color }) },
|
||||
...Object.entries(CENTRE_FILES)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([path, svg]) => {
|
||||
const name = path.split('/').pop()!.replace(/\.svg$/i, '')
|
||||
const label = name.replace(/[-_]+/g, ' ').replace(/^./, (c) => c.toUpperCase())
|
||||
const src = toDataUrl(svg)
|
||||
return { id: `file:${name}`, label, centre: () => ({ kind: 'image', src }) as QrCentre }
|
||||
}),
|
||||
]
|
||||
|
||||
/* ── Contrast ──────────────────────────────────────────────────
|
||||
WCAG relative luminance and contrast ratio. Below MIN_CONTRAST
|
||||
some phone cameras struggle; a code lighter than its background
|
||||
is "inverted", which many scanners don't read at all. */
|
||||
const MIN_CONTRAST = 4
|
||||
|
||||
function luminance(hex: string): number {
|
||||
const m = hex.replace('#', '').match(/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i)
|
||||
if (!m) return 0
|
||||
const [r, g, b] = m.slice(1).map((h) => {
|
||||
const c = parseInt(h, 16) / 255
|
||||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
|
||||
})
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
function scanWarning(ink: string, paper: string): string | null {
|
||||
const a = luminance(ink)
|
||||
const b = luminance(paper)
|
||||
if (a > b) return 'The code is lighter than its background. Many scanners can’t read an inverted code.'
|
||||
const ratio = (b + 0.05) / (a + 0.05)
|
||||
if (ratio < MIN_CONTRAST) {
|
||||
return `Low contrast (${ratio.toFixed(1)}:1). Use a darker code or a lighter background so it scans reliably.`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/* What a typed link means: a site path goes to the live site, a
|
||||
full address is used as it is, a bare domain gets https://.
|
||||
Anything else isn't a link. */
|
||||
function typedUrl(raw: string): string | null {
|
||||
const value = raw.trim()
|
||||
if (!value) return null
|
||||
if (value.startsWith('/') && !value.startsWith('//')) return siteUrl(value)
|
||||
const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(value) ? value : /^[^\s/]+\.[^\s/]+/.test(value) ? `https://${value}` : null
|
||||
if (!withScheme) return null
|
||||
try {
|
||||
const url = new URL(withScheme)
|
||||
return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/* Organizations are grouped by kind in the dropdown, in this order. */
|
||||
const ORG_GROUPS: Array<[string, string]> = [
|
||||
['national', 'NGU'],
|
||||
|
|
@ -109,12 +193,22 @@ function groupsFor(kind: Kind, directory: Directory | null): Group[] {
|
|||
return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }]
|
||||
case 'blog_posts':
|
||||
return [{ choices: directory.blog_posts.map((b) => ({ path: blogHref(b.id), label: b.name })) }]
|
||||
case 'custom':
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/* "/regions/northwest#events" → "regions-northwest-events". */
|
||||
function fileStem(path: string): string {
|
||||
const stem = path.replace(/^\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '')
|
||||
/* "/regions/northwest#events" → "regions-northwest-events"; a typed
|
||||
link keeps its host too: "example-org-page". */
|
||||
function fileStem(target: string): string {
|
||||
let name = target
|
||||
try {
|
||||
const url = new URL(target)
|
||||
name = `${url.hostname.replace(/^www\./, '')}${url.pathname}${url.hash}`
|
||||
} catch {
|
||||
/* a site path */
|
||||
}
|
||||
const stem = name.replace(/^\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '')
|
||||
return `ngu-qr-${stem || 'home'}`
|
||||
}
|
||||
|
||||
|
|
@ -163,7 +257,11 @@ export default function QrCodeMaker() {
|
|||
const [kind, setKind] = useState<Kind>('pages')
|
||||
const [path, setPath] = useState('/')
|
||||
const [section, setSection] = useState('')
|
||||
const [dove, setDove] = useState(true)
|
||||
const [custom, setCustom] = useState('')
|
||||
const [centreId, setCentreId] = useState('dove')
|
||||
const [ink, setInk] = useState(QR_INK)
|
||||
const [paper, setPaper] = useState(QR_PAPER)
|
||||
const [doveColor, setDoveColor] = useState(QR_DOVE)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const svgRef = useRef<SVGSVGElement>(null)
|
||||
|
||||
|
|
@ -181,8 +279,13 @@ export default function QrCodeMaker() {
|
|||
|
||||
const sections = kind === 'pages' ? (PAGE_SECTIONS[path] ?? []) : []
|
||||
const selected = choices.find((c) => c.path === path) ?? null
|
||||
const target = selected ? `${selected.path}${section}` : null
|
||||
const url = target ? siteUrl(target) : null
|
||||
const typed = kind === 'custom' ? typedUrl(custom) : null
|
||||
const target = kind === 'custom' ? typed : selected ? `${selected.path}${section}` : null
|
||||
const url = kind === 'custom' ? typed : target ? siteUrl(target) : null
|
||||
|
||||
const centreOption = CENTRES.find((c) => c.id === centreId) ?? CENTRES[0]
|
||||
const centre = centreOption.centre(doveColor)
|
||||
const warning = scanWarning(ink, paper)
|
||||
|
||||
useEffect(() => setCopied(false), [url])
|
||||
|
||||
|
|
@ -198,7 +301,7 @@ export default function QrCodeMaker() {
|
|||
}
|
||||
}
|
||||
|
||||
const needsDirectory = kind !== 'pages'
|
||||
const needsDirectory = kind !== 'pages' && kind !== 'custom'
|
||||
|
||||
return (
|
||||
<div className="grid gap-10 lg:grid-cols-2 lg:items-start">
|
||||
|
|
@ -211,7 +314,27 @@ export default function QrCodeMaker() {
|
|||
))}
|
||||
</Select>
|
||||
|
||||
{needsDirectory && loading && !directory ? (
|
||||
{kind === 'custom' ? (
|
||||
<div>
|
||||
<label htmlFor="qr-custom" className="block text-sm font-medium text-[#26454c]">
|
||||
Link
|
||||
</label>
|
||||
<input
|
||||
id="qr-custom"
|
||||
type="text"
|
||||
inputMode="url"
|
||||
value={custom}
|
||||
onChange={(e) => setCustom(e.target.value)}
|
||||
placeholder="https://… or /retreats"
|
||||
className={`mt-2 ${inputClass}`}
|
||||
/>
|
||||
<p className="mt-1 text-sm" style={{ color: custom.trim() && !typed ? '#b3261e' : MUTED }}>
|
||||
{custom.trim() && !typed
|
||||
? 'That isn’t a web address. Use https://…, a domain, or a site path like /retreats.'
|
||||
: 'A full address, a domain (example.org), or a path on this site (/retreats).'}
|
||||
</p>
|
||||
</div>
|
||||
) : needsDirectory && loading && !directory ? (
|
||||
<p style={{ color: MUTED }}>Loading the list…</p>
|
||||
) : needsDirectory && error ? (
|
||||
<p className="text-[#b3261e]">Couldn't load the list of pages. {error}</p>
|
||||
|
|
@ -258,15 +381,43 @@ export default function QrCodeMaker() {
|
|||
</Select>
|
||||
)}
|
||||
|
||||
<label className="flex items-center gap-3 text-[#26454c]">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={dove}
|
||||
onChange={(e) => setDove(e.target.checked)}
|
||||
className="h-4 w-4 accent-[#138ba0]"
|
||||
/>
|
||||
NGU dove in the centre
|
||||
</label>
|
||||
<Select id="qr-centre" label="In the centre" value={centreId} onChange={setCentreId}>
|
||||
{CENTRES.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
<fieldset>
|
||||
<legend className="text-sm font-medium text-[#26454c]">Colours</legend>
|
||||
<div className="mt-2 flex flex-wrap items-end gap-5">
|
||||
<ColourInput id="qr-ink" label="Code" value={ink} onChange={setInk} />
|
||||
<ColourInput id="qr-paper" label="Background" value={paper} onChange={setPaper} />
|
||||
{centreOption.id === 'dove' && (
|
||||
<ColourInput id="qr-dove" label="Dove" value={doveColor} onChange={setDoveColor} />
|
||||
)}
|
||||
{(ink !== QR_INK || paper !== QR_PAPER || doveColor !== QR_DOVE) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setInk(QR_INK)
|
||||
setPaper(QR_PAPER)
|
||||
setDoveColor(QR_DOVE)
|
||||
}}
|
||||
className="pb-2 text-sm underline"
|
||||
style={{ color: TEAL }}
|
||||
>
|
||||
Reset colours
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{warning && (
|
||||
<p role="status" className="mt-2 rounded-lg bg-[#fdf3f2] px-3 py-2 text-sm text-[#b3261e]">
|
||||
{warning}
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{url && (
|
||||
<div>
|
||||
|
|
@ -295,7 +446,9 @@ export default function QrCodeMaker() {
|
|||
<QrCode
|
||||
ref={svgRef}
|
||||
value={url}
|
||||
dove={dove}
|
||||
centre={centre}
|
||||
ink={ink}
|
||||
paper={paper}
|
||||
label={`QR code for ${url}`}
|
||||
className="block h-auto w-full"
|
||||
/>
|
||||
|
|
@ -333,6 +486,52 @@ function DownloadButton({ onClick, children }: { onClick: () => void; children:
|
|||
)
|
||||
}
|
||||
|
||||
const inputClass =
|
||||
'w-full rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 text-[#26454c] ' +
|
||||
'outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25'
|
||||
|
||||
/* A colour well with its hex beside it, both editable. */
|
||||
function ColourInput({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
const [text, setText] = useState(value)
|
||||
useEffect(() => setText(value), [value])
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor={id} className="block text-xs font-medium" style={{ color: MUTED }}>
|
||||
{label}
|
||||
</label>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<input
|
||||
id={id}
|
||||
type="color"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="h-9 w-11 cursor-pointer rounded border border-[#4a6b72]/25 bg-white"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
aria-label={`${label} colour, as hex`}
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value)
|
||||
if (/^#[0-9a-f]{6}$/i.test(e.target.value)) onChange(e.target.value.toLowerCase())
|
||||
}}
|
||||
className="w-24 rounded-lg border border-[#4a6b72]/25 bg-white px-2 py-1.5 font-mono text-sm text-[#26454c] outline-none focus:border-[#138ba0]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const selectClass =
|
||||
'w-full appearance-none rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 pr-10 text-[#26454c] ' +
|
||||
'outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25'
|
||||
|
|
|
|||
|
|
@ -20,9 +20,13 @@
|
|||
video a featured video under a "Featured video" badge.
|
||||
Never autoplays: an embed waits for play, a file
|
||||
shows the browser's player
|
||||
event an event's card under a "Featured event" badge:
|
||||
its photo, dates, place and buttons. The API picks
|
||||
the event (pinned, else the countdown's)
|
||||
|
||||
A choice with nothing to show falls back: photos with no photos
|
||||
to brand, a feature with no link set to none. A link that can't
|
||||
to brand, a feature with no link set (or no event to show) to
|
||||
none. A link that can't
|
||||
be framed still gets a "Watch live" or "Watch the video" button,
|
||||
so switching a feature on is never a no-op.
|
||||
|
||||
|
|
@ -33,11 +37,16 @@
|
|||
|
||||
import { useEffect, useState, type CSSProperties } from 'react'
|
||||
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import HomeLink from './HomeLink.tsx'
|
||||
import DoveMark from '../../../components/DoveMark.tsx'
|
||||
import PlatformIcon from '../../../components/PlatformIcon.tsx'
|
||||
import { livestreamEmbedUrl, videoSource, type VideoSource } from '../../../lib/embeds.ts'
|
||||
import { heroPhoto } from '../../../lib/media.ts'
|
||||
import type { Hero, HeroBackdrop, HeroFeature, HeroSlide } from '../../../lib/useFrontPage.ts'
|
||||
import { eventBackground, heroPhoto } from '../../../lib/media.ts'
|
||||
import { eventHref } from '../../../lib/hrefs.ts'
|
||||
import { seriesLabel } from '../../../lib/eventSeries.ts'
|
||||
import type { Hero, HeroBackdrop, HeroEvent, HeroFeature, HeroSlide } from '../../../lib/useFrontPage.ts'
|
||||
|
||||
const DEEP = '#04262e'
|
||||
|
||||
|
|
@ -54,9 +63,11 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
|
|||
? 'livestream'
|
||||
: hero?.feature === 'video' && hero.video
|
||||
? 'video'
|
||||
: 'none'
|
||||
: hero?.feature === 'event' && hero.event
|
||||
? 'event'
|
||||
: 'none'
|
||||
|
||||
// Both features share a layout: words left, player right.
|
||||
// Every feature shares a layout: words left, feature right.
|
||||
const beside = feature !== 'none'
|
||||
|
||||
return (
|
||||
|
|
@ -87,6 +98,12 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
|
|||
<VideoFrame source={video} url={hero.video.url} title={hero.video.title} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{feature === 'event' && hero?.event && (
|
||||
<div className="lg:col-span-7">
|
||||
<EventPanel event={hero.event} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
|
@ -111,6 +128,11 @@ function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
|
|||
</span>
|
||||
)}
|
||||
</p>
|
||||
) : feature === 'event' ? (
|
||||
<p className="mb-6 inline-flex items-center gap-3 rounded-full bg-white/10 px-4 py-1.5 text-sm font-semibold uppercase tracking-[0.2em] backdrop-blur">
|
||||
<span className="text-[#9fe7d0]" aria-hidden="true">★</span>
|
||||
Featured event
|
||||
</p>
|
||||
) : feature === 'video' ? (
|
||||
<p className="mb-6 inline-flex items-center gap-3 rounded-full bg-white/10 px-4 py-1.5 text-sm font-semibold uppercase tracking-[0.2em] backdrop-blur">
|
||||
<span className="text-[#9fe7d0]" aria-hidden="true">▶</span>
|
||||
|
|
@ -413,3 +435,71 @@ function VideoFrame({
|
|||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Featured event ──────────────────────────────────────────── */
|
||||
|
||||
/* The event's own card for the hero: its background photo (or its
|
||||
colour), then what, when and where, then its buttons and a way
|
||||
to its page. The first action link is the filled button, since
|
||||
it's usually Register. */
|
||||
function EventPanel({ event }: { event: HeroEvent }) {
|
||||
const color = event.color || '#138ba0'
|
||||
const photo = eventBackground(event.card_image)
|
||||
const when = seriesLabel(event.series, event.starts_on) ?? event.date_label
|
||||
const where = event.is_online && !event.location_label ? 'Online' : event.location_label
|
||||
|
||||
return (
|
||||
<div
|
||||
className="overflow-hidden rounded-3xl border border-white/15 bg-white/10 text-white shadow-2xl backdrop-blur"
|
||||
style={{ boxShadow: `0 30px 80px -20px ${color}66` }}
|
||||
>
|
||||
{photo ? (
|
||||
<img src={photo} alt="" className="aspect-[16/7] w-full object-cover" />
|
||||
) : (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="aspect-[16/7] w-full"
|
||||
style={{ background: `linear-gradient(135deg, ${color}, #04262e)` }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="space-y-4 p-8">
|
||||
<div>
|
||||
<h2 className="font-display text-3xl font-extrabold leading-tight md:text-4xl">
|
||||
<Link to={eventHref(event.id)} className="hover:underline">
|
||||
{event.title}
|
||||
</Link>
|
||||
</h2>
|
||||
{event.theme && <p className="mt-1 text-lg font-semibold text-[#9fe7d0]">"{event.theme}"</p>}
|
||||
</div>
|
||||
|
||||
{(when || where) && (
|
||||
<p className="text-lg text-white/85">{[when, where].filter(Boolean).join(' · ')}</p>
|
||||
)}
|
||||
{event.tagline && <p className="text-white/70">{event.tagline}</p>}
|
||||
|
||||
<div className="flex flex-wrap gap-3 pt-2">
|
||||
{event.links.map((link, index) => (
|
||||
<HomeLink
|
||||
key={link.url}
|
||||
url={link.url}
|
||||
className={`inline-flex items-center gap-2 rounded-full px-6 py-3 font-semibold transition-transform hover:scale-105 ${
|
||||
index === 0 ? 'text-[#04262e]' : 'border border-white/35 text-white hover:bg-white/10'
|
||||
}`}
|
||||
style={index === 0 ? { background: 'linear-gradient(120deg, #9fe7d0, #5ce7ff)' } : undefined}
|
||||
>
|
||||
<PlatformIcon platform={link.platform} />
|
||||
{link.label}
|
||||
</HomeLink>
|
||||
))}
|
||||
<Link
|
||||
to={eventHref(event.id)}
|
||||
className="rounded-full border border-white/35 px-6 py-3 font-semibold text-white transition-colors hover:bg-white/10"
|
||||
>
|
||||
Event details →
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,6 +39,8 @@ export default defineConfig({
|
|||
|
||||
type SiteConfiguration = {
|
||||
title?: string
|
||||
/** The live site's origin, eg. https://nextgenerationofunity.org. */
|
||||
url?: string
|
||||
description?: string
|
||||
language?: string
|
||||
robots?: { index?: boolean }
|
||||
|
|
@ -76,7 +78,13 @@ function siteConfigurationPlugin(config: SiteConfiguration): Plugin {
|
|||
const headEnd = config.customScripts?.headEnd ?? ''
|
||||
const bodyStart = config.customScripts?.bodyStart ?? ''
|
||||
const bodyEnd = config.customScripts?.bodyEnd ?? ''
|
||||
const robotsTxt = config.robots?.index === false ? 'User-agent: *\nDisallow: /\n' : ''
|
||||
// Blocked: nothing may be crawled. Allowed: everything but the
|
||||
// admin and the API, with the sitemap the API serves.
|
||||
const robotsTxt =
|
||||
config.robots?.index === false
|
||||
? 'User-agent: *\nDisallow: /\n'
|
||||
: 'User-agent: *\nDisallow: /admin\nDisallow: /api\n' +
|
||||
(config.url ? `\nSitemap: ${config.url.replace(/\/$/, '')}/sitemap.xml\n` : '')
|
||||
|
||||
return {
|
||||
name: 'site-configuration',
|
||||
|
|
|
|||