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
5 changes: 5 additions & 0 deletions .changeset/admin-edit-route-doc-form.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/cms-ui-react': minor
---

The admin edit route is rebuilt on `DocForm` and core's `createDocEditorStore`. The form owns field state, and the store owns the baseline, the versions a save sends, and where the document stands. Saves go through `save` with a patch of the changed fields: the whole document only when nothing is stored yet. Every save runs through the form's submit, so form validators gate it. The header shows the strategy's state label (`data-testid="editor-state"`), and it offers the workflow actions the document's strategy gives the user (approve, reject, discard, publish an approved change, a custom step), run with `act`. `schedule` stays in the review queue. The save buttons follow `availableActions`: `edit` and `submit` choose between Save and Submit for review, and `draft` adds Save draft for publishers. A server-side change after a save (computed fields, `_revision`) now shows in the editor without a reload. `docPatch` is now core's, re-exported unchanged.
5 changes: 5 additions & 0 deletions .changeset/doc-editor-meta-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/cms-api': minor
---

`getDocEditorMeta` also returns `state` and `availableActions`, with the same shapes `save` returns, for the caller. An editor can then show where a document stands and the actions it offers before the first save.
25 changes: 25 additions & 0 deletions .changeset/doc-editor-write-results.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
'@tanstack/cms-core': minor
---

`createDocEditorStore` speaks `save` and `act`. Its state gains:

- `baseline`, the stored document that `doc` is edited from;
- `writeState`;
- `availableActions`.

Options gain `baseline`, `state` and `availableActions`. `state` sets the default `baseRevision` and `pendingVersion`.

`transport.save` receives `patch`, the changed top-level fields (or the whole document while nothing is stored). When the result carries `state`:

- its `doc` becomes the baseline, keeping edits made while the save was in flight;
- its versions are the next save's;
- the status follows from the change set.

New store methods:

- `act(action, input?)` runs one of the document's actions through `transport.act` with the open change set's version, and adopts the result.
- `change(doc)` replaces the doc with an edit.
- `transport.load` fetches the document with its state, and `reloadLatest` and `discardDraft` prefer it to `reload`, which is now optional.

`DocEditorError.action` names the action that failed. `docPatch(baseline, doc)` is exported from core. Existing transports work unchanged.
2 changes: 1 addition & 1 deletion .changeset/doc-form-primitive.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
'@tanstack/cms-ui-react': minor
---

Add `DocForm` and `useDocForm` to `@tanstack/cms-ui-react/primitives`: a schema-driven document form on TanStack Form. Pass a collection name and it renders a control per field in schema order, honouring `showWhen` and, given `access`, field-level read and write rules. Use it controlled (`value`/`onChange`) or uncontrolled (`defaultValue`). `onSubmit` receives a patch of the fields that changed since the baseline, plus the whole document and any `submit(meta)` argument. `renderers` passes the app's renderers module (`defineRenderers`) to every `FieldInput`, and `fieldRenderers` replaces the control for a field type in one form, built-in types included. `fieldRenderers` is checked first. `docPatch(baseline, doc)` is also exported. Nothing breaks: the admin edit route doesn't use the form yet.
Add `DocForm` and `useDocForm` to `@tanstack/cms-ui-react/primitives`: a schema-driven document form on TanStack Form. Pass a collection name and it renders a control per field in schema order, honouring `showWhen` and, given `access`, field-level read and write rules. Use it controlled (`value`/`onChange`) or uncontrolled (`defaultValue`). `onSubmit` receives a patch of the fields that changed since the baseline, plus the whole document and any `submit(meta)` argument. `renderers` passes the app's renderers module (`defineRenderers`) to every `FieldInput`, and `fieldRenderers` replaces the control for a field type in one form, built-in types included. `fieldRenderers` is checked first. `docPatch(baseline, doc)` is also exported. Nothing breaks.
5 changes: 3 additions & 2 deletions docs/agents/review-queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Every commit records a **revision**, and every decision (a direct save, an appro

Pending proposals have a monotonically increasing `version`. Send the version shown to the reviewer as `expectedVersion` when calling `approveChange` or `rejectChange`; the built-in review screen does this automatically. A rejected, replaced or already decided proposal conflicts even with `force: true`. `force` overrides a stale live revision, while `forceDelete` separately opts into deleting referenced content and records a forced deletion in revision history.

Editing reads expose `pendingVersion`. Pass it as `expectedPendingVersion` to `saveDoc` (use `0` when there is no pending copy) to detect another editor changing a draft/proposal; the built-in editor does this alongside `expectedRevision`.
Editing reads expose `pendingVersion`. Pass it as `expectedPendingVersion` to `saveDoc` (use `0` when there is no pending copy) to detect another editor changing a draft/proposal. The built-in editor reads both versions from `getDocEditorMeta`'s `state` and sends them with `save` as `expectedRevision` and `expectedPendingVersion`.

## Who Commits, Who Drafts, Who Is Reviewed

Expand All @@ -41,7 +41,8 @@ When someone saves in the editor (the `saveDoc` operation), the outcome depends
| Cannot publish (`author`) | **Staged** for review | **Staged** for review |
| Any agent (content agent, MCP, WebMCP) | **Staged** for review | **Staged** for review |

- **Drafts** are private working copies of a published document. They don't appear in the review queue. The editor shows the draft over the live version; **Publish changes** commits it, and **Discard draft** (`discardDraft`, publishers only) throws it away.
- **Drafts** are private working copies of a published document. They don't appear in the review queue. The editor shows the draft over the live version; **Publish changes** commits it, and **Discard draft** (the strategy's `discard` action, for publishers) throws it away.
- **The editor's header** shows the strategy's label for the document (**Published**, **Draft**, **Pending Review**, …) and the actions the strategy offers the user. A reviewer can **Approve** or **Reject** a pending change from the document itself. Scheduling a change set stays in `/review`.
- **Staged changes** appear in `/review`, attributed to their author: `human` for an author's save, or `content-agent`, `mcp`, or `webmcp` for agent writes.

