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:
parent
e4c7e165d1
commit
a6c66d4607
13 changed files with 576 additions and 65 deletions
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue