- {PAGE_LINKS.map((page, i) => (
+ {pages.map((page, i) => (
{i > 0 && ' · '}
{page.label}
diff --git a/src/components/SiteLink.tsx b/src/components/SiteLink.tsx
new file mode 100644
index 0000000..069c49e
--- /dev/null
+++ b/src/components/SiteLink.tsx
@@ -0,0 +1,30 @@
+import { Link } from 'react-router-dom'
+
+import type { NavLink } from '../navConfig.ts'
+
+/* A nav link (Pages → Navigation): a route on the site, or a plain
+ link for an address off it or one set to open in a new tab. */
+export default function SiteLink({
+ link,
+ children,
+ ...rest
+}: {
+ link: NavLink
+ children: React.ReactNode
+ className?: string
+ style?: React.CSSProperties
+ onClick?: () => void
+}) {
+ if (!link.path.startsWith('/') || link.newTab) {
+ return (
+
+ {children}
+
+ )
+ }
+ return (
+
+ {children}
+
+ )
+}
diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts
index 20c348d..5fe00bc 100644
--- a/src/lib/adminSchema.ts
+++ b/src/lib/adminSchema.ts
@@ -27,6 +27,7 @@ import { timeline } from "./adminSchema/timeline.ts";
import { frontPage } from "./adminSchema/frontPage.ts";
import { blogPosts } from "./adminSchema/blog.ts";
import { siteSettings } from "./adminSchema/siteSettings.ts";
+import { siteNav } from "./adminSchema/siteNav.ts";
import { personTagTypes } from "./adminSchema/personTags.ts";
import { tags } from "./adminSchema/tags.ts";
import { contactTypes } from "./adminSchema/contactTypes.ts";
@@ -37,6 +38,7 @@ import {
resourcesPage,
organizationPage,
historyPage,
+ shopPage,
} from "./adminSchema/sitePages.ts";
export const ADMIN_ENTITIES: Record = {
@@ -57,6 +59,8 @@ export const ADMIN_ENTITIES: Record = {
resources_page: resourcesPage,
organization_page: organizationPage,
history_page: historyPage,
+ shop_page: shopPage,
+ navigation: siteNav,
site_settings: siteSettings,
};
diff --git a/src/lib/adminSchema/siteNav.ts b/src/lib/adminSchema/siteNav.ts
new file mode 100644
index 0000000..4bd56ed
--- /dev/null
+++ b/src/lib/adminSchema/siteNav.ts
@@ -0,0 +1,104 @@
+import siteConfiguration from "../../../site.json";
+
+/* ── Navigation (075_site_nav.sql) ───────────────────────────────
+ Pages → Navigation: the header's and footer's links, and each
+ static page's title, intro and whether it's hidden. Admins and up
+ save it, since hiding takes a page off the site. Server side:
+ server/src/admin-schema/siteNav.js; the site reads it through
+ server/src/siteNav.js and src/lib/useSiteNav.ts. */
+
+const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).map(
+ ([path, page]) => [path, `${page.title} (${path})`],
+);
+
+const PLACES: [string, string][] = [
+ ["main", "Header: pages"],
+ ["action", "Header: buttons"],
+ ["footer", "Footer: Get in Touch"],
+ ["legal", "Footer: bottom row"],
+];
+
+const placeLabel = (place) => PLACES.find(([key]) => key === place)?.[1];
+
+export const siteNav = {
+ key: "navigation",
+ label: "Navigation",
+ singular: "navigation",
+ idLabel: "Navigation",
+ singleton: "site",
+ writeRole: "admin",
+
+ list: { columns: [], filters: [] },
+
+ groups: [],
+
+ children: [
+ {
+ key: "links",
+ label: "Links",
+ note: "Top to bottom, in the order each place shows them. A link to a hidden page is only shown to signed-in admin accounts. A header page lists its sections under it by itself (Pages → the page).",
+ addLabel: "Add link",
+ title: (row) => (row.label ? `${row.label} · ${placeLabel(row.place) ?? "No place"}` : "New link"),
+ blank: { place: "", label: "", path: "", parent_path: "", style: "", new_tab: 0 },
+ fields: [
+ { path: "place", label: "Shows in", widget: "select", options: PLACES, required: true },
+ { path: "label", label: "Label", required: true, help: "eg. Shop" },
+ {
+ path: "path",
+ label: "Link",
+ required: true,
+ full: true,
+ help: "A page on the site, a section of one, or an address elsewhere, eg. /shop, /organization#contact or https://www.bonfire.com/store/…",
+ },
+ {
+ path: "parent_path",
+ label: "Under page",
+ widget: "select",
+ options: [["/", "Home (/)"], ...SITE_PAGES],
+ blankLabel: "Default: its own place in the header",
+ help: "Lists it in that page's menu, after its sections, instead of in the header's row",
+ when: { path: "place", value: "main" },
+ },
+ {
+ path: "style",
+ label: "Style",
+ widget: "select",
+ options: [["filled", "Filled, like Give (also beside the footer's logo)"]],
+ blankLabel: "Default: outlined",
+ when: { path: "place", value: "action" },
+ },
+ { path: "new_tab", label: "Opens in a new tab", widget: "checkbox" },
+ ],
+ },
+ {
+ key: "pages",
+ label: "Pages",
+ note: "A page's heading and intro (also its search title and description), and whether it's hidden. A hidden page is out of the menus and the sitemap and says Not found to everyone but signed-in admin accounts, who see it with a bar saying it's hidden. Blank fields keep site.json's. A page not listed here shows as site.json has it.",
+ addLabel: "Add page",
+ title: (row) =>
+ `${SITE_PAGES.find(([path]) => path === row.path)?.[1] ?? "New page"}${row.is_hidden ? " · Hidden" : ""}`,
+ blank: { path: "", title: "", description: "", is_hidden: 0 },
+ fields: [
+ { path: "path", label: "Page", widget: "select", options: SITE_PAGES, required: true },
+ {
+ path: "is_hidden",
+ label: "Hidden",
+ widget: "checkbox",
+ help: "Not found to everyone but signed-in admin accounts, eg. a page that isn't done",
+ },
+ {
+ path: "title",
+ label: "Title",
+ help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.title ?? ""}` : undefined),
+ },
+ {
+ path: "description",
+ label: "Intro",
+ widget: "textarea",
+ full: true,
+ help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.description ?? ""}` : undefined),
+ },
+ ],
+ },
+ ],
+};
diff --git a/src/lib/adminSchema/sitePages.ts b/src/lib/adminSchema/sitePages.ts
index 8f0d8fc..9e5f3f9 100644
--- a/src/lib/adminSchema/sitePages.ts
+++ b/src/lib/adminSchema/sitePages.ts
@@ -1,5 +1,6 @@
/* ── The site's own pages (056_site_pages.sql) ───────────────────
- Pages → Community, Retreats, Resources, Organization, History:
+ Pages → Community, Retreats, Resources, Organization, History,
+ Shop (075):
each page is its sections, in order, and each section is its
heading and its own content blocks, then a preset if it has one
(a prebuilt part of the site, drawn under the blocks). Server
@@ -254,3 +255,4 @@ export const retreatsPage = sitePage("retreats", "Retreats page", ["events"]);
export const resourcesPage = sitePage("resources", "Resources page", ["people_directory"]);
export const organizationPage = sitePage("organization", "Organization page", ["people_directory"]);
export const historyPage = sitePage("history", "History page", ["timeline"]);
+export const shopPage = sitePage("shop", "Shop page", []);
diff --git a/src/lib/adminSchema/siteSettings.ts b/src/lib/adminSchema/siteSettings.ts
index 3dbee2e..b55f2fe 100644
--- a/src/lib/adminSchema/siteSettings.ts
+++ b/src/lib/adminSchema/siteSettings.ts
@@ -4,10 +4,8 @@ import { THEME_DEFAULTS } from "../../../server/src/themeDefaults.js";
/* ── Site settings (035_site_settings.sql) ───────────────────────
Overrides for site.json, superadmins only: every blank falls back
- to what site.json says, which is shown as the default. */
-const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).map(
- ([path, page]) => [path, `${page.title} (${path})`],
-);
+ to what site.json says, which is shown as the default. Page titles
+ and intros are Pages → Navigation's (siteNav.ts). */
/* The palette an admin can change, in the order the dropdown lists
it: token and label. The defaults come from the server's list
@@ -218,28 +216,5 @@ export const siteSettings = {
},
],
},
- {
- key: "pages",
- label: "Page titles and intros",
- note: "Change a static page's heading and intro, which are also its search title and description. Blank fields keep site.json's.",
- addLabel: "Change a page",
- title: (row) => SITE_PAGES.find(([path]) => path === row.path)?.[1] ?? "New page",
- blank: { path: "", title: "", description: "" },
- fields: [
- { path: "path", label: "Page", widget: "select", options: SITE_PAGES, required: true },
- {
- path: "title",
- label: "Title",
- help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.title ?? ""}` : undefined),
- },
- {
- path: "description",
- label: "Intro",
- widget: "textarea",
- full: true,
- help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.description ?? ""}` : undefined),
- },
- ],
- },
],
};
diff --git a/src/lib/hrefs.ts b/src/lib/hrefs.ts
index 5ec719a..536a13f 100644
--- a/src/lib/hrefs.ts
+++ b/src/lib/hrefs.ts
@@ -13,7 +13,7 @@
table, so there is one answer to "where does an event live" and
changing it is changing EVENT_BASE below.
- navConfig.ts stays the source of truth for the *nav*: these are
+ The nav is Pages → Navigation's (useSiteNav.ts): these are
record routes, which never appear in it.
── On missing ids ──
diff --git a/src/lib/useSiteNav.ts b/src/lib/useSiteNav.ts
new file mode 100644
index 0000000..8d7fa8d
--- /dev/null
+++ b/src/lib/useSiteNav.ts
@@ -0,0 +1,56 @@
+/* ═══════════════════════════════════════════════════════════════
+ SITE NAV: the header's and footer's links, and the hidden pages
+
+ Pages → Navigation, for this visitor (server/src/siteNav.js): a
+ link to a hidden page is only sent to a viewer and up. The page
+ HTML carries it (window.__SITE__.nav), so the menus draw on the
+ first paint; GET /api/nav asks again, which is also how the dev
+ server (no page metadata) and a sign-in in another tab get it.
+ Until either answers, navConfig.ts's defaults.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useMemo } from 'react'
+
+import { NAV_DEFAULTS, type NavLink } from '../navConfig.ts'
+import { useRecord } from './useRecord.ts'
+
+export type SiteNav = {
+ links: NavLink[]
+ /** Paths of hidden pages, eg. '/shop'. */
+ hidden: string[]
+ /** This visitor sees hidden pages (signed in, viewer and up). */
+ seesHidden: boolean
+}
+
+const fromPage: SiteNav | undefined =
+ typeof window !== 'undefined' ? (window as unknown as { __SITE__?: { nav?: SiteNav } }).__SITE__?.nav : undefined
+
+const DEFAULTS: SiteNav = { links: NAV_DEFAULTS, hidden: [], seesHidden: false }
+
+/** A path's page: no #section or ?query, no trailing slash. */
+export const pageOf = (path: string): string => path.split(/[?#]/)[0].replace(/(.)\/+$/, '$1') || '/'
+
+export function useSiteNav() {
+ const { data } = useRecord('/nav', 'nav')
+ const nav = data ?? fromPage ?? DEFAULTS
+
+ return useMemo(() => {
+ const main = nav.links.filter((l) => l.place === 'main')
+ const top = main.filter((l) => !l.parent)
+ const tops = new Set(top.map((l) => pageOf(l.path)))
+ return {
+ ...nav,
+ /** The header's pages, each with the links set under it. */
+ main: top.map((page) => ({
+ ...page,
+ children: main.filter((l) => l.parent && l.parent === pageOf(page.path)),
+ })),
+ /** Every main link, children included, for lists of the site's pages. */
+ pages: main.filter((l) => !l.parent || tops.has(l.parent)),
+ actions: nav.links.filter((l) => l.place === 'action'),
+ footer: nav.links.filter((l) => l.place === 'footer'),
+ legal: nav.links.filter((l) => l.place === 'legal'),
+ isHidden: (path: string) => nav.hidden.includes(pageOf(path)),
+ }
+ }, [nav])
+}
diff --git a/src/navConfig.ts b/src/navConfig.ts
index 03c5422..eb75fcc 100644
--- a/src/navConfig.ts
+++ b/src/navConfig.ts
@@ -1,22 +1,56 @@
-// Single source of truth for navigation.
-// Add a page here and in App.jsx, and both tiers of the nav update.
+/* ═══════════════════════════════════════════════════════════════
+ NAV DEFAULTS
-export const PAGE_LINKS = [
- { label: "Home", path: "/" },
- { label: "Retreats", path: "/retreats" },
- { label: "Community", path: "/community" },
- { label: "Resources", path: "/resources" },
- { label: "Organization", path: "/organization" },
- { label: "History", path: "/history" },
-];
+ The header's and footer's links are edited in Pages → Navigation
+ (075_site_nav.sql) and reach the app through useSiteNav
+ (src/lib/useSiteNav.ts). This is what the app starts from before
+ they arrive: the same links the migration seeded, so a dev server
+ with no page metadata, or a moment before /api/nav answers, still
+ has a menu. Change the menus in the admin, not here.
-// Right-side actions. `variant` picks the styling, not the destination.
-export const NAV_ACTIONS = [
- { label: "Contact Us", to: "/organization#contact", variant: "ghost" },
- {
- label: "Give",
- to: "/give",
- variant: "fancy",
- external: true,
- },
-];
+ place: main the header's pages (sections drop down under
+ each); with a parent, in that page's dropdown
+ action the header's buttons (filled: the Give style,
+ also beside the footer's logo)
+ footer the footer's Get in Touch list
+ legal the footer's bottom row
+ ═══════════════════════════════════════════════════════════════ */
+
+export type NavPlace = 'main' | 'action' | 'footer' | 'legal'
+
+export type NavLink = {
+ place: NavPlace
+ label: string
+ /** '/retreats', '/organization#contact', or an https:// address. */
+ path: string
+ /** A main link's page whose dropdown it sits in. */
+ parent: string | null
+ filled: boolean
+ newTab: boolean
+}
+
+const link = (place: NavPlace, label: string, path: string, more: Partial = {}): NavLink => ({
+ place,
+ label,
+ path,
+ parent: null,
+ filled: false,
+ newTab: false,
+ ...more,
+})
+
+export const NAV_DEFAULTS: NavLink[] = [
+ link('main', 'Home', '/'),
+ link('main', 'Retreats', '/retreats'),
+ link('main', 'Community', '/community'),
+ link('main', 'Resources', '/resources'),
+ link('main', 'Organization', '/organization'),
+ link('main', 'History', '/history'),
+ link('action', 'Contact Us', '/organization#contact'),
+ link('action', 'Give', '/give', { filled: true, newTab: true }),
+ link('footer', 'Feedback', '/feedback'),
+ link('footer', 'Request', '/request'),
+ link('footer', 'Contact Us', '/organization#contact'),
+ link('legal', 'Privacy Policy', '/privacy'),
+ link('legal', 'Terms of Service', '/terms'),
+]
diff --git a/src/pages/NotFound.tsx b/src/pages/NotFound.tsx
index 2864570..aa061fd 100644
--- a/src/pages/NotFound.tsx
+++ b/src/pages/NotFound.tsx
@@ -18,7 +18,7 @@ import { useMemo } from 'react'
import { Link, useLocation } from 'react-router-dom'
import PageShell from '../components/PageShell.tsx'
-import { PAGE_LINKS } from '../navConfig.ts'
+import { useSiteNav } from '../lib/useSiteNav.ts'
import { SITE_PAGES } from '../lib/site.ts'
import { useDirectory, type Directory } from '../lib/useContent.ts'
import { blogHref, eventHref, orgHref, personHref, teamHref, awardHref } from '../lib/hrefs.ts'
@@ -33,10 +33,11 @@ const ORG_KIND_LABEL: Record = {
partner: 'Partner',
}
-/* Everything an address could have meant: the static pages, then
- each kind of record, with the words to match it by. */
-function candidates(directory: Directory | null): Candidate[] {
- const pages: Candidate[] = Object.entries(SITE_PAGES).map(([path, page]) => ({
+/* Everything an address could have meant: the static pages (not the
+ hidden ones), then each kind of record, with the words to match
+ it by. */
+function candidates(directory: Directory | null, isHidden: (path: string) => boolean): Candidate[] {
+ const pages: Candidate[] = Object.entries(SITE_PAGES).filter(([path]) => !isHidden(path)).map(([path, page]) => ({
href: path,
label: page.title,
detail: 'Page',
@@ -65,7 +66,11 @@ function candidates(directory: Directory | null): Candidate[] {
export default function NotFound() {
const { pathname } = useLocation()
const { data: directory, loading } = useDirectory()
- const matches = useMemo(() => suggest(pathname, candidates(directory ?? null)), [pathname, directory])
+ const { main: pages, isHidden } = useSiteNav()
+ const matches = useMemo(
+ () => suggest(pathname, candidates(directory ?? null, isHidden)),
+ [pathname, directory, isHidden],
+ )
const reading = useReadingMode()
return (
@@ -118,7 +123,7 @@ export default function NotFound() {
accent: ACCENTS.green,
content: (
- {PAGE_LINKS.map((page) => (
+ {pages.map((page) => (
Not page-specific
- {PAGE_LINKS.map((p) => (
+ {pages.map((p) => (
{p.label}
@@ -238,9 +240,9 @@ function LocationPicker({ page, section, onPageChange, onSectionChange }) {
}
// Human-readable version of the picked location, for the thank-you panel.
-function describeLocation(page, section, sectionsOf: (path: string) => NavSection[]) {
+function describeLocation(page, section, sectionsOf: (path: string) => NavSection[], pages: { path: string; label: string }[]) {
if (page === SITE_WIDE) return null;
- const pageLabel = PAGE_LINKS.find((p) => p.path === page)?.label ?? page;
+ const pageLabel = pages.find((p) => p.path === page)?.label ?? page;
const sectionLabel = sectionsOf(page).find(
(s) => s.hash === section,
)?.label;
@@ -251,6 +253,7 @@ function describeLocation(page, section, sectionsOf: (path: string) => NavSectio
export default function FeedbackForm({ fixedType }: { fixedType?: string } = {}) {
const sectionsOf = useNavSections();
+ const { pages } = useSiteNav();
const request = fixedType === DATA_REQUEST.id;
const [type, setType] = useState
(fixedType ?? null);
const [page, setPage] = useState(SITE_WIDE);
@@ -320,7 +323,7 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
}
if (status === "sent") {
- const where = describeLocation(page, section, sectionsOf);
+ const where = describeLocation(page, section, sectionsOf, pages);
return (
({ path: p.path, label: p.label }))
+ on the site rather than an anchor on one of them (Give, not
+ Contact Us). */
+function mainPages(nav: ReturnType
): Choice[] {
+ const pages = nav.pages.map((p) => ({ path: p.path, label: p.label }))
const known = new Set(pages.map((p) => p.path))
- for (const action of NAV_ACTIONS) {
- const path = action.to.split('#')[0]
- if (!action.to.includes('#') && !known.has(path)) {
- pages.push({ path, label: action.label })
- known.add(path)
- }
+ for (const action of nav.actions) {
+ if (!action.path.startsWith('/') || action.path.includes('#') || known.has(action.path)) continue
+ pages.push({ path: action.path, label: action.label })
+ known.add(action.path)
}
return pages
}
-function groupsFor(kind: Kind, directory: Directory | null): Group[] {
- if (kind === 'pages') return [{ choices: mainPages() }]
+function groupsFor(kind: Kind, directory: Directory | null, nav: ReturnType): Group[] {
+ if (kind === 'pages') return [{ choices: mainPages(nav) }]
if (!directory) return []
switch (kind) {
@@ -268,7 +267,8 @@ export default function QrCodeMaker() {
const [copied, setCopied] = useState(false)
const svgRef = useRef(null)
- const groups = useMemo(() => groupsFor(kind, directory), [kind, directory])
+ const nav = useSiteNav()
+ const groups = useMemo(() => groupsFor(kind, directory, nav), [kind, directory, nav])
const choices = useMemo(() => groups.flatMap((group) => group.choices), [groups])
// Past FILTER_FROM records, a box above the select narrows them;
// the one chosen always stays.
From e4c7e165d13faa750b8cea7fad19404650ae5abe Mon Sep 17 00:00:00 2001
From: Aidan Dona
Date: Fri, 16 Oct 2026 18:14:30 -0500
Subject: [PATCH 37/90] Profile accounts: invites, any-Google sign-in, claiming
People, visibility, Discord
Migration 076 adds a member role below viewer (the site and its own
profile, never the admin: /api/admin now needs viewer), invites, person
claims, a Discord link on accounts and people.hide_* switches. Public reads
of people go through v_people_public, which nulls hidden fields, and the
views that read people are rebuilt over it.
Admins invite an email from Data -> Profile accounts (link shown once,
emailed on request). The invitee sets a password or signs in with any
Google account under that email, asks to claim their People record, and
once approved edits it and chooses what shows at /account.
Co-Authored-By: Claude Opus 5.5
---
CLAUDE.md | 3 +-
docs/google-sign-in.md | 9 +-
docs/profile-accounts.md | 78 +++
server/src/admin-schema/people.js | 3 +
server/src/auth.js | 17 +-
server/src/discordAuth.js | 84 ++++
server/src/googleAuth.js | 22 +-
server/src/index.js | 15 +-
server/src/invites.js | 89 ++++
.../src/migrations/076_profile_accounts.sql | 264 ++++++++++
server/src/pageMeta.js | 12 +-
server/src/routes/account.js | 333 +++++++++++++
server/src/routes/auth.js | 75 ++-
server/src/routes/blog.js | 2 +-
server/src/routes/content.js | 8 +-
server/src/routes/history.js | 2 +-
server/src/routes/home.js | 2 +-
server/src/routes/people.js | 6 +-
server/src/routes/profiles.js | 198 ++++++++
server/src/shape.js | 7 +-
src/App.tsx | 20 +-
src/components/Footer.tsx | 10 +-
src/components/GoogleLogo.tsx | 12 +
src/lib/adminSchema/people.ts | 14 +
src/lib/api.ts | 2 +-
src/lib/auth.tsx | 22 +-
src/lib/roles.ts | 19 +-
src/lib/useAccount.ts | 44 ++
src/pages/Account.tsx | 416 ++++++++++++++++
src/pages/AccountWelcome.tsx | 142 ++++++
src/pages/SignIn.tsx | 157 ++++++
src/pages/admin/AdminLogin.tsx | 14 +-
src/pages/admin/AdminProfiles.tsx | 450 ++++++++++++++++++
src/pages/admin/adminNav.ts | 6 +
34 files changed, 2483 insertions(+), 74 deletions(-)
create mode 100644 docs/profile-accounts.md
create mode 100644 server/src/discordAuth.js
create mode 100644 server/src/invites.js
create mode 100644 server/src/migrations/076_profile_accounts.sql
create mode 100644 server/src/routes/account.js
create mode 100644 server/src/routes/profiles.js
create mode 100644 src/components/GoogleLogo.tsx
create mode 100644 src/lib/useAccount.ts
create mode 100644 src/pages/Account.tsx
create mode 100644 src/pages/AccountWelcome.tsx
create mode 100644 src/pages/SignIn.tsx
create mode 100644 src/pages/admin/AdminProfiles.tsx
diff --git a/CLAUDE.md b/CLAUDE.md
index b8b9a67..c0b625b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -40,6 +40,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`.
+- Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at `/account`. Public reads of people go through the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`.
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`.
## Git workflow
@@ -67,7 +68,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
## Rules and gotchas
-- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
+- **Role checks must use ladder comparisons, never equality.** Roles rank member → viewer → editor → admin → superadmin (member is a profile account: the site and its own profile, never the admin; `/api/admin` needs viewer, `requireStaff`). Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `isStaff`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
- **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere.
- **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names.
- **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface.
diff --git a/docs/google-sign-in.md b/docs/google-sign-in.md
index 7c5f30a..c57fe90 100644
--- a/docs/google-sign-in.md
+++ b/docs/google-sign-in.md
@@ -6,12 +6,16 @@ off until the service has an OAuth client ID and secret.
## Who gets in
-Two kinds of account can sign in with Google:
+Three kinds of account can sign in with Google:
- **Group accounts**, when access groups are set up (below): anyone in
one of the site's Workspace groups. Their account is made at their
first sign-in, and their role follows the group.
- **Accounts made with admin-cli**, as before.
+- **Profile accounts** (members, `docs/profile-accounts.md`), invited
+ from Data → Profile accounts. These are the one case outside the
+ Workspace: any Google account under the invited email, from the
+ site's `/sign-in` page or the invite's welcome page.
Created with
`admin-cli.js add ` (the password it asks for stays as a way in
@@ -23,7 +27,8 @@ changes. `admin-cli.js list` shows which accounts are linked.
Refused, with a message on the login page: no admin account for that
email (and in no access group), an email already linked to a different Google account, a
disabled account, any account outside the Workspace domain (checked by
-Google's `hd` claim, not just the email), an unverified email.
+Google's `hd` claim, not just the email) unless it's a profile account's,
+an unverified email.
Code: `server/src/googleAuth.js` (the Google side),
`server/src/routes/auth.js` (matching and linking accounts) and
diff --git a/docs/profile-accounts.md b/docs/profile-accounts.md
new file mode 100644
index 0000000..28c3e30
--- /dev/null
+++ b/docs/profile-accounts.md
@@ -0,0 +1,78 @@
+# Profile accounts
+
+People can have an account on the site for their own profile (migration
+076). Nobody signs up: an admin invites them.
+
+## How it goes
+
+1. **Invite.** Data → Profile accounts → Invite someone (admins and up):
+ an email, and a name if you like. That makes a *member* account with
+ no password, and shows its invite link once, for 14 days. Copy it to
+ send yourself, or press Email invite to send a fresh one through
+ Gmail (needs Gmail set up, `docs/google-drive-and-mail.md`; the link
+ shown before stops working).
+2. **Sign up.** The link opens `/account/welcome`: they set a password,
+ or continue with Google under the invited email (any Google account,
+ not only @nextgenerationofunity.org, when Google sign-in is on,
+ `docs/google-sign-in.md`). Either takes up the invite.
+3. **Claim.** On `/account` (Your profile, also the footer's Sign in
+ link) they pick the People record that's them and send the request.
+ It waits under Claims on Data → Profile accounts until an admin
+ approves or declines it. An admin can also set an account's record
+ directly there.
+4. **Edit.** With a record, they edit its pronouns, tagline, location,
+ public email and phone, bio and photo, and tick what to hide on the
+ site. Their name, publishing and everything else stay the admin's.
+ Changes are live as soon as they save.
+
+A member is below viewer: signed in to the site, never to the admin
+(`/api/admin` refuses anything under viewer, `requireStaff` in
+`server/src/auth.js`). Staff accounts can claim a record too, from
+`/account`.
+
+Forgotten password: on the account's row, New sign-in link (or Email a
+sign-in link); opening it sets a new password.
+
+Turn off stops an account signing in and ends its sessions. Remove
+deletes the account; its People record stays.
+
+## What "hidden" does
+
+Each hidden part (photo, pronouns, tagline, bio, public email, public
+phone, location, links) stays in the record, and the admin's People
+editor shows the same switches (Hidden on the site). The site never
+shows it: every public read goes through the `v_people_public` view,
+which nulls hidden fields, and person links are left out when links are
+hidden (`loadLinks` in `server/src/shape.js`). When adding a public
+query on people, read `v_people_public`, not `people`.
+
+## Discord
+
+A profile can link its Discord account (the `identify` scope only: the
+Discord user id and name), kept for the gamification to come. Off until
+the service has a Discord application:
+
+1. https://discord.com/developers/applications → New Application.
+2. OAuth2 → Redirects: add `https://nextgenerationofunity.org/api/account/discord/callback`
+ (and the dev server's address, if you test there).
+3. Copy the Client ID and Client Secret into the service's environment
+ (`systemctl edit ngu-api`):
+
+ ```
+ [Service]
+ Environment=DISCORD_CLIENT_ID=...
+ Environment=DISCORD_CLIENT_SECRET=...
+ ```
+
+ `DISCORD_REDIRECT_URI` overrides the return address (default: site.json's
+ `url` plus `/api/account/discord/callback`).
+4. `systemctl restart ngu-api`.
+
+An admin can set or clear an account's Discord id by hand on its row
+(the long number from Discord: Developer Mode, then Copy User ID).
+
+Code: `server/src/invites.js`, `server/src/discordAuth.js`,
+`server/src/routes/account.js` (the member's own routes),
+`server/src/routes/profiles.js` (the admin's), `src/pages/Account.tsx`,
+`src/pages/AccountWelcome.tsx`, `src/pages/SignIn.tsx`,
+`src/pages/admin/AdminProfiles.tsx`.
diff --git a/server/src/admin-schema/people.js b/server/src/admin-schema/people.js
index 32a3b48..be4a011 100644
--- a/server/src/admin-schema/people.js
+++ b/server/src/admin-schema/people.js
@@ -42,6 +42,9 @@ export const people = {
text("location_label"),
bool("is_published"),
bool("is_listed"),
+ // What's taken off the site (076): its owner's choice on their
+ // profile, or an admin's. v_people_public applies it.
+ ...["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"].map((key) => bool(`hide_${key}`)),
],
extensions: [
diff --git a/server/src/auth.js b/server/src/auth.js
index f8972e6..6c688d6 100644
--- a/server/src/auth.js
+++ b/server/src/auth.js
@@ -219,14 +219,27 @@ export async function requireAuth(c, next) {
await next();
}
-export const ROLES = ["viewer", "editor", "admin", "superadmin"];
-const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
+/* member is a profile account (076): signed in to the site and their
+ own profile, below every admin role, so it passes no admin check.
+ /api/admin as a whole needs viewer (index.js, requireStaff). */
+export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"];
+const RANK = { member: 1, viewer: 2, editor: 3, admin: 4, superadmin: 5 };
/* Whether a user is at least this rank. A ladder, never equality. */
export function hasRole(user, role) {
return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity);
}
+/* Anyone who uses the admin: a signed-in account of viewer and up.
+ A profile account (member) is signed in but gets 403 here. */
+export async function requireStaff(c, next) {
+ const user = currentUser(c.get("db"), c);
+ if (!user) return c.json({ error: "Not signed in." }, 401);
+ if (!hasRole(user, "viewer")) return c.json({ error: "Not allowed." }, 403);
+ c.set("user", user);
+ await next();
+}
+
export function requireRole(...roles) {
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
return async (c, next) => {
diff --git a/server/src/discordAuth.js b/server/src/discordAuth.js
new file mode 100644
index 0000000..f0f3f6e
--- /dev/null
+++ b/server/src/discordAuth.js
@@ -0,0 +1,84 @@
+/* ═══════════════════════════════════════════════════════════════
+ DISCORD LINKING
+
+ A profile account links its Discord account (076): OAuth 2.0 with
+ the identify scope only, which gives the Discord user's id and
+ name and nothing else (no servers, no messages). The routes are in
+ routes/account.js; an admin can also set or clear it by hand
+ (routes/profiles.js). Kept for the gamification to come, which
+ matches Discord members to people by this id.
+
+ DISCORD_CLIENT_ID from the Discord developer portal
+ DISCORD_CLIENT_SECRET the same; never in the repo
+ DISCORD_REDIRECT_URI default /api/account/discord/callback
+
+ With no client id or secret it's off: the profile page doesn't
+ offer it and the routes answer 404. Setup: docs/profile-accounts.md.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { randomBytes } from "node:crypto";
+
+import { loadSite } from "./pageMeta.js";
+
+const AUTHORIZE = "https://discord.com/oauth2/authorize";
+const TOKEN = "https://discord.com/api/oauth2/token";
+const ME = "https://discord.com/api/users/@me";
+
+export function discordConfig() {
+ const clientId = process.env.DISCORD_CLIENT_ID;
+ const clientSecret = process.env.DISCORD_CLIENT_SECRET;
+ if (!clientId || !clientSecret) return null;
+
+ let redirectUri = process.env.DISCORD_REDIRECT_URI ?? null;
+ if (!redirectUri) {
+ try {
+ const origin = (loadSite().url ?? "").replace(/\/$/, "");
+ if (origin) redirectUri = `${origin}/api/account/discord/callback`;
+ } catch {
+ redirectUri = null;
+ }
+ }
+ return { clientId, clientSecret, redirectUri };
+}
+
+/* Where to send the browser, and the state to keep until it's back. */
+export function startLink(config) {
+ const state = randomBytes(24).toString("base64url");
+ const url = new URL(AUTHORIZE);
+ url.search = new URLSearchParams({
+ client_id: config.clientId,
+ redirect_uri: config.redirectUri,
+ response_type: "code",
+ scope: "identify",
+ state,
+ prompt: "consent",
+ });
+ return { url: url.toString(), state };
+}
+
+/* Trade the code for a token, then ask who it is. Returns
+ { id, name } or throws. */
+export async function finishLink(config, code) {
+ const res = await fetch(TOKEN, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ client_id: config.clientId,
+ client_secret: config.clientSecret,
+ grant_type: "authorization_code",
+ code,
+ redirect_uri: config.redirectUri,
+ }),
+ signal: AbortSignal.timeout(10_000),
+ });
+ const token = await res.json().catch(() => ({}));
+ if (!res.ok || !token.access_token) throw new Error(`Discord didn't accept the link (${res.status}).`);
+
+ const me = await fetch(ME, {
+ headers: { Authorization: `Bearer ${token.access_token}` },
+ signal: AbortSignal.timeout(10_000),
+ });
+ const user = await me.json().catch(() => ({}));
+ if (!me.ok || !user.id) throw new Error(`Discord didn't say who you are (${me.status}).`);
+ return { id: String(user.id), name: String(user.global_name || user.username || "").slice(0, 100) || null };
+}
diff --git a/server/src/googleAuth.js b/server/src/googleAuth.js
index 6baaedb..e77da0a 100644
--- a/server/src/googleAuth.js
+++ b/server/src/googleAuth.js
@@ -30,6 +30,12 @@
Nothing here creates an account. A Google login is only let in
if admin-cli has already made one for that email (see auth.js
routes), and is linked to it on first use.
+
+ Profile accounts (076) are the one case outside the domain: an
+ invited member may sign in with any Google account under the
+ invited email. finishLogin says whether the identity is in the
+ Workspace domain (inDomain) instead of refusing it, and the
+ callback lets an outside identity reach a member account only.
═══════════════════════════════════════════════════════════════ */
import { createHash, randomBytes } from "node:crypto";
@@ -70,8 +76,10 @@ export function googleConfig() {
}
/* The first leg: where to send the browser, and the state and PKCE
- verifier to keep (in a short-lived cookie) until it comes back. */
-export function startLogin(config) {
+ verifier to keep (in a short-lived cookie) until it comes back.
+ anyDomain: a profile account's sign-in, so the account chooser
+ isn't narrowed to the Workspace. */
+export function startLogin(config, { anyDomain = false } = {}) {
const state = base64url(randomBytes(24));
const verifier = base64url(randomBytes(48));
const challenge = base64url(createHash("sha256").update(verifier).digest());
@@ -87,7 +95,7 @@ export function startLogin(config) {
code_challenge_method: "S256",
// Only a hint to Google's account chooser; the hd claim is what's
// actually checked on the way back.
- hd: config.domain,
+ ...(anyDomain ? {} : { hd: config.domain }),
prompt: "select_account",
});
@@ -102,7 +110,7 @@ export class GoogleLoginError extends Error {
}
/* The second leg: trade the code for tokens and check the identity.
- Returns { sub, email, name } or throws GoogleLoginError. */
+ Returns { sub, email, name, inDomain } or throws GoogleLoginError. */
export async function finishLogin(config, code, verifier) {
let res;
try {
@@ -145,9 +153,7 @@ export async function finishLogin(config, code, verifier) {
if (!claims.email_verified || !email) {
throw new GoogleLoginError("unverified", "That Google account's email isn't verified.");
}
- if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) {
- throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`);
- }
+ const inDomain = String(claims.hd ?? "").toLowerCase() === config.domain && email.endsWith(`@${config.domain}`);
- return { sub: String(claims.sub), email, name: claims.name ?? null };
+ return { sub: String(claims.sub), email, name: claims.name ?? null, inDomain };
}
diff --git a/server/src/index.js b/server/src/index.js
index 7da8748..925c37c 100644
--- a/server/src/index.js
+++ b/server/src/index.js
@@ -32,6 +32,8 @@ import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
import auth from "./routes/auth.js";
+import account from "./routes/account.js";
+import profiles from "./routes/profiles.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
@@ -43,7 +45,7 @@ import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
-import { logSafe, startSessionSweeper } from "./auth.js";
+import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
@@ -134,7 +136,7 @@ app.use(
so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
-for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login"]) app.use(path, smallBody);
+for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */
@@ -206,9 +208,18 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,
// and Google has already checked the person by the second.
app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 }));
+// The whole admin is for viewer and up; a profile account (member)
+// is signed in but kept out. Each router still checks its own.
+app.use("/api/admin/*", requireStaff);
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
+// A profile account's own page (076); setting a password from an
+// invite is held to the login's pace.
+app.use("/api/account/accept", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
+app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
+app.route("/api/account", account);
app.route("/api/admin", admin);
+app.route("/api/admin", profiles);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);
diff --git a/server/src/invites.js b/server/src/invites.js
new file mode 100644
index 0000000..c3d66ab
--- /dev/null
+++ b/server/src/invites.js
@@ -0,0 +1,89 @@
+/* ═══════════════════════════════════════════════════════════════
+ INVITES: how a profile account (076) comes to exist
+
+ Nobody signs up. An admin adds an email (Data → Profile
+ accounts, routes/profiles.js), which makes a member account with
+ no password, and issues an invite: a link to /account/welcome
+ with a random token. The token itself is shown once, to the
+ admin, and emailed if they press Email invite; the database
+ keeps only its SHA-256, like a session's. Issuing a new one
+ replaces the old, so a link sent to the wrong place can be
+ killed by sending another.
+
+ The link lets its holder set a password (routes/account.js).
+ Signing in with Google under the invited email takes it up too
+ (routes/auth.js). Either way the token is cleared.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { createHash, randomBytes } from "node:crypto";
+
+import { loadSite } from "./pageMeta.js";
+import { mailReady, sendMail } from "./googleService.js";
+
+export const INVITE_DAYS = 14;
+
+const sha256 = (value) => createHash("sha256").update(value).digest("hex");
+
+/* A new invite for this account, replacing any before it. Returns
+ the link, which is never stored. */
+export function issueInvite(db, accountId, invitedBy) {
+ const token = randomBytes(32).toString("base64url");
+ db.prepare(
+ `UPDATE admin_users
+ SET invite_hash = ?, invite_expires_at = datetime('now', ?),
+ invited_at = datetime('now'), invited_by = ?
+ WHERE id = ?`,
+ ).run(sha256(token), `+${INVITE_DAYS} days`, invitedBy, accountId);
+ return inviteLink(token);
+}
+
+export function inviteLink(token) {
+ let origin = "";
+ try {
+ origin = (loadSite().url ?? "").replace(/\/$/, "");
+ } catch {
+ origin = "";
+ }
+ return `${origin}/account/welcome?token=${encodeURIComponent(token)}`;
+}
+
+/* The account an unexpired invite token belongs to, or null. */
+export function accountForInvite(db, token) {
+ if (typeof token !== "string" || token.length < 20 || token.length > 100) return null;
+ return (
+ db
+ .prepare(
+ `SELECT id, email, name, role, is_active
+ FROM admin_users
+ WHERE invite_hash = ? AND invite_expires_at > datetime('now') AND is_active = 1`,
+ )
+ .get(sha256(token)) ?? null
+ );
+}
+
+/* The invite as an email, through Gmail (googleService.js). */
+export async function emailInvite(db, account, link) {
+ if (!mailReady()) throw new Error("Gmail isn't set up on the server (docs/google-drive-and-mail.md).");
+ let site = { title: "Next Generation of Unity" };
+ try {
+ site = loadSite();
+ } catch {
+ // The default name will do.
+ }
+ const hello = account.name ? `Hi ${account.name},` : "Hi,";
+ await sendMail({
+ to: account.email,
+ subject: `Your ${site.title} profile`,
+ text: [
+ hello,
+ "",
+ `You're invited to make a profile account on the ${site.title} website. Open this link to set a password, or to sign in with Google under this email:`,
+ "",
+ link,
+ "",
+ `The link works once, for ${INVITE_DAYS} days. Once you're in, you can find your profile on the site, ask to claim it, and choose what of it shows.`,
+ "",
+ "If you weren't expecting this, you can ignore it.",
+ ].join("\n"),
+ });
+}
diff --git a/server/src/migrations/076_profile_accounts.sql b/server/src/migrations/076_profile_accounts.sql
new file mode 100644
index 0000000..ec2310a
--- /dev/null
+++ b/server/src/migrations/076_profile_accounts.sql
@@ -0,0 +1,264 @@
+-- ═══════════════════════════════════════════════════════════════
+-- 076 PROFILE ACCOUNTS
+--
+-- Accounts for people, not only for the admin. An admin invites an
+-- email (Data → Profile accounts); nobody signs up on their own. The
+-- invite's link lets them set a password, or they sign in with
+-- Google under that email, any Google account, not only
+-- @nextgenerationofunity.org. Then they claim their People record,
+-- an admin approves it, and they edit their profile and choose what
+-- of it shows.
+--
+-- admin_users is rebuilt (its CHECKs can't change in place):
+-- role takes 'member', below viewer: signs in to the
+-- site and their own profile, never to the admin
+-- access_source takes 'invite', an account made by an invite
+-- person_id the People record it claimed (one account each)
+-- invite_hash SHA-256 of the invite link's token, until used
+-- invite_expires_at, invited_at, invited_by
+-- discord_id, discord_name the linked Discord account, set by
+-- its owner through Discord or by an admin
+--
+-- person_claims: a request to be a People record, approved or
+-- declined by an admin.
+--
+-- people.hide_*: what its owner (or an admin) took off the site.
+-- The value stays, for the admin; v_people_public is the record as
+-- the site shows it, the hidden fields null, and every public read
+-- goes through it, the views below included.
+-- ═══════════════════════════════════════════════════════════════
+
+CREATE TABLE admin_users_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+
+ -- Stored lowercased. The application lowercases on every read
+ -- and write, so the UNIQUE index is genuinely case-insensitive
+ -- without depending on a collation.
+ email TEXT NOT NULL UNIQUE,
+ name TEXT,
+
+ -- Null for a Google-only account, or an invite not yet taken up.
+ -- A row with both can use either route in.
+ password_hash TEXT,
+
+ -- Google's stable subject id. Nullable, unique when present,
+ -- SQLite allows any number of NULLs in a unique index.
+ google_sub TEXT UNIQUE,
+
+ -- Listed low to high. The application treats these as a ladder,
+ -- not a set: each one passes every check the one below it
+ -- passes. The default stays 'admin' so no existing tooling
+ -- starts creating accounts with different powers than it did
+ -- yesterday.
+ --
+ -- member their own profile, on the site; no admin
+ -- viewer read the admin
+ -- editor + create and update
+ -- admin + delete, invite members, approve claims
+ -- superadmin + accounts, roles and sessions
+ role TEXT NOT NULL DEFAULT 'admin'
+ CHECK (role IN ('member', 'viewer', 'editor', 'admin', 'superadmin')),
+ is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
+ last_login_at TEXT,
+ access_source TEXT NOT NULL DEFAULT 'manual'
+ CHECK (access_source IN ('manual', 'group', 'invite')),
+ group_disabled INTEGER NOT NULL DEFAULT 0 CHECK (group_disabled IN (0, 1)),
+ groups_checked_at TEXT,
+
+ person_id TEXT UNIQUE REFERENCES people (id) ON DELETE SET NULL,
+ invite_hash TEXT UNIQUE,
+ invite_expires_at TEXT,
+ invited_at TEXT,
+ invited_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
+ discord_id TEXT UNIQUE,
+ discord_name TEXT
+) STRICT;
+
+INSERT INTO admin_users_new
+ (id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
+ access_source, group_disabled, groups_checked_at)
+SELECT id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
+ access_source, group_disabled, groups_checked_at
+ FROM admin_users;
+
+-- sessions, media, clip_jobs and drive_files name admin_users;
+-- legacy mode leaves them alone through the rename.
+PRAGMA legacy_alter_table = ON;
+DROP TABLE admin_users;
+ALTER TABLE admin_users_new RENAME TO admin_users;
+PRAGMA legacy_alter_table = OFF;
+
+CREATE TABLE person_claims (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ account_id INTEGER NOT NULL REFERENCES admin_users (id) ON DELETE CASCADE,
+ person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
+ message TEXT,
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'approved', 'declined')),
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ decided_at TEXT,
+ decided_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL
+) STRICT;
+CREATE INDEX person_claims_status_idx ON person_claims (status, created_at);
+CREATE INDEX person_claims_account_idx ON person_claims (account_id);
+-- One open request per account.
+CREATE UNIQUE INDEX person_claims_one_pending ON person_claims (account_id) WHERE status = 'pending';
+
+ALTER TABLE people ADD COLUMN hide_photo INTEGER NOT NULL DEFAULT 0 CHECK (hide_photo IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_pronouns INTEGER NOT NULL DEFAULT 0 CHECK (hide_pronouns IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_tagline INTEGER NOT NULL DEFAULT 0 CHECK (hide_tagline IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_bio INTEGER NOT NULL DEFAULT 0 CHECK (hide_bio IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_email INTEGER NOT NULL DEFAULT 0 CHECK (hide_email IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_phone INTEGER NOT NULL DEFAULT 0 CHECK (hide_phone IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_location INTEGER NOT NULL DEFAULT 0 CHECK (hide_location IN (0, 1));
+ALTER TABLE people ADD COLUMN hide_links INTEGER NOT NULL DEFAULT 0 CHECK (hide_links IN (0, 1));
+
+-- A person as the site shows them. Every public read uses this, not
+-- people; the admin reads people.
+CREATE VIEW v_people_public AS
+SELECT
+ id,
+ display_name,
+ sort_name,
+ CASE WHEN hide_pronouns = 0 THEN pronouns END AS pronouns,
+ CASE WHEN hide_tagline = 0 THEN tagline END AS tagline,
+ CASE WHEN hide_photo = 0 THEN photo END AS photo,
+ CASE WHEN hide_email = 0 THEN public_email END AS public_email,
+ CASE WHEN hide_phone = 0 THEN public_phone END AS public_phone,
+ CASE WHEN hide_location = 0 THEN locality END AS locality,
+ CASE WHEN hide_location = 0 THEN state_code END AS state_code,
+ country,
+ CASE WHEN hide_location = 0 THEN location_label END AS location_label,
+ is_published,
+ created_at,
+ updated_at,
+ CASE WHEN hide_bio = 0 THEN bio END AS bio,
+ primary_org_id,
+ is_listed,
+ specialty,
+ hide_links
+FROM people;
+
+-- The views that read people's public fields, over v_people_public.
+
+DROP VIEW v_event_people;
+CREATE VIEW v_event_people AS
+SELECT
+ ep.event_id, ep.person_id, ep.role, ep.title, ep.sort_order,
+ p.display_name, p.pronouns, p.tagline, p.photo
+FROM event_people ep
+JOIN v_people_public p ON p.id = ep.person_id AND p.is_published = 1
+WHERE ep.is_public = 1;
+
+DROP VIEW v_timeline;
+CREATE VIEW v_timeline AS
+SELECT
+ t.id,
+ t.kind,
+ t.ref_kind,
+ t.ref_id,
+ t.precision,
+ t.is_featured,
+ t.is_published,
+ t.sort_order,
+
+ COALESCE(t.occurred_on, e.starts_on, pa.awarded_on) AS effective_date,
+
+ COALESCE(
+ t.title,
+ e.title,
+ o.name,
+ aw.name,
+ p.display_name,
+ tm.name
+ ) AS effective_title,
+
+ COALESCE(t.blurb, e.tagline, o.tagline, aw.description, p.tagline, tm.tagline)
+ AS effective_blurb,
+ t.meta,
+ t.link_url,
+
+ -- Filename only. The directory is the frontend's business.
+ COALESCE(e.event_logo, e.org_logo, o.logo, aw.logo, p.photo, tm.logo)
+ AS effective_logo,
+
+ o.kind AS org_kind,
+ tm.org_id AS team_org_id,
+ tm.name AS team_name,
+
+ -- Whether the referenced record is itself visible. An entry must not
+ -- outlive the thing it points at being unpublished, a draft event
+ -- would otherwise leak its title and date onto a public page. Null
+ -- for a standalone milestone, which answers to nothing but its own
+ -- is_published.
+ CASE t.ref_kind
+ WHEN 'event' THEN e.is_published
+ WHEN 'organization' THEN o.is_published
+ WHEN 'person' THEN p.is_published
+ WHEN 'team' THEN tm.is_published
+ ELSE NULL
+ END AS ref_is_published,
+ t.occurred_on,
+ t.title AS title_override
+FROM timeline_entries t
+LEFT JOIN events e ON t.ref_kind = 'event' AND e.id = t.ref_id
+LEFT JOIN organizations o ON t.ref_kind = 'organization' AND o.id = t.ref_id
+LEFT JOIN awards aw ON t.ref_kind = 'award' AND aw.id = t.ref_id
+LEFT JOIN v_people_public p ON t.ref_kind = 'person' AND p.id = t.ref_id
+LEFT JOIN teams tm ON t.ref_kind = 'team' AND tm.id = t.ref_id
+LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.ref_id
+ AND pa.id = (SELECT MIN(id) FROM person_awards
+ WHERE award_id = t.ref_id);
+
+DROP VIEW v_org_leadership;
+CREATE VIEW v_org_leadership AS
+SELECT
+ a.org_id,
+ a.team_id,
+ t.name AS team_name,
+ t.sort_order AS team_sort_order,
+ a.person_id,
+ a.title,
+ a.role,
+ a.is_owner,
+ a.sort_order,
+ p.display_name,
+ p.sort_name,
+ p.pronouns,
+ p.tagline,
+ p.photo,
+ p.public_email,
+ p.location_label,
+ p.bio,
+ o.id AS primary_org_id,
+ o.name AS primary_org_name
+FROM affiliations a
+JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
+LEFT JOIN teams t ON t.id = a.team_id
+LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
+WHERE a.is_public = 1
+ AND a.ended_on IS NULL
+ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;
+
+DROP VIEW v_event_hosts;
+CREATE VIEW v_event_hosts AS
+SELECT
+ eh.id,
+ eh.event_id,
+ eh.sort_order,
+ CASE WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
+ AS host_kind,
+ COALESCE(eh.org_id, eh.person_id) AS host_id,
+ COALESCE(o.name, p.display_name) AS host_name,
+ o.kind AS host_org_kind,
+ o.logo AS host_logo,
+ o.color AS host_color,
+ p.photo AS host_photo,
+ COALESCE(o.is_published, p.is_published) AS host_is_published,
+ t.id AS host_team_id,
+ t.name AS host_team_name
+FROM event_hosts eh
+LEFT JOIN organizations o ON o.id = eh.org_id
+LEFT JOIN v_people_public p ON p.id = eh.person_id
+LEFT JOIN teams t ON t.id = eh.team_id AND eh.org_id IS NOT NULL AND t.is_published = 1;
diff --git a/server/src/pageMeta.js b/server/src/pageMeta.js
index 5cc3139..464cacc 100644
--- a/server/src/pageMeta.js
+++ b/server/src/pageMeta.js
@@ -302,7 +302,7 @@ function awardMeta(site, db, id, meta) {
}
function personMeta(site, db, id, meta) {
- const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
+ const row = db.prepare(`SELECT * FROM v_people_public WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
@@ -332,7 +332,7 @@ function blogMeta(site, db, id, meta) {
.prepare(
`SELECT p.display_name AS name
FROM blog_post_authors a
- JOIN people p ON p.id = a.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id = ? ORDER BY a.sort_order`,
)
.all(id)
@@ -364,6 +364,10 @@ function blogMeta(site, db, id, meta) {
};
}
+/* The profile account pages and their titles (src/pages/SignIn.tsx,
+ Account.tsx, AccountWelcome.tsx say the same). */
+const ACCOUNT_PAGES = { "/sign-in": "Sign in", "/account": "Your profile", "/account/welcome": "Welcome" };
+
/* The metadata for one request path, for this visitor (the signed-in
user or null, who decides whether a hidden page is there). */
export function metaFor(db, rawPath, user = null) {
@@ -402,6 +406,10 @@ export function metaFor(db, rawPath, user = null) {
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
+ // A profile account's pages (076): there for anyone, about no one
+ // in particular, so never indexed or in the sitemap.
+ if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
+
const page = site.pages?.[pathname];
if (page && hiddenFrom(db, user, pathname)) return notFound(meta);
if (page) {
diff --git a/server/src/routes/account.js b/server/src/routes/account.js
new file mode 100644
index 0000000..af3d754
--- /dev/null
+++ b/server/src/routes/account.js
@@ -0,0 +1,333 @@
+/* ═══════════════════════════════════════════════════════════════
+ ACCOUNT ROUTES: a profile account's own page (076), mounted
+ under /api/account
+
+ GET /invite?token= who an invite link is for (welcome page)
+ POST /accept { token, password }: set the password,
+ sign in, take up the invite
+ GET / me: the account, my person (as I edit
+ it), my claim, Discord
+ GET /people the People records I could claim
+ POST /claim { person_id, message }: ask to be one
+ DELETE /claim take back the open request
+ PATCH /profile my person's text and what of it shows
+ POST /photo my person's photo (multipart, `file`)
+ GET /discord off to Discord to link it
+ GET /discord/callback back from it
+ DELETE /discord unlink it
+
+ Every route but the first two needs a session; any role will do,
+ so an admin with a claimed record has a profile too. Only the
+ account's own person is ever written, and only the fields in
+ PROFILE_FIELDS: name, published and listed stay the admin's.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { Hono } from "hono";
+import { bodyLimit } from "hono/body-limit";
+import { deleteCookie, getCookie, setCookie } from "hono/cookie";
+
+import { SECURE_COOKIE, createSession, currentUser, hashPassword } from "../auth.js";
+import { accountForInvite } from "../invites.js";
+import { discordConfig, finishLink, startLink } from "../discordAuth.js";
+import { googleConfig } from "../googleAuth.js";
+import { MAX_UPLOAD_BYTES, MediaError, publicPath } from "../media.js";
+import { addToLibrary } from "./media.js";
+import { NO_STORE } from "../shape.js";
+
+const account = new Hono();
+
+const MIN_PASSWORD = 12;
+
+/* What an owner edits on their own record, and its longest. */
+const PROFILE_FIELDS = {
+ pronouns: 40,
+ tagline: 160,
+ bio: 4000,
+ public_email: 254,
+ public_phone: 40,
+ location_label: 120,
+};
+
+/* What an owner can take off the site (people.hide_*). */
+export const HIDE_FIELDS = ["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"];
+
+async function body(c) {
+ try {
+ return (await c.req.json()) ?? {};
+ } catch {
+ return null;
+ }
+}
+
+/* ── Invites ─────────────────────────────────────────────────── */
+
+account.get("/invite", (c) => {
+ const invited = accountForInvite(c.get("db"), c.req.query("token"));
+ if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404, NO_STORE);
+ return c.json({ invite: { email: invited.email, name: invited.name, google: Boolean(googleConfig()) } }, 200, NO_STORE);
+});
+
+account.post("/accept", async (c) => {
+ const data = await body(c);
+ if (!data) return c.json({ error: "Expected a JSON body." }, 400);
+
+ const db = c.get("db");
+ const invited = accountForInvite(db, data.token);
+ if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404);
+
+ const password = String(data.password ?? "");
+ if (password.length < MIN_PASSWORD) {
+ return c.json({ error: `Use at least ${MIN_PASSWORD} characters.`, fields: { password: "Too short." } }, 422);
+ }
+ if (password.length > 200) return c.json({ error: "That password is too long." }, 422);
+
+ db.prepare(
+ `UPDATE admin_users
+ SET password_hash = ?, invite_hash = NULL, invite_expires_at = NULL, last_login_at = datetime('now')
+ WHERE id = ?`,
+ ).run(hashPassword(password), invited.id);
+ createSession(db, c, invited.id);
+ console.log(`invite taken up by ${invited.email}`);
+
+ return c.json({ user: { id: invited.id, email: invited.email, name: invited.name, role: invited.role } }, 200, NO_STORE);
+});
+
+/* ── Signed in from here ─────────────────────────────────────── */
+
+account.use("*", async (c, next) => {
+ const path = c.req.path;
+ if (path.endsWith("/invite") || path.endsWith("/accept")) return next();
+ const user = currentUser(c.get("db"), c);
+ if (!user) return c.json({ error: "Not signed in." }, 401, NO_STORE);
+ c.set("user", user);
+ await next();
+});
+
+/* My person as I edit it: the stored values, not the public view,
+ with what's hidden said separately. */
+function myPerson(db, accountId) {
+ const row = db
+ .prepare(
+ `SELECT p.* FROM people p JOIN admin_users u ON u.person_id = p.id WHERE u.id = ?`,
+ )
+ .get(accountId);
+ if (!row) return null;
+ return {
+ id: row.id,
+ display_name: row.display_name,
+ is_published: row.is_published === 1,
+ photo: row.photo,
+ ...Object.fromEntries(Object.keys(PROFILE_FIELDS).map((key) => [key, row[key]])),
+ hidden: Object.fromEntries(HIDE_FIELDS.map((key) => [key, row[`hide_${key}`] === 1])),
+ };
+}
+
+account.get("/", (c) => {
+ const db = c.get("db");
+ const user = c.get("user");
+ const row = db.prepare(`SELECT discord_id, discord_name FROM admin_users WHERE id = ?`).get(user.id);
+ const claim = db
+ .prepare(
+ `SELECT c.id, c.person_id, p.display_name, c.status, c.created_at, c.decided_at
+ FROM person_claims c JOIN people p ON p.id = c.person_id
+ WHERE c.account_id = ? ORDER BY c.id DESC LIMIT 1`,
+ )
+ .get(user.id);
+
+ return c.json(
+ {
+ account: {
+ user,
+ person: myPerson(db, user.id),
+ claim: claim ?? null,
+ discord: { enabled: Boolean(discordConfig()), id: row?.discord_id ?? null, name: row?.discord_name ?? null },
+ },
+ },
+ 200,
+ NO_STORE,
+ );
+});
+
+/* Published records nobody has claimed, to pick from. */
+account.get("/people", (c) => {
+ const people = c
+ .get("db")
+ .prepare(
+ `SELECT p.id, p.display_name AS name
+ FROM people p
+ WHERE p.is_published = 1
+ AND NOT EXISTS (SELECT 1 FROM admin_users u WHERE u.person_id = p.id)
+ ORDER BY COALESCE(p.sort_name, p.display_name)`,
+ )
+ .all();
+ return c.json({ people }, 200, NO_STORE);
+});
+
+account.post("/claim", async (c) => {
+ const data = await body(c);
+ if (!data) return c.json({ error: "Expected a JSON body." }, 400);
+ const db = c.get("db");
+ const user = c.get("user");
+
+ if (db.prepare(`SELECT person_id FROM admin_users WHERE id = ?`).get(user.id)?.person_id) {
+ return c.json({ error: "Your account already has a profile." }, 409);
+ }
+ const personId = String(data.person_id ?? "");
+ const person = db.prepare(`SELECT id FROM people WHERE id = ? AND is_published = 1`).get(personId);
+ if (!person) return c.json({ error: "Pick a person from the list.", fields: { person_id: "Pick one." } }, 422);
+ if (db.prepare(`SELECT 1 FROM admin_users WHERE person_id = ?`).get(personId)) {
+ return c.json({ error: "Someone has already claimed that profile." }, 409);
+ }
+
+ const message = String(data.message ?? "").trim().slice(0, 1000) || null;
+ try {
+ db.prepare(`INSERT INTO person_claims (account_id, person_id, message) VALUES (?, ?, ?)`).run(
+ user.id,
+ personId,
+ message,
+ );
+ } catch (err) {
+ if (/UNIQUE/.test(err.message)) return c.json({ error: "You already have a request waiting." }, 409);
+ throw err;
+ }
+ console.log(`claim: ${user.email} asked for ${personId}`);
+ return c.body(null, 204);
+});
+
+account.delete("/claim", (c) => {
+ c.get("db")
+ .prepare(`DELETE FROM person_claims WHERE account_id = ? AND status = 'pending'`)
+ .run(c.get("user").id);
+ return c.body(null, 204);
+});
+
+account.patch("/profile", async (c) => {
+ const data = await body(c);
+ if (!data) return c.json({ error: "Expected a JSON body." }, 400);
+ const db = c.get("db");
+ const person = myPerson(db, c.get("user").id);
+ if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
+
+ const sets = [];
+ const values = [];
+ const fields = {};
+ for (const [key, max] of Object.entries(PROFILE_FIELDS)) {
+ if (!(key in data)) continue;
+ const value = data[key] == null ? "" : String(data[key]).trim();
+ if (value.length > max) fields[key] = `Up to ${max} characters.`;
+ sets.push(`${key} = ?`);
+ values.push(value || null);
+ }
+ if (data.public_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(data.public_email).trim())) {
+ fields.public_email = "That doesn't look like an email address.";
+ }
+ if (Object.keys(fields).length) return c.json({ error: "Check the highlighted fields.", fields }, 422);
+
+ for (const key of HIDE_FIELDS) {
+ if (data.hidden && key in data.hidden) {
+ sets.push(`hide_${key} = ?`);
+ values.push(data.hidden[key] ? 1 : 0);
+ }
+ }
+ if (sets.length) {
+ db.prepare(`UPDATE people SET ${sets.join(", ")}, updated_at = datetime('now') WHERE id = ?`).run(
+ ...values,
+ person.id,
+ );
+ console.log(`profile ${person.id} updated by ${c.get("user").email}`);
+ }
+ return c.json({ person: myPerson(db, c.get("user").id) }, 200, NO_STORE);
+});
+
+account.post(
+ "/photo",
+ bodyLimit({ maxSize: MAX_UPLOAD_BYTES + 64 * 1024, onError: (c) => c.json({ error: "That file is too large." }, 413) }),
+ async (c) => {
+ const db = c.get("db");
+ const user = c.get("user");
+ const person = myPerson(db, user.id);
+ if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
+
+ let form;
+ try {
+ form = await c.req.parseBody();
+ } catch {
+ return c.json({ error: "Expected a file upload." }, 400);
+ }
+ const file = form.file;
+ if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
+ if (!/^image\/(jpeg|png|webp)$/.test(file.type)) {
+ return c.json({ error: "Use a JPEG, PNG or WebP photo." }, 415);
+ }
+
+ let row;
+ try {
+ row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
+ originalName: person.display_name,
+ folder: "images",
+ userId: user.id,
+ });
+ } catch (err) {
+ if (err instanceof MediaError) return c.json({ error: err.message }, err.status ?? 422);
+ throw err;
+ }
+ db.prepare(`UPDATE people SET photo = ?, updated_at = datetime('now') WHERE id = ?`).run(
+ publicPath(row.filename),
+ person.id,
+ );
+ console.log(`profile ${person.id} photo ${row.filename} by ${user.email}`);
+ return c.json({ person: myPerson(db, user.id) }, 200, NO_STORE);
+ },
+);
+
+/* ── Discord ─────────────────────────────────────────────────── */
+
+const DISCORD_COOKIE = SECURE_COOKIE ? "__Host-site_discord" : "site_discord";
+const DISCORD_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, sameSite: "Lax", path: "/" };
+const backToAccount = (c, result) => c.redirect(`/account?discord=${encodeURIComponent(result)}`, 302);
+
+account.get("/discord", (c) => {
+ const config = discordConfig();
+ if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
+ if (!config.redirectUri) {
+ console.error("discord link: no return address. Set DISCORD_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.");
+ return backToAccount(c, "failed");
+ }
+ const { url, state } = startLink(config);
+ setCookie(c, DISCORD_COOKIE, state, { ...DISCORD_COOKIE_OPTIONS, maxAge: 600 });
+ return c.redirect(url, 302);
+});
+
+account.get("/discord/callback", async (c) => {
+ const config = discordConfig();
+ if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
+ const state = getCookie(c, DISCORD_COOKIE);
+ deleteCookie(c, DISCORD_COOKIE, DISCORD_COOKIE_OPTIONS);
+
+ if (c.req.query("error")) return backToAccount(c, "canceled");
+ const code = c.req.query("code");
+ if (!state || !code || c.req.query("state") !== state) return backToAccount(c, "expired");
+
+ let who;
+ try {
+ who = await finishLink(config, code);
+ } catch (err) {
+ console.warn(`discord link failed: ${err.message}`);
+ return backToAccount(c, "failed");
+ }
+
+ const db = c.get("db");
+ const user = c.get("user");
+ const taken = db.prepare(`SELECT id FROM admin_users WHERE discord_id = ? AND id <> ?`).get(who.id, user.id);
+ if (taken) return backToAccount(c, "taken");
+ db.prepare(`UPDATE admin_users SET discord_id = ?, discord_name = ? WHERE id = ?`).run(who.id, who.name, user.id);
+ console.log(`discord ${who.id} linked to ${user.email}`);
+ return backToAccount(c, "linked");
+});
+
+account.delete("/discord", (c) => {
+ c.get("db").prepare(`UPDATE admin_users SET discord_id = NULL, discord_name = NULL WHERE id = ?`).run(c.get("user").id);
+ return c.body(null, 204);
+});
+
+export default account;
diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js
index 157c0f6..0cd3c5e 100644
--- a/server/src/routes/auth.js
+++ b/server/src/routes/auth.js
@@ -5,7 +5,9 @@
POST /api/auth/logout deletes the session row and cookie
GET /api/auth/me who am I, or 401
GET /api/auth/providers which ways in are switched on
- GET /api/auth/google off to Google's account chooser
+ GET /api/auth/google off to Google's account chooser;
+ ?for=account from the site's sign-in
+ page (any Google account, back there)
GET /api/auth/google/callback back from it: sign in, or
back to the login page with ?error=
@@ -27,6 +29,11 @@
email, which then links it. A matching email already linked to a
different Google account is refused rather than relinked.
googleAuth.js checks the identity itself.
+
+ Profile accounts (076) are made by an admin's invite
+ (routes/profiles.js). One may sign in with a Google account
+ outside the Workspace, under the invited email; an outside
+ identity reaches nothing else. Signing in takes up the invite.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
@@ -153,7 +160,11 @@ const OAUTH_COOKIE_OPTIONS = {
const safeNext = (value) =>
typeof value === "string" && /^\/admin(\/[\w\-/]*)?$/.test(value) ? value : "/admin/home";
-const backToLogin = (c, code) => c.redirect(`/admin/login?error=${encodeURIComponent(code)}`, 302);
+// The page a sign-in started from: the admin's, or the site's
+// (/sign-in, for profile accounts) when `from` is 'account'.
+const SIGN_IN_PAGES = { admin: "/admin/login", account: "/sign-in" };
+const backToLogin = (c, code, from = "admin") =>
+ c.redirect(`${SIGN_IN_PAGES[from] ?? SIGN_IN_PAGES.admin}?error=${encodeURIComponent(code)}`, 302);
auth.get("/providers", (c) =>
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
@@ -162,17 +173,18 @@ auth.get("/providers", (c) =>
auth.get("/google", (c) => {
const config = googleConfig();
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
+ const from = c.req.query("for") === "account" ? "account" : "admin";
if (!config.redirectUri) {
// Said in the log, where whoever runs the box will look; the
// person at the login page just learns it didn't work.
console.error(
"google login: no return address. Set GOOGLE_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.",
);
- return backToLogin(c, "google_failed");
+ return backToLogin(c, "google_failed", from);
}
- const { url, state, verifier } = startLogin(config);
- setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
+ const { url, state, verifier } = startLogin(config, { anyDomain: from === "account" });
+ setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, from, next: safeNext(c.req.query("next")) }), {
...OAUTH_COOKIE_OPTIONS,
maxAge: 600,
});
@@ -190,13 +202,15 @@ auth.get("/google/callback", async (c) => {
saved = null;
}
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
+ const from = saved?.from === "account" ? "account" : "admin";
+ const back = (code) => backToLogin(c, code, from);
// Pressing Cancel on Google's screen comes back as ?error=.
- if (c.req.query("error")) return backToLogin(c, "canceled");
+ if (c.req.query("error")) return back("canceled");
const code = c.req.query("code");
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
- return backToLogin(c, "expired");
+ return back("expired");
}
let identity;
@@ -205,7 +219,7 @@ auth.get("/google/callback", async (c) => {
} catch (err) {
if (err instanceof GoogleLoginError) {
console.warn(`google login refused: ${err.code}`);
- return backToLogin(c, err.code);
+ return back(err.code);
}
throw err;
}
@@ -215,6 +229,20 @@ auth.get("/google/callback", async (c) => {
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
+ // From outside the Workspace, only a profile account: by its
+ // linked Google id, or its invited email.
+ if (!identity.inDomain) {
+ user ??= db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
+ if (!user || user.role !== "member") {
+ console.warn(`google login: ${identity.email} is outside the Workspace and has no profile account`);
+ return back(user ? "wrong_domain" : "no_account");
+ }
+ if (user.google_sub && user.google_sub !== identity.sub) {
+ console.warn(`google login: ${identity.email} is linked to another Google account`);
+ return back("linked_elsewhere");
+ }
+ }
+
// What the access groups give this person (accessGroups.js), asked
// only when it matters. Unanswerable is a refusal: a sign-in has to
// be shown to be allowed.
@@ -232,14 +260,14 @@ auth.get("/google/callback", async (c) => {
if (!byEmail) {
if (!accessEnabled(db)) {
console.warn(`google login: no account for ${identity.email}`);
- return backToLogin(c, "no_account");
+ return back("no_account");
}
// In an access group: the account is made now, Google only.
const found = await roleFromGroups();
- if (found.failed) return backToLogin(c, "groups_unreachable");
+ if (found.failed) return back("groups_unreachable");
if (!found.role) {
console.warn(`google login: ${identity.email} is in no access group`);
- return backToLogin(c, "not_in_group");
+ return back("not_in_group");
}
const id = db
.prepare(
@@ -251,10 +279,10 @@ auth.get("/google/callback", async (c) => {
user = byId(id);
} else if (byEmail.google_sub) {
console.warn(`google login: ${identity.email} is linked to another Google account`);
- return backToLogin(c, "linked_elsewhere");
+ return back("linked_elsewhere");
} else {
// Before linking: a refused sign-in mustn't change the account.
- if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
+ if (byEmail.is_active !== 1) return back("disabled");
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
console.log(`google account linked to ${byEmail.email}`);
user = byEmail;
@@ -266,23 +294,30 @@ auth.get("/google/callback", async (c) => {
// and with access groups switched off none gets in (it can't be
// rechecked, so it would keep its last role for good).
if (user.access_source === "group" && user.role !== "superadmin") {
- if (!accessEnabled(db)) return backToLogin(c, "not_in_group");
- if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
+ if (!accessEnabled(db)) return back("not_in_group");
+ if (user.is_active !== 1 && user.group_disabled !== 1) return back("disabled");
const found = await roleFromGroups();
- if (found.failed) return backToLogin(c, "groups_unreachable");
+ if (found.failed) return back("groups_unreachable");
applyGroupRole(db, user, found.role);
- if (!found.role) return backToLogin(c, "not_in_group");
+ if (!found.role) return back("not_in_group");
user = byId(user.id);
}
- if (user.is_active !== 1) return backToLogin(c, "disabled");
+ if (user.is_active !== 1) return back("disabled");
createSession(db, c, user.id);
+ // The invite is taken up: its link stops working.
db.prepare(
- `UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
- ).run(identity.name, user.id);
+ `UPDATE admin_users
+ SET last_login_at = datetime('now'), name = COALESCE(name, ?), google_sub = COALESCE(google_sub, ?),
+ invite_hash = NULL, invite_expires_at = NULL
+ WHERE id = ?`,
+ ).run(identity.name, identity.sub, user.id);
console.log(`login ${user.email} (google)`);
+ // A profile account, or a sign-in from the site, goes to the
+ // profile page; the admin's goes back where it was headed.
+ if (user.role === "member" || from === "account") return c.redirect("/account", 302);
// Checked again: the cookie came back from the browser.
return c.redirect(safeNext(saved.next), 302);
});
diff --git a/server/src/routes/blog.js b/server/src/routes/blog.js
index 0b437ea..f02799b 100644
--- a/server/src/routes/blog.js
+++ b/server/src/routes/blog.js
@@ -45,7 +45,7 @@ function loadAuthors(db, ids) {
.prepare(
`SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo
FROM blog_post_authors a
- JOIN people p ON p.id = a.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id IN (${marks(ids.length)})
ORDER BY a.post_id, a.sort_order`,
)
diff --git a/server/src/routes/content.js b/server/src/routes/content.js
index f95a4bb..3191e17 100644
--- a/server/src/routes/content.js
+++ b/server/src/routes/content.js
@@ -437,7 +437,7 @@ function attachAwards(db, orgs) {
`SELECT a.id, a.org_id, a.name, a.description, a.logo,
(SELECT COUNT(*)
FROM person_awards pa
- JOIN people p ON p.id = pa.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a
WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 AND a.is_listed = 1
@@ -579,7 +579,7 @@ content.get("/events/:id", (c) => {
pa.person_id, p.display_name, p.photo
FROM person_awards pa
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
- JOIN people p ON p.id = pa.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.event_id = ? AND pa.is_public = 1
ORDER BY a.sort_order, a.name, COALESCE(p.sort_name, p.display_name)`,
)
@@ -774,7 +774,7 @@ content.get("/awards", (c) => {
`SELECT a.*, o.name AS org_name, o.kind AS org_kind,
(SELECT COUNT(*)
FROM person_awards pa
- JOIN people p ON p.id = pa.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
FROM awards a
LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1
@@ -818,7 +818,7 @@ content.get("/awards/:id", (c) => {
p.display_name, p.photo, p.tagline,
e.id AS event_id, e.title AS event_title
FROM person_awards pa
- JOIN people p ON p.id = pa.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
LEFT JOIN events e ON e.id = pa.event_id AND e.is_published = 1
WHERE pa.award_id = ? AND pa.is_public = 1
ORDER BY pa.awarded_on DESC, COALESCE(p.sort_name, p.display_name)`,
diff --git a/server/src/routes/history.js b/server/src/routes/history.js
index c94208a..289ea87 100644
--- a/server/src/routes/history.js
+++ b/server/src/routes/history.js
@@ -188,7 +188,7 @@ function loadRosters(db, rows) {
`SELECT tep.entry_id, tep.person_id, tep.note,
p.display_name, p.photo
FROM timeline_entry_people tep
- JOIN people p ON p.id = tep.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = tep.person_id AND p.is_published = 1
WHERE tep.entry_id IN (${marks(ids.length)})
ORDER BY tep.entry_id, tep.sort_order`,
)
diff --git a/server/src/routes/home.js b/server/src/routes/home.js
index 1c5b1c5..523f369 100644
--- a/server/src/routes/home.js
+++ b/server/src/routes/home.js
@@ -66,7 +66,7 @@ const STAT_QUERIES = {
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
awards_given: `SELECT COUNT(*) AS n
FROM person_awards pa
- JOIN people p ON p.id = pa.person_id AND p.is_published = 1
+ JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
WHERE pa.is_public = 1`,
};
diff --git a/server/src/routes/people.js b/server/src/routes/people.js
index c8172c8..072572c 100644
--- a/server/src/routes/people.js
+++ b/server/src/routes/people.js
@@ -129,7 +129,7 @@ people.get("/people", (c) => {
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
- FROM people p
+ FROM v_people_public p
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id IN (${marks(ids.length)})
AND p.is_published = 1`,
@@ -167,7 +167,7 @@ people.get("/directories/:tag", (c) => {
o.id AS primary_org_id,
o.name AS primary_org_name
FROM person_tags t
- JOIN people p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1
+ JOIN v_people_public p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE t.tag_id = ?
ORDER BY COALESCE(p.sort_name, p.display_name)`,
@@ -221,7 +221,7 @@ people.get("/people/:id", (c) => {
o.id AS primary_org_id,
o.name AS primary_org_name,
o.kind AS primary_org_kind
- FROM people p
+ FROM v_people_public p
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE p.id = ? AND p.is_published = 1`,
)
diff --git a/server/src/routes/profiles.js b/server/src/routes/profiles.js
new file mode 100644
index 0000000..480a147
--- /dev/null
+++ b/server/src/routes/profiles.js
@@ -0,0 +1,198 @@
+/* ═══════════════════════════════════════════════════════════════
+ PROFILE ACCOUNT ROUTES (076): Data → Profile accounts, mounted
+ under /api/admin, admins and up
+
+ GET /profiles every profile account, and the
+ claims waiting
+ POST /profiles { email, name }: a new account,
+ invited (its link comes back)
+ POST /profiles/:id/invite a new link, replacing the old;
+ { email: true } also emails it
+ PATCH /profiles/:id { person_id, discord_id,
+ discord_name, is_active }: an
+ admin's own say
+ DELETE /profiles/:id remove the account
+ POST /profiles/claims/:id/approve the request's person is theirs
+ POST /profiles/claims/:id/decline
+
+ Only member accounts are listed or changed here. The admin roles
+ are the Panel's (superadmins), so an admin can't make or touch
+ another admin from this page.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { Hono } from "hono";
+
+import { destroyAllSessionsFor, logSafe, requireRole } from "../auth.js";
+import { tx } from "../db.js";
+import { emailInvite, issueInvite } from "../invites.js";
+import { mailReady } from "../googleService.js";
+import { NO_STORE } from "../shape.js";
+
+const profiles = new Hono();
+
+profiles.use("/profiles", requireRole("admin"));
+profiles.use("/profiles/*", requireRole("admin"));
+
+const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+async function body(c) {
+ try {
+ return (await c.req.json()) ?? {};
+ } catch {
+ return null;
+ }
+}
+
+const member = (db, id) =>
+ db.prepare(`SELECT * FROM admin_users WHERE id = ? AND role = 'member'`).get(Number(id)) ?? null;
+
+profiles.get("/profiles", (c) => {
+ const db = c.get("db");
+ const accounts = db
+ .prepare(
+ `SELECT u.id, u.email, u.name, u.is_active, u.created_at, u.last_login_at,
+ u.invited_at, u.invite_expires_at,
+ (u.invite_hash IS NOT NULL AND u.invite_expires_at > datetime('now')) AS invite_open,
+ (u.password_hash IS NOT NULL OR u.google_sub IS NOT NULL) AS signed_up,
+ u.person_id, p.display_name AS person_name,
+ u.discord_id, u.discord_name
+ FROM admin_users u
+ LEFT JOIN people p ON p.id = u.person_id
+ WHERE u.role = 'member'
+ ORDER BY u.created_at DESC, u.id DESC`,
+ )
+ .all();
+ const claims = db
+ .prepare(
+ `SELECT c.id, c.account_id, u.email, u.name, c.person_id, p.display_name AS person_name,
+ c.message, c.created_at
+ FROM person_claims c
+ JOIN admin_users u ON u.id = c.account_id
+ JOIN people p ON p.id = c.person_id
+ WHERE c.status = 'pending'
+ ORDER BY c.created_at`,
+ )
+ .all();
+ return c.json({ accounts, claims, mail: mailReady() }, 200, NO_STORE);
+});
+
+profiles.post("/profiles", async (c) => {
+ const data = await body(c);
+ if (!data) return c.json({ error: "Expected a JSON body." }, 400);
+ const db = c.get("db");
+ const email = String(data.email ?? "").trim().toLowerCase().slice(0, 254);
+ const name = String(data.name ?? "").trim().slice(0, 120) || null;
+ if (!EMAIL.test(email)) return c.json({ error: "Enter an email address.", fields: { email: "Needed." } }, 422);
+ if (db.prepare(`SELECT 1 FROM admin_users WHERE email = ?`).get(email)) {
+ return c.json({ error: "That email already has an account.", fields: { email: "Already has one." } }, 409);
+ }
+
+ const id = db
+ .prepare(
+ `INSERT INTO admin_users (email, name, role, access_source) VALUES (?, ?, 'member', 'invite')`,
+ )
+ .run(email, name).lastInsertRowid;
+ const link = issueInvite(db, id, c.get("user").id);
+ console.log(`profile account ${logSafe(email)} invited by ${c.get("user").email}`);
+ return c.json({ id: Number(id), link }, 201, NO_STORE);
+});
+
+profiles.post("/profiles/:id/invite", async (c) => {
+ const db = c.get("db");
+ const account = member(db, c.req.param("id"));
+ if (!account) return c.json({ error: "No such profile account." }, 404);
+ const data = (await body(c)) ?? {};
+
+ const link = issueInvite(db, account.id, c.get("user").id);
+ if (data.email) {
+ try {
+ await emailInvite(db, account, link);
+ } catch (err) {
+ console.warn(`invite email to ${account.email} failed: ${err.message}`);
+ return c.json({ link, emailed: false, error: `The email didn't go: ${err.message}` }, 502, NO_STORE);
+ }
+ }
+ console.log(`invite for ${account.email} ${data.email ? "emailed" : "issued"} by ${c.get("user").email}`);
+ return c.json({ link, emailed: Boolean(data.email) }, 200, NO_STORE);
+});
+
+profiles.patch("/profiles/:id", async (c) => {
+ const db = c.get("db");
+ const account = member(db, c.req.param("id"));
+ if (!account) return c.json({ error: "No such profile account." }, 404);
+ const data = await body(c);
+ if (!data) return c.json({ error: "Expected a JSON body." }, 400);
+
+ const sets = [];
+ const values = [];
+ if ("person_id" in data) {
+ const personId = data.person_id ? String(data.person_id) : null;
+ if (personId) {
+ if (!db.prepare(`SELECT 1 FROM people WHERE id = ?`).get(personId)) {
+ return c.json({ error: "No such person.", fields: { person_id: "Pick one." } }, 422);
+ }
+ const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ? AND id <> ?`).get(personId, account.id);
+ if (holder) return c.json({ error: `${holder.email} already has that profile.` }, 409);
+ }
+ sets.push("person_id = ?");
+ values.push(personId);
+ }
+ if ("discord_id" in data) {
+ const discordId = data.discord_id ? String(data.discord_id).trim() : null;
+ if (discordId && !/^\d{5,25}$/.test(discordId)) {
+ return c.json({ error: "A Discord id is the long number (Developer Mode → Copy User ID).", fields: { discord_id: "Digits only." } }, 422);
+ }
+ if (discordId && db.prepare(`SELECT 1 FROM admin_users WHERE discord_id = ? AND id <> ?`).get(discordId, account.id)) {
+ return c.json({ error: "Another account has that Discord id." }, 409);
+ }
+ sets.push("discord_id = ?", "discord_name = ?");
+ values.push(discordId, discordId ? String(data.discord_name ?? "").trim().slice(0, 100) || null : null);
+ }
+ if ("is_active" in data) {
+ sets.push("is_active = ?");
+ values.push(data.is_active ? 1 : 0);
+ }
+ if (!sets.length) return c.json({ error: "Nothing to change." }, 422);
+
+ db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run(...values, account.id);
+ if ("is_active" in data && !data.is_active) destroyAllSessionsFor(db, account.id);
+ console.log(`profile account ${account.email} changed by ${c.get("user").email}`);
+ return c.body(null, 204);
+});
+
+profiles.delete("/profiles/:id", (c) => {
+ const db = c.get("db");
+ const account = member(db, c.req.param("id"));
+ if (!account) return c.json({ error: "No such profile account." }, 404);
+ db.prepare(`DELETE FROM admin_users WHERE id = ?`).run(account.id);
+ console.log(`profile account ${account.email} removed by ${c.get("user").email}`);
+ return c.body(null, 204);
+});
+
+function decide(c, approve) {
+ const db = c.get("db");
+ const claim = db
+ .prepare(`SELECT * FROM person_claims WHERE id = ? AND status = 'pending'`)
+ .get(Number(c.req.param("id")));
+ if (!claim) return c.json({ error: "That request was already answered." }, 404);
+
+ const taken = tx(db, () => {
+ if (approve) {
+ const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ?`).get(claim.person_id);
+ if (holder) return holder.email;
+ db.prepare(`UPDATE admin_users SET person_id = ? WHERE id = ?`).run(claim.person_id, claim.account_id);
+ }
+ db.prepare(
+ `UPDATE person_claims SET status = ?, decided_at = datetime('now'), decided_by = ? WHERE id = ?`,
+ ).run(approve ? "approved" : "declined", c.get("user").id, claim.id);
+ return null;
+ });
+ if (taken) return c.json({ error: `${taken} already has that profile. Decline this one.` }, 409);
+ console.log(`claim ${claim.id} (${claim.person_id}) ${approve ? "approved" : "declined"} by ${c.get("user").email}`);
+ return c.body(null, 204);
+}
+
+profiles.post("/profiles/claims/:id/approve", (c) => decide(c, true));
+profiles.post("/profiles/claims/:id/decline", (c) => decide(c, false));
+
+export default profiles;
diff --git a/server/src/shape.js b/server/src/shape.js
index e79c939..8881f2b 100644
--- a/server/src/shape.js
+++ b/server/src/shape.js
@@ -27,11 +27,14 @@ export function loadLinks(db, ownerKind, ids) {
const out = new Map();
if (ids.length === 0) return out;
+ // A person who took their links off the site (people.hide_links,
+ // 076) has none here.
const rows = db
.prepare(
`SELECT owner_id, kind, platform, label, url, is_primary
FROM links
WHERE owner_kind = ? AND owner_id IN (${placeholders(ids.length)})
+ AND NOT (owner_kind = 'person' AND owner_id IN (SELECT id FROM people WHERE hide_links = 1))
ORDER BY owner_id, sort_order`,
)
.all(ownerKind, ...ids);
@@ -106,7 +109,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
p.id AS person_id, p.display_name AS person_name,
p.photo AS person_photo, p.tagline AS person_tagline
FROM content_block_items i
- LEFT JOIN people p ON p.id = i.person_id AND p.is_published = 1
+ LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
WHERE i.block_id IN (${placeholders(blockIds.length)})
ORDER BY i.block_id, i.sort_order`,
)
@@ -266,7 +269,7 @@ const FEATURED_REFS = {
person: {
sql: (marks) =>
`SELECT id, display_name AS title, tagline AS blurb, photo
- FROM people WHERE is_published = 1 AND id IN (${marks})`,
+ FROM v_people_public WHERE is_published = 1 AND id IN (${marks})`,
image: (row) => (row.photo ? { file: row.photo, kind: "person" } : null),
},
team: {
diff --git a/src/App.tsx b/src/App.tsx
index 3048d73..1744096 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -59,6 +59,10 @@ const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
const Terms = lazyPage(() => import("./pages/Terms.tsx"))
const NotFound = lazyPage(() => import("./pages/NotFound.tsx"))
+// Profile accounts (076): signing in, an invite's welcome, the profile.
+const SignIn = lazyPage(() => import("./pages/SignIn.tsx"))
+const AccountWelcome = lazyPage(() => import("./pages/AccountWelcome.tsx"))
+const Account = lazyPage(() => import("./pages/Account.tsx"))
/*Entity Pages*/
const EventDetail = lazyPage(() => import("./pages/EventDetail.tsx"))
@@ -82,12 +86,15 @@ const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.tsx"))
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
+const AdminProfiles = lazyPage(() => import("./pages/admin/AdminProfiles.tsx"))
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
export default function App() {
return (
+ {/* The whole app: the site shows a profile link and hidden pages by who's signed in. */}
+
{/* Layout renders the nav once and swaps page content into */}
}>
@@ -114,6 +121,9 @@ export default function App() {
} />
} />
} />
+ } />
+ } />
+ } />
} />
{/* A schedule as a slideshow for a screen: full screen, no Layout. */}
@@ -127,11 +137,9 @@ export default function App() {
/>
-
-
-
-
+
+
+
}
>
} />
@@ -152,6 +160,7 @@ export default function App() {
}>
} />
+ } />
} />
} />
@@ -159,6 +168,7 @@ export default function App() {
+
)
}
diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx
index 7ccbada..529ca7c 100644
--- a/src/components/Footer.tsx
+++ b/src/components/Footer.tsx
@@ -1,6 +1,7 @@
import { Link } from "react-router-dom";
import { useNavSections } from "../lib/navSections.ts";
import { useSiteNav } from "../lib/useSiteNav.ts";
+import { useAuth } from "../lib/auth.tsx";
import SiteLink from "./SiteLink.tsx";
import siteLogo from "../assets/logos/NGU_Logo.svg";
import PlatformIcon from "./PlatformIcon.tsx";
@@ -10,7 +11,8 @@ import { SOCIAL_LINKS } from "../data/socialLinks.ts";
/* Every link here is Pages → Navigation's (useSiteNav): the filled
header buttons (Give) beside the logo, Get in Touch, the site map
(the header's pages, their sections and the pages set under them)
- and the bottom row. */
+ and the bottom row. The bottom row ends with the profile account's
+ way in (076): Sign in, or Your profile once signed in. */
const footerLinkClass =
"text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors";
@@ -27,6 +29,7 @@ const headingClass = "text-white/90 text-sm font-semibold mb-4";
export default function Footer() {
const sectionsOf = useNavSections();
const nav = useSiteNav();
+ const { user } = useAuth();
return (
@@ -144,12 +147,15 @@ export default function Footer() {
© 2026 Next Generation of Unity. All rights reserved.
-
+
{nav.legal.map((link) => (
{link.label}
))}
+
+ {user ? "Your profile" : "Sign in"}
+
diff --git a/src/components/GoogleLogo.tsx b/src/components/GoogleLogo.tsx
new file mode 100644
index 0000000..5d59139
--- /dev/null
+++ b/src/components/GoogleLogo.tsx
@@ -0,0 +1,12 @@
+/* Google's "G", for the Sign in with Google buttons: a brand mark,
+ so drawn as Google gives it rather than as a Phosphor icon. */
+export default function GoogleLogo({ className = 'h-5 w-5' }: { className?: string }) {
+ return (
+
+
+
+
+
+
+ )
+}
diff --git a/src/lib/adminSchema/people.ts b/src/lib/adminSchema/people.ts
index c9e6b9a..7cd4986 100644
--- a/src/lib/adminSchema/people.ts
+++ b/src/lib/adminSchema/people.ts
@@ -83,6 +83,20 @@ export const people = {
note: "Unpublished people are invisible everywhere.",
fields: [PUBLISHED_FIELD, LISTED_FIELD],
},
+ {
+ legend: "Hidden on the site",
+ note: "Ticked parts stay here but don't show anywhere on the site. Someone with a profile account who has claimed this person sets these on their profile too (Data → Profile accounts).",
+ fields: [
+ ["photo", "Photo"],
+ ["pronouns", "Pronouns"],
+ ["tagline", "Tagline"],
+ ["bio", "Bio"],
+ ["email", "Public email"],
+ ["phone", "Public phone"],
+ ["location", "Location"],
+ ["links", "Links"],
+ ].map(([key, label]) => ({ path: `hide_${key}`, label: `Hide ${label.toLowerCase()}`, widget: "checkbox" })),
+ },
],
children: [
diff --git a/src/lib/api.ts b/src/lib/api.ts
index cf550ba..f5379ea 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -123,7 +123,7 @@ export function peek(path) {
return settled.get(path);
}
-export function invalidate(path) {
+export function invalidate(path?: string) {
if (path) {
cache.delete(path);
settled.delete(path);
diff --git a/src/lib/auth.tsx b/src/lib/auth.tsx
index 6c952f0..f299aab 100644
--- a/src/lib/auth.tsx
+++ b/src/lib/auth.tsx
@@ -10,13 +10,19 @@
RequireAuth guards routes. Worth being clear about what that
does and doesn't do: it hides the interface, not the data. The
protection is the 401 from /api/admin, this only stops someone
- staring at an empty table.
+ staring at an empty table. A profile account (member) is signed
+ in but has no admin, so it's sent to its page on the site.
+
+ The provider wraps the whole app, since the site shows a profile
+ link and hidden pages by who's signed in. Signing in or out drops
+ the API cache: the nav and hidden pages depend on it.
═══════════════════════════════════════════════════════════════ */
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";
-import { get, post, ApiError } from "./api.ts";
+import { get, invalidate, post, ApiError } from "./api.ts";
+import { isStaff } from "./roles.ts";
const AuthContext = createContext
(null);
@@ -45,6 +51,7 @@ export function AuthProvider({ children }) {
const login = useCallback(async (email, password) => {
const data = await post("/auth/login", { email, password });
+ invalidate();
setUser(data.user);
return data.user;
}, []);
@@ -54,12 +61,19 @@ export function AuthProvider({ children }) {
await post("/auth/logout", {});
} finally {
// Whatever the server said, this browser is done.
+ invalidate();
setUser(null);
}
}, []);
+ // After a sign-in the server did itself (an invite's password).
+ const signedIn = useCallback((next) => {
+ invalidate();
+ setUser(next);
+ }, []);
+
return (
-
+
{children}
);
@@ -94,5 +108,7 @@ export function RequireAuth() {
return ;
}
+ if (!isStaff(user)) return ;
+
return ;
}
diff --git a/src/lib/roles.ts b/src/lib/roles.ts
index 794b12f..d94b525 100644
--- a/src/lib/roles.ts
+++ b/src/lib/roles.ts
@@ -14,18 +14,22 @@
role to be added, and there's now a fourth.
═══════════════════════════════════════════════════════════════ */
-export const ROLES = ["viewer", "editor", "admin", "superadmin"] as const;
+/* member is a profile account (076): the site and their own profile,
+ never the admin. */
+export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"] as const;
export type Role = (typeof ROLES)[number];
export const ROLE_RANK: Record = {
- viewer: 1,
- editor: 2,
- admin: 3,
- superadmin: 4,
+ member: 1,
+ viewer: 2,
+ editor: 3,
+ admin: 4,
+ superadmin: 5,
};
export const ROLE_LABELS: Record = {
+ member: "Profile",
viewer: "Viewer",
editor: "Editor",
admin: "Admin",
@@ -35,9 +39,10 @@ export const ROLE_LABELS: Record = {
/* Each line is what that role adds to the one above it in the
list. Read top to bottom, they describe the whole ladder. */
export const ROLE_NOTES: Record = {
+ member: "Signs in to the site to edit their own profile. No admin.",
viewer: "Can read everything in the CMS and change nothing.",
editor: "Can create and update records. Can't delete anything.",
- admin: "Can delete records, including feedback.",
+ admin: "Can delete records, including feedback. Invites profile accounts and approves their claims.",
superadmin: "Can manage accounts, roles and sessions.",
};
@@ -55,3 +60,5 @@ export function atLeast(user: MaybeUser, role: Role): boolean {
export const canWrite = (user: MaybeUser) => atLeast(user, "editor");
export const canDelete = (user: MaybeUser) => atLeast(user, "admin");
export const isSuper = (user: MaybeUser) => atLeast(user, "superadmin");
+/* Uses the admin at all: a profile account (member) doesn't. */
+export const isStaff = (user: MaybeUser) => atLeast(user, "viewer");
diff --git a/src/lib/useAccount.ts b/src/lib/useAccount.ts
new file mode 100644
index 0000000..0e3c9da
--- /dev/null
+++ b/src/lib/useAccount.ts
@@ -0,0 +1,44 @@
+/* A profile account's own page (server/src/routes/account.js): the
+ account, the People record it has (as its owner edits it), its
+ claim, and Discord. Not cached: it changes as they edit it. */
+
+import { useRecord, type Resource } from './useRecord.ts'
+
+/* What an owner can take off the site (people.hide_*), in the order
+ the profile page lists them. */
+export const HIDE_FIELDS = [
+ ['photo', 'Photo'],
+ ['pronouns', 'Pronouns'],
+ ['tagline', 'Tagline'],
+ ['bio', 'Bio'],
+ ['email', 'Public email'],
+ ['phone', 'Public phone'],
+ ['location', 'Location'],
+ ['links', 'Links'],
+] as const
+
+export type HideField = (typeof HIDE_FIELDS)[number][0]
+
+export type MyPerson = {
+ id: string
+ display_name: string
+ is_published: boolean
+ photo: string | null
+ pronouns: string | null
+ tagline: string | null
+ bio: string | null
+ public_email: string | null
+ public_phone: string | null
+ location_label: string | null
+ hidden: Record
+}
+
+export type MyAccount = {
+ user: { id: number; email: string; name: string | null; role: string }
+ person: MyPerson | null
+ claim: { id: number; person_id: string; display_name: string; status: 'pending' | 'approved' | 'declined' } | null
+ discord: { enabled: boolean; id: string | null; name: string | null }
+}
+
+export const useMyAccount = (enabled: boolean): Resource =>
+ useRecord(enabled ? '/account' : null, 'account')
diff --git a/src/pages/Account.tsx b/src/pages/Account.tsx
new file mode 100644
index 0000000..161c873
--- /dev/null
+++ b/src/pages/Account.tsx
@@ -0,0 +1,416 @@
+/* ═══════════════════════════════════════════════════════════════
+ YOUR PROFILE: /account, a profile account's page (076)
+
+ Your account who's signed in, sign out (and the admin, for
+ an admin account)
+ Your profile before a record is theirs: ask to claim one (an
+ admin approves it); after: edit its text and
+ photo, and choose what of it shows on the site
+ Discord link it (or unlink), for the gamification to come
+
+ Signed out, it's the sign-in page's job. Everything is saved
+ through routes/account.js, which only ever writes the account's
+ own person.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useEffect, useState } from 'react'
+import { Link, Navigate, useSearchParams } from 'react-router-dom'
+import { ArrowSquareOut, SignOut } from '@phosphor-icons/react'
+
+import PageShell from '../components/PageShell.tsx'
+import { useAuth } from '../lib/auth.tsx'
+import { ApiError, del, get, patch, post, upload } from '../lib/api.ts'
+import { ACCENTS, BRAND } from '../lib/color.ts'
+import { mediaUrl } from '../lib/media.ts'
+import { personHref } from '../lib/hrefs.ts'
+import { ROLE_LABELS, isStaff, type Role } from '../lib/roles.ts'
+import { HIDE_FIELDS, useMyAccount, type MyAccount, type MyPerson } from '../lib/useAccount.ts'
+import { fieldClass, primaryButton } from './SignIn.tsx'
+
+const quietButton =
+ 'btn border border-brand px-5 py-2.5 text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:opacity-60'
+
+/* What ?discord= says after the trip to Discord (routes/account.js). */
+const DISCORD_RESULTS: Record = {
+ linked: 'Your Discord account is linked.',
+ canceled: 'Linking Discord was canceled.',
+ expired: 'That took too long. Try again.',
+ taken: 'That Discord account is already linked to another profile.',
+ failed: "Discord didn't link. Try again in a moment.",
+}
+
+const message = (err: unknown) =>
+ err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."
+
+function Alert({ children, tone = 'danger' }: { children: React.ReactNode; tone?: 'danger' | 'ok' }) {
+ return (
+
+ {children}
+
+ )
+}
+
+export default function Account() {
+ const { user, loading, logout } = useAuth()
+ const { data, error, reload } = useMyAccount(Boolean(user))
+
+ if (loading) return null
+ if (!user) return
+
+ const content = (part: React.ReactNode) => {part}
+
+ return (
+
+
+
{user.name || user.email}
+
+ {user.email} · {ROLE_LABELS[user.role as Role] ?? user.role}
+
+
+
+ {isStaff(user) && (
+
+ Admin
+
+ )}
+
+
+ Sign out
+
+
+ ,
+ ),
+ },
+ {
+ id: 'profile',
+ title: 'Your profile',
+ blurb: 'Your page on the site, eg. on a team or an event. Ask for yours, then edit it here.',
+ accent: ACCENTS.green,
+ content: content(
+ error ? (
+ Couldn't load your profile. {error}
+ ) : !data ? (
+
+ ) : data.person ? (
+
+ ) : (
+
+ ),
+ ),
+ },
+ {
+ id: 'discord',
+ title: 'Discord',
+ blurb: 'Link your Discord account so what you do there can count here.',
+ accent: ACCENTS.amber,
+ content: content(data ? : null),
+ },
+ ]}
+ />
+ )
+}
+
+/* ── Claiming a record ───────────────────────────────────────── */
+
+function Claim({ account, onChange }: { account: MyAccount; onChange: () => void }) {
+ const [people, setPeople] = useState<{ id: string; name: string }[] | null>(null)
+ const [personId, setPersonId] = useState('')
+ const [note, setNote] = useState('')
+ const [error, setError] = useState(null)
+ const [busy, setBusy] = useState(false)
+ const pending = account.claim?.status === 'pending' ? account.claim : null
+
+ useEffect(() => {
+ if (pending) return
+ get('/account/people', { ttl: 0 })
+ .then((data) => setPeople(data.people))
+ .catch((err) => setError(message(err)))
+ }, [pending])
+
+ async function run(action: () => Promise) {
+ setBusy(true)
+ setError(null)
+ try {
+ await action()
+ onChange()
+ } catch (err) {
+ setError(message(err))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ if (pending) {
+ return (
+
+
+ You asked to be {pending.display_name} . An admin will look at it soon.
+
+
run(() => del('/account/claim'))} className={`mt-4 ${quietButton}`}>
+ Take back the request
+
+ {error &&
{error} }
+
+ )
+ }
+
+ return (
+
+ )
+}
+
+/* ── Editing it ──────────────────────────────────────────────── */
+
+const TEXT_FIELDS: { key: keyof MyPerson; label: string; help?: string; long?: boolean; type?: string }[] = [
+ { key: 'pronouns', label: 'Pronouns', help: 'eg. she/her' },
+ { key: 'tagline', label: 'Tagline', help: 'A line under your name when you have no title, eg. Musician and youth leader' },
+ { key: 'location_label', label: 'Location', help: 'eg. Kansas City, MO' },
+ { key: 'public_email', label: 'Public email', type: 'email', help: 'Shown on your page. Leave it blank for none.' },
+ { key: 'public_phone', label: 'Public phone', type: 'tel' },
+ { key: 'bio', label: 'Bio', long: true, help: 'A blank line starts a new paragraph.' },
+]
+
+function ProfileEditor({ person, onSaved }: { person: MyPerson; onSaved: () => void }) {
+ const [values, setValues] = useState(() =>
+ Object.fromEntries(TEXT_FIELDS.map(({ key }) => [key, (person[key] as string | null) ?? ''])),
+ )
+ const [hidden, setHidden] = useState(person.hidden)
+ const [photo, setPhoto] = useState(person.photo)
+ const [fields, setFields] = useState>({})
+ const [error, setError] = useState(null)
+ const [saved, setSaved] = useState(false)
+ const [busy, setBusy] = useState(false)
+
+ async function save(event: React.FormEvent) {
+ event.preventDefault()
+ setBusy(true)
+ setError(null)
+ setFields({})
+ setSaved(false)
+ try {
+ await patch('/account/profile', { ...values, hidden })
+ setSaved(true)
+ onSaved()
+ } catch (err) {
+ setError(message(err))
+ if (err instanceof ApiError && err.fields) setFields(err.fields)
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function sendPhoto(file: File | undefined) {
+ if (!file) return
+ setBusy(true)
+ setError(null)
+ try {
+ const form = new FormData()
+ form.append('file', file)
+ const data = await upload('/account/photo', form)
+ setPhoto(data.person.photo)
+ } catch (err) {
+ setError(message(err))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+ {photo ? (
+
+ ) : (
+
No photo
+ )}
+
+
{person.display_name}
+ {person.is_published ? (
+
+ Your page on the site
+
+
+ ) : (
+
Your page isn't on the site yet.
+ )}
+
+ {photo ? 'Change photo' : 'Add a photo'}
+ sendPhoto(e.target.files?.[0])}
+ />
+
+
+
+ Your name is changed by an admin: ask through the Request page.
+
+
+ {TEXT_FIELDS.map(({ key, label, help, long, type }) => (
+
+
+ {label}
+
+ {long ? (
+
setValues({ ...values, [key]: e.target.value })}
+ aria-describedby={help ? `profile-${key}-help` : undefined}
+ className={`mt-2 ${fieldClass}`}
+ />
+ ) : (
+ setValues({ ...values, [key]: e.target.value })}
+ aria-describedby={help ? `profile-${key}-help` : undefined}
+ aria-invalid={Boolean(fields[key])}
+ className={`mt-2 ${fieldClass}`}
+ />
+ )}
+ {fields[key] && {fields[key]}
}
+ {help && (
+
+ {help}
+
+ )}
+
+ ))}
+
+
+
+ Hide on the site
+
+ Ticked parts stay saved but don't show anywhere on the site: your page, team and event lists, people tiles.
+
+
+ {HIDE_FIELDS.map(([key, label]) => (
+
+ setHidden({ ...hidden, [key]: e.target.checked })}
+ className="h-4 w-4 accent-[var(--color-action)]"
+ />
+ Hide {label.toLowerCase()}
+
+ ))}
+
+
+
+ {error && {error} }
+ {saved && !error && Saved. It's on the site now. }
+
+ {busy ? 'Saving…' : 'Save profile'}
+
+
+ )
+}
+
+/* ── Discord ─────────────────────────────────────────────────── */
+
+function Discord({ account, onChange }: { account: MyAccount; onChange: () => void }) {
+ const [searchParams] = useSearchParams()
+ const result = searchParams.get('discord')
+ const [error, setError] = useState(null)
+ const { discord } = account
+
+ async function unlink() {
+ setError(null)
+ try {
+ await del('/account/discord')
+ onChange()
+ } catch (err) {
+ setError(message(err))
+ }
+ }
+
+ return (
+
+ {discord.id ? (
+
+
+ Linked to {discord.name ?? discord.id} .
+
+
+ Unlink
+
+
+ ) : discord.enabled ? (
+
+ Link Discord
+
+ ) : (
+
Linking Discord isn't switched on yet. An admin can link it for you.
+ )}
+ {result && DISCORD_RESULTS[result] && (
+
{DISCORD_RESULTS[result]}
+ )}
+ {error &&
{error} }
+
+ )
+}
diff --git a/src/pages/AccountWelcome.tsx b/src/pages/AccountWelcome.tsx
new file mode 100644
index 0000000..6fc2092
--- /dev/null
+++ b/src/pages/AccountWelcome.tsx
@@ -0,0 +1,142 @@
+/* ═══════════════════════════════════════════════════════════════
+ WELCOME: /account/welcome?token=…, an invite's link (076)
+
+ Who the invite is for, then a password to set, or Google under the
+ invited email. Either takes up the invite: the link stops working
+ and the account is signed in (routes/account.js, routes/auth.js).
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useEffect, useState } from 'react'
+import { Link, useNavigate, useSearchParams } from 'react-router-dom'
+
+import PageShell from '../components/PageShell.tsx'
+import { useAuth } from '../lib/auth.tsx'
+import { ApiError, get, post } from '../lib/api.ts'
+import { BRAND } from '../lib/color.ts'
+import { GoogleButton, fieldClass, primaryButton } from './SignIn.tsx'
+
+const MIN_PASSWORD = 12
+
+type Invite = { email: string; name: string | null; google: boolean }
+
+export default function AccountWelcome() {
+ const [searchParams] = useSearchParams()
+ const token = searchParams.get('token') ?? ''
+ const navigate = useNavigate()
+ const { signedIn } = useAuth()
+
+ const [invite, setInvite] = useState(null)
+ const [problem, setProblem] = useState(null)
+ const [password, setPassword] = useState('')
+ const [again, setAgain] = useState('')
+ const [error, setError] = useState(null)
+ const [busy, setBusy] = useState(false)
+
+ useEffect(() => {
+ if (!token) {
+ setProblem('This page needs the link from your invite email.')
+ return
+ }
+ get(`/account/invite?token=${encodeURIComponent(token)}`, { ttl: 0 })
+ .then((data) => setInvite(data.invite))
+ .catch((err) => setProblem(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."))
+ }, [token])
+
+ async function submit(event: React.FormEvent) {
+ event.preventDefault()
+ if (busy) return
+ if (password.length < MIN_PASSWORD) return setError(`Use at least ${MIN_PASSWORD} characters.`)
+ if (password !== again) return setError("The two passwords don't match.")
+ setBusy(true)
+ setError(null)
+ try {
+ const data = await post('/account/accept', { token, password })
+ signedIn(data.user)
+ navigate('/account', { replace: true })
+ } catch (err) {
+ setError(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment.")
+ setBusy(false)
+ }
+ }
+
+ return (
+
+ {problem ? (
+
+
{problem}
+
+ Already set up? Sign in. Otherwise ask whoever invited you for a new link.
+
+
+ ) : !invite ? (
+
+ ) : (
+
+
+ Your account is {invite.email} .
+
+ {invite.google && (
+ <>
+
+
+
+ Sign in to Google as {invite.email}.
+
+
+ or set a password
+
+
+ >
+ )}
+
+ Password
+
+ setPassword(e.target.value)}
+ aria-describedby="welcome-password-help"
+ className={`mt-2 ${fieldClass}`}
+ />
+
+ At least {MIN_PASSWORD} characters.
+
+
+ Password again
+
+ setAgain(e.target.value)}
+ className={`mt-2 ${fieldClass}`}
+ />
+ {error && (
+
+ {error}
+
+ )}
+
+ {busy ? 'Setting up…' : 'Set password and sign in'}
+
+
+ )}
+
+ ),
+ },
+ ]}
+ />
+ )
+}
diff --git a/src/pages/SignIn.tsx b/src/pages/SignIn.tsx
new file mode 100644
index 0000000..cbd81a8
--- /dev/null
+++ b/src/pages/SignIn.tsx
@@ -0,0 +1,157 @@
+/* ═══════════════════════════════════════════════════════════════
+ SIGN IN: /sign-in, for profile accounts (076)
+
+ Accounts are by invite only (Data → Profile accounts), so there's
+ no sign-up here: an invite's link (/account/welcome) sets the
+ password, or the invited email signs in with Google, any Google
+ account. The admin's own login (/admin/login) is the same accounts
+ through another door; either lands an admin where they asked.
+
+ A Google refusal comes back here as ?error= (routes/auth.js).
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useEffect, useState } from 'react'
+import { Navigate, useNavigate, useSearchParams } from 'react-router-dom'
+
+import PageShell from '../components/PageShell.tsx'
+import GoogleLogo from '../components/GoogleLogo.tsx'
+import { useAuth } from '../lib/auth.tsx'
+import { ApiError, get } from '../lib/api.ts'
+import { BRAND } from '../lib/color.ts'
+
+export const SIGN_IN_TITLE = 'Sign in'
+
+const GOOGLE_ERRORS: Record = {
+ canceled: 'Google sign-in was canceled.',
+ expired: 'That sign-in took too long or was already used. Try again.',
+ no_account: "There's no profile account for that Google account. Accounts are by invite: ask us to invite your email.",
+ linked_elsewhere: "That email's account is linked to a different Google account.",
+ disabled: 'That account has been turned off.',
+ wrong_domain: 'Use your @nextgenerationofunity.org Google account for that one.',
+ unverified: "That Google account's email isn't verified.",
+ google_unreachable: "Couldn't reach Google. Try again in a moment.",
+ google_failed: "Google sign-in didn't work. Try again, or use your password.",
+ not_in_group: "That Google account isn't in a website access group.",
+ groups_unreachable: "Couldn't check your Google groups just now. Try again in a moment.",
+}
+
+export const fieldClass =
+ 'w-full border border-muted/50 bg-surface px-4 py-3 text-body outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25'
+
+export const primaryButton =
+ 'btn bg-action px-6 py-3 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'
+
+export function GoogleButton({ label = 'Sign in with Google' }: { label?: string }) {
+ return (
+
+
+ {label}
+
+ )
+}
+
+/* Whether the server has Google sign-in switched on. */
+export function useGoogleSignIn(): boolean {
+ const [google, setGoogle] = useState(false)
+ useEffect(() => {
+ get('/auth/providers', { ttl: 0 })
+ .then((data) => setGoogle(Boolean(data.google)))
+ .catch(() => setGoogle(false))
+ }, [])
+ return google
+}
+
+export default function SignIn() {
+ const { user, loading, login } = useAuth()
+ const navigate = useNavigate()
+ const [searchParams] = useSearchParams()
+ const googleError = searchParams.get('error')
+ const google = useGoogleSignIn()
+
+ const [email, setEmail] = useState('')
+ const [password, setPassword] = useState('')
+ const [error, setError] = useState(
+ googleError ? (GOOGLE_ERRORS[googleError] ?? GOOGLE_ERRORS.google_failed) : null,
+ )
+ const [busy, setBusy] = useState(false)
+
+ if (!loading && user) return
+
+ async function submit(event: React.FormEvent) {
+ event.preventDefault()
+ if (busy) return
+ setBusy(true)
+ setError(null)
+ try {
+ await login(email.trim(), password)
+ navigate('/account', { replace: true })
+ } catch (err) {
+ setError(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment.")
+ setPassword('')
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+ {google && (
+ <>
+
+
+
+ or with a password
+
+
+ >
+ )}
+
+ Email
+
+ setEmail(e.target.value)}
+ className={`mt-2 ${fieldClass}`}
+ />
+
+ Password
+
+ setPassword(e.target.value)}
+ className={`mt-2 ${fieldClass}`}
+ />
+ {error && (
+
+ {error}
+
+ )}
+
+ {busy ? 'Signing in…' : 'Sign in'}
+
+
+
+ ),
+ },
+ ]}
+ />
+ )
+}
diff --git a/src/pages/admin/AdminLogin.tsx b/src/pages/admin/AdminLogin.tsx
index ce9195c..da159b0 100644
--- a/src/pages/admin/AdminLogin.tsx
+++ b/src/pages/admin/AdminLogin.tsx
@@ -18,6 +18,8 @@ import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx";
import { ApiError, get } from "../../lib/api.ts";
+import { isStaff } from "../../lib/roles.ts";
+import GoogleLogo from "../../components/GoogleLogo.tsx";
/* What a ?error= from the Google callback means, in the words the
person at the login page needs. */
@@ -74,8 +76,9 @@ export default function AdminLogin() {
setError(null);
try {
- await login(email.trim(), password);
- navigate(destination, { replace: true });
+ const user = await login(email.trim(), password);
+ // A profile account has no admin: its page is on the site.
+ navigate(isStaff(user) ? destination : "/account", { replace: true });
} catch (err) {
setError(
err instanceof ApiError
@@ -106,12 +109,7 @@ export default function AdminLogin() {
href={`/api/auth/google?next=${encodeURIComponent(destination)}`}
className="flex items-center justify-center gap-3 btn border border-muted/30 px-6 py-3 text-body transition-colors hover:bg-tint"
>
-
-
-
-
-
-
+
Sign in with Google
diff --git a/src/pages/admin/AdminProfiles.tsx b/src/pages/admin/AdminProfiles.tsx
new file mode 100644
index 0000000..8c6cbb8
--- /dev/null
+++ b/src/pages/admin/AdminProfiles.tsx
@@ -0,0 +1,450 @@
+/* ═══════════════════════════════════════════════════════════════
+ ADMIN: PROFILE ACCOUNTS (Data → Profile accounts, admins and up)
+
+ Profile accounts (076) are by invite: an email added here gets an
+ account with no password and a link to set one (or to sign in
+ with Google under that email). The link is shown once, to copy;
+ Email invite sends a fresh one through Gmail and shows it too
+ (the one before stops working). For an account already set up,
+ the same link is a way back in when a password is forgotten.
+
+ Then: the claims waiting (someone asking to be a People record),
+ and each account's record, Discord and whether it's on. Server
+ side: server/src/routes/profiles.js. Admin accounts (viewer and
+ up) are the Panel's, not this page's.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useCallback, useEffect, useId, useState, type FormEvent } from "react";
+
+import { ApiError, del, get, patch, post } from "../../lib/api.ts";
+import { preview } from "../../lib/text.ts";
+
+const MUTED = "var(--color-muted)";
+
+const button =
+ "btn border border-brand px-3 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
+const primary =
+ "btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
+const danger =
+ "btn border border-danger/40 px-3 py-1.5 text-sm text-danger transition-colors hover:bg-danger-tint disabled:opacity-50";
+const input =
+ "w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
+
+type Account = {
+ id: number;
+ email: string;
+ name: string | null;
+ is_active: number;
+ created_at: string;
+ last_login_at: string | null;
+ invited_at: string | null;
+ invite_expires_at: string | null;
+ invite_open: number;
+ signed_up: number;
+ person_id: string | null;
+ person_name: string | null;
+ discord_id: string | null;
+ discord_name: string | null;
+};
+
+type Claim = {
+ id: number;
+ account_id: number;
+ email: string;
+ name: string | null;
+ person_id: string;
+ person_name: string;
+ message: string | null;
+ created_at: string;
+};
+
+const message = (err: unknown) => (err instanceof ApiError ? err.message : "Couldn't reach the server.");
+const day = (value: string | null) => (value ? value.slice(0, 10) : "-");
+
+/* A link to copy, shown once. */
+function LinkBox({ link, note }: { link: string; note: string }) {
+ const [copied, setCopied] = useState(false);
+ return (
+
+
+ {note}
+
+
+ {link}
+ {
+ try {
+ await navigator.clipboard.writeText(link);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ } catch {
+ setCopied(false);
+ }
+ }}
+ >
+ {copied ? "Copied" : "Copy link"}
+
+
+
+ );
+}
+
+export default function AdminProfiles() {
+ const [data, setData] = useState<{ accounts: Account[]; claims: Claim[]; mail: boolean } | null>(null);
+ const [people, setPeople] = useState<{ id: string; label: string }[]>([]);
+ const [error, setError] = useState
(null);
+
+ const load = useCallback(() => {
+ get("/admin/profiles", { ttl: 0 })
+ .then(setData)
+ .catch((err) => setError(message(err)));
+ }, []);
+
+ useEffect(() => {
+ load();
+ get("/admin/options?only=people", { ttl: 0 })
+ .then((body) => setPeople(body.options.people))
+ .catch(() => setPeople([]));
+ }, [load]);
+
+ return (
+
+
+
Profile accounts
+
+ People with an account on the site for their own profile. By invite only.
+
+
+
+
+
+ {error &&
{error}
}
+
+
+ Claims waiting
+ {!data ? null : data.claims.length === 0 ? (
+ Nobody is waiting.
+ ) : (
+
+ {data.claims.map((claim) => (
+
+ ))}
+
+ )}
+
+
+
+ Accounts
+ {!data ? (
+
+ ) : data.accounts.length === 0 ? (
+ No profile accounts yet. Invite someone above.
+ ) : (
+
+ {data.accounts.map((account) => (
+
+ ))}
+
+ )}
+
+
+ );
+}
+
+function Invite({ mail, onDone }: { mail: boolean; onDone: () => void }) {
+ const emailId = useId();
+ const nameId = useId();
+ const [email, setEmail] = useState("");
+ const [name, setName] = useState("");
+ const [made, setMade] = useState<{ id: number; email: string; link: string } | null>(null);
+ const [error, setError] = useState(null);
+ const [busy, setBusy] = useState(false);
+
+ async function submit(event: FormEvent) {
+ event.preventDefault();
+ setBusy(true);
+ setError(null);
+ try {
+ const result = await post("/admin/profiles", { email, name });
+ setMade({ id: result.id, email: email.trim().toLowerCase(), link: result.link });
+ setEmail("");
+ setName("");
+ onDone();
+ } catch (err) {
+ setError(message(err));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+
+ );
+}
+
+/* Email a fresh link (the last one stops working). */
+function EmailInvite({ id, label, onDone }: { id: number; label: string; onDone: (link: string) => void }) {
+ const [state, setState] = useState<"idle" | "busy" | "sent" | string>("idle");
+ return (
+
+ {
+ setState("busy");
+ try {
+ const result = await post(`/admin/profiles/${id}/invite`, { email: true });
+ onDone(result.link);
+ setState("sent");
+ } catch (err) {
+ setState(message(err));
+ }
+ }}
+ >
+ {state === "busy" ? "Sending…" : label}
+
+ {state === "sent" && Sent. The link above is the one in the email. }
+ {!["idle", "busy", "sent"].includes(state) && {state} }
+
+ );
+}
+
+function ClaimRow({ claim, onDone }: { claim: Claim; onDone: () => void }) {
+ const [error, setError] = useState(null);
+ const [busy, setBusy] = useState(false);
+
+ async function decide(answer: "approve" | "decline") {
+ setBusy(true);
+ setError(null);
+ try {
+ await post(`/admin/profiles/claims/${claim.id}/${answer}`, {});
+ onDone();
+ } catch (err) {
+ setError(message(err));
+ setBusy(false);
+ }
+ }
+
+ return (
+
+
+
+ {claim.name || claim.email}
+ {claim.name && ({claim.email}) } asks to be{" "}
+
+ {claim.person_name}
+
+
+ {" "}
+ · {day(claim.created_at)}
+
+
+
+ decide("approve")}>
+ Approve
+
+ decide("decline")}>
+ Decline
+
+
+
+ {claim.message && “{preview(claim.message, 300)}”
}
+ {error && {error}
}
+
+ );
+}
+
+function AccountRow({
+ account,
+ people,
+ mail,
+ onDone,
+}: {
+ account: Account;
+ people: { id: string; label: string }[];
+ mail: boolean;
+ onDone: () => void;
+}) {
+ const personId = useId();
+ const discordId = useId();
+ const discordName = useId();
+ const [person, setPerson] = useState(account.person_id ?? "");
+ const [discord, setDiscord] = useState(account.discord_id ?? "");
+ const [discordLabel, setDiscordLabel] = useState(account.discord_name ?? "");
+ const [link, setLink] = useState(null);
+ const [error, setError] = useState(null);
+ const [busy, setBusy] = useState(false);
+
+ async function run(action: () => Promise) {
+ setBusy(true);
+ setError(null);
+ try {
+ await action();
+ onDone();
+ } catch (err) {
+ setError(message(err));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const status = !account.is_active
+ ? "Turned off"
+ : account.signed_up
+ ? `Signed up · last in ${day(account.last_login_at)}`
+ : account.invite_open
+ ? `Invited · link works until ${day(account.invite_expires_at)}`
+ : "Invited · link expired";
+
+ return (
+
+
+
+ {account.name || account.email}
+ {account.name && {account.email} }
+ {status}
+ Profile: {account.person_name ?? "-"}
+ Discord: {account.discord_name ?? account.discord_id ?? "-"}
+
+
+
+
+
+ Profile (People record)
+
+ setPerson(e.target.value)} className={`mt-1 ${input}`}>
+ Default: none
+ {people.map((p) => (
+
+ {p.label}
+
+ ))}
+
+
+
run(() => patch(`/admin/profiles/${account.id}`, { person_id: person || null }))}
+ >
+ Save profile
+
+
+
+
+
+
+ Discord user ID
+
+ setDiscord(e.target.value)} className={`mt-1 ${input}`} />
+
+
+
+ Discord name
+
+ setDiscordLabel(e.target.value)} className={`mt-1 ${input}`} />
+
+
+ run(() => patch(`/admin/profiles/${account.id}`, { discord_id: discord || null, discord_name: discordLabel }))
+ }
+ >
+ Save Discord
+
+
+
+ They link it themselves from their profile; this overrides it. The ID is the long number from Discord (Developer Mode, then Copy User ID), eg. 80351110224678912. Blank unlinks it.
+
+
+
+
+ run(async () => {
+ const result = await post(`/admin/profiles/${account.id}/invite`, {});
+ setLink(result.link);
+ })
+ }
+ >
+ {account.signed_up ? "New sign-in link" : "New invite link"}
+
+ {mail && (
+
+ )}
+ run(() => patch(`/admin/profiles/${account.id}`, { is_active: !account.is_active }))}
+ >
+ {account.is_active ? "Turn off" : "Turn on"}
+
+ {
+ if (window.confirm(`Remove ${account.email}'s account? Their People record stays.`)) {
+ run(() => del(`/admin/profiles/${account.id}`));
+ }
+ }}
+ >
+ Remove
+
+
+ {link && (
+
+ )}
+ {error &&
{error}
}
+
+
+
+ );
+}
diff --git a/src/pages/admin/adminNav.ts b/src/pages/admin/adminNav.ts
index 3fac3e2..f4b9689 100644
--- a/src/pages/admin/adminNav.ts
+++ b/src/pages/admin/adminNav.ts
@@ -95,6 +95,12 @@ export const DATA_NAV = {
label: "Links/redirects",
blurb: "Short /go/ links for the newsletter, with click counts, Plausible and UTM tracking.",
},
+ {
+ to: "/admin/profiles",
+ label: "Profile accounts",
+ blurb: "Invite people to make a profile account, approve their claims to a People record, and link their Discord.",
+ minRole: "admin",
+ },
{
to: "/admin/blog_posts",
label: "Blog posts",
From a6c66d46070eb9cb2fe57f627611b8c1993cfc4f Mon Sep 17 00:00:00 2001
From: Aidan Dona
Date: Fri, 16 Oct 2026 18:21:53 -0500
Subject: [PATCH 38/90] Drafts of every record, previewed on the real page
Migration 077 keeps one draft per record of any entity. Saving a draft
checks it by applying it in a transaction that is rolled back; Preview
opens the record's page in a tab that sends X-Draft-Preview, and the
server answers those reads from a second connection holding the applied
draft, then rolls back, so nobody else sees it. Publish is the ordinary
save, which drops the draft. tx() now nests as a savepoint.
Also commits TODO.md: the answered questions, and parts 1 to 3 moved to
Done.
Co-Authored-By: Claude Opus 5.5
---
CLAUDE.md | 1 +
TODO.md | 84 +++++++--------
docs/drafts.md | 46 ++++++++
server/src/db.js | 48 ++++++++-
server/src/drafts.js | 156 +++++++++++++++++++++++++++
server/src/index.js | 5 +
server/src/migrations/077_drafts.sql | 25 +++++
server/src/routes/admin-entities.js | 34 +++++-
src/components/Layout.tsx | 15 ++-
src/lib/adminSchema.ts | 26 +++++
src/lib/api.ts | 42 +++++++-
src/pages/admin/EntityEdit.tsx | 137 +++++++++++++++++++++--
src/pages/admin/EntityList.tsx | 22 ++--
13 files changed, 576 insertions(+), 65 deletions(-)
create mode 100644 docs/drafts.md
create mode 100644 server/src/drafts.js
create mode 100644 server/src/migrations/077_drafts.sql
diff --git a/CLAUDE.md b/CLAUDE.md
index c0b625b..fa0d046 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -88,6 +88,7 @@ Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema/` (se
- The `OMIT` sentinel distinguishes unsent fields from deliberate clears.
- `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree.
- `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift.
+- Drafts (migration 077, `server/src/drafts.js`, `docs/drafts.md`): any existing record can be saved as a draft (one per record), previewed on the real page and published (the ordinary PATCH, which drops the draft). Checking and previewing apply the draft in a transaction that is rolled back; `tx()` nests as a savepoint for that, so never call `BEGIN` by hand. A new entity with a public page adds its path to `PREVIEW_PATHS` in `src/lib/adminSchema.ts`.
## Migrations
- `server/src/migrations/066_schema.sql` is the baseline: the whole schema, consolidated on 2026-10-04 from the old 023–066 (generated from the live schema, so the comments are the ones inside each table). `066_seed.sql` runs right after it with the least a new database needs (single rows, event scopes, the site pages' sections, the Musicians tag); content is typed in through the admin. Both only run on an empty database; the runner refuses a database between v1 and v65 (bring it to v66 with a release from before the consolidation first). It's the place to read the schema, not to change it: a database that already exists never re-runs it.
diff --git a/TODO.md b/TODO.md
index a7b934c..61b0a9e 100644
--- a/TODO.md
+++ b/TODO.md
@@ -13,8 +13,7 @@
- [ ] Are these three tabs, three sections (each in the side nav), or a filter over one list? Answer:
- [ ] Does each resource belong to exactly one audience, or can it be in several (eg. a tag per audience)? Answer:
- [ ] What happens to the page's current sections: move under an audience, or replaced? Answer:
-- [ ] **Library (New Thought Nexus)**: a library for NGUers.
- - [ ] Which name: Library, New Thought Nexus, or both (Nexus as the page, Library as a section)? Answer:
+- [ ] **Library**: a library for NGUers.
- [ ] What goes in it: links out, uploaded files (Drive "Media"), books, videos, our own articles? Answer:
- [ ] Public, or only for NGUers? If only NGUers, how do they sign in (there are only admin accounts today)? Answer:
- [ ] Is the metaphysics dictionary / Metaphysical Bible Dictionary part of it (see Future: Poetry Builder needs the same import)? Answer:
@@ -53,27 +52,24 @@
- [ ] Is this a section to build (eg. on Organization or Partners), or a question to answer in a blog post? Answer:
## Page Features
-- [ ] **Full profiles**: people get full profile pages.
+- [ ] **Full profiles**: people get full profile pages. Profile accounts, claiming and visibility are done (Part 2, Accounts); what's left is the page itself.
- [ ] What is missing from a person's page today that makes it "full": bio, more photos, links, events they spoke at, groups, blog posts they wrote? Answer:
- - [ ] Do people edit their own profile (they'd need accounts), or do admins edit them? Answer:
- - [ ] Every person, or only those with a profile switched on (privacy)? Answer:
- - [ ] Ties to Planning Center sync (Data) and the gamification below? Answer:
+ - [ ] Ties to Planning Center sync (Data) and the gamification below? Answer:
- [ ] **Page preview images per page**: the event's banner on event pages, the person's photo on theirs, the org's logo on org pages.
- Already done in `server/src/pageMeta.js`: events use the event photo, then the event logo, then its org's logo; people their photo; orgs, teams and awards their logo; blog posts their cover. SVG logos are skipped (social sites don't show them).
- [ ] Which page showed the wrong picture, and where (Discord, iMessage, Facebook)? Answer:
- [ ] Is it production (not deployed yet?) or the SVG skip? Should an SVG logo get a PNG copy made at upload for previews? Answer:
- [ ] Should event pages prefer the card background ("banner") over the event photo? Answer:
-- [ ] **Blog page tabs**: a blog index with tabs (there is no /blog index page today, only /blog/).
- - [ ] Tabs by tag, by author, or fixed kinds (eg. News, Stories, Guides, Website updates)? Answer:
- - [ ] A new /blog page in the nav, or tabs on the Community blog section? Answer:
-- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord.
- - [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer:
- - [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer:
- - [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer:
- - [ ] How do we match a person to their Discord account (they link it themselves)? Answer:
+- [ ] **Blog page tabs**: tabs within a blog post, at the top.
+ - [ ] each tab would switch the active display of content and table of contents, there could be some title/intro content above the tabs.
+- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord. Linking a profile to Discord is done (Part 2, Accounts); the bot, points and badges are next.
+ - [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer: all of the above, we could create badges on profiles.
+ - [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer: shown on profiles when logged in, no leaderboard for now, and when using a command in discord. this content would not show on the public bio section of a user when viewing from a people tile.
+ - [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer: would like a bot built, for if things in discord update or affect gamification shown on the website. most things will be assigned to users by moderators.
+ - [ ] How do we match a person to their Discord account (they link it themselves)? Answer: they can link it, admins can overwrite and update/set
- [ ] **Site version names**: each update gets a name, "The ___ Update", Minecraft style.
- - [ ] Shown where: the footer next to the version, the changelog, both? Answer:
- - [ ] Does the tag suffix become the name (v1.13.2-region-cards → "The Region Cards Update"), or a name of its own? Answer:
+ - [ ] Shown where: the footer next to the version, the changelog, both? Answer: both
+ - [ ] Does the tag suffix become the name (v1.13.2-region-cards → "The Region Cards Update"), or a name of its own? Answer: yeah the tag.
## Accessibility Features
- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner.
@@ -84,48 +80,31 @@
## Mobile
- [ ] **Featured event label on the front page**: where it sits doesn't make sense, at least on mobile.
- - [ ] Where should it go: above the card, on the card's photo, or dropped on mobile? Answer:
- - [ ] Same change on desktop? [ ] yes
+ - [ ] Where should it go: above the card, on the card's photo, or dropped on mobile? Answer: droppd on mobile
+ - [ ] Same change on desktop? move above the section on the right displaying the featured event.
## Page Editing
-- [ ] **Draft edits of sections and pages**: change a page or section without publishing it straight away.
- - [ ] Which editors: Pages (Front page, Retreats, Community...) only, or every record (events, people...) too? Answer:
- - [ ] Preview the draft on the real page before publishing? [ ] yes
- - [ ] Can editors save drafts and only admins publish (an approval step), or does anyone who can edit publish? Answer:
- - [ ] One draft per page at a time, or several? Answer:
## Admin
## Data
- [ ] **Planning Center sync to People**: Planning Center People into the site's people records.
- - [ ] One way (Planning Center → site), or both? Answer:
- - [ ] Who gets synced: everyone, or a Planning Center list or tag (eg. "Website")? Most people in Planning Center shouldn't have a public page. Answer:
+ - [ ] One way (Planning Center → site), or both? Answer: to site only
+ - [ ] Who gets synced: everyone, or a Planning Center list or tag (eg. "Website")? Most people in Planning Center shouldn't have a public page. Answer:a specific list
- [ ] Which fields: name, photo, email, phone, birthday? Which win when both sides differ? Answer:
- - [ ] How often: a button in Data, hourly, nightly? Answer:
- - [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer:
-- [ ] **New Thought young adult directory**: authors and TikTok and Instagram creators (faceless but organic).
- - [ ] People records with a new People tag (like Musicians), or a separate list of links (they aren't NGU people)? Answer:
- - [ ] What does "faceless but organic" mean for what's shown: no photo, only their handle and a link? Answer:
- - [ ] Do they agree to be listed, or is it a public list of public accounts? Answer:
- - [ ] Where does it show: Resources (For Young Adults), the Library, Community? Answer:
+ - [ ] How often: a button in Data, hourly, nightly? Answer: manually only
+ - [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer: use the API
+- [ ] **New Thought young adult directory**: things like authors and TikTok and Instagram creators.
+ - [ ] section in the community page, Directories. tabs with different people lists, we have musicians already.
+ - [ ] Do they agree to be listed, or is it a public list of public accounts? Answer: we add them to the list as admins
## Navigation
-- [ ] **Shop button** at the top right of the header.
- - [ ] Where does it go: an existing store (which URL), or a shop we build? Answer:
- - [ ] Shown on mobile too (in the menu, or beside it)? Answer:
-- [ ] **Manage the nav, sitemap and page headers from the admin**, so pages that aren't done can be hidden.
- - [ ] Hidden means: out of the nav and sitemap only (the address still works, like Unlisted), or the page returns Not found to non-admins? Answer:
- - [ ] What else is editable: link order, labels, which header menu a link is in, page titles and their blurbs? Answer:
- - [ ] `navConfig.ts` is the source of truth today; OK to move the editable parts into the database with navConfig as the defaults? [ ] yes
## Tools
- [ ] **File conversion**: a simple tool, eg. WebP to JPG.
- - [ ] Which conversions: images only (WebP, JPG, PNG, HEIC?), or also documents (Word to PDF) and video? Answer:
- - [ ] In the browser (nothing uploaded, images only), or on the server (more formats)? Answer:
+ - [ ] Which conversions: images only (WebP, JPG, PNG, HEIC?), or also documents (Word to PDF) and video? Answer: image converson
+ - [ ] In the browser (nothing uploaded, images only), or on the server (more formats)? Answer: images only.
- [ ] Also a "Download as JPG" on files in the Media library? [ ] yes
-- [ ] **What is needed for SEE**: list it.
- - [ ] What is SEE (an event, a program, a system)? Answer:
- - [ ] Is the list a page on the site, a TODO here, or a document? Answer:
## Content
- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post.
@@ -154,6 +133,23 @@
# Part 2: Done
+## Page Editing (branch `nav-access`, no PR yet; migration 077)
+- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft.
+- [x] **Preview on the real page**: Preview saves the draft and opens the record's page in a new tab with it applied, under an amber "Previewing a draft" bar, for signed-in admin accounts only; anyone else sees the live page. The server answers that tab's reads from a second connection holding the draft in a transaction it rolls back, so no page needed code of its own.
+ - [ ] Check in a browser: save a draft of an event, a site page (a section's title) and Navigation (a link), preview each, publish one, discard one; open the same address signed out.
+
+## Accounts (branch `nav-access`, no PR yet; migration 076, back up the database before deploying)
+- [x] **Profile accounts** (migration 076, `docs/profile-accounts.md`): a member role below viewer, signed in to the site and their own profile, never the admin (`/api/admin` now refuses anything under viewer). By invite only: Data → Profile accounts (admins and up) adds an email and shows its link once; Email invite sends a fresh one through Gmail. The link (`/account/welcome`) sets a password, or they sign in with Google under that email, any Google account. A New sign-in link on the account doubles as a password reset.
+- [x] **Claiming a People record**: on `/account` (Your profile; the footer's Sign in link) they ask to be a record; admins approve or decline it under Claims, or set it directly on the account.
+- [x] **Editing it and choosing what shows**: with a record, they edit its pronouns, tagline, location, public email and phone, bio and photo, and hide any of photo, pronouns, tagline, bio, email, phone, location, links. Hidden parts stay in the record (the People editor shows the same switches) and are left out everywhere on the site: every public read of people goes through the new `v_people_public` view, and the views that read people were rebuilt over it.
+- [x] **Discord linking**: a profile links its Discord account (identify scope: id and name) from `/account`; an admin can set or clear it on the account. Off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set on the service.
+ - [ ] Check in a browser: invite (copy link and Email invite), the welcome page with a password and with a non-org Google account, a claim and its approval, editing and hiding (then the person's page, a team page and a people tile signed out), Discord linking once it's set up, a member opening /admin.
+
+## Navigation (branch `nav-access`, no PR yet; migration 075, back up the database before deploying)
+- [x] **Pages → Navigation** (migration 075): the header's pages and buttons, the footer's Get in Touch and bottom row, edited in the admin (admins and up): place, order, label, link (a page, a #section or an address elsewhere), a header page set under another page's menu (after its sections), a filled button (Give's style, also beside the footer's logo), new tab. `navConfig.ts` is now only the defaults the app starts from before the nav loads. Page titles and intros moved here from Site settings (the old rows came along).
+- [x] **Hidden pages**: a page ticked Hidden in Navigation answers Not found (404, noindex) to everyone below viewer, server and app both, and is out of the menus, the sitemap and the not-found page's suggestions; links to it are only sent to viewers and up. Signed in, it shows with a bar saying it's hidden. Its sections aren't cached (`server/src/siteNav.js`, `GET /api/nav`).
+- [x] **Shop**: a Shop page of sections at `/shop` (Pages → Shop, empty for now), starting hidden, with a Shop button in the header (beside Contact Us and Give, and in the phone menu's list with them). Unhide it in Navigation once it has content; its sections can link out to the Bonfire store.
+ - [ ] Check in a browser: the header and phone menu, a page set under another's menu, the footer, signed out and signed in (the hidden bar, Shop showing), light and dark.
## Feature updates (branch `feature-updates`, v1.13.x, no PR yet; migrations 069 to 071, back up the database before deploying)
- [x] **Partner cards, logo first**: the organization cards (Partners, Ministries) lead with the logo, large and centered, the name under it as a small line (still the heading); with no logo, its initials. Cards sit raised with a shadow and an accent top edge.
- [x] **Frame a photo on upload**: photo fields (people, event photo and card background, blog cover and guest photo, hero photos, link card pictures, block images, schedule graphics and map images; not logos) open Frame the photo for a JPEG, PNG or WebP: drag (or arrow keys) to place, zoom slider, a shape menu (the field's own first; As uploaded keeps the photo's). The framed part is what uploads; Upload as is skips. Nothing stored beside the picture, so re-framing is uploading again.
diff --git a/docs/drafts.md b/docs/drafts.md
new file mode 100644
index 0000000..f275ed3
--- /dev/null
+++ b/docs/drafts.md
@@ -0,0 +1,46 @@
+# Drafts
+
+Any record the admin edits (events, people, organizations, blog posts,
+the front page, the site pages, Navigation, Site settings...) can be
+saved as a draft instead of going live (migration 077). One draft per
+record; anyone who can edit the record can save, preview, publish or
+discard it.
+
+## In the editor
+
+- **Save draft** keeps the form as the record's draft. It's checked the
+ way a save is (same field errors), but nothing on the site changes.
+- **Preview** saves the draft and opens the record's page in a new tab
+ showing it, with an amber bar ("Previewing a draft"). Only a
+ signed-in admin account (viewer and up) sees the draft; anyone else
+ opening that address sees the live page. Stop previewing in the bar
+ returns the tab to the live site.
+- **Publish** (the Save button, while there's a draft) saves it for
+ real and drops the draft.
+- **Discard draft** throws it away; the live version is untouched.
+
+Opening a record that has a draft opens the draft, with a note saying
+who saved it and when. If the live record was saved after the draft was
+started, the note says so: publishing replaces those changes. Lists
+mark records with a draft.
+
+Records not yet created have no drafts: Create is the only save (leave
+them unpublished until they're ready).
+
+## How it works
+
+`server/src/drafts.js`. A draft is the editor's whole form, as a save
+would send it. Saving one applies it inside a transaction that is
+always rolled back (`rolledBackSync` in `server/src/db.js`), so it's
+validated without being written. A preview is a public API read sent
+with `X-Draft-Preview: /` (`src/lib/api.ts` adds it in a tab
+opened with `?preview=`): the server opens a second connection to the
+database, applies the draft in a transaction there, answers the read
+from it, and rolls back. WAL keeps those writes unseen by every other
+request. Public reads carry `Vary: X-Draft-Preview`, so a browser never
+mixes a cached live answer with a preview.
+
+`tx()` nests as a savepoint, which is what lets a save run inside the
+rolled-back transaction. Where each entity's page is: `PREVIEW_PATHS` in
+`src/lib/adminSchema.ts` (an entity without one has drafts but no
+Preview button).
diff --git a/server/src/db.js b/server/src/db.js
index 63a2cce..c645c8d 100644
--- a/server/src/db.js
+++ b/server/src/db.js
@@ -36,27 +36,67 @@ export async function openDatabase(path) {
db.exec("PRAGMA busy_timeout = 5000");
db.driverName = "node:sqlite";
+ // A draft's preview opens its own connection to the same file (drafts.js).
+ db.path = path;
return db;
}
/* ── Transactions ──────────────────────────────────────────────
node:sqlite has no db.transaction(), so do it by hand. Runs
- fn() and commits, or rolls back and rethrows.
+ fn() and commits, or rolls back and rethrows. Inside another
+ tx() (or rolledBack(), below) it's a savepoint instead, so a
+ save can run inside a transaction that's then thrown away:
+ how a draft is checked and previewed (drafts.js).
───────────────────────────────────────────────────────────── */
export function tx(db, fn) {
- db.exec("BEGIN");
+ const depth = db.txDepth ?? 0;
+ const savepoint = `tx_${depth}`;
+ db.exec(depth ? `SAVEPOINT ${savepoint}` : "BEGIN");
+ db.txDepth = depth + 1;
try {
const result = fn();
- db.exec("COMMIT");
+ db.exec(depth ? `RELEASE ${savepoint}` : "COMMIT");
return result;
} catch (err) {
try {
- db.exec("ROLLBACK");
+ db.exec(depth ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
} catch {
/* already rolled back */
}
throw err;
+ } finally {
+ db.txDepth = depth;
+ }
+}
+
+/* Runs fn() in a transaction that is always rolled back, whatever
+ fn() does: its writes are seen only by fn() itself. fn() may wait,
+ so only on a connection of its own (a draft's preview, drafts.js):
+ on the main one, another request would see the writes meanwhile. */
+export async function rolledBack(db, fn) {
+ if (db.txDepth) throw new Error("rolledBack() can't run inside a transaction.");
+ db.exec("BEGIN");
+ db.txDepth = 1;
+ try {
+ return await fn();
+ } finally {
+ db.txDepth = 0;
+ db.exec("ROLLBACK");
+ }
+}
+
+/* The same for a synchronous fn(), which nothing else can run
+ during, so the main connection is fine (checking a draft). */
+export function rolledBackSync(db, fn) {
+ if (db.txDepth) throw new Error("rolledBackSync() can't run inside a transaction.");
+ db.exec("BEGIN");
+ db.txDepth = 1;
+ try {
+ return fn();
+ } finally {
+ db.txDepth = 0;
+ db.exec("ROLLBACK");
}
}
diff --git a/server/src/drafts.js b/server/src/drafts.js
new file mode 100644
index 0000000..614e3e5
--- /dev/null
+++ b/server/src/drafts.js
@@ -0,0 +1,156 @@
+/* ═══════════════════════════════════════════════════════════════
+ DRAFTS (077_drafts.sql)
+
+ A record's changes saved without going live: one per record, of
+ any entity the admin edits. The draft is the editor's whole form,
+ exactly what a save would send, so publishing is that save
+ (PATCH, routes/admin-entities.js), which then drops the draft.
+
+ Nothing applies a draft for real until it's published. Twice it's
+ applied and thrown away:
+
+ checking when it's saved, in a transaction on the main
+ connection that's always rolled back
+ (rolledBackSync): updateRow is synchronous, so no
+ other request can see it, and a draft that a save
+ would refuse is refused now, with the same errors
+
+ preview a public API read sent with X-Draft-Preview:
+ / by a signed-in viewer and up runs on a
+ connection of its own (the same file), inside a
+ transaction holding the applied draft, rolled back
+ when the answer is made (previewDrafts). The site
+ draws the real page from it, with no code of its own
+ for previews. WAL keeps that connection's writes
+ unseen by everyone else; it holds the write lock
+ meanwhile, a few milliseconds, which other writes
+ wait out (busy_timeout).
+
+ The draft is applied over the live record as it is now, so a
+ save made since the draft was started is overwritten when it's
+ published; the editor says when that's so (stale).
+ ═══════════════════════════════════════════════════════════════ */
+
+import { currentUser, hasRole } from "./auth.js";
+import { openDatabase, rolledBack, rolledBackSync } from "./db.js";
+import { HttpError, normalizeId, updateRow } from "./admin-crud.js";
+import { ENTITIES } from "./admin-schema.js";
+
+/* Who may preview a draft: anyone who can read the admin. */
+export const PREVIEWS = "viewer";
+
+export const entityNamed = (key) => (Object.hasOwn(ENTITIES, key) ? ENTITIES[key] : null);
+
+const liveStamp = (db, entity, id) =>
+ entity.concurrency
+ ? db
+ .prepare(`SELECT ${entity.concurrency} AS stamp FROM ${entity.table} WHERE ${entity.idColumn} = ?`)
+ .get(normalizeId(entity, id))?.stamp
+ : undefined;
+
+/* Writes the draft over the live record, its concurrency stamp taken
+ from the live row so the check passes. Call inside a rolled-back
+ transaction, or as the real publish. */
+function apply(db, entity, id, payload) {
+ const stamp = liveStamp(db, entity, id);
+ return updateRow(db, entity, id, entity.concurrency ? { ...payload, [entity.concurrency]: stamp } : payload);
+}
+
+export function readDraft(db, key, id) {
+ const entity = entityNamed(key);
+ const row = db
+ .prepare(
+ `SELECT d.*, u.name AS updated_by_name, u.email AS updated_by_email
+ FROM drafts d LEFT JOIN admin_users u ON u.id = d.updated_by
+ WHERE d.entity = ? AND d.record_id = ?`,
+ )
+ .get(key, String(id));
+ if (!row) return null;
+ const live = entity ? liveStamp(db, entity, id) : undefined;
+ return {
+ payload: JSON.parse(row.payload),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ updated_by: row.updated_by_name ?? row.updated_by_email ?? null,
+ // The live record was saved after the draft was started.
+ stale: Boolean(entity?.concurrency && row.base_updated_at && live && live !== row.base_updated_at),
+ };
+}
+
+/* The ids of an entity's records that have a draft, for its list. */
+export const draftIds = (db, key) =>
+ db.prepare(`SELECT record_id FROM drafts WHERE entity = ?`).all(key).map((row) => row.record_id);
+
+/* Checks the draft by applying it and throwing that away, then keeps
+ it. An HttpError from the check (422 with fields, say) refuses it. */
+export function saveDraft(db, key, id, payload, userId) {
+ const entity = entityNamed(key);
+ if (!entity) throw new HttpError(404, "Unknown entity.");
+ if (!payload || typeof payload !== "object") throw new HttpError(400, "Expected the record's form.");
+ rolledBackSync(db, () => apply(db, entity, id, payload));
+
+ const existing = db.prepare(`SELECT base_updated_at FROM drafts WHERE entity = ? AND record_id = ?`).get(key, String(id));
+ const base = existing ? existing.base_updated_at : (payload[entity.concurrency] ?? null);
+ db.prepare(
+ `INSERT INTO drafts (entity, record_id, payload, base_updated_at, created_by, updated_by)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT (entity, record_id) DO UPDATE
+ SET payload = excluded.payload, updated_by = excluded.updated_by, updated_at = datetime('now')`,
+ ).run(key, String(id), JSON.stringify(payload), base, userId, userId);
+ return readDraft(db, key, id);
+}
+
+export function dropDraft(db, key, id) {
+ db.prepare(`DELETE FROM drafts WHERE entity = ? AND record_id = ?`).run(key, String(id));
+}
+
+/* Middleware for the public API: a GET carrying X-Draft-Preview from
+ a signed-in viewer and up is answered with that draft applied. Any
+ other request, or a draft that isn't there, goes on as usual. */
+export async function previewDrafts(c, next) {
+ if (c.req.method !== "GET" || /^\/api\/(admin|auth|account)(\/|$)/.test(c.req.path)) return next();
+ await answer(c, next);
+ // A public read may be kept a minute (shape.js, CACHE): never hand
+ // the live copy to a preview tab, or a preview's to anyone.
+ c.res.headers.append("Vary", "X-Draft-Preview");
+}
+
+async function answer(c, next) {
+ const wanted = c.req.header("x-draft-preview");
+ if (!wanted) return next();
+
+ const main = c.get("db");
+ if (!hasRole(currentUser(main, c), PREVIEWS)) return next();
+
+ const slash = wanted.indexOf("/");
+ const key = wanted.slice(0, slash);
+ let id;
+ try {
+ id = decodeURIComponent(wanted.slice(slash + 1));
+ } catch {
+ return next();
+ }
+ const entity = entityNamed(key);
+ const draft = slash > 0 && entity ? readDraft(main, key, id) : null;
+ if (!draft) return next();
+
+ const db = await openDatabase(main.path);
+ try {
+ await rolledBack(db, async () => {
+ // A draft the record has outgrown (a field it no longer has,
+ // say) shows the live page rather than an error; saving it in
+ // the editor says what's wrong.
+ try {
+ apply(db, entity, id, draft.payload);
+ } catch (err) {
+ console.warn(`draft preview ${key}/${id} not applied: ${err.message}`);
+ }
+ c.set("db", db);
+ await next();
+ });
+ } finally {
+ db.close();
+ }
+ // Only for this tab, never kept.
+ c.res.headers.set("Cache-Control", "no-store");
+}
diff --git a/server/src/index.js b/server/src/index.js
index 925c37c..a1ec0ea 100644
--- a/server/src/index.js
+++ b/server/src/index.js
@@ -50,6 +50,7 @@ import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
import { ENTITIES } from "./admin-schema.js";
+import { previewDrafts } from "./drafts.js";
const HOST = process.env.HOST ?? "127.0.0.1";
const PORT = Number(process.env.PORT ?? 3001);
@@ -180,6 +181,10 @@ app.use("*", async (c, next) => {
await next();
});
+// A draft's preview (drafts.js): a public read from a signed-in
+// viewer with X-Draft-Preview answers with that draft applied.
+app.use("/api/*", previewDrafts);
+
app.get("/api/health", (c) =>
c.json({ ok: true, schema: version, driver: db.driverName }),
);
diff --git a/server/src/migrations/077_drafts.sql b/server/src/migrations/077_drafts.sql
new file mode 100644
index 0000000..1a6c259
--- /dev/null
+++ b/server/src/migrations/077_drafts.sql
@@ -0,0 +1,25 @@
+-- ═══════════════════════════════════════════════════════════════
+-- 077 DRAFTS
+--
+-- A record's changes saved without going live: one draft per
+-- record, of any entity the admin edits (events, people, pages,
+-- Navigation...). payload is the editor's whole form, as a save
+-- would send it; publishing is that save, which then drops the
+-- draft. Anyone who can edit the record can save, preview, publish
+-- or discard it (drafts.js).
+--
+-- base_updated_at is the record's updated_at when the draft was
+-- started, so the editor can say the live record changed since.
+-- ═══════════════════════════════════════════════════════════════
+
+CREATE TABLE drafts (
+ entity TEXT NOT NULL, -- the descriptor key, eg. 'events'
+ record_id TEXT NOT NULL,
+ payload TEXT NOT NULL CHECK (json_valid(payload)),
+ base_updated_at TEXT,
+ created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
+ PRIMARY KEY (entity, record_id)
+) STRICT;
diff --git a/server/src/routes/admin-entities.js b/server/src/routes/admin-entities.js
index 2ead205..0656872 100644
--- a/server/src/routes/admin-entities.js
+++ b/server/src/routes/admin-entities.js
@@ -6,7 +6,11 @@
GET /api/admin/:entity/:id row with side tables and children
POST /api/admin/:entity create
PATCH /api/admin/:entity/:id replace the row and its children
+ (publishing a draft too: it's dropped)
DELETE /api/admin/:entity/:id
+ GET /api/admin/:entity/:id/draft its draft, or null (drafts.js)
+ PUT /api/admin/:entity/:id/draft save the form as its draft
+ DELETE /api/admin/:entity/:id/draft discard it
Mounted alongside the existing admin router, which keeps the
feedback routes. Both sit under the same requireAuth.
@@ -29,6 +33,7 @@ import {
deleteRow,
} from "../admin-crud.js";
import { NO_STORE } from "../shape.js";
+import { draftIds, dropDraft, readDraft, saveDraft } from "../drafts.js";
const entities = new Hono();
@@ -84,7 +89,8 @@ entities.get("/options", (c) => {
entities.get("/:entity", (c) => {
const entity = entityOr404(c);
const { rows, total } = listRows(c.get("db"), entity, c.req.query());
- return c.json({ rows, total }, 200, NO_STORE);
+ // Which of them have a draft waiting, for the list to mark.
+ return c.json({ rows, total, drafts: draftIds(c.get("db"), entity.key) }, 200, NO_STORE);
});
entities.get("/:entity/:id", (c) => {
@@ -103,6 +109,8 @@ entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
+ // Saved for real: any draft of it is published, or overtaken.
+ dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
return c.json({ row }, 200, NO_STORE);
});
@@ -111,10 +119,34 @@ entities.delete("/:entity/:id", requireRole("admin"), (c) => {
const entity = entityOr404(c);
const id = c.req.param("id");
deleteRow(c.get("db"), entity, id);
+ dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
+/* ── Drafts (drafts.js) ──────────────────────────────────────── */
+
+entities.get("/:entity/:id/draft", (c) => {
+ const entity = entityOr404(c);
+ return c.json({ draft: readDraft(c.get("db"), entity.key, c.req.param("id")) }, 200, NO_STORE);
+});
+
+entities.put("/:entity/:id/draft", requireRole("editor"), async (c) => {
+ const entity = entityForWrite(c);
+ const id = c.req.param("id");
+ const draft = saveDraft(c.get("db"), entity.key, id, await json(c), c.get("user").id);
+ console.log(`${entity.key} ${id} draft saved by ${c.get("user").email}`);
+ return c.json({ draft }, 200, NO_STORE);
+});
+
+entities.delete("/:entity/:id/draft", requireRole("editor"), (c) => {
+ const entity = entityForWrite(c);
+ const id = c.req.param("id");
+ dropDraft(c.get("db"), entity.key, id);
+ console.log(`${entity.key} ${id} draft discarded by ${c.get("user").email}`);
+ return c.body(null, 204);
+});
+
async function json(c) {
try {
return await c.req.json();
diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx
index 4c2a0f3..0bf5727 100644
--- a/src/components/Layout.tsx
+++ b/src/components/Layout.tsx
@@ -1,4 +1,4 @@
-import { X, List, EyeSlash } from "@phosphor-icons/react";
+import { X, List, EyeSlash, PencilSimple } from "@phosphor-icons/react";
import { lazy, Suspense, useState, useEffect, useRef } from "react";
import { NavLink, Link, Outlet, useLocation } from "react-router-dom";
import type { NavLink as NavLinkItem } from "../navConfig.ts";
@@ -15,6 +15,7 @@ import ReaderView from "./ReaderView.tsx";
import ThemeToggle from "./ThemeToggle.tsx";
import { jumpTo } from "../lib/focus.ts";
import { useReadingMode } from "../lib/readingMode.ts";
+import { draftPreview, stopPreview } from "../lib/api.ts";
const NotFound = lazy(() => import("../pages/NotFound.tsx"));
@@ -87,6 +88,17 @@ export default function Layout() {
const page = (
{hiddenHere && !nav.seesHidden ? : }
);
+ // A draft's preview tab (api.ts): the page as it would be with the
+ // draft published, for signed-in admin accounts.
+ const previewBar = draftPreview && (
+
+
+ Previewing a draft: this is how it will look once published. Nobody else sees it.
+
+ Stop previewing
+
+
+ );
const hiddenBar = hiddenHere && nav.seesHidden && (
@@ -323,6 +335,7 @@ export default function Layout() {
{/* Page content */}
+ {previewBar}
{hiddenBar}
{page}
diff --git a/src/lib/adminSchema.ts b/src/lib/adminSchema.ts
index 5fe00bc..5393f63 100644
--- a/src/lib/adminSchema.ts
+++ b/src/lib/adminSchema.ts
@@ -18,6 +18,7 @@
and never fills in reads as real input instead of being skipped.
═══════════════════════════════════════════════════════════════ */
+import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from "./hrefs.ts";
import { organizations } from "./adminSchema/organizations.ts";
import { events } from "./adminSchema/events.ts";
import { people } from "./adminSchema/people.ts";
@@ -64,6 +65,31 @@ export const ADMIN_ENTITIES: Record = {
site_settings: siteSettings,
};
+/* Where each entity's record shows on the site, for its draft's
+ Preview (EntityEdit.tsx opens it with ?preview=, which api.ts sends
+ on as X-Draft-Preview; server/src/drafts.js). An entity without
+ one has drafts but nothing to preview them on. */
+export const PREVIEW_PATHS: Record string | null> = {
+ organizations: (row) => (row.kind === "ministry" ? null : orgHref(row.id, row.kind)),
+ events: (row) => eventHref(row.id),
+ people: (row) => personHref(row.id),
+ person_tag_types: (row) => `/directory/${encodeURIComponent(row.id)}`,
+ teams: (row) => teamHref(row.id),
+ awards: (row) => awardHref(row.id),
+ timeline: () => "/history",
+ front_page: () => "/",
+ blog_posts: (row) => blogHref(row.id),
+ community_page: () => "/community",
+ retreats_page: () => "/retreats",
+ resources_page: () => "/resources",
+ organization_page: () => "/organization",
+ history_page: () => "/history",
+ shop_page: () => "/shop",
+ // The menus are on every page.
+ navigation: () => "/",
+ site_settings: () => "/",
+};
+
/* The /admin/options request for the option lists `part` of a
manifest names (any `optionsFrom` inside it, at any depth), so a
form gets only the lists its selects use. An empty request would
diff --git a/src/lib/api.ts b/src/lib/api.ts
index f5379ea..1302bda 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -21,6 +21,36 @@ import { visionColor } from "./color.ts";
const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
const DEFAULT_TTL = 60_000;
+/* A draft's preview (server/src/drafts.js): a tab opened from the
+ editor's Preview with ?preview=/ sends it with every
+ read of the site's data, for as long as the tab lasts, and the
+ server answers with that draft applied (to a signed-in viewer and
+ up; anyone else gets the live site). Never for the admin's own
+ reads. */
+const PREVIEW_KEY = "site-draft-preview";
+
+export const draftPreview: string | null = (() => {
+ if (typeof window === "undefined") return null;
+ try {
+ const asked = new URLSearchParams(window.location.search).get("preview");
+ if (asked) sessionStorage.setItem(PREVIEW_KEY, asked);
+ return asked ?? sessionStorage.getItem(PREVIEW_KEY);
+ } catch {
+ return null;
+ }
+})();
+
+export function stopPreview() {
+ try {
+ sessionStorage.removeItem(PREVIEW_KEY);
+ } catch {
+ // Nothing kept to clear.
+ }
+ const url = new URL(window.location.href);
+ url.searchParams.delete("preview");
+ window.location.replace(url.toString());
+}
+
const cache = new Map(); // path → { at, promise }
const settled = new Map(); // path → the last body it answered with
@@ -44,9 +74,11 @@ const NOT_THE_API: Record = {
};
async function request(path, options: RequestInit = {}) {
+ const preview: Record =
+ draftPreview && !String(path).startsWith("/admin") ? { "X-Draft-Preview": draftPreview } : {};
const response = await fetch(`${BASE}${path}`, {
...options,
- headers: { Accept: "application/json", ...options.headers },
+ headers: { Accept: "application/json", ...preview, ...(options.headers as Record) },
});
if (response.status === 204) return null;
@@ -151,6 +183,14 @@ export function patch(path, data) {
});
}
+export function put(path, data) {
+ return request(path, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(data),
+ });
+}
+
export function del(path) {
return request(path, { method: "DELETE" });
}
diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx
index 7a12bfa..67f8e3d 100644
--- a/src/pages/admin/EntityEdit.tsx
+++ b/src/pages/admin/EntityEdit.tsx
@@ -33,6 +33,15 @@
None of this is protection. The server refuses the request; this
only decides whether to draw a button that would be refused.
+ Drafts (server/src/drafts.js): an existing record can be saved as
+ a draft instead, which isn't live. One per record: opening the
+ record opens its draft, if it has one, for anyone who edits it.
+ Preview saves it and opens the record's page (PREVIEW_PATHS) in a
+ new tab showing it; Publish is the ordinary save, which drops the
+ draft; Discard throws it away. A draft is applied over the live
+ record as it is when published, so the editor says when the live
+ one was saved after the draft was started.
+
The page is laid out as sections: the URL ID, each field group,
then each child collection in a card of its own. SectionNav lists
them (a sticky column on wide screens, a "Jump to" bar below lg),
@@ -50,11 +59,11 @@ import { ArrowLeft, Check, Copy } from "@phosphor-icons/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
-import { get, post, patch, del, ApiError } from "../../lib/api.ts";
+import { get, post, patch, put, del, ApiError } from "../../lib/api.ts";
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
import { useAdminDetail } from "../../lib/adminTitle.tsx";
import { useWideAdminPage } from "../../lib/adminWidth.tsx";
-import { ADMIN_ENTITIES, optionsPath, slugify } from "../../lib/adminSchema.ts";
+import { ADMIN_ENTITIES, PREVIEW_PATHS, optionsPath, slugify } from "../../lib/adminSchema.ts";
import { atLeast } from "../../lib/roles.ts";
import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx";
import {
@@ -154,6 +163,8 @@ export default function EntityEdit() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [slugTouched, setSlugTouched] = useState(false);
+ // This record's draft, when it has one: who saved it, when, stale.
+ const [draft, setDraft] = useState(null);
// The last state the server confirmed. Everything else compares
// against this to decide whether there's anything to lose.
@@ -191,8 +202,17 @@ export default function EntityEdit() {
setForm(start);
} else {
const data = await get(`/admin/${manifest.key}/${id}`, { ttl: 0 });
- setForm(data.row);
- baseline.current = JSON.stringify(data.row);
+ const saved = (await get(`/admin/${manifest.key}/${id}/draft`, { ttl: 0 })).draft;
+ // With a draft, the form is the draft, over the live record's
+ // updated_at so publishing it passes the concurrency check.
+ const start = saved
+ ? data.row.updated_at === undefined
+ ? saved.payload
+ : { ...saved.payload, updated_at: data.row.updated_at }
+ : data.row;
+ setDraft(saved);
+ setForm(start);
+ baseline.current = JSON.stringify(start);
}
setMessage(null);
} catch (err) {
@@ -292,7 +312,8 @@ export default function EntityEdit() {
setForm(data.row);
baseline.current = JSON.stringify(data.row);
- setMessage({ tone: "ok", text: "Saved." });
+ setMessage({ tone: "ok", text: draft ? "Published." : "Saved." });
+ setDraft(null);
if (isNew) navigate(`/admin/${manifest.key}/${data.row.id}`, { replace: true });
} catch (err) {
@@ -321,6 +342,64 @@ export default function EntityEdit() {
}
}
+ /* Saves the form as the draft. True when it took. */
+ async function saveDraft(): Promise {
+ setSaving(true);
+ setErrors({});
+ setMessage(null);
+ try {
+ const data = await put(`/admin/${manifest.key}/${id}/draft`, form);
+ setDraft(data.draft);
+ baseline.current = JSON.stringify(form);
+ setMessage({ tone: "ok", text: "Draft saved. It isn't live until you publish it." });
+ return true;
+ } catch (err) {
+ if (isUnauthorized(err)) {
+ navigate("/admin/login", { replace: true });
+ return false;
+ }
+ if (err instanceof ApiError) {
+ setErrors(err.fields ?? {});
+ setMessage({
+ tone: "error",
+ text: err.fields ? "Some fields need attention." : friendly(err.message, manifest.singular),
+ });
+ } else {
+ setMessage({ tone: "error", text: "Couldn't reach the server." });
+ }
+ return false;
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function preview() {
+ const path = PREVIEW_PATHS[manifest.key]?.(form);
+ if (!path) return;
+ // Opened now, while this is still the click, so it isn't taken
+ // for a popup; it's sent to the page once the draft is saved.
+ const tab = window.open("about:blank", "_blank");
+ if ((dirty || !draft) && !(await saveDraft())) {
+ tab?.close();
+ return;
+ }
+ const url = `${path}${path.includes("?") ? "&" : "?"}preview=${encodeURIComponent(`${manifest.key}/${id}`)}`;
+ if (tab) tab.location.href = url;
+ else window.location.href = url;
+ }
+
+ async function discardDraft() {
+ if (!window.confirm("Discard this draft? The live version stays as it is.")) return;
+ try {
+ await del(`/admin/${manifest.key}/${id}/draft`);
+ setDraft(null);
+ await load();
+ setMessage({ tone: "ok", text: "Draft discarded." });
+ } catch (err) {
+ setMessage({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
+ }
+ }
+
async function remove() {
if (!window.confirm(`Delete ${heading}? Its links, blocks and roles go with it.`)) return;
@@ -383,6 +462,20 @@ export default function EntityEdit() {
{isNew ? `New ${manifest.singular}` : heading}
+ {draft && (
+
+
+ You're editing a draft , saved{draft.updated_by ? ` by ${draft.updated_by}` : ""} on{" "}
+ {draft.updated_at}. It isn't live: Publish puts it on the site, Discard draft throws it away.
+
+ {draft.stale && (
+
+ The live version was saved after this draft was started. Publishing replaces those changes with the draft.
+
+ )}
+
+ )}
+
{fromRequest && (
- {saving ? "Saving…" : isNew ? "Create" : "Save changes"}
+ {saving ? "Saving…" : isNew ? "Create" : draft ? "Publish" : "Save changes"}
+ {!isNew && (
+
+ Save draft
+
+ )}
+ {!isNew && PREVIEW_PATHS[manifest.key]?.(form) && (
+
+ Preview
+
+ )}
+ {draft && (
+
+ Discard draft
+
+ )}
{!isNew && !singleton && canDelete && (
([]);
const [total, setTotal] = useState(0);
+ // Ids with a draft waiting (server/src/drafts.js), marked in the list.
+ const [drafts, setDrafts] = useState>(() => new Set());
const [loadingMore, setLoadingMore] = useState(false);
const [options, setOptions] = useState({});
const [loading, setLoading] = useState(true);
@@ -57,6 +59,7 @@ export default function EntityList() {
]);
setRows(list.rows);
setTotal(list.total);
+ setDrafts(new Set((list.drafts ?? []).map(String)));
setOptions(opts.options);
} catch (err) {
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
@@ -203,13 +206,18 @@ export default function EntityList() {
}`}
>
{column.key === linkKey ? (
- e.stopPropagation()}
- className="hover:underline"
- >
- {row[column.key] || row.id}
-
+ <>
+ e.stopPropagation()}
+ className="hover:underline"
+ >
+ {row[column.key] || row.id}
+
+ {drafts.has(String(row.id)) && (
+ Draft
+ )}
+ >
) : column.widget === "bool" ? (
row[column.key] ? (
"Yes"
From 31afa889d6bfaef340bfa4f01cebcb267018ebba Mon Sep 17 00:00:00 2001
From: Aidan Dona
Date: Fri, 16 Oct 2026 19:37:07 -0500
Subject: [PATCH 39/90] Page features: directory and blog post tabs, image
converter, version names
- Featured event badge: above the event's card from lg up, left out on phones
- Version names from the tag (The Region Cards Update) in the site and admin footers
- Tools -> Image converter (JPG, PNG, WebP in the browser) and Download as in Media
- People directory sections take several tags, a tab each (migration 078)
- Tab blocks split a blog post into tabs; contents follow the open tab (migration 079)
- The side nav sun fades out as the page scrolls into the footer
Co-Authored-By: Claude Opus 5.5
---
TODO.md | 28 ++-
server/src/admin-schema/columns.js | 2 +
server/src/admin-schema/sitePages.js | 9 +-
server/src/migrations/078_directory_tabs.sql | 66 +++++++
server/src/migrations/079_tab_blocks.sql | 76 +++++++
server/src/routes/sitePages.js | 14 +-
src/App.tsx | 2 +
src/components/ContentBlocks.tsx | 8 +-
src/components/Footer.tsx | 9 +-
src/components/PageShell.css | 7 +-
src/components/PageShell.tsx | 12 +-
src/components/admin/DownloadAs.tsx | 45 +++++
src/lib/adminSchema/blog.ts | 33 +++-
src/lib/adminSchema/sitePages.ts | 23 +--
src/lib/contents.ts | 37 +++-
src/lib/convertImage.ts | 72 +++++++
src/lib/useContent.ts | 1 +
src/lib/useSitePages.ts | 4 +-
src/lib/version.ts | 24 ++-
src/pages/BlogPost.tsx | 135 ++++++++++++-
src/pages/SitePage.tsx | 6 +-
src/pages/admin/AdminConvert.tsx | 196 +++++++++++++++++++
src/pages/admin/AdminHome.tsx | 4 +-
src/pages/admin/AdminLayout.tsx | 4 +-
src/pages/admin/AdminMedia.tsx | 4 +
src/pages/admin/adminNav.ts | 5 +
src/pages/sections/PeopleDirectory.tsx | 101 +++++++++-
src/pages/sections/home/HeroStage.tsx | 21 +-
28 files changed, 878 insertions(+), 70 deletions(-)
create mode 100644 server/src/migrations/078_directory_tabs.sql
create mode 100644 server/src/migrations/079_tab_blocks.sql
create mode 100644 src/components/admin/DownloadAs.tsx
create mode 100644 src/lib/convertImage.ts
create mode 100644 src/pages/admin/AdminConvert.tsx
diff --git a/TODO.md b/TODO.md
index 61b0a9e..6128bf1 100644
--- a/TODO.md
+++ b/TODO.md
@@ -60,16 +60,13 @@
- [ ] Which page showed the wrong picture, and where (Discord, iMessage, Facebook)? Answer:
- [ ] Is it production (not deployed yet?) or the SVG skip? Should an SVG logo get a PNG copy made at upload for previews? Answer:
- [ ] Should event pages prefer the card background ("banner") over the event photo? Answer:
-- [ ] **Blog page tabs**: tabs within a blog post, at the top.
- - [ ] each tab would switch the active display of content and table of contents, there could be some title/intro content above the tabs.
+
- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord. Linking a profile to Discord is done (Part 2, Accounts); the bot, points and badges are next.
- [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer: all of the above, we could create badges on profiles.
- [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer: shown on profiles when logged in, no leaderboard for now, and when using a command in discord. this content would not show on the public bio section of a user when viewing from a people tile.
- [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer: would like a bot built, for if things in discord update or affect gamification shown on the website. most things will be assigned to users by moderators.
- [ ] How do we match a person to their Discord account (they link it themselves)? Answer: they can link it, admins can overwrite and update/set
-- [ ] **Site version names**: each update gets a name, "The ___ Update", Minecraft style.
- - [ ] Shown where: the footer next to the version, the changelog, both? Answer: both
- - [ ] Does the tag suffix become the name (v1.13.2-region-cards → "The Region Cards Update"), or a name of its own? Answer: yeah the tag.
+- [ ] **Site version names**: in the footers now (Part 2, Page features); still to show them in the changelog once it's built (Pages: Website changelog).
## Accessibility Features
- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner.
@@ -79,9 +76,6 @@
- [ ] A Listen button in the Accessibility panel, or on each page by its title? Answer:
## Mobile
-- [ ] **Featured event label on the front page**: where it sits doesn't make sense, at least on mobile.
- - [ ] Where should it go: above the card, on the card's photo, or dropped on mobile? Answer: droppd on mobile
- - [ ] Same change on desktop? move above the section on the right displaying the featured event.
## Page Editing
@@ -94,17 +88,12 @@
- [ ] Which fields: name, photo, email, phone, birthday? Which win when both sides differ? Answer:
- [ ] How often: a button in Data, hourly, nightly? Answer: manually only
- [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer: use the API
-- [ ] **New Thought young adult directory**: things like authors and TikTok and Instagram creators.
- - [ ] section in the community page, Directories. tabs with different people lists, we have musicians already.
- - [ ] Do they agree to be listed, or is it a public list of public accounts? Answer: we add them to the list as admins
+ - Skipped on 2026-10-16 until the fields (and which side wins) are decided.
+- [ ] **New Thought young adult directory**: the tabs are built (Part 2, Page features). Content: make the People tags (eg. Authors, Creators), tag people, and set Community's Directories section to them.
## Navigation
## Tools
-- [ ] **File conversion**: a simple tool, eg. WebP to JPG.
- - [ ] Which conversions: images only (WebP, JPG, PNG, HEIC?), or also documents (Word to PDF) and video? Answer: image converson
- - [ ] In the browser (nothing uploaded, images only), or on the server (more formats)? Answer: images only.
- - [ ] Also a "Download as JPG" on files in the Media library? [ ] yes
## Content
- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post.
@@ -133,6 +122,15 @@
# Part 2: Done
+## Page features (branch `page-features`, on top of `nav-access`, no PR yet; migrations 078 and 079, back up the database before deploying)
+- [x] **Featured event label** (Mobile): the "Featured event" badge left the headline; from lg up it sits above the event's card it names, and on a phone (the card under the words) it's left out.
+- [x] **Site version names**: the tag's words after the number are the version's name, `v1.13.2-region-cards` → "The Region Cards Update" (`src/lib/version.ts`), shown with the number in the site's footer and beside the version in the admin's footer and home.
+- [x] **Image converter** (Tools → Image converter): pictures to JPG, PNG or WebP in the browser (nothing uploaded): pick or drop several, a quality slider for JPG and WebP, download each or all. JPG fills transparency white. Media's images each have a Download as… (JPG, PNG, WebP) doing the same (`src/lib/convertImage.ts`).
+- [x] **Directory tabs** (migration 078): the People directory preset takes several People tags, a tab each in the order picked (Directory: tags under the section); one tag shows without tabs, reading mode lists every tag. Each section's old single tag became its first.
+- [x] **Blog post tabs** (migration 079): a Tab block in a post (its text the tab's title) starts a tab holding the blocks after it; blocks before the first Tab are the intro above the tabs. The contents list follows the open tab, a link to a heading in another tab opens it, and Download PDF and reading mode show every tab under its title. Outside a post a Tab block reads as a heading.
+- [x] **Side nav sun into the footer** (Navigation): the sun is far bigger than the sticky layer that carries it, so once the last section went up past the list it hung over the footer. It now fades out as the list leaves with the last section, and back in on the way up.
+ - [ ] Check in a browser: the side nav sun fading at the end of a long page (2xl screen) and with a tall footer; the featured event hero at phone and desktop width, the footers' version line, converting a PNG with transparency to JPG and a JPG to WebP (and Download as in Media), a Directories section with two tags and with one, a post with an intro and three tabs (contents, keyboard arrows, PDF, reading mode).
+
## Page Editing (branch `nav-access`, no PR yet; migration 077)
- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft.
- [x] **Preview on the real page**: Preview saves the draft and opens the record's page in a new tab with it applied, under an amber "Previewing a draft" bar, for signed-in admin accounts only; anyone else sees the live page. The server answers that tab's reads from a second connection holding the draft in a transaction it rolls back, so no page needed code of its own.
diff --git a/server/src/admin-schema/columns.js b/server/src/admin-schema/columns.js
index da5ec75..d524795 100644
--- a/server/src/admin-schema/columns.js
+++ b/server/src/admin-schema/columns.js
@@ -152,6 +152,8 @@ export const blocksChild = (ownerKind) => ({
"table",
"cards",
"people",
+ // A blog post's tab (079): its text is the tab's title.
+ "tab",
],
{ required: true },
),
diff --git a/server/src/admin-schema/sitePages.js b/server/src/admin-schema/sitePages.js
index ddc1836..5a28fc1 100644
--- a/server/src/admin-schema/sitePages.js
+++ b/server/src/admin-schema/sitePages.js
@@ -36,12 +36,19 @@ const sectionsChild = {
text("scope_id"),
enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]),
enumeration("view", ["carousel", "grid", "map"]),
- text("tag_id"),
// Organization cards (067): the kinds listed by themselves.
enumeration("org_kinds", ["partner", "ministry", "partner,ministry"]),
],
children: [
blocksChild("page_section"),
+ {
+ // A People directory's tags (078), a tab each, in order.
+ key: "tags",
+ table: "page_section_tags",
+ owner: { column: "section_id" },
+ order: "sort_order",
+ columns: [text("tag_id", { required: true })],
+ },
{
// Organization cards (067): a hand-picked list, shown instead.
key: "orgs",
diff --git a/server/src/migrations/078_directory_tabs.sql b/server/src/migrations/078_directory_tabs.sql
new file mode 100644
index 0000000..500ad31
--- /dev/null
+++ b/server/src/migrations/078_directory_tabs.sql
@@ -0,0 +1,66 @@
+-- ═══════════════════════════════════════════════════════════════
+-- 078 DIRECTORY TABS
+--
+-- A People directory section (page_sections.preset
+-- 'people_directory') shows several People tags, a tab each, in
+-- the order picked: Community's Directories, eg. Musicians, Authors,
+-- Creators. page_section_tags holds them; each section's one tag_id
+-- becomes its first, and the column goes (page_sections is rebuilt,
+-- since a column with a REFERENCES can't be dropped in place).
+-- ═══════════════════════════════════════════════════════════════
+
+CREATE TABLE page_section_tags (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ tag_id TEXT NOT NULL REFERENCES person_tag_types (id) ON DELETE CASCADE
+) STRICT;
+
+CREATE INDEX page_section_tags_section_idx ON page_section_tags (section_id, sort_order);
+
+INSERT INTO page_section_tags (section_id, sort_order, tag_id)
+SELECT id, 0, tag_id FROM page_sections WHERE tag_id IS NOT NULL;
+
+CREATE TABLE page_sections_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ page_id TEXT NOT NULL REFERENCES site_pages (id) ON DELETE CASCADE,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ anchor TEXT NOT NULL
+ CONSTRAINT "A section's URL ID can use only lowercase letters, numbers and hyphens, eg. leadership."
+ CHECK (anchor <> '' AND anchor NOT GLOB '*[^a-z0-9-]*'),
+ title TEXT NOT NULL
+ CONSTRAINT "A section title can be 30 characters at most (it's listed in the page's side nav)."
+ CHECK (length(title) <= 30),
+ blurb TEXT,
+ accent TEXT CHECK (accent IN ('teal', 'deep', 'green', 'amber')),
+ preset TEXT CHECK (preset IN ('community_blog', 'group_map', 'region_list', 'partner_list',
+ 'events', 'timeline', 'people_directory')),
+ -- An events preset's filter and first view.
+ scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
+ event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')),
+ view TEXT CHECK (view IN ('carousel', 'grid', 'map')),
+ -- Organization cards (067): the kinds listed by themselves.
+ org_kinds TEXT CHECK (org_kinds IN ('partner', 'ministry', 'partner,ministry')),
+ UNIQUE (page_id, anchor)
+) STRICT;
+
+INSERT INTO page_sections_new
+ (id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds)
+SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
+ FROM page_sections;
+
+-- page_section_orgs, page_section_tags and content_blocks' owner
+-- trigger name page_sections; legacy mode leaves them alone through
+-- the rename.
+PRAGMA legacy_alter_table = ON;
+DROP TABLE page_sections;
+ALTER TABLE page_sections_new RENAME TO page_sections;
+PRAGMA legacy_alter_table = OFF;
+
+CREATE INDEX page_sections_page_idx ON page_sections (page_id, sort_order);
+
+CREATE TRIGGER page_sections_cleanup
+AFTER DELETE ON page_sections
+BEGIN
+ DELETE FROM content_blocks WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
+END;
diff --git a/server/src/migrations/079_tab_blocks.sql b/server/src/migrations/079_tab_blocks.sql
new file mode 100644
index 0000000..af58bf7
--- /dev/null
+++ b/server/src/migrations/079_tab_blocks.sql
@@ -0,0 +1,76 @@
+-- ═══════════════════════════════════════════════════════════════
+-- 079 TAB BLOCKS
+--
+-- A blog post can be split into tabs: a 'tab' block (its text the
+-- tab's title) starts a tab holding the blocks after it, up to the
+-- next one; the blocks before the first are the intro above the
+-- tabs. The post's contents follow the open tab (BlogPost.tsx).
+-- content_blocks.type's CHECK can't change in place, so the table is
+-- rebuilt, then its index and owner trigger are made again.
+-- ═══════════════════════════════════════════════════════════════
+
+CREATE TABLE content_blocks_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ owner_kind TEXT NOT NULL
+ CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post', 'page_section',
+ 'newsletter')),
+ owner_id TEXT NOT NULL,
+ slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body', 'both')),
+ sort_order INTEGER NOT NULL DEFAULT 0,
+
+ type TEXT NOT NULL
+ CHECK (type IN ('heading', 'subheading', 'paragraph',
+ 'list', 'links', 'quote', 'image', 'divider',
+ 'video', 'button', 'callout', 'schedule', 'table', 'cards',
+ 'people', 'tab')),
+ text TEXT,
+ media TEXT,
+ href TEXT,
+ alt TEXT,
+ cite TEXT,
+ team_id TEXT REFERENCES teams (id) ON DELETE SET NULL,
+ captions TEXT
+) STRICT;
+
+INSERT INTO content_blocks_new
+ (id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions)
+SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id, captions
+ FROM content_blocks;
+
+-- The block items and the owners' cleanup triggers name
+-- content_blocks; legacy mode leaves them alone through the rename.
+PRAGMA legacy_alter_table = ON;
+DROP TABLE content_blocks;
+ALTER TABLE content_blocks_new RENAME TO content_blocks;
+PRAGMA legacy_alter_table = OFF;
+
+CREATE INDEX content_blocks_owner_idx
+ ON content_blocks (owner_kind, owner_id, slot, sort_order);
+
+CREATE TRIGGER content_blocks_owner_exists
+BEFORE INSERT ON content_blocks
+BEGIN
+ SELECT CASE
+ WHEN new.owner_kind = 'event'
+ AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such event')
+ WHEN new.owner_kind = 'organization'
+ AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such organization')
+ WHEN new.owner_kind = 'person'
+ AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such person')
+ WHEN new.owner_kind = 'team'
+ AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such team')
+ WHEN new.owner_kind = 'blog_post'
+ AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such blog post')
+ WHEN new.owner_kind = 'page_section'
+ AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such page section')
+ WHEN new.owner_kind = 'newsletter'
+ AND NOT EXISTS (SELECT 1 FROM newsletters WHERE CAST(id AS TEXT) = new.owner_id)
+ THEN RAISE(ABORT, 'content_blocks: no such newsletter')
+ END;
+END;
diff --git a/server/src/routes/sitePages.js b/server/src/routes/sitePages.js
index 6101056..bb22705 100644
--- a/server/src/routes/sitePages.js
+++ b/server/src/routes/sitePages.js
@@ -49,7 +49,7 @@ sitePages.get("/site-pages/:id", (c) => {
const rows = db
.prepare(
- `SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, tag_id, org_kinds
+ `SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, org_kinds
FROM page_sections WHERE page_id = ? ORDER BY sort_order, id`,
)
.all(id);
@@ -64,6 +64,17 @@ sitePages.get("/site-pages/:id", (c) => {
.all(id)) {
picked.set(section_id, [...(picked.get(section_id) ?? []), org_id]);
}
+ // A People directory's tags (078), in order.
+ const tags = new Map();
+ for (const { section_id, tag_id } of db
+ .prepare(
+ `SELECT t.section_id, t.tag_id FROM page_section_tags t
+ JOIN page_sections s ON s.id = t.section_id
+ WHERE s.page_id = ? ORDER BY t.section_id, t.sort_order, t.id`,
+ )
+ .all(id)) {
+ tags.set(section_id, [...(tags.get(section_id) ?? []), tag_id]);
+ }
// A hidden page is only for those signed in: never kept.
const send = hidden ? (body) => c.json(body, 200, NO_STORE) : (body) => json(c, body);
@@ -74,6 +85,7 @@ sitePages.get("/site-pages/:id", (c) => {
...section,
blocks: blocks.get(String(sectionId)) ?? [],
org_ids: picked.get(sectionId) ?? [],
+ tag_ids: tags.get(sectionId) ?? [],
})),
},
});
diff --git a/src/App.tsx b/src/App.tsx
index 1744096..83bb43b 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -87,6 +87,7 @@ const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.tsx"))
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
const AdminProfiles = lazyPage(() => import("./pages/admin/AdminProfiles.tsx"))
+const AdminConvert = lazyPage(() => import("./pages/admin/AdminConvert.tsx"))
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
@@ -155,6 +156,7 @@ export default function App() {
} />
} />
} />
+ } />
}>
} />
diff --git a/src/components/ContentBlocks.tsx b/src/components/ContentBlocks.tsx
index e432181..0b035c5 100644
--- a/src/components/ContentBlocks.tsx
+++ b/src/components/ContentBlocks.tsx
@@ -63,10 +63,13 @@ export default function ContentBlocks({
accent = BRAND,
className = '',
presentAt,
+ anchorPrefix = '',
}: {
blocks?: ContentBlock[] | null
accent?: string
className?: string
+ /** Put before each heading's id: a blog post's tab (contents.ts, splitTabs). */
+ anchorPrefix?: string
/** An event page's presentation route: each schedule gets a Present
* button to it, `?block=` naming which schedule (from 0). */
presentAt?: string
@@ -74,7 +77,7 @@ export default function ContentBlocks({
if (!blocks?.length) return null
// Headings get ids so a post's contents (PostContents) and a shared
// link (#getting-there) can point at them.
- const { idAt } = headingAnchors(blocks)
+ const { idAt } = headingAnchors(blocks, anchorPrefix)
// The heading level a block's own headings take: under the last
// heading (h3) or subheading (h4) before it, else the section's h2.
let under = 2
@@ -182,6 +185,9 @@ function Block({
const reading = useReadingMode()
switch (block.type) {
+ // A blog post's tab marker (BlogPost.tsx splits the post at
+ // them); anywhere else, it reads as a heading.
+ case 'tab':
case 'heading':
return (
diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx
index 529ca7c..f3dda88 100644
--- a/src/components/Footer.tsx
+++ b/src/components/Footer.tsx
@@ -2,6 +2,7 @@ import { Link } from "react-router-dom";
import { useNavSections } from "../lib/navSections.ts";
import { useSiteNav } from "../lib/useSiteNav.ts";
import { useAuth } from "../lib/auth.tsx";
+import { VERSION_NAME, VERSION_NUMBER } from "../lib/version.ts";
import SiteLink from "./SiteLink.tsx";
import siteLogo from "../assets/logos/NGU_Logo.svg";
import PlatformIcon from "./PlatformIcon.tsx";
@@ -146,7 +147,13 @@ export default function Footer() {
-
© 2026 Next Generation of Unity. All rights reserved.
+
+
© 2026 Next Generation of Unity. All rights reserved.
+
+ {VERSION_NUMBER}
+ {VERSION_NAME && <> · {VERSION_NAME}>}
+
+
{nav.legal.map((link) => (
diff --git a/src/components/PageShell.css b/src/components/PageShell.css
index 744d6b0..7900a5c 100644
--- a/src/components/PageShell.css
+++ b/src/components/PageShell.css
@@ -15,7 +15,12 @@
width 0.6s ease-in-out,
height 0.6s ease-in-out,
left 0.6s ease-in-out,
- top 0.6s ease-in-out;
+ top 0.6s ease-in-out,
+ opacity 0.4s ease-in-out;
+}
+/* The page has scrolled into the footer (PageShell.tsx, leaving). */
+.side-nav-circle[data-leaving] {
+ opacity: 0;
}
.side-nav-circle[data-family="green"] {
background: var(--pal-green-3);
diff --git a/src/components/PageShell.tsx b/src/components/PageShell.tsx
index 65f4676..2a73468 100644
--- a/src/components/PageShell.tsx
+++ b/src/components/PageShell.tsx
@@ -215,7 +215,12 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
// Stuck: the page has scrolled the list up to its place under the
// header. The circle then becomes the corner sun (below).
+ // Leaving: the last section is going up past the list, so the list
+ // goes with it into the footer; the sun, far bigger than its sticky
+ // layer, would hang over the footer, so it fades out.
const [stuck, setStuck] = useState(false);
+ const [leaving, setLeaving] = useState(false);
+ const listHeight = listBox?.height ?? 0;
useEffect(() => {
const column = columnRef.current;
if (!sideNav || !column) return;
@@ -223,7 +228,9 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
const measure = () => {
frame = 0;
const header = parseFloat(getComputedStyle(column).getPropertyValue("--header-h")) || 80;
- setStuck(column.getBoundingClientRect().top + listTop <= header + STUCK_TOP + 1);
+ const box = column.getBoundingClientRect();
+ setStuck(box.top + listTop <= header + STUCK_TOP + 1);
+ setLeaving(box.bottom <= header + STUCK_TOP + listHeight + CIRCLE_MARGIN);
};
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(measure);
@@ -236,7 +243,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
window.removeEventListener("resize", onScroll);
if (frame) cancelAnimationFrame(frame);
};
- }, [sideNav, listTop]);
+ }, [sideNav, listTop, listHeight]);
// The circle's box, from its layer's top left (which sticks with
// the list). At rest: `rest` above. Stuck: a sun in the corner,
@@ -314,6 +321,7 @@ export default function PageShell({ title, intro, sections, sideNav = false }: P
('idle')
+
+ async function download(type: OutputType) {
+ setState('busy')
+ try {
+ const response = await fetch(url)
+ if (!response.ok) throw new Error(`Couldn't fetch the picture (HTTP ${response.status}).`)
+ saveBlob(await convertImage(await response.blob(), type), renamed(name, type))
+ setState('idle')
+ } catch (err) {
+ setState(err instanceof Error ? err.message : "Couldn't convert it.")
+ }
+ }
+
+ return (
+
+
+ Download {name} as
+
+ e.target.value && download(e.target.value as OutputType)}
+ className="border border-muted/25 bg-surface px-1 py-0.5 text-xs text-link"
+ >
+ {state === 'busy' ? 'Converting…' : 'Download as…'}
+ {OUTPUT_FORMATS.map((format) => (
+
+ {format.label}
+
+ ))}
+
+ {state !== 'idle' && state !== 'busy' && {state} }
+
+ )
+}
diff --git a/src/lib/adminSchema/blog.ts b/src/lib/adminSchema/blog.ts
index 1ea61b0..7a6033d 100644
--- a/src/lib/adminSchema/blog.ts
+++ b/src/lib/adminSchema/blog.ts
@@ -1,17 +1,42 @@
import { mediaUrl } from "../media.ts";
-import { PUBLISHED_FIELD, LISTED_FIELD, blocksChild } from "./shared.ts";
+import { PUBLISHED_FIELD, LISTED_FIELD, BLOCK_TYPES, TEXT_TYPES, blocksChild } from "./shared.ts";
/* ── Blog (031_blog.sql) ─────────────────────────────────────────
Posts at /blog/:id. The Community page's blog section is edited
with that page (sitePages.ts). */
/* A post's body is the content blocks without the card/body choice:
- a post only has a body. */
+ a post only has a body. Posts also take Tab blocks (079), which
+ split the post into tabs (BlogPost.tsx, splitTabs). */
+const TAB_TYPE = [
+ "tab",
+ "Tab",
+ "Starts a tab, titled by its text, holding the blocks after it up to the next Tab. Blocks before the first Tab are the intro above the tabs. The contents list follows the open tab.",
+];
+const POST_BLOCK_TYPES = [...BLOCK_TYPES, TAB_TYPE];
+
const blogBlocksChild = {
...blocksChild,
label: "Post body",
- note: "The post, top to bottom. The first paragraph doubles as the excerpt when that's left blank.",
- fields: blocksChild.fields.filter((field) => field.path !== "slot"),
+ note: "The post, top to bottom. The first paragraph doubles as the excerpt when that's left blank. Add Tab blocks to split it into tabs.",
+ fields: blocksChild.fields
+ .filter((field) => field.path !== "slot")
+ .map((field) =>
+ field.path === "type"
+ ? {
+ ...field,
+ options: POST_BLOCK_TYPES.map(([value, label]) => [value, label]),
+ help: (row) => POST_BLOCK_TYPES.find(([value]) => value === row?.type)?.[2],
+ }
+ : field.path === "text"
+ ? {
+ ...field,
+ label: (row) => (row?.type === "tab" ? "Tab title" : (field.label as any)(row)),
+ when: { path: "type", value: [...TEXT_TYPES, "tab"] },
+ help: (row) => (row?.type === "tab" ? "eg. Overview" : (field.help as any)(row)),
+ }
+ : field,
+ ),
};
export const blogPosts = {
diff --git a/src/lib/adminSchema/sitePages.ts b/src/lib/adminSchema/sitePages.ts
index 9e5f3f9..5d559a5 100644
--- a/src/lib/adminSchema/sitePages.ts
+++ b/src/lib/adminSchema/sitePages.ts
@@ -102,19 +102,6 @@ const sectionsChild = (presets: string[]) => ({
},
]
: []),
- ...(presets.includes("people_directory")
- ? [
- {
- path: "tag_id",
- label: "Directory: tag",
- widget: "select",
- optionsFrom: "person_tag_types",
- blankLabel: "Default: none (shows nothing)",
- help: "Shows the first of its people and links to the full directory",
- when: { path: "preset", value: "people_directory" },
- },
- ]
- : []),
...(presets.includes("partner_list")
? [
{
@@ -146,6 +133,16 @@ const sectionsChild = (presets: string[]) => ({
: []),
],
children: [
+ {
+ key: "tags",
+ label: "Directory: tags",
+ note: "Each People tag is a tab, in this order, eg. Musicians, Authors, Creators: the first of its people, and a link to its full directory. One tag shows without tabs. Tags are made under Data → People tags.",
+ addLabel: "Add tag",
+ when: { path: "preset", value: "people_directory" },
+ title: (row, options) => options?.person_tag_types?.find((t) => t.id === row.tag_id)?.label ?? "New tag",
+ blank: { tag_id: "" },
+ fields: [{ path: "tag_id", label: "Tag", widget: "select", optionsFrom: "person_tag_types", required: true }],
+ },
{
key: "orgs",
label: "Cards: organizations",
diff --git a/src/lib/contents.ts b/src/lib/contents.ts
index 93cd6c3..5f08590 100644
--- a/src/lib/contents.ts
+++ b/src/lib/contents.ts
@@ -25,8 +25,9 @@ const slug = (text: string) =>
.slice(0, 60) || 'section'
/* One entry per heading or subheading block, in order, and the id
- for each block index that is one. */
-export function headingAnchors(blocks?: ContentBlock[] | null): {
+ for each block index that is one. prefix keeps a blog post's tabs
+ apart (splitTabs): "Overview" in two tabs is two ids. */
+export function headingAnchors(blocks?: ContentBlock[] | null, prefix = ''): {
entries: ContentsEntry[]
idAt: Map
} {
@@ -40,9 +41,39 @@ export function headingAnchors(blocks?: ContentBlock[] | null): {
const base = slug(text)
const n = (seen.get(base) ?? 0) + 1
seen.set(base, n)
- const id = n === 1 ? base : `${base}-${n}`
+ const id = `${prefix}${n === 1 ? base : `${base}-${n}`}`
idAt.set(index, id)
entries.push({ id, text, level: block.type === 'heading' ? 1 : 2 })
})
return { entries, idAt }
}
+
+/* ── A blog post's tabs (079) ──────────────────────────────────
+ A 'tab' block starts a tab, titled by its text, holding the
+ blocks after it up to the next; the blocks before the first are
+ the intro above the tabs. Each tab's heading ids start with its
+ own, so the same heading in two tabs is two ids; the intro's
+ keep their plain ids. */
+
+export type PostTab = { id: string; title: string; prefix: string; blocks: ContentBlock[] }
+
+export function splitTabs(blocks?: ContentBlock[] | null): { intro: ContentBlock[]; tabs: PostTab[] } {
+ const intro: ContentBlock[] = []
+ const tabs: PostTab[] = []
+ const seen = new Map()
+ for (const block of blocks ?? []) {
+ if (block.type === 'tab') {
+ const title = (block.text ?? '').trim() || `Part ${tabs.length + 1}`
+ const base = `tab-${slug(title)}`
+ const n = (seen.get(base) ?? 0) + 1
+ seen.set(base, n)
+ const id = n === 1 ? base : `${base}-${n}`
+ tabs.push({ id, title, prefix: `${id}-`, blocks: [] })
+ } else if (tabs.length) {
+ tabs[tabs.length - 1].blocks.push(block)
+ } else {
+ intro.push(block)
+ }
+ }
+ return { intro, tabs }
+}
diff --git a/src/lib/convertImage.ts b/src/lib/convertImage.ts
new file mode 100644
index 0000000..3d2580f
--- /dev/null
+++ b/src/lib/convertImage.ts
@@ -0,0 +1,72 @@
+/* ═══════════════════════════════════════════════════════════════
+ IMAGE CONVERSION, in the browser
+
+ Tools → Image converter and the Media library's Download as: a
+ picture redrawn on a canvas and saved as another format. Nothing
+ is uploaded. Reads whatever this browser can show (JPEG, PNG,
+ WebP, GIF's first frame, AVIF, BMP, SVG; HEIC in Safari only).
+ JPEG has no transparency, so a JPEG's see-through parts are
+ filled white.
+ ═══════════════════════════════════════════════════════════════ */
+
+export const OUTPUT_FORMATS = [
+ { type: 'image/jpeg', label: 'JPG', ext: 'jpg', lossy: true },
+ { type: 'image/png', label: 'PNG', ext: 'png', lossy: false },
+ { type: 'image/webp', label: 'WebP', ext: 'webp', lossy: true },
+] as const
+
+export type OutputType = (typeof OUTPUT_FORMATS)[number]['type']
+
+/* An SVG with no size of its own is drawn this wide. */
+const SVG_EDGE = 2048
+
+function loadImage(blob: Blob): Promise {
+ const url = URL.createObjectURL(blob)
+ return new Promise((resolve, reject) => {
+ const img = new Image()
+ img.onload = () => resolve(img)
+ img.onerror = () => reject(new Error("This browser can't read that picture."))
+ img.src = url
+ }).finally(() => URL.revokeObjectURL(url)) as Promise
+}
+
+/** The picture as `type`; quality 0 to 1 for JPG and WebP. */
+export async function convertImage(blob: Blob, type: OutputType, quality = 0.9): Promise {
+ const img = await loadImage(blob)
+ const width = img.naturalWidth || SVG_EDGE
+ const height = img.naturalHeight || SVG_EDGE
+ const canvas = document.createElement('canvas')
+ canvas.width = width
+ canvas.height = height
+ const context = canvas.getContext('2d')
+ if (!context) throw new Error("This browser can't draw the picture.")
+ if (type === 'image/jpeg') {
+ context.fillStyle = '#ffffff'
+ context.fillRect(0, 0, width, height)
+ }
+ context.drawImage(img, 0, 0, width, height)
+ const out = await new Promise((resolve) => canvas.toBlob(resolve, type, quality))
+ // A browser that can't write the format (old Safari and WebP)
+ // hands back a PNG, or nothing.
+ if (!out || out.type !== type) throw new Error(`This browser can't save ${type.split('/')[1].toUpperCase()}.`)
+ return out
+}
+
+/** A file name with the new format's extension. */
+export function renamed(name: string, type: OutputType): string {
+ const ext = OUTPUT_FORMATS.find((f) => f.type === type)?.ext ?? 'img'
+ const stem = name.replace(/\.[^./]+$/, '') || 'image'
+ return `${stem}.${ext}`
+}
+
+/** Hands the browser a file to save. */
+export function saveBlob(blob: Blob, filename: string) {
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ a.remove()
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
+}
diff --git a/src/lib/useContent.ts b/src/lib/useContent.ts
index 63abdda..8b27a55 100644
--- a/src/lib/useContent.ts
+++ b/src/lib/useContent.ts
@@ -38,6 +38,7 @@ export type ContentBlock = {
| 'callout'
| 'schedule'
| 'table'
+ | 'tab'
| 'cards'
| 'people'
text?: string | null
diff --git a/src/lib/useSitePages.ts b/src/lib/useSitePages.ts
index 27eeae5..2b654ce 100644
--- a/src/lib/useSitePages.ts
+++ b/src/lib/useSitePages.ts
@@ -15,8 +15,8 @@ export type SitePageSection = {
scope_id?: string | null
event_type?: string | null
view?: string | null
- /** A people_directory preset's tag (Data → People tags). */
- tag_id?: string | null
+ /** A people_directory preset's tags (Data → People tags), a tab each, in order. */
+ tag_ids: string[]
/** Organization cards: the kinds listed ('partner', 'ministry' or both, comma separated). */
org_kinds?: string | null
/** Organization cards: a hand-picked list, in order, shown instead. */
diff --git a/src/lib/version.ts b/src/lib/version.ts
index d5ef2c4..77e3696 100644
--- a/src/lib/version.ts
+++ b/src/lib/version.ts
@@ -2,9 +2,27 @@
SITE VERSION: src/lib/version.ts
One string, bumped by hand when the working directory name
- changes. The admin footer is the only thing reading it today;
- keep it here rather than in a component so the panel, an about
- box or a build banner can read the same value later.
+ changes. Read by the admin's footer and home, and the site's
+ footer.
+
+ Each version has a name, Minecraft style: the tag's words after
+ the number, "v1.13.2-region-cards" → "The Region Cards Update".
+ A version with no words after its number has no name.
═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.13.2-region-cards";
+
+/** The number, eg. v1.13.2. */
+export const VERSION_NUMBER: string = SITE_VERSION.match(/v\d+(?:\.\d+)*/)?.[0] ?? SITE_VERSION
+
+/** The version's name from its tag, eg. The Region Cards Update, or null. */
+export const VERSION_NAME: string | null = (() => {
+ const words = SITE_VERSION.match(/v\d+(?:\.\d+)*-(.+)$/)?.[1]
+ if (!words) return null
+ const title = words
+ .split('-')
+ .filter(Boolean)
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(' ')
+ return `The ${title} Update`
+})()
diff --git a/src/pages/BlogPost.tsx b/src/pages/BlogPost.tsx
index cb2ade4..eda2c20 100644
--- a/src/pages/BlogPost.tsx
+++ b/src/pages/BlogPost.tsx
@@ -8,9 +8,16 @@
There's no /blog index on purpose: the Community page's blog
section is where posts are listed, so "back" goes there.
+
+ Tab blocks (079) split the body into tabs (contents.ts,
+ splitTabs): the blocks before the first are an intro above them,
+ and the contents list follows the open tab. A link to a heading
+ in another tab (#tab-…) opens that tab. Printed (Download PDF) or
+ in reading mode, every tab shows, each under its title.
═══════════════════════════════════════════════════════════════ */
-import { Link, useParams } from "react-router-dom"
+import { useEffect, useId, useState, type KeyboardEvent } from "react"
+import { Link, useLocation, useParams } from "react-router-dom"
import PageShell, { type ShellSection } from "../components/PageShell.tsx"
import PageState from "../components/PageState.tsx"
@@ -18,9 +25,11 @@ import ContentBlocks from "../components/ContentBlocks.tsx"
import PeopleTiles from "../components/PeopleTiles.tsx"
import { mediaUrl } from "../lib/media.ts"
import { postDate, useBlogPost } from "../lib/useBlog.ts"
-import { accentText, BRAND } from "../lib/color.ts"
+import { accentText, BRAND, readableOn, withAlpha } from "../lib/color.ts"
+import { useReadingMode } from "../lib/readingMode.ts"
+import { jumpTo } from "../lib/focus.ts"
import PostContents from "../components/PostContents.tsx"
-import { headingAnchors } from "../lib/contents.ts"
+import { headingAnchors, splitTabs, type PostTab } from "../lib/contents.ts"
import QrCode from "../components/QrCode.tsx"
import RequestLink from "../components/RequestLink.tsx"
import { siteUrl } from "../lib/site.ts"
@@ -34,6 +43,22 @@ const BACK = { to: "/community#blog", label: "Community Blog" }
export default function BlogPost() {
const { id } = useParams()
const { data: post, loading, error, notFound, reload } = useBlogPost(id)
+ const [tabIndex, setTabIndex] = useState(0)
+ const reading = useReadingMode()
+ const { hash } = useLocation()
+
+ // A link into another tab (#tab-…) opens it, then goes to the heading.
+ useEffect(() => {
+ if (!post || !hash.startsWith("#tab-")) return
+ const target = decodeURIComponent(hash.slice(1))
+ const found = splitTabs(post.blocks).tabs
+ const index = found.findIndex((tab) => target === tab.id || target.startsWith(tab.prefix))
+ if (index < 0) return
+ setTabIndex(index)
+ // The tab's own id is its printed title, hidden on screen: opening
+ // it is enough. A heading inside it is scrolled to once it shows.
+ if (target !== found[index].id) requestAnimationFrame(() => jumpTo(target))
+ }, [post, hash])
if (!post) {
return (
@@ -49,8 +74,16 @@ export default function BlogPost() {
)
}
- // Two headings or more make a list worth showing.
- const contents = post.show_contents ? headingAnchors(post.blocks).entries : []
+ const { intro, tabs } = splitTabs(post.blocks)
+ const current = Math.min(tabIndex, Math.max(tabs.length - 1, 0))
+
+ // Two headings or more make a list worth showing: the intro's and
+ // the open tab's.
+ const contents = post.show_contents
+ ? tabs.length
+ ? [...headingAnchors(intro).entries, ...headingAnchors(tabs[current].blocks, tabs[current].prefix).entries]
+ : headingAnchors(post.blocks).entries
+ : []
const withContents = contents.length >= 2
const postUrl = siteUrl(`/blog/${post.id}`)
@@ -146,7 +179,14 @@ export default function BlogPost() {
/>
)}
-
+ {tabs.length ? (
+ <>
+
+
+ >
+ ) : (
+
+ )}
Have a story to share?
@@ -190,3 +230,86 @@ export default function BlogPost() {
/>
)
}
+
+/* The post's tabs: a row of buttons, then the open tab's blocks. The
+ others stay in the page, hidden, so print shows them all; `all`
+ (reading mode) shows every tab, each under its title. */
+function PostTabs({
+ tabs,
+ current,
+ onSelect,
+ all,
+}: {
+ tabs: PostTab[]
+ current: number
+ onSelect: (index: number) => void
+ all: boolean
+}) {
+ const baseId = useId()
+
+ // Arrows move one tab and wrap; Home and End jump to the ends.
+ const onKey = (e: KeyboardEvent
) => {
+ const last = tabs.length - 1
+ const next =
+ e.key === "ArrowRight" ? (current + 1) % tabs.length
+ : e.key === "ArrowLeft" ? (current + last) % tabs.length
+ : e.key === "Home" ? 0
+ : e.key === "End" ? last
+ : null
+ if (next === null) return
+ e.preventDefault()
+ onSelect(next)
+ document.getElementById(`${baseId}-tab-${next}`)?.focus()
+ }
+
+ return (
+
+ {!all && (
+
+ {tabs.map((tab, index) => {
+ const selected = index === current
+ return (
+ onSelect(index)}
+ onKeyDown={onKey}
+ className="btn border px-5 py-2 text-sm transition-colors"
+ style={
+ selected
+ ? { background: BRAND, borderColor: BRAND, color: readableOn(BRAND) }
+ : { borderColor: withAlpha(BRAND, 33), color: accentText(BRAND) }
+ }
+ >
+ {tab.title}
+
+ )
+ })}
+
+ )}
+ {tabs.map((tab, index) => (
+
+
+ {tab.title}
+
+
+
+ ))}
+
+ )
+}
diff --git a/src/pages/SitePage.tsx b/src/pages/SitePage.tsx
index b4a1b5a..8b8f140 100644
--- a/src/pages/SitePage.tsx
+++ b/src/pages/SitePage.tsx
@@ -31,7 +31,7 @@ import OrgListCards from './sections/OrgList-Card.tsx'
import EventListCards, { EventCardsToggle } from './sections/EventList-Cards.tsx'
import CommunityBlog from './sections/CommunityBlog.tsx'
import HistoryTimeline from './sections/history/HistoryTimeline.tsx'
-import PeopleDirectory, { DIRECTORY_PREVIEW } from './sections/PeopleDirectory.tsx'
+import { DirectoryTabs, DIRECTORY_PREVIEW } from './sections/PeopleDirectory.tsx'
/* Year the program starts: decades ending before it get the
pre-program look on the timeline. */
@@ -91,8 +91,8 @@ const PRESETS: Record Record>
}),
timeline: () => ({ Component: Timeline }),
people_directory: (section) => ({
- Component: PeopleDirectory,
- props: { tag: section.tag_id, limit: DIRECTORY_PREVIEW },
+ Component: DirectoryTabs,
+ props: { tags: section.tag_ids, limit: DIRECTORY_PREVIEW },
}),
}
diff --git a/src/pages/admin/AdminConvert.tsx b/src/pages/admin/AdminConvert.tsx
new file mode 100644
index 0000000..3d0cb46
--- /dev/null
+++ b/src/pages/admin/AdminConvert.tsx
@@ -0,0 +1,196 @@
+/* ═══════════════════════════════════════════════════════════════
+ ADMIN: IMAGE CONVERTER (Tools → Image converter, everyone)
+
+ Pictures turned into JPG, PNG or WebP in the browser
+ (src/lib/convertImage.ts): pick or drop any number, choose the
+ format (and quality, for JPG and WebP), download each. Nothing is
+ uploaded or kept. The Media library's Download as does the same
+ for a picture already there.
+ ═══════════════════════════════════════════════════════════════ */
+
+import { useId, useState } from "react";
+
+import { OUTPUT_FORMATS, convertImage, renamed, saveBlob, type OutputType } from "../../lib/convertImage.ts";
+
+const MUTED = "var(--color-muted)";
+
+const button =
+ "btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
+const primary =
+ "btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
+
+type Item = { file: File; result?: Blob; error?: string };
+
+const kb = (bytes: number) => (bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);
+
+export default function AdminConvert() {
+ const inputId = useId();
+ const formatId = useId();
+ const qualityId = useId();
+ const [items, setItems] = useState- ([]);
+ const [type, setType] = useState
("image/jpeg");
+ const [quality, setQuality] = useState(90);
+ const [busy, setBusy] = useState(false);
+ const [over, setOver] = useState(false);
+ const lossy = OUTPUT_FORMATS.find((f) => f.type === type)?.lossy;
+
+ const add = (files: FileList | null) => {
+ const pictures = [...(files ?? [])].filter((file) => file.type.startsWith("image/") || /\.(heic|heif)$/i.test(file.name));
+ setItems((current) => [...current, ...pictures.map((file) => ({ file }))]);
+ };
+
+ async function convertAll() {
+ setBusy(true);
+ const next: Item[] = [];
+ for (const item of items) {
+ try {
+ next.push({ file: item.file, result: await convertImage(item.file, type, quality / 100) });
+ } catch (err) {
+ next.push({ file: item.file, error: err instanceof Error ? err.message : "Couldn't convert it." });
+ }
+ }
+ setItems(next);
+ setBusy(false);
+ }
+
+ const done = items.filter((item) => item.result);
+
+ return (
+
+
+
Image converter
+
+ Turn pictures into JPG, PNG or WebP. Done in your browser: nothing is uploaded.
+
+
+
+
+ {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ add(e.dataTransfer.files);
+ }}
+ className={`block cursor-pointer border-2 p-8 text-center text-sm transition-colors ${
+ over ? "border-brand bg-tint" : "border-muted/30"
+ }`}
+ >
+ Choose pictures or drop them here
+
+ JPEG, PNG, WebP, GIF, AVIF, BMP or SVG (HEIC in Safari only)
+
+ {
+ add(e.target.files);
+ e.target.value = "";
+ }}
+ />
+
+
+
+
+
+ Save as
+
+ {
+ setType(e.target.value as OutputType);
+ setItems((current) => current.map(({ file }) => ({ file })));
+ }}
+ className="mt-1 border border-muted/25 bg-surface px-3 py-2 text-sm text-body"
+ >
+ {OUTPUT_FORMATS.map((format) => (
+
+ {format.label}
+
+ ))}
+
+
+ {lossy && (
+
+
+ Quality: {quality}
+
+ {
+ setQuality(Number(e.target.value));
+ setItems((current) => current.map(({ file }) => ({ file })));
+ }}
+ className="mt-2 w-48 accent-[var(--color-action)]"
+ />
+
+ )}
+
+ {busy ? "Converting…" : `Convert ${items.length || ""}`.trim()}
+
+ {done.length > 1 && (
+
done.forEach((item) => saveBlob(item.result as Blob, renamed(item.file.name, type)))}
+ >
+ Download all
+
+ )}
+ {items.length > 0 && (
+
setItems([])}>
+ Clear
+
+ )}
+
+ {type === "image/jpeg" && (
+
+ JPG has no transparency: see-through parts turn white.
+
+ )}
+
+
+ {items.length > 0 && (
+
+ {items.map((item, index) => (
+
+
+ {item.file.name}
+
+ {kb(item.file.size)}
+ {item.result ? (
+ <>
+ → {kb(item.result.size)}
+ saveBlob(item.result as Blob, renamed(item.file.name, type))}
+ >
+ Download {renamed(item.file.name, type)}
+
+ >
+ ) : item.error ? (
+ {item.error}
+ ) : (
+ Ready
+ )}
+
+ ))}
+
+ )}
+
+ );
+}
diff --git a/src/pages/admin/AdminHome.tsx b/src/pages/admin/AdminHome.tsx
index d1b818b..232bc70 100644
--- a/src/pages/admin/AdminHome.tsx
+++ b/src/pages/admin/AdminHome.tsx
@@ -26,7 +26,7 @@ import { ArrowRight, ArrowUpRight } from "@phosphor-icons/react";
import { Link } from "react-router-dom";
import { useAuth } from "../../lib/auth.tsx";
import { useWideAdminPage } from "../../lib/adminWidth.tsx";
-import { SITE_VERSION } from "../../lib/version.ts";
+import { SITE_VERSION, VERSION_NAME } from "../../lib/version.ts";
import { ROLE_LABELS, isSuper } from "../../lib/roles.ts";
import { PALETTE } from "../../lib/color.ts";
import { DATA_NAV, FORMS_NAV, PAGES_NAV, PANEL_NAV, TOOLS_NAV, target, visibleItems } from "./adminNav.ts";
@@ -187,7 +187,7 @@ export default function AdminHome() {
- {SITE_VERSION}
+ {SITE_VERSION}{VERSION_NAME && ` · ${VERSION_NAME}`}
- {SITE_VERSION}
+ {SITE_VERSION}{VERSION_NAME && ` · ${VERSION_NAME}`}
diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx
index e96c652..a671142 100644
--- a/src/pages/admin/AdminMedia.tsx
+++ b/src/pages/admin/AdminMedia.tsx
@@ -17,6 +17,7 @@
a page (an image field stores the path, not a foreign key).
═══════════════════════════════════════════════════════════════ */
+import DownloadAs from "../../components/admin/DownloadAs.tsx";
import { useEffect, useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
@@ -641,6 +642,9 @@ export default function AdminMedia() {
>
Open
+ {item.content_type?.startsWith("image/") && (
+
+ )}
{roleCanWrite(user) && (
)
}
+
+/* ── Several tags, a tab each ────────────────────────────────── */
+
+type DirectoryTabsProps = {
+ tags: string[]
+ limit?: number
+ accent?: string
+}
+
+export function DirectoryTabs({ tags, limit, accent = BRAND }: DirectoryTabsProps) {
+ const [active, setActive] = useState(0)
+ const baseId = useId()
+ const reading = useReadingMode()
+
+ if (tags.length <= 1) return
+
+ if (reading) {
+ return (
+ <>
+ {tags.map((tag) => (
+
+ ))}
+ >
+ )
+ }
+
+ const current = Math.min(active, tags.length - 1)
+
+ // Arrows move one tab and wrap; Home and End jump to the ends.
+ const onKey = (e: KeyboardEvent) => {
+ const last = tags.length - 1
+ const next =
+ e.key === 'ArrowRight' ? (current + 1) % tags.length
+ : e.key === 'ArrowLeft' ? (current + last) % tags.length
+ : e.key === 'Home' ? 0
+ : e.key === 'End' ? last
+ : null
+ if (next === null) return
+ e.preventDefault()
+ setActive(next)
+ document.getElementById(`${baseId}-tab-${next}`)?.focus()
+ }
+
+ return (
+ <>
+
+
+ {tags.map((tag, index) => {
+ const selected = index === current
+ return (
+ setActive(index)}
+ onKeyDown={onKey}
+ className="btn border px-5 py-2 text-sm transition-colors"
+ style={
+ selected
+ ? { background: accent, borderColor: accent, color: readableOn(accent) }
+ : { borderColor: withAlpha(accent, 33), color: accentText(accent) }
+ }
+ >
+
+
+ )
+ })}
+
+
+
+ >
+ )
+}
+
+/* A tag's name, from its directory (asked once, and kept for its tab). */
+function TagName({ tag }: { tag: string }) {
+ const { data } = useDirectory(tag)
+ return <>{data?.name ?? tag}>
+}
diff --git a/src/pages/sections/home/HeroStage.tsx b/src/pages/sections/home/HeroStage.tsx
index 45f58d5..a296858 100644
--- a/src/pages/sections/home/HeroStage.tsx
+++ b/src/pages/sections/home/HeroStage.tsx
@@ -19,9 +19,11 @@
video a featured video under a "Featured video" badge.
Never autoplays: an embed waits for play, a file
shows the browser's player
- event an event's card under a "Featured event" badge:
- its photo, dates, place and buttons. The API picks
- the event (pinned, else the countdown's)
+ event an event's card, under a "Featured event" badge
+ from lg up (on a phone the card sits under the
+ words and the badge is left out): its photo, dates,
+ place and buttons. The API picks the event (pinned,
+ else the countdown's)
A choice with nothing to show falls back: photos with no photos
to brand, a feature with no link set (or no event to show) to
@@ -125,6 +127,12 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
{feature === 'event' && hero?.event && (
+ {/* Over the card it names, not over the headline beside it;
+ on a phone the card under the words speaks for itself. */}
+
+
+ Featured event
+
)}
@@ -151,12 +159,7 @@ function Words({ hero, feature }: { hero: Hero; feature: HeroFeature }) {
)}
- ) : feature === 'event' ? (
-
-
- Featured event
-
- ) : feature === 'video' ? (
+ ) : feature === 'event' ? null : feature === 'video' ? (
Featured video
From 3b034eb00e6e3f3864dfedb0f35f3ff337f229e9 Mon Sep 17 00:00:00 2001
From: Aidan Dona
Date: Fri, 16 Oct 2026 20:20:04 -0500
Subject: [PATCH 40/90] v1.14.0-profiles: bump SITE_VERSION
Co-Authored-By: Claude Opus 5.5
---
TODO.md | 2 +-
src/lib/version.ts | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/TODO.md b/TODO.md
index 6128bf1..0381195 100644
--- a/TODO.md
+++ b/TODO.md
@@ -122,7 +122,7 @@
# Part 2: Done
-## Page features (branch `page-features`, on top of `nav-access`, no PR yet; migrations 078 and 079, back up the database before deploying)
+## v1.14.0-profiles: page features (branch `page-features`, with `nav-access` under it, no PR yet; migrations 078 and 079, back up the database before deploying)
- [x] **Featured event label** (Mobile): the "Featured event" badge left the headline; from lg up it sits above the event's card it names, and on a phone (the card under the words) it's left out.
- [x] **Site version names**: the tag's words after the number are the version's name, `v1.13.2-region-cards` → "The Region Cards Update" (`src/lib/version.ts`), shown with the number in the site's footer and beside the version in the admin's footer and home.
- [x] **Image converter** (Tools → Image converter): pictures to JPG, PNG or WebP in the browser (nothing uploaded): pick or drop several, a quality slider for JPG and WebP, download each or all. JPG fills transparency white. Media's images each have a Download as… (JPG, PNG, WebP) doing the same (`src/lib/convertImage.ts`).
diff --git a/src/lib/version.ts b/src/lib/version.ts
index 77e3696..1bad3de 100644
--- a/src/lib/version.ts
+++ b/src/lib/version.ts
@@ -10,7 +10,7 @@
A version with no words after its number has no name.
═══════════════════════════════════════════════════════════════ */
-export const SITE_VERSION = "NGU-Web.v1.13.2-region-cards";
+export const SITE_VERSION = "NGU-Web.v1.14.0-profiles";
/** The number, eg. v1.13.2. */
export const VERSION_NUMBER: string = SITE_VERSION.match(/v\d+(?:\.\d+)*/)?.[0] ?? SITE_VERSION
From 56acedf92654f433798c84081e3ecbad0783aeda Mon Sep 17 00:00:00 2001
From: Aidan Dona
Date: Fri, 16 Oct 2026 20:43:25 -0500
Subject: [PATCH 41/90] Featured event card beside the hero text; Word import:
tabs, quotes, callouts, dividers, videos, buttons
From lg up the featured event's photo sits beside its words, so the card
is about as tall as the hero text. Word import turns a 'Tab:' line into a
tab, the Quote and Intense Quote styles into quotes and callouts, '---'
into a divider, a lone video link into a video and 'Button: label' into
a button; Blog posts shows the whole mapping beside Import from Word.
Co-Authored-By: Claude Opus 5.5
---
TODO.md | 4 +-
docs/importing.md | 13 +++++++
server/src/docx.js | 53 ++++++++++++++++++++++++++-
server/src/routes/import.js | 5 +++
src/lib/adminSchema/blog.ts | 27 +++++++++++++-
src/pages/admin/EntityEdit.tsx | 2 +
src/pages/admin/EntityList.tsx | 29 ++++++++++++++-
src/pages/sections/home/HeroStage.tsx | 26 +++++++------
8 files changed, 143 insertions(+), 16 deletions(-)
diff --git a/TODO.md b/TODO.md
index 0381195..54b9896 100644
--- a/TODO.md
+++ b/TODO.md
@@ -128,8 +128,10 @@
- [x] **Image converter** (Tools → Image converter): pictures to JPG, PNG or WebP in the browser (nothing uploaded): pick or drop several, a quality slider for JPG and WebP, download each or all. JPG fills transparency white. Media's images each have a Download as… (JPG, PNG, WebP) doing the same (`src/lib/convertImage.ts`).
- [x] **Directory tabs** (migration 078): the People directory preset takes several People tags, a tab each in the order picked (Directory: tags under the section); one tag shows without tabs, reading mode lists every tag. Each section's old single tag became its first.
- [x] **Blog post tabs** (migration 079): a Tab block in a post (its text the tab's title) starts a tab holding the blocks after it; blocks before the first Tab are the intro above the tabs. The contents list follows the open tab, a link to a heading in another tab opens it, and Download PDF and reading mode show every tab under its title. Outside a post a Tab block reads as a heading.
+- [x] **Featured event card height** (Sections): from lg up the event's photo sits beside its words instead of above them, with tighter type and buttons, so the card is about as tall as the hero's text beside it; stacked as before on a phone. The photo stays whole (16:9).
+- [x] **Word import, more of it** (Page Features): a line starting `Tab:` (any style) starts a tab; the Quote style becomes a Quote (a dash and a name at the end is who said it), Intense Quote a Callout, a line of `---` a Divider, a YouTube, Vimeo or Facebook link alone on its line a Video, and `Button: Register` with Register linked a Button. Blog posts → What becomes what (beside Import from Word) shows the whole mapping; `docs/importing.md` too. The note after an import counts tabs and the rest.
- [x] **Side nav sun into the footer** (Navigation): the sun is far bigger than the sticky layer that carries it, so once the last section went up past the list it hung over the footer. It now fades out as the list leaves with the last section, and back in on the way up.
- - [ ] Check in a browser: the side nav sun fading at the end of a long page (2xl screen) and with a tall footer; the featured event hero at phone and desktop width, the footers' version line, converting a PNG with transparency to JPG and a JPG to WebP (and Download as in Media), a Directories section with two tags and with one, a post with an intro and three tabs (contents, keyboard arrows, PDF, reading mode).
+ - [ ] Check in a browser: the featured event card beside a two-line headline at 1024, 1280 and 1536px; What becomes what and a real Word document with Tab: lines, a quote and a video link; the side nav sun fading at the end of a long page (2xl screen) and with a tall footer; the featured event hero at phone and desktop width, the footers' version line, converting a PNG with transparency to JPG and a JPG to WebP (and Download as in Media), a Directories section with two tags and with one, a post with an intro and three tabs (contents, keyboard arrows, PDF, reading mode).
## Page Editing (branch `nav-access`, no PR yet; migration 077)
- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft.
diff --git a/docs/importing.md b/docs/importing.md
index 3d770f2..1c77c96 100644
--- a/docs/importing.md
+++ b/docs/importing.md
@@ -18,6 +18,19 @@ authors and a cover, then tick Published.
| Tables | Table blocks: a row per line, cells split by `\|`, the first row the header |
| Bold, italic, links (http, https, mailto) | `**bold**`, `*italic*`, `[text](url)`, in paragraphs, list items and table cells |
+And lines written a certain way, in any style:
+
+| In the document | In the post |
+| --- | --- |
+| A line starting `Tab:`, eg. `Tab: Overview` | A Tab block: the post is split into tabs from there (the blocks before the first are the intro above the tabs) |
+| The Quote style | A Quote block; a dash and a name at the end (`... - Jane Doe`) is who said it |
+| The Intense Quote style | A Callout block |
+| A line of `---` alone | A Divider |
+| A YouTube, Vimeo or Facebook link alone on its line (the link text can be anything) | A Video block |
+| `Button: Register`, with "Register" linked | A Button block, its label and link |
+
+The same table is on Blog posts, beside Import from Word (What becomes what).
+
A post with three headings or more gets **Show contents** turned on. The
URL ID is the title as a slug, with `-2`, `-3` when it's taken.
diff --git a/server/src/docx.js b/server/src/docx.js
index 09d0567..d7b7806 100644
--- a/server/src/docx.js
+++ b/server/src/docx.js
@@ -14,6 +14,17 @@
cells split by |)
bold, italic, links **bold**, *italic*, [text](url)
+ And a few lines written a certain way (docs/importing.md), any
+ style:
+ "Tab: Overview" a tab block (079): the post
+ is split into tabs there
+ the Quote style a quote block
+ the Intense Quote style a callout block
+ "---" alone a divider
+ a YouTube, Vimeo or Facebook link a video block
+ alone on its line
+ "Button: [Register](https://…)" a button block
+
Images, text boxes, footnotes and comments aren't carried over;
the result counts what was skipped so the editor can say so.
@@ -216,7 +227,7 @@ export function readDocx(buf) {
if (!text) continue;
const level = style === "title" ? 0 : Number(/^heading (\d)/.exec(style)?.[1] ?? NaN);
- if (!title && (level === 0 || level === 1)) {
+ if (!title && (level === 0 || level === 1) && !lineBlock(text, style)) {
close();
title = text.replace(/\*/g, "");
continue;
@@ -231,6 +242,12 @@ export function readDocx(buf) {
continue;
}
}
+ const special = lineBlock(text, style);
+ if (special) {
+ close();
+ blocks.push(special);
+ continue;
+ }
if (level >= 1) {
close();
blocks.push({ type: level <= 2 ? "heading" : "subheading", text: text.replace(/\*/g, "") });
@@ -248,3 +265,37 @@ export function readDocx(buf) {
return { title, date, blocks, skipped: counts };
}
+
+/* ── Lines written a certain way ──────────────────────────────── */
+
+const VIDEO_HOST = /^https?:\/\/(www\.)?(youtube\.com|youtu\.be|m\.youtube\.com|vimeo\.com|player\.vimeo\.com|facebook\.com|fb\.watch)\//i;
+
+/* The one link a line is made of, "[text](url)" or a bare url, or null. */
+function loneLink(text) {
+ const md = /^\[[^\]]*\]\(([^)\s]+)\)$/.exec(text);
+ if (md) return md[1];
+ return /^https?:\/\/\S+$/.test(text) ? text : null;
+}
+
+/* A block a paragraph stands for by how it's written, or null for an
+ ordinary one (docs/importing.md). */
+function lineBlock(text, style) {
+ const plain = text.replace(/\*/g, "").trim();
+ const tab = /^tab:\s*(.+)$/i.exec(plain);
+ if (tab) return { type: "tab", text: tab[1].trim().slice(0, 80) };
+ if (/^(-{3,}|_{3,})$/.test(plain)) return { type: "divider" };
+
+ const button = /^button:\s*\[([^\]]+)\]\(([^)\s]+)\)$/i.exec(text.trim());
+ if (button) return { type: "button", text: button[1].replace(/\*/g, ""), href: button[2] };
+
+ const link = loneLink(text.trim());
+ if (link && VIDEO_HOST.test(link)) return { type: "video", href: link };
+
+ if (style === "intense quote") return { type: "callout", text };
+ if (style === "quote") {
+ // A dash and a name at the end ("… - Jane Doe", any dash) is who said it.
+ const said = /^(.*\S)\s+[—–-]\s*([^—–-]{2,80})$/.exec(text);
+ return said ? { type: "quote", text: said[1], cite: said[2].trim() } : { type: "quote", text };
+ }
+ return null;
+}
diff --git a/server/src/routes/import.js b/server/src/routes/import.js
index d1c591d..e47818d 100644
--- a/server/src/routes/import.js
+++ b/server/src/routes/import.js
@@ -74,6 +74,8 @@ export function importDocx(db, buffer, fileName, byEmail) {
slot: "body",
type: block.type,
text: block.text ?? null,
+ href: block.href ?? null,
+ cite: block.cite ?? null,
items: block.items ?? [],
})),
});
@@ -87,6 +89,9 @@ export function importDocx(db, buffer, fileName, byEmail) {
paragraphs: count("paragraph"),
lists: count("list"),
tables: count("table"),
+ tabs: count("tab"),
+ // Quotes, callouts, dividers, videos and buttons.
+ others: doc.blocks.filter((b) => ["quote", "callout", "divider", "video", "button"].includes(b.type)).length,
skipped: doc.skipped,
},
};
diff --git a/src/lib/adminSchema/blog.ts b/src/lib/adminSchema/blog.ts
index 7a6033d..d70a5c0 100644
--- a/src/lib/adminSchema/blog.ts
+++ b/src/lib/adminSchema/blog.ts
@@ -46,7 +46,32 @@ export const blogPosts = {
idLabel: "URL ID",
slugFrom: "title",
// Blog posts → Import from Word (server/src/routes/import.js).
- importer: { label: "Import from Word", endpoint: "/admin/import/docx", accept: ".docx" },
+ // `guide` is what becomes what (server/src/docx.js, docs/importing.md),
+ // shown beside the button.
+ importer: {
+ label: "Import from Word",
+ endpoint: "/admin/import/docx",
+ accept: ".docx",
+ guide: {
+ intro: "A .docx becomes a new, unpublished post. In the document:",
+ rows: [
+ ["The Title style, or the first Heading 1", "The post's title"],
+ ["A date line under it, eg. Sep 28, 2026", "The post's date"],
+ ["Heading 1 and Heading 2", "Heading blocks"],
+ ["Heading 3 and smaller", "Subheading blocks"],
+ ["A line starting Tab:, eg. Tab: Overview (any style)", "A Tab: the post is split into tabs from there"],
+ ["The Quote style", "A Quote (a dash and a name at the end is who said it)"],
+ ["The Intense Quote style", "A Callout"],
+ ["Bulleted or numbered paragraphs", "One List block"],
+ ["Tables", "Table blocks"],
+ ["A line of --- alone", "A Divider"],
+ ["A YouTube, Vimeo or Facebook link alone on its line", "A Video"],
+ ["Button: Register, with Register linked", "A Button, its label and link"],
+ ["Other paragraphs", "Paragraphs, keeping bold, italic and links"],
+ ],
+ outro: "Images, text boxes, footnotes, comments, colors and fonts aren't carried over: add images as Image blocks after. PDFs: save as .docx first.",
+ },
+ },
list: {
columns: [
diff --git a/src/pages/admin/EntityEdit.tsx b/src/pages/admin/EntityEdit.tsx
index 67f8e3d..f7fed00 100644
--- a/src/pages/admin/EntityEdit.tsx
+++ b/src/pages/admin/EntityEdit.tsx
@@ -691,6 +691,8 @@ function ImportedNote() {
`${summary.paragraphs} paragraphs`,
`${summary.lists} lists`,
`${summary.tables} tables`,
+ ...(summary.tabs ? [`${summary.tabs} tabs`] : []),
+ ...(summary.others ? [`${summary.others} quotes, callouts, dividers, videos and buttons`] : []),
];
return (
diff --git a/src/pages/admin/EntityList.tsx b/src/pages/admin/EntityList.tsx
index 072f9fd..86b5b45 100644
--- a/src/pages/admin/EntityList.tsx
+++ b/src/pages/admin/EntityList.tsx
@@ -282,13 +282,40 @@ function ImportButton({ manifest }: { manifest: any }) {
}
}
+ const guide = manifest.importer.guide;
+
return (
-
+
{error && (
{error}
)}
+ {guide && (
+
+ What becomes what
+