The rules come from the session's role, so custom roles and collection `access` rules change them too. See [Authentication & Access Control](../architecture/authentication).
Expand Down
94 changes: 93 additions & 1 deletion docs/api/cms-ui-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,99 @@ export function PostEditor({ post, save }: { post: Doc; save: (patch: Doc, publi
}
```

`useDocForm` returns `{ form, collection, values, baseline, patch, dirty, submitting, error, submit, reset, setValue }`. `form` is the TanStack Form instance, for `form.Field` and `form.Subscribe`. `submit(meta?)` resolves `true` when `onSubmit` succeeded. `reset()` goes back to the baseline, and `reset(doc)` loads `doc` and makes it the baseline. `docPatch(baseline, doc)` is the patch computation on its own.
`useDocForm` returns `{ form, collection, values, baseline, patch, dirty, submitting, error, submit, reset, setValue }`. `form` is the TanStack Form instance, for `form.Field` and `form.Subscribe`. `submit(meta?)` resolves `true` when `onSubmit` succeeded. `reset()` goes back to the baseline, and `reset(doc)` loads `doc` and makes it the baseline. `docPatch(baseline, doc)` is the patch computation on its own (also exported from `@tanstack/cms-core`).

#### With the core editor store

The admin's edit route is built this way. `DocForm` owns the fields' state, and `createDocEditorStore` from `@tanstack/cms-core` owns the rest:

- the baseline;
- the versions the next save sends (optimistic concurrency);
- where the document stands;
- the actions its workflow offers.

The store's transport calls `save` and `act` (from `@tanstack/cms-api/start` or the client). Their results set the next baseline, `state` and `availableActions`:

```tsx
import { createDocEditorStore } from '@tanstack/cms-core'
import { act, save } from '@tanstack/cms-api/start'
import { DocForm, useDocForm } from '@tanstack/cms-ui-react/primitives'
import { useStore } from '@tanstack/react-store'
import { useState } from 'react'
import type { ActionDescriptor, Doc, WriteState } from '@tanstack/cms-core'

export function PostEditor(props: {
id: string
post: Doc
state: WriteState
availableActions: Array<ActionDescriptor>
}) {
const ref = { collection: 'post', id: props.id }
const [ed] = useState(() =>
createDocEditorStore({
initialDoc: props.post,
state: props.state,
availableActions: props.availableActions,
transport: {
// `patch` is the changed fields; the store sends both versions.
save: (args) =>
save({
data: {
...ref,
doc: args.patch,
expectedRevision: args.expectedRevision,
expectedPendingVersion: args.expectedPendingVersion,
publish: args.publish,
},
}),
act: (args) => act({ data: { ...ref, ...args } }),
},
}),
)
const doc = useStore(ed.store, (s) => s.doc)
const baseline = useStore(ed.store, (s) => s.baseline)
const state = useStore(ed.store, (s) => s.writeState)
const actions = useStore(ed.store, (s) => s.availableActions)
const form = useDocForm<{ publish?: boolean }>({
collection: 'post',
value: doc,
baseline,
onChange: (next) => ed.change(next),
onSubmit: (patch, { meta }) => ed.save({ patch, publish: meta?.publish }),
})
return (
<>
<header>
<span>{state?.label}</span>
{actions
.filter((a) => a.type === 'approve' || a.type === 'discard')
.map((a) => (
<button key={a.type} type="button" onClick={() => void ed.act(a.type)}>
{a.label}
</button>
))}
<button type="button" onClick={() => void form.submit()}>
Save
</button>
</header>
<DocForm form={form} />
</>
)
}
```

Saving through `form.submit` lets the form's validators gate every save. The store keeps edits made while a save is in flight, and gives `act` the open change set's version.

The editor loads `state` and `availableActions` with `getDocEditorMeta`. The store's state includes:

| Field | What it holds |
| --- | --- |
| `doc` | The document being edited. |
| `baseline` | The stored document that `doc` is edited from. |
| `writeState` | Where the document stands. |
| `availableActions` | The actions its workflow offers. |
| `status` | `'saved'`, `'draft'` or `'staged'` after a save. A change set the save didn't touch counts as someone else's, so the save went live. |
| `error` | The last failure, with `action` set when `act` failed. |

---

Expand Down
2 changes: 1 addition & 1 deletion docs/api/routes-and-endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/
| `resolveRedirect` | GET | public | `{ path }` | `{ to, status }` or `null` |
| `getPublicDocument` | GET | public | `{ slugOrId, preferred?: string[] }` | `{ collection, id, doc }` or `null`. Published only, except for callers with `content.read`. A slug-or-id lookup across collections, trying `preferred` first; `get` reads one collection. |
| `listPublishedDocuments` | GET | public | `{ collection, where?, sort?: { field, dir? }, limit? (≤ 500, default 100), offset?, cursor? }` | `{ items: [{ id, doc }], total, nextCursor? }`. The older form of `list`; it never populates. |
| `getDocEditorMeta` | GET | `content.read` | `{ collection, id }` | `{ revisions, translations, references }` |
| `getDocEditorMeta` | GET | `content.read` | `{ collection, id }` | `{ state, availableActions, revisions, translations, references }`. `state` and `availableActions` are the caller's, as `save` returns them. |
| `restoreDocRevision` | POST | `content.publish` | `{ collection, id, revisionId }` | `{ ok, doc }` |
| `saveDoc` | POST | `content.write` | `{ collection, id, doc, expectedRevision?, publish? }` | `{ ok, staged, draft?, pendingId?, doc }`. Deprecated: use `save`. Staged for review without publish rights; a draft when the document is published and `publish` is not set. |
| `createDoc` | POST | `content.write` | `{ collection, id, doc? }` | As `saveDoc`. Deprecated: use `save` with `create: true`. `CONFLICT` when the id exists. |
Expand Down
2 changes: 1 addition & 1 deletion docs/mcp/operations-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ interface CmsOperation<TInput, TOutput> {
| `resolveRedirect` | GET | public | Look up a path in the redirects collection |
| `listDocumentSummaries` | GET | `content.read` | Admin list with search, status filter, sort, and pagination |
| `getDocument` | GET | `content.read` | One document for editing, with any pending version overlaid |
| `getDocEditorMeta` | GET | `content.read` | Revisions, translations, and inbound references |
| `getDocEditorMeta` | GET | `content.read` | Revisions, translations, inbound references, and the document's state and actions |
| `reviewSnapshot` | GET | `content.read` | Pending changes (with their strategy label and the caller's actions) and audit trail |
| `saveDoc` | POST | `content.write` | Save a document (commit, draft, or stage for review) |
| `createDoc` | POST | `content.write` | Create a document |
Expand Down
43 changes: 43 additions & 0 deletions examples/blog/e2e/editor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,49 @@ test('an editor restores an earlier revision', async ({ page, context }) => {
)
})

test('the editor shows where a document stands and runs its workflow actions', async ({
page,
context,
}) => {
await signInAs(context, 'admin')
await createDocument(page, 'post', 'E2E workflow')
const state = page.getByTestId('editor-state')
const title = page.getByRole('textbox', { name: /^Title/ })
await expect(state).toHaveText('Unpublished')
await page.getByRole('checkbox', { name: /Published/ }).check()
await page.getByRole('button', { name: SAVE }).click()
await expect(page.getByText(/(Saved|Published) ✓/).first()).toBeVisible()
await expect(state).toHaveText('Published')

// A publisher's edit to a live post is a draft; discarding it is an action.
await title.fill('E2E workflow, draft')
await page.getByRole('button', { name: 'Save draft' }).click()
await expect(page.getByText('Draft saved ✓').first()).toBeVisible()
await expect(state).toHaveText('Draft')
await page.getByRole('button', { name: 'Discard draft' }).click()
await expect(state).toHaveText('Published')
await expect(title).toHaveValue('E2E workflow')

// An author's edit waits for review, and a reviewer approves it in place.
await signInAs(context, 'author')
await open(page, '/edit/post/e2e-workflow')
await title.fill('E2E workflow, reviewed')
await page.getByRole('button', { name: 'Submit for review' }).click()
await expect(page.getByText('Submitted for review ✓').first()).toBeVisible()
await expect(state).toHaveText('Pending Review')
await expect(page.getByRole('button', { name: 'Approve' })).toHaveCount(0)

await signInAs(context, 'editor')
await open(page, '/edit/post/e2e-workflow')
await expect(state).toHaveText('Pending Review')
await page.getByRole('button', { name: 'Approve', exact: true }).click()
await expect(state).toHaveText('Published')
await expect(title).toHaveValue('E2E workflow, reviewed')
expect((await getDoc(page.request, 'post', 'e2e-workflow')).title).toBe(
'E2E workflow, reviewed',
)
})

test('a block is edited in place on the page', async ({ page, context }) => {
await signInAs(context, 'admin')
await open(page, '/p/home')
Expand Down
18 changes: 12 additions & 6 deletions packages/api/src/ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
approve,
availableDocumentActions,
documentStateLabel,
documentWriteState,
readChangeSet,
assertTrustedOrigin,
runOp,
Expand Down Expand Up @@ -681,7 +682,7 @@ const _ops = {
method: 'GET',
access: 'content.read',
description:
'Revisions, translations, and inbound references for the document editor (admin).',
'Revisions, translations, inbound references, and where the document stands (`state`, `availableActions`, as `save` returns them) for the document editor (admin).',
input: docRef,
run: async (input: z.infer<typeof docRef>, ctx: CmsOpContext) => {
const access = editing(ctx)
Expand All @@ -697,12 +698,17 @@ const _ops = {
id: input.id,
doc: live ?? current.doc,
})
const [revisions, translations, references] = await Promise.all([
listRevisionsAs(access, input.collection, input.id),
listTranslationsAs(OP_READ, input.collection, input.id),
findReferencesAs(access, input.collection, input.id),
])
const [revisions, translations, references, state, actions] =
await Promise.all([
listRevisionsAs(access, input.collection, input.id),
listTranslationsAs(OP_READ, input.collection, input.id),
findReferencesAs(access, input.collection, input.id),
documentWriteState(input.collection, input.id),
availableDocumentActions(access, input.collection, input.id),
])
return {
state,
availableActions: actions.map((a) => ({ ...a })),
revisions,
translations: (
await Promise.all(
Expand Down
44 changes: 44 additions & 0 deletions packages/api/tests/ops.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,50 @@ describe('reading', () => {
])
})

it('editor meta reports where the document stands, as save does', async () => {
await seed()
const editor = await call(
'getDocEditorMeta',
{ collection: 'post', id: 'live' },
'editor',
)
expect(editor.result.state).toEqual({
label: 'Published',
published: true,
revision: 1,
changeSet: null,
})
expect(
editor.result.availableActions.map((a: { type: string }) => a.type),
).toEqual(['edit', 'draft'])

await call(
'save',
{ collection: 'post', id: 'live', doc: { title: 'Proposed' } },
'author',
)
const author = await call(
'getDocEditorMeta',
{ collection: 'post', id: 'live' },
'author',
)
expect(author.result.state).toMatchObject({
label: 'Pending Review',
changeSet: { version: 1, source: 'review' },
})
expect(
author.result.availableActions.map((a: { type: string }) => a.type),
).toEqual(['submit'])
const reviewer = await call(
'getDocEditorMeta',
{ collection: 'post', id: 'live' },
'editor',
)
expect(
reviewer.result.availableActions.map((a: { type: string }) => a.type),
).toContain('approve')
})

it('reports the current session', async () => {
setup()
const res = await call('getAuthSession', {}, 'editor')
Expand Down
14 changes: 9 additions & 5 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,15 +418,19 @@ export type {
CmsAuthStore,
} from './lib/ui'

// Headless document-editor state machine (framework-agnostic). Tracks dirty
// state, save (with optimistic-concurrency / conflict handling), staged/draft
// status, and reload/discard-draft flows. All server calls and post-mutation
// settle steps are injected via the transport interface and onSettled callback.
export { createDocEditorStore } from './lib/doc-editor'
// Headless document-editor state machine (framework-agnostic). Tracks the
// baseline and dirty state, save (a patch, with optimistic-concurrency /
// conflict handling), the document's state and actions, and reload flows. All
// server calls and post-mutation settle steps are injected via the transport
// interface and onSettled callback.
export { createDocEditorStore, docPatch } from './lib/doc-editor'
export type {
DocEditorStatus,
DocEditorSaveArgs,
DocEditorSaveResult,
DocEditorSnapshot,
DocEditorActArgs,
DocEditorActResult,
DocEditorTransport,
DocEditorError,
DocEditorState,
Expand Down
Loading
Loading