Compare commits

..

No commits in common. "e7743829bea5aa3125b3872ba32abdac487cf3be" and "7f12824c93469b6ab2f18a9ba63f26ebc1422907" have entirely different histories.

44 changed files with 138 additions and 1564 deletions

View file

@ -37,7 +37,6 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`.
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
- Request form (`/request`): files go to a Google Drive folder (a shared drive) and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`); off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_DRIVE_FOLDER` / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.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

View file

@ -1,118 +0,0 @@
# Google Drive and Gmail (the Request form)
The Request form (`/request`) keeps the files people send in a Google
Drive folder, and new requests can be emailed to whoever is listed in
Panel → Site settings → Notices. Both go through one Google **service
account** (`server/src/googleService.js`). Nothing here is needed for
the rest of the site; until it's set up, the form takes no files and no
mail goes out.
| Setting on the `ngu-api` service | What it is |
| --- | --- |
| `GOOGLE_SERVICE_ACCOUNT` | Path to the service account's key file, eg. `/etc/ngu/google-service-account.json` |
| `GOOGLE_DRIVE_FOLDER` | The Drive folder's id (the last part of its URL) |
| `GOOGLE_MAIL_FROM` | The Workspace address notices are sent from, eg. `web@nextgenerationofunity.org` |
Files need the first two; mail needs the first and third.
## 1. The service account
1. In Google Cloud Console (the project that holds the Google sign-in
client is fine), enable the **Google Drive API** and the **Gmail
API**.
2. IAM & Admin → Service accounts → Create. Name it eg. `ngu-site`. It
needs no roles on the project.
3. Open it → Keys → Add key → JSON. Copy the file to the VPS, outside
the app and the repo:
```sh
sudo mkdir -p /etc/ngu
sudo mv ngu-site-*.json /etc/ngu/google-service-account.json
sudo chown <ngu-api user>: /etc/ngu/google-service-account.json
sudo chmod 600 /etc/ngu/google-service-account.json
```
Note the account's email (`ngu-site@<project>.iam.gserviceaccount.com`)
and, from its Details page, its **Client ID** (a long number).
## 2. The Drive folder
A service account has no Drive storage of its own, so the folder must
be in a **shared drive**.
1. In Google Drive, make (or pick) a shared drive, eg. "NGU Website",
and a folder in it, eg. "Requests".
2. Shared drive → Manage members → add the service account's email as
**Content manager**.
3. Open the folder; its id is the end of the address:
`https://drive.google.com/drive/folders/<this part>`.
Files are named `Request 12 - original name.docx`, so the number matches
the one in Forms → Content requests. Deleting a request in the admin
deletes its files from Drive too.
## 3. Gmail (domain-wide delegation)
For the service account to send as a Workspace user:
1. Google Admin console → Security → Access and data control → API
controls → **Manage domain wide delegation** → Add new.
2. Client ID: the service account's Client ID from step 1.
OAuth scopes: `https://www.googleapis.com/auth/gmail.send`
3. `GOOGLE_MAIL_FROM` is the address it sends as. It must be a real
user or group-owned mailbox in the Workspace (not an alias); a
dedicated `web@` account keeps the sent mail out of anyone's inbox.
Then in the admin, Panel → Site settings → Notices → "Email new
requests to": one or more addresses, separated by commas. Each new
content request and data request sends one plain-text email with a link
to the queue; replying goes to the person who sent the request.
## 4. The service and nginx
```sh
sudo systemctl edit ngu-api
```
```ini
[Service]
Environment=GOOGLE_SERVICE_ACCOUNT=/etc/ngu/google-service-account.json
Environment=GOOGLE_DRIVE_FOLDER=<folder id>
Environment=GOOGLE_MAIL_FROM=web@nextgenerationofunity.org
```
nginx caps `/api/` bodies at 64k, so the form needs its own block in
the site's `server` block, beside `/api/admin/import/docx` (`nginx-dev`
has it):
```nginx
location = /api/requests {
proxy_pass http://127.0.0.1:3001;
# the usual proxy_set_header lines
proxy_read_timeout 120s;
client_max_body_size 31m;
}
```
`sudo nginx -t && sudo systemctl reload nginx && sudo systemctl restart ngu-api`.
## Checking it
- Send a request with a small file at `/request`. The journal shows
`feedback #N (content: new blog, 1 files)`, and with mail on,
`feedback #N: notice sent to 1`.
- The file is in the Drive folder, and downloads from Forms → Content
requests.
- `token refused: unauthorized_client` on mail means the delegation
(step 3) is missing or has the wrong Client ID or scope. `404 File not
found` on upload means the folder id is wrong or the service account
isn't a member of the shared drive.
## What the form takes
Up to 3 files of 10 MB each: Word documents (.docx), PDFs, JPEG and PNG,
checked by their contents rather than their names
(`server/src/routes/requests.js`). A Word document on a request can be
turned into an unpublished blog post from the queue ("Make a blog post
from it"), the same conversion as Blog posts → Import from Word
(`docs/importing.md`).

View file

@ -1,6 +1,6 @@
# Importing a Word document as a blog post
Admin → Data → Blog posts → **Import from Word** (editors and up). Pick
Admin → Pages → Blog posts → **Import from Word** (editors and up). Pick
a `.docx`; the server turns it into a new blog post, **unpublished**, and
opens it in the editor with a note of what came over. Check it, add the
authors and a cover, then tick Published.

View file

@ -29,7 +29,7 @@ what a dropdown in the admin editor says.
| ------------------------------------------------------------ | ---------------- | ------------------------------------ |
| 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 → Pages → Front page |
| Blog posts, and the Community page's blog section (headings, pins, feeds) | the database | Admin → Data → Blog posts, and Admin → Pages → Community blog section |
| 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) |
@ -273,7 +273,6 @@ The numbers band's "Number Source" dropdown works the same way:
| 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 → Data → Organizations → a region → Map areas). |
| Feedback form types | `src/data/feedbackTypes.ts` **and** `TYPES` in `server/src/routes/feedback.js` | Keep the ids identical in both; the server stores unknown ids as `general`. Labels and hints are client-only. `DATA_REQUEST` ('privacy') isn't a tile: the Privacy page's form sends it, and the server requires an email for it. |
| Request form types (what `/request` can ask for) | `src/data/requestTypes.ts` **and** `CATEGORIES` in `server/src/routes/requests.js` **and** the CHECK on `feedback.category` (`046_content_requests.sql`) | Ids and allowed actions (new, update) identical in all three; a new id needs a migration. Labels, hints and the name field's question are client-only. A button to the form opened on one type: `request: { type, label }` on a section manifest entry, or `<RequestLink>` (`src/components/RequestLink.tsx`). |
| The site's colours, light and dark | the database over `src/index.css` | Admin → Panel → Site settings → Colours (superadmins): pick a colour, set its light and/or dark value; saving refuses anything that makes text hard to read. The defaults are `THEME_DEFAULTS` in `server/src/themeDefaults.js` (the admin and the contrast check read it) and the same values as CSS in `src/index.css`; the build stops if the two differ. The admin's labels for them are `THEME_LABELS` in `src/lib/adminSchema/siteSettings.ts`. Change a token's value in both modes and every use follows. Use the token utilities (`text-muted`, `bg-surface`, `border-brand/20`) or `var(--color-…)`, not hex. A colour that arrives as data (a page accent, an event's or region's colour) goes through `src/lib/color.ts`: `withAlpha` for tints, `accentText` for text in it, `readableOn` for text on it. |
| The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. |
| A page section's accent colour | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a colour there, not a hex in a page. Each is readable as text on white and the tints. |

View file

@ -149,7 +149,6 @@ export const blocksChild = (ownerKind) => ({
"callout",
"schedule",
"table",
"cards",
],
{ required: true },
),

View file

