v1.14.0-profiles: profile accounts, drafts, page management, Planning Center #32

Merged
ngu-git-admin merged 15 commits from page-management into main 2026-10-28 07:00:10 +00:00
13 changed files with 576 additions and 65 deletions
Showing only changes of commit a6c66d4607 - Show all commits

View file

@ -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.

84
TODO.md
View file

@ -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/<id>).
- [ ] 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.

46
docs/drafts.md Normal file
View file

@ -0,0 +1,46 @@
# Drafts
Any record the admin edits (events, people, organizations, blog posts,
the front page, the site pages, Navigation, Site settings...) can be
saved as a draft instead of going live (migration 077). One draft per
record; anyone who can edit the record can save, preview, publish or
discard it.
## In the editor
- **Save draft** keeps the form as the record's draft. It's checked the
way a save is (same field errors), but nothing on the site changes.
- **Preview** saves the draft and opens the record's page in a new tab
showing it, with an amber bar ("Previewing a draft"). Only a
signed-in admin account (viewer and up) sees the draft; anyone else
opening that address sees the live page. Stop previewing in the bar
returns the tab to the live site.
- **Publish** (the Save button, while there's a draft) saves it for
real and drops the draft.
- **Discard draft** throws it away; the live version is untouched.
Opening a record that has a draft opens the draft, with a note saying
who saved it and when. If the live record was saved after the draft was
started, the note says so: publishing replaces those changes. Lists
mark records with a draft.
Records not yet created have no drafts: Create is the only save (leave
them unpublished until they're ready).
## How it works
`server/src/drafts.js`. A draft is the editor's whole form, as a save
would send it. Saving one applies it inside a transaction that is
always rolled back (`rolledBackSync` in `server/src/db.js`), so it's
validated without being written. A preview is a public API read sent
with `X-Draft-Preview: <entity>/<id>` (`src/lib/api.ts` adds it in a tab
opened with `?preview=`): the server opens a second connection to the
database, applies the draft in a transaction there, answers the read
from it, and rolls back. WAL keeps those writes unseen by every other
request. Public reads carry `Vary: X-Draft-Preview`, so a browser never
mixes a cached live answer with a preview.
`tx()` nests as a savepoint, which is what lets a save run inside the
rolled-back transaction. Where each entity's page is: `PREVIEW_PATHS` in
`src/lib/adminSchema.ts` (an entity without one has drafts but no
Preview button).

View file

@ -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");
}
}

156
server/src/drafts.js Normal file
View file

