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 <noreply@anthropic.com>
This commit is contained in:
Aidan Dona 2026-10-16 18:21:53 -05:00
parent e4c7e165d1
commit a6c66d4607
13 changed files with 576 additions and 65 deletions

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"