@ -30,7 +30,6 @@ export const siteSettings = {
text("apple_touch_icon"),
enumeration("indexing", ["on", "off"]),
text("privacy_email"),
text("notify_emails"),
],
children: [

View file

@ -1,166 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
GOOGLE SERVICE ACCOUNT: Drive files and Gmail
The server acting as itself (not a person signing in, that's
googleAuth.js). A service account's key signs a short JWT, which
Google swaps for an access token (RS256 with node:crypto, no
library). Two uses:
Drive files sent with the Request form are kept in one folder,
in a shared drive (a service account has no storage of
its own), and read back for the admin.
Gmail new-request notices, sent as a Workspace user through
domain-wide delegation.
Configured by the service environment:
GOOGLE_SERVICE_ACCOUNT path to the key's .json file (never in
the repo)
GOOGLE_DRIVE_FOLDER the folder's id, from its URL
GOOGLE_MAIL_FROM the Workspace address notices come from
Each part is off until its settings are there: without a folder the
form offers no uploads, and without a sender no mail goes out.
Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */
import { readFileSync } from "node:fs";
import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send";
const DRIVE = "https://www.googleapis.com/drive/v3/files";
const DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
export class GoogleError extends Error {}
let key = null;
function serviceKey() {
const file = process.env.GOOGLE_SERVICE_ACCOUNT;
if (!file) return null;
if (!key) {
const parsed = JSON.parse(readFileSync(file, "utf8"));
if (!parsed.client_email || !parsed.private_key) throw new GoogleError(`${file} is not a service account key.`);
key = parsed;
}
return key;
}
export const driveReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_DRIVE_FOLDER);
export const mailReady = () => Boolean(process.env.GOOGLE_SERVICE_ACCOUNT && process.env.GOOGLE_MAIL_FROM);
/* ── Access tokens, kept until a minute before they run out ──── */
const tokens = new Map();
async function accessToken(scope, subject) {
const cacheKey = `${scope} ${subject ?? ""}`;
const cached = tokens.get(cacheKey);
if (cached && cached.until > Date.now()) return cached.token;
const sa = serviceKey();
if (!sa) throw new GoogleError("GOOGLE_SERVICE_ACCOUNT is not set.");
const now = Math.floor(Date.now() / 1000);
const part = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const unsigned = `${part({ alg: "RS256", typ: "JWT" })}.${part({
iss: sa.client_email,
scope,
aud: sa.token_uri ?? "https://oauth2.googleapis.com/token",
iat: now,
exp: now + 3600,
...(subject ? { sub: subject } : {}),
})}`;
const signature = createSign("RSA-SHA256").update(unsigned).sign(sa.private_key, "base64url");
const res = await fetch(sa.token_uri ?? "https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: `${unsigned}.${signature}`,
}),
signal: AbortSignal.timeout(15_000),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.access_token) {
throw new GoogleError(`token refused: ${data.error_description ?? data.error ?? res.status}`);
}
tokens.set(cacheKey, { token: data.access_token, until: Date.now() + (data.expires_in - 60) * 1000 });
return data.access_token;
}
async function call(url, init, scope, subject) {
const res = await fetch(url, {
...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) {
const detail = await res.json().catch(() => null);
throw new GoogleError(`${res.status} ${detail?.error?.message ?? res.statusText}`);
}
return res;
}
/* ── Drive ───────────────────────────────────────────────────── */
/* One file into the folder. Returns Drive's id for it. */
export async function driveUpload(name, mime, buffer) {
const boundary = `ngu${Date.now().toString(36)}`;
const meta = JSON.stringify({ name, parents: [process.env.GOOGLE_DRIVE_FOLDER] });
const body = Buffer.concat([
Buffer.from(
`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n` +
`--${boundary}\r\nContent-Type: ${mime}\r\n\r\n`,
),
buffer,
Buffer.from(`\r\n--${boundary}--`),
]);
const res = await call(
`${DRIVE_UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`,
{ method: "POST", headers: { "Content-Type": `multipart/related; boundary=${boundary}` }, body },
DRIVE_SCOPE,
);
return (await res.json()).id;
}
export async function driveDownload(id) {
const res = await call(`${DRIVE}/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`, {}, DRIVE_SCOPE);
return Buffer.from(await res.arrayBuffer());
}
export async function driveDelete(id) {
await call(`${DRIVE}/${encodeURIComponent(id)}?supportsAllDrives=true`, { method: "DELETE" }, DRIVE_SCOPE);
}
/* ── Gmail ───────────────────────────────────────────────────── */
// A header value can't be allowed to start a new header.
const oneLine = (value) => String(value ?? "").replace(/[\r\n]+/g, " ").trim();
const encodeWord = (value) => `=?UTF-8?B?${Buffer.from(oneLine(value)).toString("base64")}?=`;
/* Plain text mail from GOOGLE_MAIL_FROM. replyTo lets a reply go
straight to whoever filled in the form. */
export async function sendMail({ to, subject, text, replyTo }) {
const from = process.env.GOOGLE_MAIL_FROM;
const headers = [
`From: ${oneLine(from)}`,
`To: ${to.map(oneLine).join(", ")}`,
...(replyTo ? [`Reply-To: ${oneLine(replyTo)}`] : []),
`Subject: ${encodeWord(subject)}`,
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: base64",
];
const raw = `${headers.join("\r\n")}\r\n\r\n${Buffer.from(text).toString("base64")}`;
await call(
"https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ raw: Buffer.from(raw).toString("base64url") }),
},
GMAIL_SCOPE,
from,
);
}

View file

@ -28,7 +28,6 @@ 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 requests from "./routes/requests.js";
import auth from "./routes/auth.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
@ -171,9 +170,6 @@ app.route("/api", blog);
// Tighter limit on the write path than anything else gets.
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback);
// Requests carry files: fewer again.
app.use("/api/requests", rateLimit({ windowMs: 10 * 60_000, max: 5 }));
app.route("/api/requests", requests);
app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,

View file

@ -1,70 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 045 LINK CARD BLOCKS
--
-- A content block of type 'cards': link cards, one per item, like a
-- link shared in a chat. The item's text is the title, detail the
-- description, url the link and media the picture (the item columns
-- there already are); Fetch preview in the admin fills them.
-- ContentBlocks.tsx draws it.
--
-- Only the type's CHECK changes, so the table is rebuilt as 044 did
-- (legacy_alter_table around the rename, then its index and owner
-- trigger again).
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post')),
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', 'table', 'cards')),
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);
-- ── 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;

View file

@ -1,39 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 046 CONTENT REQUESTS
--
-- The Request form (/request): someone asks for a blog post, an
-- event, or a new or updated chapter, region, partner, team, award
-- or person, and can attach files (a .docx to fill in, photos).
-- Requests are feedback rows of type 'content', so they share the
-- admin's triage (Forms → Content requests): status, notes, delete.
--
-- category what it's about (REQUEST_TYPES in
-- src/data/requestTypes.ts)
-- request_action 'new' or 'update'
-- subject the title or name, or which record to update
--
-- The files themselves live in Google Drive (googleService.js);
-- feedback_files keeps Drive's id for each, and goes with its row.
--
-- site_settings.notify_emails: who gets an email for each new
-- content or data request (Panel → Site settings), comma separated.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE feedback ADD COLUMN category TEXT
CHECK (category IN ('blog', 'event', 'chapter', 'region', 'partner', 'team', 'award', 'person'));
ALTER TABLE feedback ADD COLUMN request_action TEXT
CHECK (request_action IN ('new', 'update'));
ALTER TABLE feedback ADD COLUMN subject TEXT;
CREATE TABLE feedback_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
feedback_id INTEGER NOT NULL REFERENCES feedback (id) ON DELETE CASCADE,
drive_id TEXT NOT NULL,
name TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL
) STRICT;
CREATE INDEX feedback_files_owner_idx ON feedback_files (feedback_id);
ALTER TABLE site_settings ADD COLUMN notify_emails TEXT;

View file

@ -1,40 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
NEW-REQUEST NOTICES
An email to the people in Panel → Site settings → "Email new
requests to" when a content request (/request) or a data request
(the Privacy page) comes in. Sent after the row is saved and never
waited on: a mail problem is logged, the submission stands.
Off until Gmail is set up (googleService.js) and someone is listed.
═══════════════════════════════════════════════════════════════ */
import { mailReady, sendMail } from "./googleService.js";
import { siteFor } from "./pageMeta.js";
const EMAIL = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
export function recipients(db) {
const row = db.prepare(`SELECT notify_emails FROM site_settings WHERE id = 'site'`).get();
return String(row?.notify_emails ?? "")
.split(/[\s,;]+/)
.filter((address) => EMAIL.test(address));
}
/* queue: the admin path of the queue it landed in, eg. /admin/requests */
export function notifyNew(db, { id, subject, lines, replyTo, queue }) {
if (!mailReady()) return;
const to = recipients(db);
if (to.length === 0) return;
let origin = "";
try {
origin = (siteFor(db).url ?? "").replace(/\/$/, "");
} catch {
// No site.json: the notice goes without a link.
}
const text = [...lines, "", origin ? `Open it: ${origin}${queue}` : `In the admin: Forms, ${queue}`, ""].join("\n");
sendMail({ to, subject, text, replyTo: EMAIL.test(replyTo ?? "") ? replyTo : undefined })
.then(() => console.log(`feedback #${id}: notice sent to ${to.length}`))
.catch((err) => console.warn(`feedback #${id}: notice failed: ${err.message}`));
}

View file