@ -0,0 +1,156 @@
/* ═══════════════════════════════════════════════════════════════
DRAFTS (077_drafts.sql)
A record's changes saved without going live: one per record, of
any entity the admin edits. The draft is the editor's whole form,
exactly what a save would send, so publishing is that save
(PATCH, routes/admin-entities.js), which then drops the draft.
Nothing applies a draft for real until it's published. Twice it's
applied and thrown away:
checking when it's saved, in a transaction on the main
connection that's always rolled back
(rolledBackSync): updateRow is synchronous, so no
other request can see it, and a draft that a save
would refuse is refused now, with the same errors
preview a public API read sent with X-Draft-Preview:
<entity>/<id> by a signed-in viewer and up runs on a
connection of its own (the same file), inside a
transaction holding the applied draft, rolled back
when the answer is made (previewDrafts). The site
draws the real page from it, with no code of its own
for previews. WAL keeps that connection's writes
unseen by everyone else; it holds the write lock
meanwhile, a few milliseconds, which other writes
wait out (busy_timeout).
The draft is applied over the live record as it is now, so a
save made since the draft was started is overwritten when it's
published; the editor says when that's so (stale).
═══════════════════════════════════════════════════════════════ */
import { currentUser, hasRole } from "./auth.js";
import { openDatabase, rolledBack, rolledBackSync } from "./db.js";
import { HttpError, normalizeId, updateRow } from "./admin-crud.js";
import { ENTITIES } from "./admin-schema.js";
/* Who may preview a draft: anyone who can read the admin. */
export const PREVIEWS = "viewer";
export const entityNamed = (key) => (Object.hasOwn(ENTITIES, key) ? ENTITIES[key] : null);
const liveStamp = (db, entity, id) =>
entity.concurrency
? db
.prepare(`SELECT ${entity.concurrency} AS stamp FROM ${entity.table} WHERE ${entity.idColumn} = ?`)
.get(normalizeId(entity, id))?.stamp
: undefined;
/* Writes the draft over the live record, its concurrency stamp taken
from the live row so the check passes. Call inside a rolled-back
transaction, or as the real publish. */
function apply(db, entity, id, payload) {
const stamp = liveStamp(db, entity, id);
return updateRow(db, entity, id, entity.concurrency ? { ...payload, [entity.concurrency]: stamp } : payload);
}
export function readDraft(db, key, id) {
const entity = entityNamed(key);
const row = db
.prepare(
`SELECT d.*, u.name AS updated_by_name, u.email AS updated_by_email
FROM drafts d LEFT JOIN admin_users u ON u.id = d.updated_by
WHERE d.entity = ? AND d.record_id = ?`,
)
.get(key, String(id));
if (!row) return null;
const live = entity ? liveStamp(db, entity, id) : undefined;
return {
payload: JSON.parse(row.payload),
created_at: row.created_at,
updated_at: row.updated_at,
updated_by: row.updated_by_name ?? row.updated_by_email ?? null,
// The live record was saved after the draft was started.
stale: Boolean(entity?.concurrency && row.base_updated_at && live && live !== row.base_updated_at),
};
}
/* The ids of an entity's records that have a draft, for its list. */
export const draftIds = (db, key) =>
db.prepare(`SELECT record_id FROM drafts WHERE entity = ?`).all(key).map((row) => row.record_id);
/* Checks the draft by applying it and throwing that away, then keeps
it. An HttpError from the check (422 with fields, say) refuses it. */
export function saveDraft(db, key, id, payload, userId) {
const entity = entityNamed(key);
if (!entity) throw new HttpError(404, "Unknown entity.");
if (!payload || typeof payload !== "object") throw new HttpError(400, "Expected the record's form.");
rolledBackSync(db, () => apply(db, entity, id, payload));
const existing = db.prepare(`SELECT base_updated_at FROM drafts WHERE entity = ? AND record_id = ?`).get(key, String(id));
const base = existing ? existing.base_updated_at : (payload[entity.concurrency] ?? null);
db.prepare(
`INSERT INTO drafts (entity, record_id, payload, base_updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (entity, record_id) DO UPDATE
SET payload = excluded.payload, updated_by = excluded.updated_by, updated_at = datetime('now')`,
).run(key, String(id), JSON.stringify(payload), base, userId, userId);
return readDraft(db, key, id);
}
export function dropDraft(db, key, id) {
db.prepare(`DELETE FROM drafts WHERE entity = ? AND record_id = ?`).run(key, String(id));
}
/* Middleware for the public API: a GET carrying X-Draft-Preview from
a signed-in viewer and up is answered with that draft applied. Any
other request, or a draft that isn't there, goes on as usual. */
export async function previewDrafts(c, next) {
if (c.req.method !== "GET" || /^\/api\/(admin|auth|account)(\/|$)/.test(c.req.path)) return next();
await answer(c, next);
// A public read may be kept a minute (shape.js, CACHE): never hand
// the live copy to a preview tab, or a preview's to anyone.
c.res.headers.append("Vary", "X-Draft-Preview");
}
async function answer(c, next) {
const wanted = c.req.header("x-draft-preview");
if (!wanted) return next();
const main = c.get("db");
if (!hasRole(currentUser(main, c), PREVIEWS)) return next();
const slash = wanted.indexOf("/");
const key = wanted.slice(0, slash);
let id;
try {
id = decodeURIComponent(wanted.slice(slash + 1));
} catch {
return next();
}
const entity = entityNamed(key);
const draft = slash > 0 && entity ? readDraft(main, key, id) : null;
if (!draft) return next();
const db = await openDatabase(main.path);
try {
await rolledBack(db, async () => {
// A draft the record has outgrown (a field it no longer has,
// say) shows the live page rather than an error; saving it in
// the editor says what's wrong.
try {
apply(db, entity, id, draft.payload);
} catch (err) {
console.warn(`draft preview ${key}/${id} not applied: ${err.message}`);
}
c.set("db", db);
await next();
});
} finally {
db.close();
}
// Only for this tab, never kept.
c.res.headers.set("Cache-Control", "no-store");
}

