diff --git a/CLAUDE.md b/CLAUDE.md index 04b725c..32e5a12 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,6 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Never run commands against the production server or database unless explicitly asked. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. +- 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). nginx setup: `docs/seo.md`. ## Git workflow - Remote is a self-hosted Forgejo server, not GitHub. Do not use `gh`. diff --git a/docs/seo.md b/docs/seo.md new file mode 100644 index 0000000..22840b4 --- /dev/null +++ b/docs/seo.md @@ -0,0 +1,80 @@ +# 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 + +| 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/` 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/`); set them on the + `ngu-api` unit if the deploy puts them elsewhere: + + ```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 + location = /sitemap.xml { + proxy_pass http://127.0.0.1:3001; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + location / { + try_files $uri @page; + } + + location @page { + proxy_pass http://127.0.0.1:3001; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_intercept_errors on; + error_page 502 503 504 = @static; + } + + location @static { + try_files /index.html =404; + } + ``` + + Keep the existing `/api/` and `/uploads/` blocks; they're more + specific and still win. Use the port the API listens on. + +3. Check it: `curl -s https://nextgenerationofunity.org/events/ | 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`. diff --git a/docs/updating-data-in-code.md b/docs/updating-data-in-code.md index 5f1ae6e..b4cc268 100644 --- a/docs/updating-data-in-code.md +++ b/docs/updating-data-in-code.md @@ -33,6 +33,7 @@ what a dropdown in the admin editor says. | The **label** a dropdown shows in the admin | code | [one file](#renaming-what-a-dropdown-shows) | | The **list of allowed values** behind a fixed dropdown | database CHECK + code | [a migration and three files](#adding-removing-or-renaming-a-stored-value) | | Navigation, page section titles, colours, the site banner, history decades, the map grid | code | [the file named below](#other-content-that-lives-in-code) | +| A static page's title and intro (also its search title and description), the site's name, address and default preview image | `site.json` | editing `pages`, `title`, `url`, `openGraph.image`. 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, diff --git a/server/src/index.js b/server/src/index.js index aa8248f..8f8cd31 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -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"; @@ -102,6 +103,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)); diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js new file mode 100644 index 0000000..69555fb --- /dev/null +++ b/server/src/pageMeta.js @@ -0,0 +1,447 @@ +/* ═══════════════════════════════════════════════════════════════ + 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, and each static page's title and + description. The pages read the same file for their heading and + intro, so the two 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 + lives in that record kind's public/ directory, anything starting + with / or a scheme is used as it is. Keep DIRS in step with it. + 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, per kind. Mirrors src/lib/media.ts. */ +const DIRS = { + person: "/people", + eventLogo: "/event-logos", + eventBackground: "/event-backgrounds", + organization: "/org-logos", + team: "/team-logos", + award: "/award-logos", + blog: "/blog", +}; + +/* ── 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(/\/$/, ""); + +/* ── 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 bare filename is in that kind's directory, or at the site's + // root for the site's own default (kind null). + const pathOrUrl = /^(https?:|\/)/.test(file) ? file : kind ? `${DIRS[kind]}/${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, + }; +} + +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 = loadSite(); + // 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, ">"); + +/* 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 = [ + /[\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, +]; + +export function renderPage(html, meta) { + const site = loadSite(); + let out = html; + for (const pattern of REPLACED) out = out.replace(pattern, ""); + + const tags = [ + `<title>${escapeHtml(meta.title)}`, + meta.description && ``, + meta.noindex && ``, + meta.status === 200 && ``, + ``, + ``, + ``, + meta.description && ``, + meta.status === 200 && ``, + meta.image && ``, + ``, + meta.image && ``, + // "${JSON.stringify(meta.jsonLd).replace(/`, + ].filter(Boolean); + + // A blocked site (site.json robots.index false) stays blocked on + // every page, whatever the record says. + if (site.robots?.index === false && !meta.noindex) { + tags.splice(2, 0, ``); + } + + return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n `); +} + +/* ── Sitemap ───────────────────────────────────────────────── */ + +export function sitemap(db) { + const site = loadSite(); + 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) => + ` ${escapeHtml(base + e.loc.split("/").map(encodeURIComponent).join("/"))}` + + (e.lastmod ? `${e.lastmod}` : "") + + ``, + ) + .join("\n"); + + return `\n\n${xml}\n\n`; +} diff --git a/server/src/routes/pages.js b/server/src/routes/pages.js new file mode 100644 index 0000000..6684c7c --- /dev/null +++ b/server/src/routes/pages.js @@ -0,0 +1,79 @@ +/* ═══════════════════════════════════════════════════════════════ + PAGE ROUTES: the site's HTML, with each page's metadata + + GET /sitemap.xml every public, listed page + 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. + + 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, 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(); + +pages.get("/sitemap.xml", (c) => + c.body(sitemap(c.get("db")), 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); + } + + const meta = metaFor(c.get("db"), pathname); + return c.html(renderPage(html, meta), meta.status, { + "Cache-Control": meta.status === 200 ? CACHE : "no-store", + }); +}); + +export default pages; diff --git a/site.json b/site.json index c0eb7d4..a0fc0c3 100644 --- a/site.json +++ b/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." + }, + "/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." + } } } diff --git a/src/components/PageShell.tsx b/src/components/PageShell.tsx index 496f926..0d2017c 100644 --- a/src/components/PageShell.tsx +++ b/src/components/PageShell.tsx @@ -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 */} diff --git a/src/lib/site.ts b/src/lib/site.ts index 75bce26..43b8cab 100644 --- a/src/lib/site.ts +++ b/src/lib/site.ts @@ -1,13 +1,39 @@ /* ═══════════════════════════════════════════════════════════════ 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 /site.json says about the site, for the browser. The server + reads the same file for the metadata it puts in each page's HTML + (server/src/pageMeta.js), so a page's visible heading and intro + and its search title and description come from one place. + + 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' + +export const SITE_NAME: string = 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 + +type PageText = { title: string; description: string } + +const PAGES: Record = 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 diff --git a/src/pages/Community.tsx b/src/pages/Community.tsx index f516c1a..c35b5f5 100644 --- a/src/pages/Community.tsx +++ b/src/pages/Community.tsx @@ -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 @@ -82,8 +86,8 @@ export default function CommunityPage() { return ( ); diff --git a/src/pages/Feedback.tsx b/src/pages/Feedback.tsx index c6caf8c..6b4f6b2 100644 --- a/src/pages/Feedback.tsx +++ b/src/pages/Feedback.tsx @@ -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 ( ); diff --git a/src/pages/Giving.tsx b/src/pages/Giving.tsx index e10290f..67210af 100644 --- a/src/pages/Giving.tsx +++ b/src/pages/Giving.tsx @@ -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 ( ); diff --git a/src/pages/History.tsx b/src/pages/History.tsx index 610e791..aa6ad28 100644 --- a/src/pages/History.tsx +++ b/src/pages/History.tsx @@ -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 ( { + document.title = documentTitle() + }, []) + return ( <> diff --git a/src/pages/Leadership.tsx b/src/pages/Leadership.tsx index 1f3f3ee..a441b18 100644 --- a/src/pages/Leadership.tsx +++ b/src/pages/Leadership.tsx @@ -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 ( ); diff --git a/src/pages/Privacy.tsx b/src/pages/Privacy.tsx index fd297d9..49a5187 100644 --- a/src/pages/Privacy.tsx +++ b/src/pages/Privacy.tsx @@ -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 ( ); diff --git a/src/pages/QrCodes.tsx b/src/pages/QrCodes.tsx index ce011d6..fa798f2 100644 --- a/src/pages/QrCodes.tsx +++ b/src/pages/QrCodes.tsx @@ -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 @@ -29,8 +33,8 @@ const SECTIONS = [ export default function QrCodes() { return ( ) diff --git a/src/pages/Resources.tsx b/src/pages/Resources.tsx index a65345c..9791357 100644 --- a/src/pages/Resources.tsx +++ b/src/pages/Resources.tsx @@ -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 ( ); diff --git a/src/pages/Retreats.tsx b/src/pages/Retreats.tsx index 2025932..a59d8e0 100644 --- a/src/pages/Retreats.tsx +++ b/src/pages/Retreats.tsx @@ -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 ( ); diff --git a/src/pages/Terms.tsx b/src/pages/Terms.tsx index a24467d..065047a 100644 --- a/src/pages/Terms.tsx +++ b/src/pages/Terms.tsx @@ -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 ( ); diff --git a/vite.config.ts b/vite.config.ts index c514c7f..3f8cd02 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -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',