@ -43,7 +43,6 @@ import { fileURLToPath } from "node:url";
import { loadBlocks, paragraphs } from "./shape.js";
import { themeCss } from "./theme.js";
import { driveReady } from "./googleService.js";
const here = path.dirname(fileURLToPath(import.meta.url));
@ -113,13 +112,7 @@ export function siteFor(db) {
}
/* What the browser app reads for headings and titles. */
// requestFiles: whether the Request form can take files (Drive set up).
const forBrowser = (site) => ({
title: site.title,
pages: site.pages,
privacyEmail: site.privacyEmail,
requestFiles: driveReady(),
});
const forBrowser = (site) => ({ title: site.title, pages: site.pages, privacyEmail: site.privacyEmail });
/* robots.txt for this database's setting, as the build writes it. */
export function robotsTxt(site) {

View file

@ -11,9 +11,6 @@
import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload } from "../googleService.js";
import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js";
const admin = new Hono();
@ -21,39 +18,13 @@ admin.use("*", requireAuth);
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
// Website feedback, data requests and content requests share the
// table but are three queues in the admin (Forms).
const KIND_WHERE = {
feedback: "feedback_type NOT IN ('privacy', 'content')",
privacy: "feedback_type = 'privacy'",
content: "feedback_type = 'content'",
};
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject`;
/* Each row with its files (content requests), in one query. */
function withFiles(db, rows) {
if (rows.length === 0) return rows;
const files = db
.prepare(
`SELECT id, feedback_id, name, mime, size FROM feedback_files
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
)
.all(...rows.map((r) => r.id));
return rows.map((row) => ({
...row,
files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f),
}));
}
const MAX_LIMIT = 200;
const NOTE_LIMIT = 2000;
/* ── GET /api/admin/feedback ─────────────────────────────────────
?status=new one of STATUSES, or omitted for all
?kind=feedback website feedback (every type but the two below)
?kind=feedback website feedback (every type but 'privacy')
?kind=privacy data requests from the Privacy page
?kind=content content requests from /request, with files
?type=broken feedback_type
?q=retreat substring of the message
?before=41 cursor: rows with a lower id than this
@ -67,7 +38,10 @@ admin.get("/feedback", (c) => {
const where = [];
const params = [];
const kindWhere = KIND_WHERE[kind] ?? null;
// Data requests and website feedback share the table but are two
// queues in the admin (Forms → Website feedback, Data requests).
const kindWhere =
kind === "privacy" ? "feedback_type = 'privacy'" : kind === "feedback" ? "feedback_type <> 'privacy'" : null;
if (kindWhere) where.push(kindWhere);
if (STATUSES.includes(status)) {
@ -79,8 +53,8 @@ admin.get("/feedback", (c) => {
params.push(type.slice(0, 40));
}
if (q) {
where.push("(message LIKE ? OR subject LIKE ?)");
params.push(`%${q.slice(0, 100)}%`, `%${q.slice(0, 100)}%`);
where.push("message LIKE ?");
params.push(`%${q.slice(0, 100)}%`);
}
if (before && Number.isInteger(Number(before))) {
where.push("id < ?");
@ -91,7 +65,8 @@ admin.get("/feedback", (c) => {
const rows = db
.prepare(
`SELECT ${COLUMNS}
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
FROM feedback
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY id DESC
@ -100,7 +75,7 @@ admin.get("/feedback", (c) => {
.all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take;
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows);
const page = hasMore ? rows.slice(0, take) : rows;
// Status counts cover this queue (kind) but ignore the other
// filters: the tabs show what's waiting, not what's left after a
@ -113,8 +88,7 @@ admin.get("/feedback", (c) => {
}
const newByKind = db
.prepare(
`SELECT SUM(${KIND_WHERE.feedback}) AS feedback, SUM(${KIND_WHERE.privacy}) AS privacy,
SUM(${KIND_WHERE.content}) AS content
`SELECT SUM(feedback_type <> 'privacy') AS feedback, SUM(feedback_type = 'privacy') AS privacy
FROM feedback WHERE status = 'new'`,
)
.get();
@ -123,11 +97,7 @@ admin.get("/feedback", (c) => {
{
feedback: page,
counts,
newByKind: {
feedback: newByKind?.feedback ?? 0,
privacy: newByKind?.privacy ?? 0,
content: newByKind?.content ?? 0,
},
newByKind: { feedback: newByKind?.feedback ?? 0, privacy: newByKind?.privacy ?? 0 },
nextCursor: hasMore ? page[page.length - 1].id : null,
},
200,
@ -185,7 +155,13 @@ function db_update(db, id, sets, params) {
if (changed.changes === 0) return null;
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0];
return db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
FROM feedback WHERE id = ?`,
)
.get(id);
}
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -194,78 +170,20 @@ function db_update(db, id, sets, params) {
the content itself shouldn't stay on disk.
───────────────────────────────────────────────────────────── */
admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
admin.delete("/feedback/:id", requireRole("admin"), (c) => {
const id = Number(c.req.param("id"));
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
const db = c.get("db");
const files = db.prepare(`SELECT drive_id FROM feedback_files WHERE feedback_id = ?`).all(id);
const result = db.prepare("DELETE FROM feedback WHERE id = ?").run(id);
if (result.changes === 0) return c.json({ error: "No such feedback." }, 404);
const result = c
.get("db")
.prepare("DELETE FROM feedback WHERE id = ?")
.run(id);
// The row is gone either way; a file Drive won't delete is logged
// for someone to remove from the folder by hand.
for (const { drive_id } of files) {
try {
await driveDelete(drive_id);
} catch (err) {
console.warn(`feedback #${id}: Drive file ${drive_id} not deleted: ${err.message}`);
}
}
if (result.changes === 0) return c.json({ error: "No such feedback." }, 404);
console.log(`feedback #${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
/* ── A content request's files ───────────────────────────────────
GET /feedback/:id/files/:file download, from Drive
POST /feedback/:id/files/:file/blog-post a .docx as a new
unpublished blog post (import.js), editors and up
───────────────────────────────────────────────────────────── */
function fileOf(c) {
return c
.get("db")
.prepare(`SELECT id, drive_id, name, mime FROM feedback_files WHERE id = ? AND feedback_id = ?`)
.get(Number(c.req.param("file")), Number(c.req.param("id")));
}
async function fromDrive(file) {
try {
return await driveDownload(file.drive_id);
} catch (err) {
console.warn(`feedback file ${file.id}: Drive download failed: ${err.message}`);
throw new HttpError(502, "Google Drive didn't send that file. Try again, or find it in the Drive folder.");
}
}
admin.get("/feedback/:id/files/:file", async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
try {
return c.body(await fromDrive(file), 200, {
...NO_STORE,
"Content-Type": file.mime,
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`,
"X-Content-Type-Options": "nosniff",
});
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message }, err.status);
throw err;
}
});
admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
if (!/\.docx$/i.test(file.name)) return c.json({ error: "Only a Word document (.docx) can become a post." }, 400);
try {
return c.json(importDocx(c.get("db"), await fromDrive(file), file.name, c.get("user").email), 201, NO_STORE);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;
}
});
export default admin;

View file