View file

@ -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 }),
);

View file

@ -0,0 +1,25 @@
-- ═══════════════════════════════════════════════════════════════
-- 077 DRAFTS
--
-- A record's changes saved without going live: one draft per
-- record, of any entity the admin edits (events, people, pages,
-- Navigation...). payload is the editor's whole form, as a save
-- would send it; publishing is that save, which then drops the
-- draft. Anyone who can edit the record can save, preview, publish
-- or discard it (drafts.js).
--
-- base_updated_at is the record's updated_at when the draft was
-- started, so the editor can say the live record changed since.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE drafts (
entity TEXT NOT NULL, -- the descriptor key, eg. 'events'
record_id TEXT NOT NULL,
payload TEXT NOT NULL CHECK (json_valid(payload)),
base_updated_at TEXT,
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (entity, record_id)
) STRICT;

View file

@ -6,7 +6,11 @@
GET /api/admin/:entity/:id row with side tables and children
POST /api/admin/:entity create
PATCH /api/admin/:entity/:id replace the row and its children
(publishing a draft too: it's dropped)
DELETE /api/admin/:entity/:id
GET /api/admin/:entity/:id/draft its draft, or null (drafts.js)
PUT /api/admin/:entity/:id/draft save the form as its draft
DELETE /api/admin/:entity/:id/draft discard it
Mounted alongside the existing admin router, which keeps the
feedback routes. Both sit under the same requireAuth.
@ -29,6 +33,7 @@ import {
deleteRow,
} from "../admin-crud.js";
import { NO_STORE } from "../shape.js";
import { draftIds, dropDraft, readDraft, saveDraft } from "../drafts.js";
const entities = new Hono();
@ -84,7 +89,8 @@ entities.get("/options", (c) => {
entities.get("/:entity", (c) => {
const entity = entityOr404(c);
const { rows, total } = listRows(c.get("db"), entity, c.req.query());
return c.json({ rows, total }, 200, NO_STORE);
// Which of them have a draft waiting, for the list to mark.
return c.json({ rows, total, drafts: draftIds(c.get("db"), entity.key) }, 200, NO_STORE);
});
entities.get("/:entity/:id", (c) => {
@ -103,6 +109,8 @@ entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
// Saved for real: any draft of it is published, or overtaken.
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
return c.json({ row }, 200, NO_STORE);
});
@ -111,10 +119,34 @@ entities.delete("/:entity/:id", requireRole("admin"), (c) => {
const entity = entityOr404(c);
const id = c.req.param("id");
deleteRow(c.get("db"), entity, id);
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
/* ── Drafts (drafts.js) ──────────────────────────────────────── */
entities.get("/:entity/:id/draft", (c) => {
const entity = entityOr404(c);
return c.json({ draft: readDraft(c.get("db"), entity.key, c.req.param("id")) }, 200, NO_STORE);
});
entities.put("/:entity/:id/draft", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const draft = saveDraft(c.get("db"), entity.key, id, await json(c), c.get("user").id);
console.log(`${entity.key} ${id} draft saved by ${c.get("user").email}`);
return c.json({ draft }, 200, NO_STORE);
});
entities.delete("/:entity/:id/draft", requireRole("editor"), (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} draft discarded by ${c.get("user").email}`);
return c.body(null, 204);
});
async function json(c) {
try {
return await c.req.json();

View file

@ -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 = (
<Suspense fallback={null}>{hiddenHere && !nav.seesHidden ? <NotFound /> : <Outlet />}</Suspense>
);
// 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 && (
<p className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 bg-[var(--pal-amber-3)] px-6 py-2 text-center text-sm text-[var(--pal-amber-1)] print:hidden">
<PencilSimple size={18} weight="bold" aria-hidden="true" />
Previewing a draft: this is how it will look once published. Nobody else sees it.
<button type="button" onClick={stopPreview} className="font-semibold underline">
Stop previewing
</button>
</p>
);
const hiddenBar = hiddenHere && nav.seesHidden && (
<p className="flex items-center justify-center gap-2 bg-tint px-6 py-2 text-center text-sm text-ink print:hidden">
<EyeSlash size={18} weight="bold" aria-hidden="true" />
@ -323,6 +335,7 @@ export default function Layout() {
{/* Page content */}
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
{previewBar}
{hiddenBar}
{page}
</main>

View file

@ -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<string, any> = {
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, (row: any) => 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

View file

@ -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=<entity>/<id> 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<number, string> = {
};
async function request(path, options: RequestInit = {}) {
const preview: Record<string, string> =
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<string, string>) },
});
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" });
}

View file

@ -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<any>(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<boolean> {
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}
</h1>
{draft && (
<div className="notice mt-4 p-4 text-sm">
<p className="text-body">
<strong>You're editing a draft</strong>, 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.
</p>
{draft.stale && (
<p className="mt-1 text-danger">
The live version was saved after this draft was started. Publishing replaces those changes with the draft.
</p>
)}
</div>
)}
<ImportedNote />
{fromRequest && (
<RequestedChanges
@ -508,11 +601,41 @@ export default function EntityEdit() {
<button
type="button"
onClick={save}
disabled={saving || !dirty}
disabled={saving || (!dirty && !draft)}
className="btn bg-action px-6 py-2 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25"
>
{saving ? "Saving…" : isNew ? "Create" : "Save changes"}
{saving ? "Saving…" : isNew ? "Create" : draft ? "Publish" : "Save changes"}
</button>
{!isNew && (
<button
type="button"
onClick={saveDraft}
disabled={saving || !dirty}
className="btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50"
>
Save draft
</button>
)}
{!isNew && PREVIEW_PATHS[manifest.key]?.(form) && (
<button
type="button"
onClick={preview}
disabled={saving}
className="btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50"
>
Preview
</button>
)}
{draft && (
<button
type="button"
onClick={discardDraft}
disabled={saving}
className="btn border border-danger/40 px-4 py-2 text-sm text-danger transition-colors hover:bg-danger-tint"
>
Discard draft
</button>
)}
{!isNew && !singleton && canDelete && (
<button
type="button"

View file

@ -29,6 +29,8 @@ export default function EntityList() {
const [params, setParams] = useSearchParams();
const [rows, setRows] = useState<any[]>([]);
const [total, setTotal] = useState(0);
// Ids with a draft waiting (server/src/drafts.js), marked in the list.
const [drafts, setDrafts] = useState<Set<string>>(() => new Set());
const [loadingMore, setLoadingMore] = useState(false);
const [options, setOptions] = useState<any>({});
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 ? (
<Link
to={`/admin/${manifest.key}/${row.id}`}
onClick={(e) => e.stopPropagation()}
className="hover:underline"
>
{row[column.key] || row.id}
</Link>
<>
<Link
to={`/admin/${manifest.key}/${row.id}`}
onClick={(e) => e.stopPropagation()}
className="hover:underline"
>
{row[column.key] || row.id}
</Link>
{drafts.has(String(row.id)) && (
<span className="ml-2 bg-tint px-2 py-0.5 text-xs font-medium text-link">Draft</span>
)}
</>
) : column.widget === "bool" ? (
row[column.key] ? (
"Yes"