Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions docs/content/docs/plugins/cms.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1495,6 +1495,85 @@ export default function DirectoryPage() {
}
```

## Revision history and scheduling

The entry editor's **Revision history** drawer lists saved versions, newest first,
with a timestamp, writer identity (or System for trusted jobs), slug, schedule,
and field snapshot. Expand a version and choose **Restore this version** to
replace the active entry. The confirmation warns that unsaved editor changes
will be discarded. Restoring keeps all existing revisions and appends a new one.

Successful content creation, updates (including schedule-only updates), rollback,
inline related-item creation, and `createCMSContentItem()` append an immutable
`contentRevision` row in the same transaction as the content write. Rejected
validation, authorization, duplicate slugs, and before-hook failures do not append
revisions. There is no operation to edit or individually delete a revision;
revision rows cascade when their content item is deleted.

School course creation, edits and archival, and automatic Job Board archival
also append snapshots in their write transactions. Custom lower-level writers
can call `recordContentRevision(tx, item, authorId?)` from
`@btst/plugin-cms/api` after writing the item in the same transaction; callers
own validation, authorization and lifecycle hooks.

`publishAt` is optional **top-level scheduling metadata**, separate from the
content type's `data`. The editor accepts local date/time and sends an ISO
timestamp with its time-zone offset converted to UTC. HTTP and operation inputs
accept ISO timestamps with a time-zone offset; omit the property to preserve the
schedule on update, or pass `null` to clear it. Serialized items and revisions
return ISO strings or `null`.
Saving other editor fields preserves the original timestamp's precision until
the schedule control is edited.

This field does not run a publisher job, set a `data.status` field, or filter
content reads. Applications remain responsible for deciding when content becomes
visible. Existing `(contentTypeId, slug)` lookup behavior and payloads for
UI Builder, Ecommerce, School, and Job Board are unchanged.

```ts
const cms = myStack.forRequest(request).operations.cms;
const item = await cms.createContentItem({
typeSlug: "article",
body: {
slug: "launch",
data: { title: "Launch announcement" },
publishAt: "2030-12-05T14:30:00Z",
},
});
const history = await cms.listContentRevisions({
typeSlug: "article", id: item.id, offset: 0,
});
await cms.restoreContentRevision({
typeSlug: "article", id: item.id, revisionId: history.items[0].id,
});
```

`GET /content/:typeSlug/:id/revisions?offset=0` returns `{ items, total }` in
pages of 20. `POST /content/:typeSlug/:id/revisions/:revisionId/restore` returns
the active item. These paths are relative to the stack API base path.
Listing requires `cms.record.read` for the authoritative record plus
`cms.contentType.read`. Restoring requires the existing record update and read
permissions, content-type read, and permission to read any restored relation
targets. Rollback runs the normal update lifecycle hooks and validates against
the current content-type schema. Incompatible old schemas, missing relation
targets, and slug conflicts fail without changing the active item.

Client hooks `useContentRevisions(typeSlug, id, enabled?)` and
`useRestoreContentRevision()` are exported from `@btst/plugin-cms/client/hooks`.
Restore refreshes content, revision history, and relation queries. The existing
create/update hooks accept optional `publishAt` alongside `slug` and `data`.

### Database upgrade

Regenerate and apply the database migration from your stack's `dbSchema` before
serving the updated plugin. The additive schema introduces `contentRevision`
(with a unique item/version `revisionKey` and cascading `contentItemId` reference)
and a nullable `contentItem.publishAt` date column. It does not rewrite content
payloads, IDs, slugs, or author ownership. Existing items start with empty history;
their first successful post-upgrade write creates version 1. Earlier versions
cannot be reconstructed. The lower-level `createCMSContentItem()` helper now
also needs the migrated schema and supports `publishAt` as a `Date` or `null`.

## API Reference

### Backend (`@btst/plugin-cms/api`)
Expand Down
142 changes: 142 additions & 0 deletions e2e/tests/smoke.cms.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -747,3 +747,145 @@ test.describe("CMS Image Upload", () => {
);
});
});

test("CMS revisions restore saved fields and publishAt in the editor", async ({
page,
request,
}) => {
const slug = `revision-${Date.now()}`;
const schedule = "2030-12-05T14:30:00.000Z";
const created = await request.post("/api/data/content/category", {
data: {
slug,
data: { name: "Original category", description: "Original fields" },
publishAt: schedule,
},
});
expect(created.ok()).toBeTruthy();
const item = await created.json();
const editor = `/pages/cms/category/${item.id}`;
await page.goto(editor, { waitUntil: "networkidle" });
await expect(page.locator('input[name="name"]')).toHaveValue(
"Original category",
);
await page.locator('input[name="name"]').fill("Updated category");
await page.getByLabel("Publish at", { exact: true }).fill("2031-12-05T15:45");
await page.getByRole("button", { name: "Save", exact: true }).click();
await page.waitForURL(/\/pages\/cms\/category$/);
await page.goto(editor, { waitUntil: "networkidle" });
await expect(page.locator('input[name="name"]')).toHaveValue(
"Updated category",
);
await page
.getByRole("button", { name: "Revision history", exact: true })
.click();
const drawer = page.getByRole("dialog", {
name: "Revision history",
exact: true,
});
const first = drawer
.locator("details")
.filter({ has: page.getByText("Version 1", { exact: true }) });
await first.locator("summary").click();
await expect(first.getByLabel("Field snapshot")).toContainText(
"Original category",
);
await first.getByRole("button", { name: "Restore this version" }).click();
await page.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(drawer).toBeVisible();
await first.getByRole("button", { name: "Restore this version" }).click();
await page
.getByRole("button", { name: "Restore version", exact: true })
.click();
await expect(page.getByRole("alertdialog")).not.toBeVisible();
await expect(page.locator('[data-slot="sheet-content"]')).not.toBeVisible();
await expect(page.locator('input[name="name"]')).toHaveValue(
"Original category",
);
const localSchedule = await page.evaluate((value) => {
const date = new Date(value);
return new Date(date.getTime() - date.getTimezoneOffset() * 60_000)
.toISOString()
.slice(0, 16);
}, schedule);
await expect(page.getByLabel("Publish at", { exact: true })).toHaveValue(
localSchedule,
);
const history = await (
await request.get(`/api/data/content/category/${item.id}/revisions`)
).json();
expect(
history.items.map((revision: { version: number }) => revision.version),
).toEqual([3, 2, 1]);
expect(history.items[0].publishAt).toBe(schedule);
await page.getByLabel("Publish at", { exact: true }).fill("");
await page.getByRole("button", { name: "Save", exact: true }).click();
await page.waitForURL(/\/pages\/cms\/category$/);
expect(
(await (await request.get(`/api/data/content/category/${item.id}`)).json())
.publishAt,
).toBeNull();
await request.delete(`/api/data/content/category/${item.id}`);
});

test("CMS revision drawer recovers from a failed history request and supports mobile keyboard dismissal", async ({
page,
request,
}) => {
const response = await request.post("/api/data/content/category", {
data: {
slug: `history-retry-${Date.now()}`,
data: { name: "History retry" },
},
});
expect(response.ok()).toBeTruthy();
const item = await response.json();
for (let index = 0; index < 20; index++) {
const update = await request.put(`/api/data/content/category/${item.id}`, {
data: { data: { description: `Save ${index + 2}` } },
});
expect(update.ok()).toBeTruthy();
}
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(`/pages/cms/category/${item.id}`, {
waitUntil: "networkidle",
});
await expect(page.locator('input[name="name"]')).toHaveValue("History retry");
const historyPath = `**/content/category/${item.id}/revisions*`;
await page.route(historyPath, (route) =>
route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ message: "History unavailable" }),
}),
);
await page
.getByRole("button", { name: "Revision history", exact: true })
.click();
const drawer = page.getByRole("dialog", {
name: "Revision history",
exact: true,
});
await expect(drawer.getByRole("alert")).toBeVisible();
await page.unroute(historyPath);
await drawer.getByRole("button", { name: "Retry", exact: true }).click();
await expect(drawer.getByText("Version 21", { exact: true })).toBeVisible();
await drawer
.getByRole("button", { name: "Load older revisions", exact: true })
.click();
await expect(drawer.getByText("Version 1", { exact: true })).toBeVisible();
await expect(
drawer.getByRole("button", { name: "Load older revisions", exact: true }),
).not.toBeVisible();
expect(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth,
),
).toBeTruthy();
await page.keyboard.press("Escape");
await expect(drawer).not.toBeVisible();
await expect(
page.getByRole("button", { name: "Revision history", exact: true }),
).toBeFocused();
await request.delete(`/api/data/content/category/${item.id}`);
});
1 change: 1 addition & 0 deletions packages/plugin-cms/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@
"react-dom": ">=19.2.6"
},
"devDependencies": {
"better-auth": "1.7.14",
"@btst/stack": "workspace:*",
"@btst/yar": "1.3.2",
"@tanstack/react-query": "5.105.0",
Expand Down
4 changes: 4 additions & 0 deletions packages/plugin-cms/src/__tests__/authorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,8 +558,10 @@ describe("CMS authorization inventory", () => {
"getInverseRelations",
"listContentByRelation",
"listContentItems",
"listContentRevisions",
"listContentTypes",
"listInverseRelationItems",
"restoreContentRevision",
"updateContentItem",
]);
expect(
Expand All @@ -576,6 +578,8 @@ describe("CMS authorization inventory", () => {
getContentItem: "cms:record.read",
createContentItem: "cms:record.create",
updateContentItem: "cms:record.update",
listContentRevisions: "cms:record.read",
restoreContentRevision: "cms:record.update",
deleteContentItem: "cms:record.delete",
getContentItemPopulated: "cms:record.read",
listContentByRelation: "cms:record.read",
Expand Down
65 changes: 65 additions & 0 deletions packages/plugin-cms/src/__tests__/client-sweep.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,71 @@ describe("CMSFileUpload notifications (useNotify)", () => {
});

describe("ContentForm inline errors", () => {
it("preserves an untouched publication timestamp when saving content", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
await render(
<StackProvider stack={createCmsStack()} overrides={{ cms: cmsOverrides }}>
<ContentForm
contentType={contentType}
initialSlug="hello"
initialData={{ title: "Updated content" }}
initialPublishAt="2030-12-05T14:30:45.123Z"
isEditing
onSubmit={onSubmit}
/>
</StackProvider>,
);
await act(async () => {
container
.querySelector("form")!
.dispatchEvent(
new Event("submit", { bubbles: true, cancelable: true }),
);
});
expect(onSubmit).toHaveBeenCalledWith({
slug: "hello",
data: { title: "Updated content" },
publishAt: "2030-12-05T14:30:45.123Z",
});
});

it("clears the publication timestamp when the schedule is explicitly emptied", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
await render(
<StackProvider stack={createCmsStack()} overrides={{ cms: cmsOverrides }}>
<ContentForm
contentType={contentType}
initialSlug="hello"
initialData={{ title: "Updated content" }}
initialPublishAt="2030-12-05T14:30:45.123Z"
isEditing
onSubmit={onSubmit}
/>
</StackProvider>,
);
const input = container.querySelector<HTMLInputElement>("#publishAt")!;
const setValue = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
"value",
)!.set!;
await act(async () => {
setValue.call(input, "");
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await act(async () => {
container
.querySelector("form")!
.dispatchEvent(
new Event("submit", { bubbles: true, cancelable: true }),
);
});
expect(onSubmit).toHaveBeenCalledWith({
slug: "hello",
data: { title: "Updated content" },
publishAt: null,
});
});

it("shows a non-field error message above the form", async () => {
await render(
<StackProvider stack={createCmsStack()} overrides={{ cms: cmsOverrides }}>
Expand Down
Loading
Loading