@ -16,7 +16,6 @@
import { Hono } from "hono";
import { clientIp, hashIp } from "../auth.js";
import { notifyNew } from "../notify.js";
const feedback = new Hono();
@ -37,14 +36,14 @@ const TYPES = ["broken", "confusing", "outdated", "request", "praise", "other",
/* ── Input cleaning ──────────────────────────────────────────── */
export function clean(value, max) {
function clean(value, max) {
if (typeof value !== "string") return "";
return value.trim().slice(0, max);
}
// Deliberately permissive. Rejecting odd-but-valid addresses loses
// real submissions, and the field is optional anyway.
export function looksLikeEmail(value) {
function looksLikeEmail(value) {
return value === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
@ -109,15 +108,6 @@ feedback.post("/", async (c) => {
// created_at and status come from column defaults.
console.log(`feedback #${result.lastInsertRowid} (${feedbackType})`);
if (feedbackType === "privacy") {
notifyNew(db, {
id: result.lastInsertRowid,
subject: "Data request from the Privacy page",
lines: [`From: ${name ? `${name} <${email}>` : email}`, "", message],
replyTo: email,
queue: "/admin/data-requests",
});
}
return c.body(null, 204);
});

View file

@ -46,52 +46,6 @@ function freeId(db, base) {
return id;
}
/* A Word document as a new unpublished blog post, through the CRUD
engine. Returns { id, summary }; an unreadable document is a 400
HttpError. Also used by Forms → Content requests, on a file someone
sent with the Request form. */
export function importDocx(db, buffer, fileName, byEmail) {
let doc;
try {
doc = readDocx(buffer);
} catch (err) {
throw new HttpError(400, err instanceof DocxError ? err.message : "That document couldn't be read. Save it again as .docx and retry.");
}
if (doc.blocks.length === 0) throw new HttpError(400, "That document has no text to import.");
const title = doc.title || String(fileName ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const row = createRow(db, ENTITIES.blog_posts, {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
});
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${byEmail}`);
return {
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
};
}
imports.post(
"/import/docx",
requireRole("editor"),
@ -110,9 +64,53 @@ imports.post(
const file = body.file;
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
let doc;
try {
const result = importDocx(db, Buffer.from(await file.arrayBuffer()), file.name, c.get("user").email);
return c.json(result, 201, NO_STORE);
doc = readDocx(Buffer.from(await file.arrayBuffer()));
} catch (err) {
if (err instanceof DocxError) return c.json({ error: err.message }, 400);
return c.json({ error: "That document couldn't be read. Save it again as .docx and retry." }, 400);
}
if (doc.blocks.length === 0) return c.json({ error: "That document has no text to import." }, 400);
const title = doc.title || String(file.name ?? "").replace(/\.docx$/i, "") || "Imported post";
const headings = doc.blocks.filter((b) => b.type === "heading" || b.type === "subheading").length;
const payload = {
id: freeId(db, slug(title)),
title: title.slice(0, 200),
published_on: doc.date,
is_published: 0,
is_listed: 1,
// A long document with sections reads better with its contents.
show_contents: headings >= 3 ? 1 : 0,
content_blocks: doc.blocks.map((block) => ({
slot: "body",
type: block.type,
text: block.text ?? null,
items: block.items ?? [],
})),
};
try {
const row = createRow(db, ENTITIES.blog_posts, payload);
const count = (type) => doc.blocks.filter((b) => b.type === type).length;
console.log(`blog_posts ${row.id} imported from Word by ${c.get("user").email}`);
return c.json(
{
id: row.id,
summary: {
blocks: doc.blocks.length,
headings,
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
skipped: doc.skipped,
},
},
201,
NO_STORE,
);
} catch (err) {
if (err instanceof HttpError) return c.json({ error: err.message, fields: err.fields }, err.status);
throw err;

View file

@ -1,165 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST ROUTE: POST /api/requests
The Request form (/request): a blog post, an event, or a new or
updated chapter, region, partner, team, award or person, with up
to MAX_FILES attachments. Stored as a feedback row of type
'content' (046_content_requests.sql), files in Google Drive.
The same defences as the feedback route (honeypot, length caps,
a rate limit where it's mounted), plus: files are judged by their
first bytes, not the name or type the browser claims, and nothing
goes to Drive until everything else has passed.
nginx caps /api/ bodies at 64k; this path needs its own block
(docs/google-drive-and-mail.md).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { clientIp, hashIp } from "../auth.js";
import { clean, looksLikeEmail } from "./feedback.js";
import { driveDelete, driveReady, driveUpload } from "../googleService.js";
import { notifyNew } from "../notify.js";
const requests = new Hono();
// Must match REQUEST_TYPES in src/data/requestTypes.ts and the CHECK
// in 046_content_requests.sql. The actions each category allows.
const CATEGORIES = {
blog: ["new"],
event: ["new", "update"],
chapter: ["new", "update"],
region: ["update"],
partner: ["new", "update"],
team: ["new", "update"],
award: ["new", "update"],
person: ["new", "update"],
};
const LIMITS = { name: 120, email: 254, subject: 200, message: 5000 };
const MIN_MESSAGE = 10;
export const MAX_FILES = 3;
export const MAX_FILE_BYTES = 10 * 1024 * 1024;
/* What a file is, from its first bytes. A zip is only taken as a
Word document when it's named like one. */
const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
function kindOf(bytes, name) {
const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
if (starts(0x25, 0x50, 0x44, 0x46, 0x2d)) return "application/pdf";
if (starts(0xff, 0xd8, 0xff)) return "image/jpeg";
if (starts(0x89, 0x50, 0x4e, 0x47)) return "image/png";
if (starts(0x50, 0x4b, 0x03, 0x04) && /\.docx$/i.test(name)) return DOCX;
return null;
}
// A file name as Drive and a download header will see it.
const safeName = (name) =>
String(name ?? "file")
.replace(/[\u0000-\u001f"\\/]+/g, " ")
.trim()
.slice(0, 150) || "file";
requests.post(
"/",
bodyLimit({
maxSize: MAX_FILES * MAX_FILE_BYTES + 64 * 1024,
onError: (c) => c.json({ error: `Files can be ${MAX_FILE_BYTES / 1024 / 1024} MB each at most.` }, 413),
}),
async (c) => {
let body;
try {
body = await c.req.parseBody({ all: true });
} catch {
return c.json({ error: "Expected a form." }, 400);
}
const field = (name, max) => clean(Array.isArray(body[name]) ? body[name][0] : body[name], max);
if (field("website", 50) !== "") return c.body(null, 204); // honeypot
const category = field("category", 20);
const action = field("action", 10);
const subject = field("subject", LIMITS.subject);
const message = field("message", LIMITS.message);
const name = field("name", LIMITS.name);
const email = field("email", LIMITS.email);
const files = [body.files ?? []].flat().filter((f) => f instanceof File && f.size > 0);
const errors = {};
if (!CATEGORIES[category]) errors.category = "Choose what this is about.";
else if (!CATEGORIES[category].includes(action)) errors.action = "Choose new or update.";
if (!subject) errors.subject = "Give it a name.";
if (message.length < MIN_MESSAGE) errors.message = "Please write a little more.";
if (!email) errors.email = "We need an email address to follow up.";
else if (!looksLikeEmail(email)) errors.email = "That email doesn't look right.";
const uploads = [];
if (files.length > 0 && !driveReady()) errors.files = "File uploads aren't set up yet. Describe it in the message instead.";
else if (files.length > MAX_FILES) errors.files = `${MAX_FILES} files at most.`;
else {
for (const file of files) {
if (file.size > MAX_FILE_BYTES) {
errors.files = `${file.name} is over ${MAX_FILE_BYTES / 1024 / 1024} MB.`;
break;
}
const buffer = Buffer.from(await file.arrayBuffer());
const mime = kindOf(buffer, file.name);
if (!mime) {
errors.files = `${file.name} isn't a Word document (.docx), PDF, JPEG or PNG.`;
break;
}
uploads.push({ name: safeName(file.name), mime, buffer });
}
}
if (Object.keys(errors).length > 0) return c.json({ error: "Validation failed", fields: errors }, 422);
const db = c.get("db");
const id = Number(
db
.prepare(
`INSERT INTO feedback
(feedback_type, category, request_action, subject, message, name, email, user_agent, ip_hash)
VALUES ('content', ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(category, action, subject, message, name || null, email, clean(c.req.header("user-agent"), 500) || null, hashIp(clientIp(c)))
.lastInsertRowid,
);
// The row first, so each file in Drive is named for it; if Drive
// fails, the row and whatever did upload go again.
const stored = [];
try {
for (const file of uploads) {
stored.push({ ...file, driveId: await driveUpload(`Request ${id} - ${file.name}`, file.mime, file.buffer) });
}
} catch (err) {
console.warn(`feedback #${id}: Drive upload failed: ${err.message}`);
await Promise.allSettled(stored.map((f) => driveDelete(f.driveId)));
db.prepare(`DELETE FROM feedback WHERE id = ?`).run(id);
return c.json({ error: "Your files couldn't be stored just now. Try again in a moment." }, 502);
}
const addFile = db.prepare(`INSERT INTO feedback_files (feedback_id, drive_id, name, mime, size) VALUES (?, ?, ?, ?, ?)`);
for (const f of stored) addFile.run(id, f.driveId, f.name, f.mime, f.buffer.length);
console.log(`feedback #${id} (content: ${action} ${category}, ${stored.length} files)`);
notifyNew(db, {
id,
subject: `Request: ${action} ${category}: ${subject}`,
lines: [
`${action === "new" ? "New" : "Update"} ${category}: ${subject}`,
`From: ${name ? `${name} <${email}>` : email}`,
...(stored.length ? [`Files: ${stored.map((f) => f.name).join(", ")}`] : []),
"",
message,
],
replyTo: email,
queue: "/admin/requests",
});
return c.body(null, 204);
},
);
export default requests;

View file

@ -132,18 +132,6 @@ const ALL_BLOCKS = [
["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" }],
["subheading", { text: "Table" }],
["table", { text: [
"Platform | Monthly cost | Best for | Notes",
"[Zeffy](https://www.zeffy.com) | Free | Fee-free giving | **0%** to the church",
"Breeze | $72 | Small churches | Flat price, all features",
"A cell with a bar \\| in it | Blank cells follow | |",
].join("\n") }],
["subheading", { text: "Link cards" }],
["cards", {}, [
{ text: "A card with a picture", detail: "Its description, up to three lines, under the title. The whole card is the link.", url: "/retreats", media: IMAGE },
{ text: "An outside link, text only", detail: "The card shows the site it goes to above the title.", url: "https://example.org" },
]],
];
/* A record page's body: a handful of types, so it reads like a

View file

@ -38,10 +38,6 @@
"title": "Feedback",
"description": "Tell us what's working, what isn't, and what you'd like to see next."
},
"/request": {
"title": "Request",
"description": "Ask for a blog post, an event, or a new or updated chapter, region, partner, team, award or person on the site."
},
"/qr": {
"title": "QR Codes",
"description": "Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colours."

View file

@ -55,7 +55,6 @@ const Leadership = lazyPage(() => import("./pages/Leadership.tsx"))
const Resources = lazyPage(() => import("./pages/Resources.tsx"))
const History = lazyPage(() => import("./pages/History.tsx"))
const Feedback = lazyPage(() => import("./pages/Feedback.tsx"))
const Request = lazyPage(() => import("./pages/Request.tsx"))
const Giving = lazyPage(() => import("./pages/Giving.tsx"))
const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
@ -105,7 +104,6 @@ export default function App() {
<Route path="resources" element={<Resources />} />
<Route path="history" element={<History />} />
<Route path="feedback" element={<Feedback />} />
<Route path="request" element={<Request />} />
<Route path="qr" element={<QrCodes />} />
<Route path="give" element={<Giving />} />
<Route path="privacy" element={<Privacy />} />
@ -131,7 +129,6 @@ export default function App() {
</Route>
<Route path="feedback" element={<AdminFeedback />} />
<Route path="data-requests" element={<AdminFeedback kind="privacy" />} />
<Route path="requests" element={<AdminFeedback kind="content" />} />
<Route path="media" element={<AdminMedia />} />
<Route element={<RequireRole role="admin" />}>
<Route path="clips" element={<AdminClips />} />

View file

@ -23,9 +23,6 @@
text, detail, url, location, person, and
a fold-out of description, media, map);
text is an optional intro. ScheduleBlock
table text: a row per line, cells split by |
cards items as link cards: text the title,
detail, url, media the picture
divider nothing
"Formatted" is InlineText.tsx: **bold**, *italic*, [text](url),
@ -37,14 +34,12 @@
═══════════════════════════════════════════════════════════════ */
import { mediaUrl } from '../lib/media.ts'
import type { ContentBlock, ContentBlockItem } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs, isExternalUrl } from './InlineText.tsx'
import type { ContentBlock } from '../lib/useContent.ts'
import { Anchor, Inline, Paragraphs } from './InlineText.tsx'
import VideoPlayer from './VideoPlayer.tsx'
import ScheduleBlock from './ScheduleBlock.tsx'
import { accentText, BRAND } from '../lib/color.ts'
import { headingAnchors } from '../lib/contents.ts'
import { SITE_NAME } from '../lib/site.ts'
import { useSmallImage } from '../lib/useSmallImage.ts'
const BODY = 'var(--color-muted)'
@ -71,37 +66,6 @@ export default function ContentBlocks({
)
}
/* One link card: the whole card is the link. The site's name above
the title says where it goes (the host for an outside link). */
function LinkCard({ item }: { item: ContentBlockItem }) {
const url = item.url ?? ''
const img = useSmallImage(mediaUrl(item.media))
const where = isExternalUrl(url)
? (() => {
try {
return new URL(url).hostname.replace(/^www\./, '')
} catch {
return url
}
})()
: SITE_NAME
return (
<Anchor
href={url}
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-brand/15 bg-surface shadow-sm transition-shadow hover:shadow-lg"
>
{!img.failed && (
<img src={img.src} alt="" loading="lazy" onError={img.onError} className="aspect-video w-full object-cover" />
)}
<span className="flex flex-1 flex-col gap-1 p-5">
<span className="text-xs font-semibold text-muted">{where}</span>
<span className="font-display text-lg font-bold leading-snug text-ink group-hover:text-link">{item.text}</span>
{item.detail && <span className="line-clamp-3 text-sm text-body">{item.detail}</span>}
</span>
</Anchor>
)
}
/* A table block's text as rows of cells: one row per line, cells
split by "|" (a literal bar is "\|"), blank lines skipped. A
leading and trailing bar, as in Markdown, is allowed. */
@ -218,20 +182,6 @@ function Block({ block, accent, anchor }: { block: ContentBlock; accent: string;
</figure>
)
case 'cards': {
const cards = (block.items ?? []).filter((item) => item.url && item.text)
if (cards.length === 0) return null
return (
<ul className={cards.length === 1 ? 'max-w-xl' : 'grid gap-4 sm:grid-cols-2'}>
{cards.map((item, i) => (
<li key={i}>
<LinkCard item={item} />
</li>
))}
</ul>
)
}
case 'table': {
const rows = tableRows(text)
if (rows.length === 0) return null

View file

@ -21,7 +21,6 @@ type TouchLink = { label: string } & (
const Get_In_Touch: TouchLink[] = [
{ label: "Feedback", to: "/feedback"},
{ label: "Request", to: "/request" },
{ label: "Contact Us", to: "/leadership#contact" },
];

View file

@ -175,7 +175,7 @@ export default function Layout() {
{/* ── NAV ─────────────────────────────────────────────── */}
<header
ref={headerRef}
className="fixed top-0 left-0 right-0 z-50 backdrop-blur-md print:hidden"
className="fixed top-0 left-0 right-0 z-50 backdrop-blur-md"
inert={mobileMenuOpen}
>
@ -273,7 +273,7 @@ export default function Layout() {
</header>
{/* Keeps page content clear of the fixed header */}
<div aria-hidden className="print:hidden" style={{ height: headerHeight }} />
<div aria-hidden style={{ height: headerHeight }} />
{/* Page content */}
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
@ -283,7 +283,7 @@ export default function Layout() {
</main>
{/*Site Footer applied to every page*/}
<div inert={mobileMenuOpen} className="print:hidden">
<div inert={mobileMenuOpen}>
<Footer />
<PrivacyNotice />
</div>

View file

@ -74,7 +74,7 @@ export default function PostContents({ entries }: { entries: ContentsEntry[] })
const lit = useLit(entries)
return (
<>
<details className="rounded-2xl border border-brand/20 bg-tint-soft p-4 lg:hidden print:hidden">
<details className="rounded-2xl border border-brand/20 bg-tint-soft p-4 lg:hidden">
<summary className="cursor-pointer font-semibold text-ink">On this page</summary>
<div className="mt-3">
<List entries={entries} lit={lit} />
@ -82,7 +82,7 @@ export default function PostContents({ entries }: { entries: ContentsEntry[] })
</details>
<nav
aria-label="On this page"
className="sticky hidden self-start lg:block print:hidden"
className="sticky hidden self-start lg:block"
style={{ top: 'calc(var(--header-h, 5rem) + 1.5rem)' }}
>
<p className="mb-2 px-3 text-sm font-semibold text-ink">On this page</p>

View file

@ -1,18 +0,0 @@
import { Link } from "react-router-dom";
import { PaperPlaneTilt } from "@phosphor-icons/react";
import { requestLink } from "../data/requestTypes.ts";
/* A button to the Request form, opened on one kind of request
(REQUEST_TYPES). Section manifests place it with `request`. */
export default function RequestLink({ type, label, className = "" }: { type: string; label: string; className?: string }) {
return (
<Link
to={requestLink(type)}
className={`inline-flex items-center gap-2 rounded-full border border-brand/40 px-4 py-2 text-sm font-semibold text-link transition-colors hover:bg-tint print:hidden ${className}`}
>
<PaperPlaneTilt aria-hidden="true" weight="bold" className="h-4 w-4" />
{label}
</Link>
);
}

View file

@ -438,7 +438,6 @@ export function LinkPreviewInput({
locked,
className,
showButton,
fills = { title: "title", blurb: "blurb", image: "image" },
onChange,
onPatch,
}: {
@ -450,9 +449,6 @@ export function LinkPreviewInput({
showButton: boolean;
onChange: (value: string) => void;
onPatch?: (patch: Record<string, any>) => void;
/** Which of the row's fields the preview fills (a list item's are
* text, detail and media). */
fills?: { title: string; blurb: string; image: string };
}) {
const { user } = useAuth();
const [busy, setBusy] = useState(false);
@ -465,9 +461,9 @@ export function LinkPreviewInput({
try {
const { preview } = await post("/admin/link-preview", { url: value });
const patch: Record<string, any> = {};
if (!row[fills.title] && preview.title) patch[fills.title] = preview.title;
if (!row[fills.blurb] && preview.description) patch[fills.blurb] = preview.description;
if (!row[fills.image] && preview.image) patch[fills.image] = preview.image.url;
if (!row.title && preview.title) patch.title = preview.title;
if (!row.blurb && preview.description) patch.blurb = preview.description;
if (!row.image && preview.image) patch.image = preview.image.url;
onPatch(patch);
const filled = Object.keys(patch).length;

View file

@ -160,13 +160,9 @@ export function fieldShown(field, row, parent?) {
the engine's deliberate clear, so it saves as NULL. */
function withHiddenCleared(spec, row, parent?) {
let next = row;
// Two fields can share a path, each shown for a different kind of
// row (a card's Description and a list item's Detail are both
// `detail`); a value is only hidden when none of them is showing.
const shownPaths = new Set(spec.fields.filter((f) => fieldShown(f, row, parent)).map((f) => f.path));
for (const field of spec.fields) {
const value = next[field.path];
if (!shownPaths.has(field.path) && value != null && value !== "") {
if (!fieldShown(field, next, parent) && value != null && value !== "") {
next = { ...next, [field.path]: "" };
}
}
@ -307,7 +303,6 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
locked={locked}
className={locked ? inputLocked : common.className}
showButton={!field.previewWhen || fieldShown({ when: field.previewWhen }, row)}
fills={field.previewFills}
onChange={onChange}
onPatch={onPatch}
/>

View file

@ -1,37 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST TYPES
What the Request form (/request) can ask for, and whether each can
be new, an update, or both. The ids and actions must match
CATEGORIES in server/src/routes/requests.js (and the CHECK in
046_content_requests.sql); keep them in step.
A link can open the form on one: requestLink("chapter") is
/request?type=chapter. People, teams and awards have no buttons on
the site, but are here to pick.
═══════════════════════════════════════════════════════════════ */
export type RequestAction = "new" | "update";
export const REQUEST_TYPES: {
id: string;
label: string;
hint: string;
actions: RequestAction[];
// What the name field asks, for a new one and for an update.
subject: string;
}[] = [
{ id: "blog", label: "Blog post", hint: "A story or article for the community blog", actions: ["new"], subject: "Its title" },
{ id: "event", label: "Event", hint: "A retreat, gathering or calendar event", actions: ["new", "update"], subject: "The event's name" },
{ id: "chapter", label: "Chapter", hint: "A local NGU chapter", actions: ["new", "update"], subject: "The chapter's name" },
{ id: "region", label: "Region", hint: "Details for a Unity region", actions: ["update"], subject: "Which region" },
{ id: "partner", label: "Partner", hint: "A partner organization", actions: ["new", "update"], subject: "The organization's name" },
{ id: "team", label: "Team", hint: "A team or committee", actions: ["new", "update"], subject: "The team's name" },
{ id: "award", label: "Award", hint: "An award and who received it", actions: ["new", "update"], subject: "The award's name" },
{ id: "person", label: "Person", hint: "Someone's profile", actions: ["new", "update"], subject: "Their name" },
];
export const requestLink = (type: string) => `/request?type=${type}`;
const BY_ID = new Map(REQUEST_TYPES.map((t) => [t.id, t.label]));
export const requestTypeLabel = (id: string) => BY_ID.get(id) ?? id;

View file

@ -149,37 +149,6 @@ h1, h2, h3, h4, h5, h6 {
}
}
/* Printing (a blog post's Download PDF, or any page): the light
palette whatever the screen shows, since paper is white and dark
mode's pale text would barely print; and backgrounds kept, so the
tinted panels and table rows come out as on screen. */
@media print {
:root,
:root[data-theme="dark"] {
--color-ink: #073d4a;
--color-body: #26454c;
--color-muted: #4a6b72;
--color-link: #0f7183;
--color-brand: #138ba0;
--color-surface: #ffffff;
--color-tint: #eef9fb;
--color-tint-soft: #f6fbfc;
--color-danger: #b3261e;
--color-danger-tint: #fdf3f2;
--accent-text-mix: 100%;
color-scheme: light;
print-color-adjust: exact;
}
.logo-plate {
background: none !important;
padding: 0 !important;
}
}
@page {
margin: 1.5cm;
}
/* Church Center's giving modal (Giving.tsx) is a transparent iframe
over the whole page, drawn for light pages. On a dark page the
browser sees the iframe's scheme differ from ours and paints its

View file

@ -279,15 +279,11 @@ export const BLOCK_TYPES = [
["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."],
["table", "Table", "A grid of text, eg. a comparison chart: one row per line, cells split by |, the first row the header."],
["cards", "Link cards", "Cards with a picture, title and description, each a link, like a link shared in a chat. Paste a link and press Fetch preview."],
["divider", "Divider", "A thin line between parts."],
];
/* An item field that only a schedule's entries have. */
export const SCHEDULE_ENTRY = { scope: "parent", path: "type", value: "schedule" };
/* Item fields for a link card, and for every other kind of item. */
export const CARD_ITEM = { scope: "parent", path: "type", value: "cards" };
export const NOT_CARD_ITEM = { scope: "parent", path: "type", value: ["list", "links", "schedule"] };
export const blockTypeLabel = (type) => BLOCK_TYPES.find(([value]) => value === type)?.[1] ?? type;
@ -388,7 +384,7 @@ export const blocksChild = {
key: "items",
label: "Items",
addLabel: "Add item",
when: { path: "type", value: ["list", "links", "schedule", "cards"] },
when: { path: "type", value: ["list", "links", "schedule"] },
title: (row) => [row.day, row.time, row.text].filter(Boolean).join(" · ") || "New item",
blank: { text: "" },
fields: [
@ -399,17 +395,7 @@ export const blocksChild = {
when: SCHEDULE_ENTRY,
},
{ path: "time", label: "Time", help: "eg. 7:00pm, or 9:00 to 10:30am", when: SCHEDULE_ENTRY },
// A card: the link first, so Fetch preview can fill the rest.
{
path: "url",
label: "Link",
widget: "linkPreview",
previewFills: { title: "text", blurb: "detail", image: "media" },
full: true,
help: "A page on this site (eg. /retreats) or anywhere else. Fetch preview fills the title, description and picture.",
when: CARD_ITEM,
},
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title. Cards: the card's title" },
{ path: "text", label: "Text", required: true, help: "Schedules: the entry's title" },
{
path: "location",
label: "Location",
@ -425,18 +411,8 @@ export const blocksChild = {
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", when: NOT_CARD_ITEM },
{ path: "detail", label: "Description", widget: "textarea", full: true, when: CARD_ITEM },
{ path: "url", label: "URL", help: "Blank for plain text. Link buttons need one.", when: NOT_CARD_ITEM },
{
path: "media",
label: "Picture",
widget: "image",
resolve: mediaUrl,
full: true,
help: "Optional. Default: none, the card is text only.",
when: CARD_ITEM,
},
{ 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",

View file

@ -122,16 +122,6 @@ export const siteSettings = {
},
],
},
{
legend: "Notices",
fields: [
{
path: "notify_emails",
label: "Email new requests to",
help: "Who gets an email for each new content request (the Request form) and data request (the Privacy page), separated by commas, eg. web@nextgenerationofunity.org, board@nextgenerationofunity.org. Needs Gmail set up on the server (docs/google-drive-and-mail.md). Default: none, check Forms instead.",
},
],
},
],
children: [

View file

@ -1,7 +1,5 @@
import { useState } from "react";
import RequestLink from "../components/RequestLink.tsx";
/* ═══════════════════════════════════════════════════════════════
SECTION MANIFEST
@ -23,10 +21,6 @@ import RequestLink from "../components/RequestLink.tsx";
default: "carousel",
Toggle: EventCardsToggle,
},
request: { // optional button
type: "chapter", // to the Request form
label: "Add or update a chapter",
},
}
Sections fetch their own data. The page never does, which is why
@ -56,25 +50,20 @@ export function useSectionManifest(manifest) {
const setView = (id, value) => setViews(prev => ({ ...prev, [id]: value }));
return manifest.map(entry => {
const { Component, props, views: spec, request, ...heading } = entry;
const { Component, props, views: spec, ...heading } = entry;
const view = views[entry.id];
const Toggle = spec?.Toggle;
return {
...heading,
actions: Toggle || request ? (
<div className="flex flex-wrap items-center gap-3">
{request && <RequestLink type={request.type} label={request.label} />}
{Toggle && (
actions: Toggle ? (
<Toggle
view={view}
setView={value => setView(entry.id, value)}
accent={entry.accent}
options={spec.options}
/>
)}
</div>
) : undefined,
content: (

View file

@ -24,7 +24,7 @@ import siteConfiguration from '../../site.json'
type PageText = { title: string; description: string }
type SiteText = { title?: string; pages?: Record<string, PageText>; privacyEmail?: string; requestFiles?: boolean }
type SiteText = { title?: string; pages?: Record<string, PageText>; privacyEmail?: string }
/* What the server wrote into the page, if it did. */
const fromServer: SiteText =
@ -38,11 +38,6 @@ export const SITE_ORIGIN: string = siteConfiguration.url
* settings, else site.json). Blank: the Privacy page's form only. */
export const PRIVACY_EMAIL: string = fromServer.privacyEmail ?? siteConfiguration.privacyEmail
/** Whether the Request form takes files (Google Drive is set up on
* the server). Unknown (the Vite dev server) offers them, and the
* server says so if it can't. */
export const REQUEST_FILES: boolean = fromServer.requestFiles ?? true
/** A site path as a full URL on the live site. */
export const siteUrl = (path: string): string => new URL(path, SITE_ORIGIN).href

View file

@ -36,7 +36,6 @@ export type ContentBlock = {
| 'callout'
| 'schedule'
| 'table'
| 'cards'
text?: string | null
media?: string | null
href?: string | null

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.9.5-content-display";
export const SITE_VERSION = "NGU-Web.v1.9.4-audit";

View file

@ -21,10 +21,6 @@ import { postDate, useBlogPost } from "../lib/useBlog.ts"
import { accentText, BRAND } from "../lib/color.ts"
import PostContents from "../components/PostContents.tsx"
import { headingAnchors } from "../lib/contents.ts"
import QrCode from "../components/QrCode.tsx"
import RequestLink from "../components/RequestLink.tsx"
import { siteUrl } from "../lib/site.ts"
import { FilePdf } from "@phosphor-icons/react"
const BODY = "var(--color-muted)"
@ -53,7 +49,6 @@ export default function BlogPost() {
const contents = post.show_contents ? headingAnchors(post.blocks).entries : []
const withContents = contents.length >= 2
const postUrl = siteUrl(`/blog/${post.id}`)
const date = postDate(post.published_on)
const cover = mediaUrl(post.cover_image)
const byline = [
@ -90,7 +85,7 @@ export default function BlogPost() {
<div
className={
withContents
? "mx-auto grid max-w-6xl gap-8 px-6 lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-12 print:block"
? "mx-auto grid max-w-6xl gap-8 px-6 lg:grid-cols-[14rem_minmax(0,1fr)] lg:gap-12"
: "contents"
}
>
@ -122,17 +117,9 @@ export default function BlogPost() {
{tag}
</span>
))}
<button
type="button"
onClick={() => window.print()}
className="ml-auto inline-flex items-center gap-1.5 rounded-full border border-link px-3 py-1 font-semibold text-link transition-colors hover:bg-tint print:hidden"
>
<FilePdf size={16} weight="bold" aria-hidden="true" />
Download PDF
</button>
<Link
to={BACK.to}
className="hover:underline print:hidden"
className="ml-auto hover:underline"
style={{ color: accentText(BRAND) }}
>
{BACK.label}
@ -148,22 +135,6 @@ export default function BlogPost() {
)}
<ContentBlocks blocks={post.blocks} accent={BRAND} />
<div className="flex flex-wrap items-center gap-3 border-t border-brand/15 pt-6 text-sm text-muted print:hidden">
Have a story to share?
<RequestLink type="blog" label="Write for the blog" />
</div>
{/* Only on paper (Download PDF): where the post lives online,
as a link and as a code to scan. */}
<footer className="hidden break-inside-avoid items-center gap-6 border-t border-brand/20 pt-6 print:flex">
<QrCode value={postUrl} label={`QR code for ${postUrl}`} className="h-28 w-28 shrink-0" />
<p className="text-sm text-body">
Read this post online at
<br />
<span className="font-semibold text-link">{postUrl}</span>
</p>
</footer>
</article>
</div>
),

View file

@ -34,7 +34,6 @@ const SECTIONS = [
accent: BRAND,
background: "var(--color-tint)",
Component: OrgListMap,
request: { type: "chapter", label: "Add or update a chapter" },
views: { options: ["map", "grid"], default: "map", Toggle: OrgMapToggle },
},
{
@ -45,7 +44,6 @@ const SECTIONS = [
accent: "#4a6b72",
background: "var(--color-surface)",
Component: OrgListVertical,
request: { type: "region", label: "Update a region" },
props: {
kind: "region",
pageLabel: "Region page",
@ -64,7 +62,6 @@ const SECTIONS = [
accent: ACCENTS.mint,
background: "var(--color-tint)",
Component: OrgListCards,
request: { type: "partner", label: "Add or update a partner" },
props: {
kind: "partner",
pageLabel: "Partner page",
@ -84,7 +81,6 @@ export default function CommunityPage() {
accent: BRAND,
background: "var(--color-surface)",
Component: CommunityBlog,
request: { type: "blog", label: "Write for the blog" },
},
...SECTIONS,
]);

View file

@ -13,8 +13,8 @@ const PAGE = sitePage("/privacy");
/* ═══════════════════════════════════════════════════════════════
Privacy policy, cookie notice included.
What it says must stay true of the code: what the feedback and
request forms store (routes/feedback.js, routes/requests.js), what the browser keeps (Banner,
What it says must stay true of the code: what the feedback form
stores (routes/feedback.js), what the browser keeps (Banner,
PrivacyNotice, the theme toggle), which embeds wait for a click
(VideoPlayer, HeroStage, ScheduleBlock), and that nothing about
a minor is shown. Change the date when the wording changes.
@ -24,7 +24,7 @@ const PAGE = sitePage("/privacy");
'privacy', in Admin → Forms → Data requests.
═══════════════════════════════════════════════════════════════ */
const LAST_UPDATED = "September 29, 2026";
const LAST_UPDATED = "September 28, 2026";
const link = "underline underline-offset-2 text-link";
@ -57,7 +57,7 @@ const PARTS: LegalPart[] = [
<strong>Feedback and requests you send.</strong> Your message, the page it's about, and, if you
give them, your name and email. With it we keep your browser's description (its user agent) and
a scrambled form of your IP address that can't be turned back into the address; we use it only to
spot abuse. Files you attach to a <Link to="/request" className={link}>request</Link> are kept with it.
spot abuse.
</>,
<>
<strong>People on the site.</strong> Leaders, speakers and volunteers can appear with a name,
@ -119,13 +119,9 @@ const PARTS: LegalPart[] = [
<>
<strong>Staff sign-in</strong> can use a Google account on our own domain.
</>,
<>
<strong>Files attached to requests</strong> are stored in our Google Workspace (Google Drive), and
our staff may be told of a new request by email through it.
</>,
],
after: [
"This site runs on a server we rent and manage ourselves; your information is stored there, not with an outside website service, apart from request files as above.",
"This site runs on a server we rent and manage ourselves; your information is stored there, not with an outside website service.",
],
},
{

View file

@ -1,33 +0,0 @@
import PageShell from "../components/PageShell.tsx";
import { sitePage } from "../lib/site.ts";
import RequestForm from "./sections/RequestForm.tsx";
import { BRAND } from "../lib/color.ts";
/* Title and intro: site.json, which also gives the search metadata. */
const PAGE = sitePage("/request");
/* ═══════════════════════════════════════════════════════════════
Request page: ask for something to be added to the site or
changed on it. The form (sections/RequestForm) reads ?type= to
start on one kind of request; requestLink() makes those links.
═══════════════════════════════════════════════════════════════ */
const SECTIONS = [
{
id: "request",
title: "Send a request",
blurb:
"Tell us what you'd like on the site, or what should change. Attach a Word document with the details and we'll take it from there.",
accent: BRAND,
background: "var(--color-tint)",
content: (
<div className="mx-auto max-w-3xl px-6">
<RequestForm />
</div>
),
},
];
export default function Request() {
return <PageShell title={PAGE.title} intro={PAGE.description} sections={SECTIONS} />;
}

View file

@ -52,7 +52,6 @@ const SECTIONS = [
Component: EventListCards,
props: { scope: "national", ...RETREATS },
views: { ...CARD_VIEWS, default: "carousel" },
request: { type: "event", label: "Add or update an event" },
},
{
id: "regional",

View file

@ -20,11 +20,10 @@
import { useCallback, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { del, get, patch, post, ApiError } from "../../lib/api.ts";
import { del, get, patch, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts";
import { feedbackTypeLabel } from "../../data/feedbackTypes.ts";
import { requestTypeLabel } from "../../data/requestTypes.ts";
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
@ -47,63 +46,6 @@ function formatDate(value) {
});
}
const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
/* A content request's files: each downloads from Drive through the
server, and a Word document can become a draft blog post
(the same import as Blog posts → Import from Word). */
function RequestFiles({ row, canWrite }) {
const navigate = useNavigate();
const [busy, setBusy] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
async function makePost(file) {
setBusy(file.id);
setError(null);
try {
const result = await post(`/admin/feedback/${row.id}/files/${file.id}/blog-post`, {});
navigate(`/admin/blog_posts/${result.id}`, { state: { imported: result.summary } });
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't reach the server.");
setBusy(null);
}
}
return (
<div className="mt-4">
<ul className="space-y-2">
{row.files.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
<a
href={`/api/admin/feedback/${row.id}/files/${file.id}`}
download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
<span className="text-xs text-muted">{sizeOf(file.size)}</span>
{canWrite && /\.docx$/i.test(file.name) && (
<button
type="button"
disabled={busy !== null}
onClick={() => makePost(file)}
className="rounded-full border border-link px-3 py-0.5 text-xs font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60"
>
{busy === file.id ? "Making the post…" : "Make a blog post from it"}
</button>
)}
</li>
))}
</ul>
{error && (
<p role="alert" className="mt-2 text-sm text-danger">
{error}
</p>
)}
</div>
);
}
function locationOf(row) {
if (!row.page_path) return "Not page-specific";
return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path;
@ -151,9 +93,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
<article className="rounded-2xl border border-brand/20 bg-surface p-5">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
<span className="font-semibold text-body">
{row.feedback_type === "content"
? `${row.request_action === "update" ? "Update" : "New"} ${requestTypeLabel(row.category).toLowerCase()}`
: feedbackTypeLabel(row.feedback_type)}
{feedbackTypeLabel(row.feedback_type)}
</span>
<span
className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
@ -162,15 +102,13 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
>
{row.status}
</span>
{row.feedback_type !== "content" && <span className="text-muted">{locationOf(row)}</span>}
<span className="text-muted">{locationOf(row)}</span>
<span className="ml-auto text-xs text-muted">
#{row.id} · {formatDate(row.created_at)}
</span>
</div>
{row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>}
<p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p>
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} />}
<p className="mt-4 whitespace-pre-wrap text-body">{row.message}</p>
<p className="mt-4 text-sm text-muted">
{row.name || row.email ? (
@ -179,7 +117,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
{row.name && row.email && " · "}
{row.email && (
<a
href={`mailto:${row.email}?subject=${encodeURIComponent(row.subject ? `Your request: ${row.subject}` : "Your NGU site feedback")}`}
href={`mailto:${row.email}?subject=Your%20NGU%20site%20feedback`}
className="text-link underline underline-offset-2"
>
{row.email}
@ -287,20 +225,14 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
/* ── The page ────────────────────────────────────────────────── */
/* The queues this page shows: the website feedback form, content
requests from /request, and data requests from the Privacy page.
Same table, same triage. */
/* The two queues this page shows: the website feedback form, and
data requests from the Privacy page. Same table, same triage. */
const QUEUES = {
feedback: {
to: "/admin/feedback",
title: "Website feedback",
blurb: "Everything submitted through the site's feedback form.",
},
content: {
to: "/admin/requests",
title: "Content requests",
blurb: "Requests from the site's Request form: blog posts, events, and new or updated organizations, teams, awards and people. Files open from Google Drive.",
},
privacy: {
to: "/admin/data-requests",
title: "Data requests",

View file

@ -75,11 +75,6 @@ export const DATA_NAV = {
label: "People",
blurb: "Bios, contact details, affiliations and awards received.",
},
{
to: "/admin/blog_posts",
label: "Blog posts",
blurb: "Posts of our own, each at /blog/…, written here or imported from Word.",
},
],
};
@ -100,6 +95,11 @@ export const PAGES_NAV = {
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",
@ -118,11 +118,6 @@ export const FORMS_NAV = {
label: "Website feedback",
blurb: "The triage queue for the feedback form.",
},
{
to: "/admin/requests",
label: "Content requests",
blurb: "Requests for blog posts, events, and new or updated organizations, teams, awards and people, with their files.",
},
{
to: "/admin/data-requests",
label: "Data requests",

View file

@ -34,16 +34,16 @@ const WHOLE_PAGE = "";
/* ── Shared field chrome ─────────────────────────────────────── */
export const fieldClass =
const fieldClass =
"w-full rounded-xl border border-muted/50 bg-surface px-4 py-3 text-body " +
"placeholder:text-muted outline-none transition-colors " +
"focus:border-brand focus:ring-2 focus:ring-brand/25";
export const errorFieldClass = "border-danger focus:border-danger focus:ring-danger/20";
const errorFieldClass = "border-danger focus:border-danger focus:ring-danger/20";
const selectClass = `${fieldClass} appearance-none pr-10`;
export function OptionalTag() {
function OptionalTag() {
return (
<span className="ml-2 rounded-full bg-tint px-2 py-0.5 text-xs font-medium text-link">
Optional
@ -51,7 +51,7 @@ export function OptionalTag() {
);
}
export function FieldError({ id, children }) {
function FieldError({ id, children }) {
if (!children) return null;
return (
<p id={id} className="mt-2 text-sm text-danger">
@ -82,38 +82,26 @@ function Select({ id, label, value, onChange, children }) {
);
}
/* ── Type picker: a tile per option (the Request form's too) ─── */
/* ── Type picker ─────────────────────────────────────────────── */
export function TilePicker({
legend,
blurb,
name,
options,
value,
onChange,
}: {
legend: string;
blurb: string;
name: string;
options: { id: string; label: string; hint: string }[];
value: string | null;
onChange: (id: string) => void;
}) {
function TypePicker({ value, onChange }) {
return (
<fieldset>
<legend className="text-base font-semibold text-body">{legend}</legend>
<legend className="text-base font-semibold text-body">
What kind of feedback is this?
</legend>
<p className="mt-1 text-sm" style={{ color: MUTED }}>
{blurb}
Pick the closest fit. It helps us route it to the right person.
</p>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{options.map((type) => {
{FEEDBACK_TYPES.map((type) => {
const selected = value === type.id;
return (
<label key={type.id} className="cursor-pointer">
<input
type="radio"
name={name}
name="feedbackType"
value={type.id}
checked={selected}
onChange={() => onChange(type.id)}
@ -329,14 +317,7 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
>
{!fixedType && (
<>
<TilePicker
legend="What kind of feedback is this?"
blurb="Pick the closest fit. It helps us route it to the right person."
name="feedbackType"
options={FEEDBACK_TYPES}
value={type}
onChange={setType}
/>
<TypePicker value={type} onChange={setType} />
<div className="mt-10">
<LocationPicker

View file

@ -1,336 +0,0 @@
/* ═══════════════════════════════════════════════════════════════
REQUEST FORM
Posts to /api/requests (server/src/routes/requests.js), as a form
so files can go with it. What can be asked for is REQUEST_TYPES;
?type=chapter in the address picks one to start with, which is how
the site's "Request" buttons open it.
Files go to Google Drive on the server; when Drive isn't set up
(REQUEST_FILES) the file field isn't shown. The limits here match
the server's, so nobody waits on an upload that will be refused.
═══════════════════════════════════════════════════════════════ */
import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import { ApiError, upload } from "../../lib/api.ts";
import { accentText, BRAND } from "../../lib/color.ts";
import { REQUEST_FILES } from "../../lib/site.ts";
import { REQUEST_TYPES, type RequestAction } from "../../data/requestTypes.ts";
import { FieldError, OptionalTag, TilePicker, errorFieldClass, fieldClass } from "./FeedbackForm.tsx";
const MUTED = "var(--color-muted)";
const MAX_CHARS = 5000;
const MIN_MESSAGE = 10; // matches the server
const MAX_FILES = 3;
const MAX_FILE_MB = 10;
const ACCEPT = ".docx,.pdf,.jpg,.jpeg,.png";
const ACTION_LABEL: Record<RequestAction, string> = {
new: "Something new",
update: "An update to what's there",
};
const PLACEHOLDER: Record<string, string> = {
blog: "A few lines about the post: what it's about, and anything we should know. Attach the post as a Word document.",
event: "When and where, who it's for, how to register, and who to contact.",
};
export default function RequestForm() {
const [params] = useSearchParams();
const start = REQUEST_TYPES.find((t) => t.id === params.get("type")) ?? null;
const [category, setCategory] = useState<string | null>(start?.id ?? null);
const [action, setAction] = useState<RequestAction | null>(start?.actions.length === 1 ? start.actions[0] : null);
const [subject, setSubject] = useState("");
const [message, setMessage] = useState("");
const [files, setFiles] = useState<File[]>([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [website, setWebsite] = useState(""); // honeypot
const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle");
const [formError, setFormError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const type = REQUEST_TYPES.find((t) => t.id === category);
const sending = status === "sending";
const fileError =
files.length > MAX_FILES
? `${MAX_FILES} files at most.`
: files.find((f) => f.size > MAX_FILE_MB * 1024 * 1024)
? `Files can be ${MAX_FILE_MB} MB each at most.`
: null;
const ready =
Boolean(type && action) &&
subject.trim() !== "" &&
message.trim().length >= MIN_MESSAGE &&
email.trim() !== "" &&
!fileError;
function pick(id: string) {
const next = REQUEST_TYPES.find((t) => t.id === id);
setCategory(id);
// One choice picks itself; otherwise keep what was chosen if it still applies.
setAction((prev) => (next?.actions.length === 1 ? next.actions[0] : prev && next?.actions.includes(prev) ? prev : null));
}
async function handleSubmit(event) {
event.preventDefault();
if (!ready || sending || !category || !action) return;
setStatus("sending");
setFormError(null);
setFieldErrors({});
const form = new FormData();
form.set("category", category);
form.set("action", action);
form.set("subject", subject.trim());
form.set("message", message.trim());
form.set("name", name.trim());
form.set("email", email.trim());
form.set("website", website);
for (const file of files) form.append("files", file);
try {
await upload("/requests", form);
setStatus("sent");
} catch (error) {
setStatus("idle");
if (error instanceof ApiError) {
setFieldErrors(error.fields ?? {});
setFormError(error.fields ? "Have another look at the highlighted fields." : error.message);
} else {
setFormError("Couldn't reach the server. Try again in a moment.");
}
}
}
function reset() {
setSubject("");
setMessage("");
setFiles([]);
setStatus("idle");
setFormError(null);
setFieldErrors({});
}
if (status === "sent") {
return (
<div aria-live="polite" className="rounded-2xl border border-brand/20 bg-surface p-8 sm:p-10">
<h3 className="text-2xl font-bold" style={{ color: accentText(BRAND) }}>
Thanks, we've got it
</h3>
<p className="mt-3 max-w-prose" style={{ color: MUTED }}>
We'll look it over and follow up at {email}, usually within a week.
</p>
<button
type="button"
onClick={reset}
className="mt-6 rounded-full border border-brand px-5 py-2.5 font-semibold text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40"
>
Send another request
</button>
</div>
);
}
return (
<form onSubmit={handleSubmit} noValidate className="rounded-2xl border border-brand/20 bg-surface p-6 sm:p-8">
<TilePicker
legend="What is this about?"
blurb="Pick the closest fit."
name="category"
options={REQUEST_TYPES}
value={category}
onChange={pick}
/>
<FieldError id="request-category-error">{fieldErrors.category}</FieldError>
{type && type.actions.length > 1 && (
<fieldset className="mt-8">
<legend className="text-base font-semibold text-body">New, or an update?</legend>
<div className="mt-3 flex flex-wrap gap-3">
{type.actions.map((a) => (
<label key={a} className="cursor-pointer">
<input
type="radio"
name="action"
value={a}
checked={action === a}
onChange={() => setAction(a)}
className="peer sr-only"
/>
<span
className={
"inline-block rounded-full border px-5 py-2 text-sm font-semibold transition-colors " +
"peer-focus-visible:ring-2 peer-focus-visible:ring-brand/40 " +
(action === a ? "border-brand bg-tint text-link" : "border-muted/30 text-body hover:border-brand/50")
}
>
{ACTION_LABEL[a]}
</span>
</label>
))}
</div>
<FieldError id="request-action-error">{fieldErrors.action}</FieldError>
</fieldset>
)}
{type?.id === "region" && (
<p className="mt-4 text-sm" style={{ color: MUTED }}>
Regions are set by Unity, so this is for updating one that's on the site.
</p>
)}
{type && (
<>
<div className="mt-8">
<label htmlFor="request-subject" className="text-base font-semibold text-body">
{action === "update" && type.actions.length > 1 ? `Which ${type.label.toLowerCase()}?` : type.subject}
</label>
<input
id="request-subject"
type="text"
maxLength={200}
value={subject}
onChange={(e) => setSubject(e.target.value)}
aria-invalid={Boolean(fieldErrors.subject)}
aria-describedby={fieldErrors.subject ? "request-subject-error" : undefined}
className={`mt-3 ${fieldClass} ${fieldErrors.subject ? errorFieldClass : ""}`}
/>
<FieldError id="request-subject-error">{fieldErrors.subject}</FieldError>
</div>
<div className="mt-8">
<label htmlFor="request-message" className="text-base font-semibold text-body">
{action === "update" ? "What should change?" : "Tell us about it"}
</label>
<textarea
id="request-message"
rows={7}
maxLength={MAX_CHARS}
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder={
action === "update"
? "What's there now, and what it should say instead."
: (PLACEHOLDER[type.id] ?? "Everything we'd need to add it: a description, links, and who to contact.")
}
aria-invalid={Boolean(fieldErrors.message)}
aria-describedby={fieldErrors.message ? "request-message-error" : undefined}
className={`mt-3 resize-y ${fieldClass} ${fieldErrors.message ? errorFieldClass : ""}`}
/>
<div className="mt-2 flex items-start justify-between gap-4">
<FieldError id="request-message-error">{fieldErrors.message}</FieldError>
<span className="ml-auto shrink-0 text-xs tabular-nums" style={{ color: MUTED }}>
{message.length} / {MAX_CHARS}
</span>
</div>
</div>
{REQUEST_FILES && (
<div className="mt-8">
<div className="flex flex-wrap items-center">
<label htmlFor="request-files" className="text-base font-semibold text-body">
Files
</label>
<OptionalTag />
</div>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
A Word document (.docx) with the details or the post itself, photos (JPEG or PNG) or a PDF. Up to{" "}
{MAX_FILES}, {MAX_FILE_MB} MB each.
</p>
<input
id="request-files"
type="file"
multiple
accept={ACCEPT}
onChange={(e) => setFiles(Array.from(e.target.files ?? []))}
aria-invalid={Boolean(fileError || fieldErrors.files)}
aria-describedby={fileError || fieldErrors.files ? "request-files-error" : undefined}
className="mt-3 block w-full text-sm text-body file:mr-4 file:rounded-full file:border-0 file:bg-tint file:px-4 file:py-2 file:font-semibold file:text-link hover:file:bg-tint-soft"
/>
<FieldError id="request-files-error">{fileError ?? fieldErrors.files}</FieldError>
</div>
)}
</>
)}
<div className="mt-8 rounded-xl border border-dashed border-muted/30 bg-tint/60 p-5 sm:p-6">
<h3 className="text-base font-semibold text-body">How we reach you</h3>
<p className="mt-1 max-w-prose text-sm" style={{ color: MUTED }}>
We use these only to follow up on this request, and we won't add you to any list.
</p>
<div className="mt-5 grid gap-4 sm:grid-cols-2">
<div>
<label htmlFor="request-name" className="block text-sm font-medium text-body">
Name <span className="font-normal text-muted">(optional)</span>
</label>
<input
id="request-name"
type="text"
autoComplete="name"
value={name}
onChange={(e) => setName(e.target.value)}
className={`mt-2 ${fieldClass}`}
/>
</div>
<div>
<label htmlFor="request-email" className="block text-sm font-medium text-body">
Email <span className="font-normal text-muted">(required)</span>
</label>
<input
id="request-email"
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? "request-email-error" : undefined}
className={`mt-2 ${fieldClass} ${fieldErrors.email ? errorFieldClass : ""}`}
/>
<FieldError id="request-email-error">{fieldErrors.email}</FieldError>
</div>
</div>
</div>
{/* Honeypot, as on the feedback form. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<label htmlFor="request-website">Website</label>
<input
id="request-website"
type="text"
tabIndex={-1}
autoComplete="off"
value={website}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
{formError && (
<p role="alert" className="mt-8 rounded-xl border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
{formError}
</p>
)}
<div className="mt-6 flex flex-wrap items-center gap-4">
<button
type="submit"
disabled={!ready || sending}
className="rounded-full bg-action px-7 py-3 font-semibold text-white transition-colors hover:bg-action-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:bg-muted/25 disabled:text-white/80"
>
{sending ? (files.length ? "Uploading…" : "Sending…") : "Send request"}
</button>
{!ready && !sending && (
<p className="text-sm" style={{ color: MUTED }}>
Choose what it's about, give it a name, write at least a sentence and give an email address to send.
</p>
)}
</div>
</form>
);
}

View file

@ -9,22 +9,18 @@
═══════════════════════════════════════════════════════════════ */
import EventCalendar from '../EventCalendar.tsx'
import RequestLink from '../../../components/RequestLink.tsx'
type CalendarBandProps = { id: string; title: string; blurb?: string | null }
export default function CalendarBand({ id, title, blurb }: CalendarBandProps) {
return (
<section id={id} className="py-24" style={{ background: 'var(--color-tint-soft)' }}>
<div className="mx-auto mb-10 flex max-w-6xl flex-wrap items-end justify-between gap-4 px-6">
<div>
<div className="mx-auto mb-10 max-w-6xl px-6">
<h2 className="font-display text-4xl font-extrabold text-ink md:text-5xl">
{title}
</h2>
{blurb && <p className="mt-3 max-w-xl text-lg text-muted">{blurb}</p>}
</div>
<RequestLink type="event" label="Add or update an event" />
</div>
<EventCalendar />
</section>