diff --git a/.changeset/admin-edit-route-doc-form.md b/.changeset/admin-edit-route-doc-form.md new file mode 100644 index 00000000..1fd9362d --- /dev/null +++ b/.changeset/admin-edit-route-doc-form.md @@ -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. diff --git a/.changeset/doc-editor-meta-state.md b/.changeset/doc-editor-meta-state.md new file mode 100644 index 00000000..6b250ae4 --- /dev/null +++ b/.changeset/doc-editor-meta-state.md @@ -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. diff --git a/.changeset/doc-editor-write-results.md b/.changeset/doc-editor-write-results.md new file mode 100644 index 00000000..411e4c1a --- /dev/null +++ b/.changeset/doc-editor-write-results.md @@ -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. diff --git a/.changeset/doc-form-primitive.md b/.changeset/doc-form-primitive.md index 92cf5c4d..dd52e8c8 100644 --- a/.changeset/doc-form-primitive.md +++ b/.changeset/doc-form-primitive.md @@ -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. diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index a645c4c9..2dfae90c 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -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 @@ -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). diff --git a/docs/api/cms-ui-react.md b/docs/api/cms-ui-react.md index 7c53567c..a014b29b 100644 --- a/docs/api/cms-ui-react.md +++ b/docs/api/cms-ui-react.md @@ -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 +}) { + 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 ( + <> +
+ {state?.label} + {actions + .filter((a) => a.type === 'approve' || a.type === 'discard') + .map((a) => ( + + ))} + +
+ + + ) +} +``` + +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. | --- diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index c45b47a9..3bdb3ad3 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -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. | diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 686bd130..e6e05708 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -50,7 +50,7 @@ interface CmsOperation { | `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 | diff --git a/examples/blog/e2e/editor.spec.ts b/examples/blog/e2e/editor.spec.ts index 56604e80..7aa4a767 100644 --- a/examples/blog/e2e/editor.spec.ts +++ b/examples/blog/e2e/editor.spec.ts @@ -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') diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 54190307..786a330f 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -47,6 +47,7 @@ import { approve, availableDocumentActions, documentStateLabel, + documentWriteState, readChangeSet, assertTrustedOrigin, runOp, @@ -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, ctx: CmsOpContext) => { const access = editing(ctx) @@ -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( diff --git a/packages/api/tests/ops.test.ts b/packages/api/tests/ops.test.ts index 33e044af..f339b141 100644 --- a/packages/api/tests/ops.test.ts +++ b/packages/api/tests/ops.test.ts @@ -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') diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3c1a601a..b956d92e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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, diff --git a/packages/core/src/lib/doc-editor.ts b/packages/core/src/lib/doc-editor.ts index ddcb4cb9..41ef8d77 100644 --- a/packages/core/src/lib/doc-editor.ts +++ b/packages/core/src/lib/doc-editor.ts @@ -1,18 +1,25 @@ /** * Framework-agnostic document-editor state machine for `@tanstack/cms-core`. * - * Tracks dirty state, save (with optimistic-concurrency), staged/draft status, - * conflict handling, and reload/discard-draft flows. All server calls and the + * Tracks the baseline (the stored document a save is a patch against), dirty + * state, save (with optimistic concurrency), staged/draft status, conflict + * handling, strategy actions, and reload flows. All server calls and the * post-mutation "settle" step (e.g. `router.invalidate()`) are injected via * `DocEditorTransport` and `onSettled`, keeping this module free of React, * router, and transport dependencies. * + * Field state and validation belong to the form that renders the document + * (`DocForm` in `@tanstack/cms-ui-react`): it reads `doc` and `baseline` from + * here and writes edits back with `change`. + * * Usage mirrors `createCmsAuthStore`: create once, read state reactively via * `@tanstack/react-store`'s `useStore(ed.store, selector)`, or subscribe via * the Svelte-compatible `ed.subscribe(run)`. */ import { Store } from '@tanstack/store' +import type { ActionDescriptor } from '../document-state' +import type { WriteState } from '../ops' import type { Doc, JsonValue } from '../schema' // ─── Public types ───────────────────────────────────────────────────────────── @@ -20,16 +27,51 @@ import type { Doc, JsonValue } from '../schema' export type DocEditorStatus = 'idle' | 'saved' | 'staged' | 'draft' export interface DocEditorSaveArgs { + /** The whole document being saved. */ doc: Doc + /** + * What `save` sends: the top-level fields that differ from the baseline, + * or the whole document while nothing is stored yet. + */ + patch: Doc expectedRevision?: number expectedPendingVersion?: number publish?: boolean } +/** + * What a save returns. With `state`, as `save` returns it, `doc` becomes the + * baseline and `state` sets the versions the next save sends; the legacy + * `staged` / `draft` flags are then ignored. + */ export interface DocEditorSaveResult { doc: Doc staged?: boolean draft?: boolean + state?: WriteState + availableActions?: ReadonlyArray +} + +/** The document with where it stands, as the editor loads it. */ +export interface DocEditorSnapshot { + doc: Doc + state?: WriteState + availableActions?: ReadonlyArray +} + +export interface DocEditorActArgs { + action: string + publishAt?: string | null + reason?: string + /** The open change set's version the editor loaded. */ + expectedVersion?: number +} + +/** What `act` returns: `doc` is `null` once the document is gone. */ +export interface DocEditorActResult { + doc: Doc | null + state: WriteState + availableActions: ReadonlyArray } /** @@ -38,8 +80,12 @@ export interface DocEditorSaveResult { */ export interface DocEditorTransport { save: (args: DocEditorSaveArgs) => Promise + /** Fetch the latest stored doc with its state. Preferred over `reload`. */ + load?: () => Promise /** Fetch the latest stored doc (already normalized by the caller if needed). */ - reload: () => Promise + reload?: () => Promise + /** Run one of the document's `availableActions` (`act`). */ + act?: (args: DocEditorActArgs) => Promise discardDraft?: () => Promise } @@ -47,6 +93,8 @@ export interface DocEditorError { cause: unknown /** Which action failed, so the UI can show the right recovery affordance. */ publish?: boolean + /** Set when `act` failed: the action it ran. An overwrite can't retry it. */ + action?: string /** * Optional i18n key for the fallback error message. When set, the UI should * use this key instead of the default `editor.saveFailed` to match the @@ -58,26 +106,39 @@ export interface DocEditorError { export interface DocEditorState { doc: Doc + /** The stored document `doc` is edited from; saves send the difference. */ + baseline: Doc status: DocEditorStatus busy: boolean error: DocEditorError | null baseRevision: number | undefined pendingVersion: number | undefined + /** Where the document stands, from the last load, save or action. */ + writeState: WriteState | null + /** What the editor's user can do next, from the document's strategy. */ + availableActions: ReadonlyArray /** JSON snapshot of the last clean (loaded/saved) doc. */ cleanJson: string } export interface CreateDocEditorOptions { initialDoc: Doc + /** The stored document `initialDoc` edits. Default: `initialDoc`. */ + baseline?: Doc + /** Default: `state.revision`. */ baseRevision?: number + /** Default: `state.changeSet.version`, or 0 with `state` and no change set. */ pendingVersion?: number + /** Where the document stands when the editor opens (`documentWriteState`). */ + state?: WriteState + availableActions?: ReadonlyArray transport: DocEditorTransport - /** Normalize a freshly-reloaded doc (e.g. merge emptyDoc defaults). */ + /** Normalize a document from the server (e.g. merge emptyDoc defaults). */ normalize?: (doc: Doc) => Doc /** * Called after a successful mutation (e.g. `router.invalidate()`). For - * `save` it runs AFTER the write; for `reloadLatest`/`discardDraft` it runs - * BEFORE the refetch (matching the current editor's ordering). + * `save` and `act` it runs AFTER the write; for `reloadLatest`/`discardDraft` + * it runs BEFORE the refetch (matching the current editor's ordering). */ onSettled?: () => Promise | void } @@ -93,9 +154,11 @@ export interface DocEditorStore { isDirty: () => boolean /** Merge a single field value into the doc and reset status to 'idle'. */ setField: (name: string, value: JsonValue) => void + /** Replace the doc with an edited one (e.g. a form's values) and reset status to 'idle'. */ + change: (next: Doc) => void /** Replace or functionally update the entire doc. Does NOT reset status. */ setDoc: (next: Doc | ((d: Doc) => Doc)) => void - /** Update the clean JSON snapshot (default: current state.doc). */ + /** Update the clean JSON snapshot and the baseline (default: current state.doc). */ markClean: (doc?: Doc) => void /** Sync the latest pendingVersion from the loader (call from useEffect). */ setPendingVersion: (v: number | undefined) => void @@ -103,31 +166,94 @@ export interface DocEditorStore { setBaseRevision: (v: number | undefined) => void /** Clear the current error. */ clearError: () => void - /** Save the current doc. `overwrite` drops both OCC checks after a conflict. */ - save: (opts?: { publish?: boolean; overwrite?: boolean }) => Promise + /** + * Save the current doc. `overwrite` drops both OCC checks after a conflict. + * `patch` is what to send; default: `docPatch(baseline, doc)`. Nothing + * stored yet (by `state`) sends the whole doc. + */ + save: (opts?: { + publish?: boolean + overwrite?: boolean + patch?: Doc + }) => Promise + /** + * Run one of `availableActions` through `transport.act`. The result + * replaces the doc and the baseline, as `discardDraft` does. Resolves + * `null` when it failed (see `error`). + */ + act: ( + action: string, + input?: { publishAt?: string | null; reason?: string }, + ) => Promise /** Invalidate the router then refetch the doc; replaces the editor state with fresh data. */ reloadLatest: () => Promise /** Discard the pending draft, invalidate, then reload. */ discardDraft: () => Promise } +// ─── Helpers ────────────────────────────────────────────────────────────────── + +const json = (v: JsonValue | undefined) => JSON.stringify(v ?? null) + +/** + * The top-level fields of `doc` whose values differ from `baseline`, compared + * as JSON. A field missing from `doc` is `null` in the patch, which `save` + * clears. + */ +export function docPatch(baseline: Doc, doc: Doc): Doc { + const patch: Doc = {} + for (const key of new Set([...Object.keys(baseline), ...Object.keys(doc)])) { + if (json(doc[key]) !== json(baseline[key])) patch[key] = doc[key] ?? null + } + return patch +} + +/** Whether `state` says anything is stored: a live row or an open change set. */ +function isStored(state: WriteState | null): boolean { + return !state || state.revision > 0 || state.changeSet !== null +} + +/** + * What a save did, from the state before and after it: nothing open is + * live; an open draft is a draft; a change set the save left untouched is + * someone else's, so the save went live; otherwise it waits for review. + */ +function savedStatus( + before: WriteState | null, + after: WriteState, +): Exclude { + const cs = after.changeSet + if (!cs) return 'saved' + if (cs.source === 'draft') return 'draft' + const prev = before?.changeSet + if (prev && prev.id === cs.id && prev.version === cs.version) return 'saved' + return 'staged' +} + // ─── Implementation ──────────────────────────────────────────────────────────── export function createDocEditorStore( options: CreateDocEditorOptions, ): DocEditorStore { - const { transport, normalize, onSettled } = options + const { transport, normalize: normalizeOption, onSettled } = options + const normalize = (doc: Doc) => (normalizeOption ? normalizeOption(doc) : doc) - const initialCleanJson = JSON.stringify(options.initialDoc) + const baseline = options.baseline ?? options.initialDoc + const state = options.state ?? null const store = new Store({ doc: options.initialDoc, + baseline, status: 'idle', busy: false, error: null, - baseRevision: options.baseRevision, - pendingVersion: options.pendingVersion, - cleanJson: initialCleanJson, + baseRevision: options.baseRevision ?? state?.revision, + pendingVersion: + options.pendingVersion ?? + (state ? (state.changeSet?.version ?? 0) : undefined), + writeState: state, + availableActions: options.availableActions ?? [], + cleanJson: JSON.stringify(options.initialDoc), }) // ─── Helpers ────────────────────────────────────────────────────────────── @@ -138,7 +264,46 @@ export function createDocEditorStore( function markCleanSnapshot(doc?: Doc) { const target = doc ?? store.state.doc - patch({ cleanJson: JSON.stringify(target) }) + patch({ cleanJson: JSON.stringify(target), baseline: target }) + } + + /** The versions and actions a result's `state` carries. */ + function fromWriteState( + next: WriteState, + actions: ReadonlyArray | undefined, + ): Partial { + return { + writeState: next, + availableActions: actions ?? [], + baseRevision: next.revision, + pendingVersion: next.changeSet?.version ?? 0, + } + } + + /** Replace the doc and baseline with a stored snapshot. */ + function adopt(snapshot: DocEditorSnapshot) { + const next = normalize(snapshot.doc) + store.setState((s) => ({ + ...s, + doc: next, + baseline: next, + cleanJson: JSON.stringify(next), + status: 'idle', + ...(snapshot.state + ? fromWriteState(snapshot.state, snapshot.availableActions) + : { + baseRevision: + typeof snapshot.doc._revision === 'number' + ? snapshot.doc._revision + : undefined, + }), + })) + } + + async function fetchLatest(): Promise { + if (transport.load) return transport.load() + if (transport.reload) return { doc: await transport.reload() } + throw new Error('The editor transport has neither `load` nor `reload`.') } // ─── Public methods ─────────────────────────────────────────────────────── @@ -166,6 +331,10 @@ export function createDocEditorStore( })) } + function change(next: Doc): void { + store.setState((s) => ({ ...s, doc: next, status: 'idle' })) + } + function setDoc(next: Doc | ((d: Doc) => Doc)): void { store.setState((s) => ({ ...s, @@ -190,34 +359,50 @@ export function createDocEditorStore( } async function save( - opts: { publish?: boolean; overwrite?: boolean } = {}, + opts: { publish?: boolean; overwrite?: boolean; patch?: Doc } = {}, ): Promise { const { publish, overwrite } = opts patch({ busy: true, error: null }) try { const s = store.state + const submitted = s.doc const result = await transport.save({ - doc: s.doc, + doc: submitted, + patch: isStored(s.writeState) + ? (opts.patch ?? docPatch(s.baseline, submitted)) + : submitted, expectedRevision: overwrite ? undefined : s.baseRevision, expectedPendingVersion: overwrite ? undefined : s.pendingVersion, publish, }) - if (result.staged) { - patch({ status: 'staged' }) - } else if ('draft' in result && result.draft) { - patch({ status: 'draft' }) + const after = result.state + if (after) { + const next = normalize(result.doc) + store.setState((cur) => ({ + ...cur, + // Edits made while the save was in flight stay in the editor. + doc: cur.doc === submitted ? next : cur.doc, + baseline: next, + cleanJson: JSON.stringify(next), + status: savedStatus(s.writeState, after), + ...fromWriteState(after, result.availableActions), + })) } else { - const updates: Partial = { status: 'saved' } - if (typeof result.doc._revision === 'number') { - updates.baseRevision = result.doc._revision + if (result.staged) { + patch({ status: 'staged' }) + } else if ('draft' in result && result.draft) { + patch({ status: 'draft' }) + } else { + const updates: Partial = { status: 'saved' } + if (typeof result.doc._revision === 'number') { + updates.baseRevision = result.doc._revision + } + patch(updates) } - patch(updates) + markCleanSnapshot(submitted) } - - // markClean uses the doc that was submitted (current state.doc, unchanged) - markCleanSnapshot(store.state.doc) await onSettled?.() } catch (e) { patch({ error: { cause: e, publish } }) @@ -226,20 +411,38 @@ export function createDocEditorStore( } } + async function act( + action: string, + input: { publishAt?: string | null; reason?: string } = {}, + ): Promise { + if (!transport.act) throw new Error('The editor transport has no `act`.') + patch({ busy: true, error: null }) + try { + const result = await transport.act({ + action, + ...input, + expectedVersion: store.state.pendingVersion, + }) + if (result.doc) { + adopt({ ...result, doc: result.doc }) + } else { + patch(fromWriteState(result.state, result.availableActions)) + } + await onSettled?.() + return result + } catch (e) { + patch({ error: { cause: e, action } }) + return null + } finally { + patch({ busy: false }) + } + } + async function reloadLatest(): Promise { patch({ busy: true, error: null }) try { await onSettled?.() - const fresh = await transport.reload() - const next = normalize ? normalize(fresh) : fresh - store.setState((s) => ({ - ...s, - doc: next, - cleanJson: JSON.stringify(next), - baseRevision: - typeof fresh._revision === 'number' ? fresh._revision : undefined, - status: 'idle', - })) + adopt(await fetchLatest()) } catch (e) { patch({ error: { cause: e } }) } finally { @@ -252,16 +455,7 @@ export function createDocEditorStore( try { await transport.discardDraft?.() await onSettled?.() - const fresh = await transport.reload() - const next = normalize ? normalize(fresh) : fresh - store.setState((s) => ({ - ...s, - doc: next, - cleanJson: JSON.stringify(next), - baseRevision: - typeof fresh._revision === 'number' ? fresh._revision : undefined, - status: 'idle', - })) + adopt(await fetchLatest()) } catch (e) { patch({ error: { cause: e } }) } finally { @@ -275,12 +469,14 @@ export function createDocEditorStore( subscribe, isDirty, setField, + change, setDoc, markClean, setPendingVersion, setBaseRevision, clearError, save, + act, reloadLatest, discardDraft, } diff --git a/packages/core/tests/doc-editor.test.ts b/packages/core/tests/doc-editor.test.ts index 5c0c9059..7790da05 100644 --- a/packages/core/tests/doc-editor.test.ts +++ b/packages/core/tests/doc-editor.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { createDocEditorStore } from '../src/lib/doc-editor' +import { createDocEditorStore, docPatch } from '../src/lib/doc-editor' import type { DocEditorTransport } from '../src/lib/doc-editor' -import type { Doc } from '../src/index' +import type { Doc, WriteState } from '../src/index' // ─── Helpers ────────────────────────────────────────────────────────────────── @@ -158,6 +158,7 @@ describe('save() – success', () => { await ed.save({ publish: true }) expect(transport.save).toHaveBeenCalledWith({ doc: BASE_DOC, + patch: {}, expectedRevision: 3, expectedPendingVersion: 9, publish: true, @@ -177,6 +178,7 @@ describe('save() – success', () => { await ed.save({ overwrite: true, publish: false }) expect(transport.save).toHaveBeenCalledWith({ doc: BASE_DOC, + patch: {}, expectedRevision: undefined, expectedPendingVersion: undefined, publish: false, @@ -475,3 +477,247 @@ describe('subscribe()', () => { expect(statuses.length).toBeGreaterThanOrEqual(1) }) }) + +// ─── 5a: save / act results ────────────────────────────────────────────────── + +const LIVE: WriteState = { + label: 'Published', + published: true, + revision: 4, + changeSet: null, +} + +function writeState( + changeSet: WriteState['changeSet'], + extra: Partial = {}, +): WriteState { + return { ...LIVE, changeSet, ...extra } +} + +const cs = ( + source: 'agent' | 'review' | 'draft', + version = 1, + id = 'cs1', +): NonNullable => ({ + id, + version, + source, + publishAt: null, +}) + +describe('docPatch', () => { + it('holds the changed top-level fields, with removed ones as null', () => { + expect( + docPatch( + { title: 'a', tags: ['x'], gone: 1 }, + { title: 'b', tags: ['x'] }, + ), + ).toEqual({ title: 'b', gone: null }) + }) +}) + +describe('with a write state', () => { + it('takes the versions from the state', () => { + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: writeState(cs('draft', 6)), + availableActions: [{ type: 'edit', label: 'Save' }], + transport: makeTransport(), + }) + const s = ed.getState() + expect(s.baseRevision).toBe(4) + expect(s.pendingVersion).toBe(6) + expect(s.availableActions.map((a) => a.type)).toEqual(['edit']) + }) + + it('saves the patch against the baseline and adopts the result', async () => { + const transport = makeTransport() + transport.save.mockResolvedValueOnce({ + doc: { title: 'Changed', body: 'World', _revision: 4, slug: 'changed' }, + state: writeState(cs('draft', 1)), + availableActions: [{ type: 'discard', label: 'Discard draft' }], + }) + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: LIVE, + transport, + }) + ed.change({ ...BASE_DOC, title: 'Changed' }) + await ed.save({ publish: false }) + + expect(transport.save.mock.calls[0]![0]).toMatchObject({ + patch: { title: 'Changed' }, + expectedRevision: 4, + expectedPendingVersion: 0, + publish: false, + }) + const s = ed.getState() + expect(s.status).toBe('draft') + expect(s.baseline.slug).toBe('changed') + expect(s.doc).toBe(s.baseline) + expect(s.pendingVersion).toBe(1) + expect(s.writeState?.changeSet?.source).toBe('draft') + expect(s.availableActions.map((a) => a.type)).toEqual(['discard']) + expect(ed.isDirty()).toBe(false) + }) + + it('prefers the caller’s patch', async () => { + const transport = makeTransport() + transport.save.mockResolvedValueOnce({ doc: BASE_DOC, state: LIVE }) + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: LIVE, + transport, + }) + await ed.save({ patch: { body: 'From the form' } }) + expect(transport.save.mock.calls[0]![0].patch).toEqual({ + body: 'From the form', + }) + }) + + it('sends the whole document while nothing is stored', async () => { + const transport = makeTransport() + transport.save.mockResolvedValueOnce({ doc: BASE_DOC, state: LIVE }) + const ed = createDocEditorStore({ + initialDoc: { ...BASE_DOC, locale: 'es' }, + state: { label: 'New', published: false, revision: 0, changeSet: null }, + transport, + }) + await ed.save({ patch: {} }) + expect(transport.save.mock.calls[0]![0].patch).toEqual({ + ...BASE_DOC, + locale: 'es', + }) + }) + + it.each([ + ['nothing open', null, null, 'saved'], + ['an open draft', null, cs('draft'), 'draft'], + ['a new review change set', null, cs('review'), 'staged'], + [ + 'a review change set it moved', + cs('review', 1), + cs('review', 2), + 'staged', + ], + ['someone else’s change set, untouched', cs('agent'), cs('agent'), 'saved'], + ] as const)('reports %s as %s', async (_, before, after, status) => { + const transport = makeTransport() + transport.save.mockResolvedValueOnce({ + doc: BASE_DOC, + state: writeState(after), + }) + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: writeState(before), + transport, + }) + await ed.save() + expect(ed.getState().status).toBe(status) + }) + + it('keeps edits made while the save was in flight', async () => { + let resolve!: (r: unknown) => void + const transport = makeTransport() + transport.save.mockReturnValueOnce(new Promise((r) => (resolve = r))) + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: LIVE, + transport, + }) + ed.change({ ...BASE_DOC, title: 'Saved' }) + const saving = ed.save() + ed.change({ ...BASE_DOC, title: 'Typed after' }) + resolve({ doc: { ...BASE_DOC, title: 'Saved' }, state: LIVE }) + await saving + const s = ed.getState() + expect(s.doc.title).toBe('Typed after') + expect(s.baseline.title).toBe('Saved') + expect(ed.isDirty()).toBe(true) + }) +}) + +describe('act()', () => { + it('runs the action with the open change set’s version and adopts the result', async () => { + const act = vi.fn().mockResolvedValueOnce({ + doc: { title: 'Approved' }, + state: writeState(null, { revision: 5 }), + availableActions: [{ type: 'edit', label: 'Save' }], + }) + const onSettled = vi.fn() + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: writeState(cs('review', 3)), + transport: { ...makeTransport(), act }, + onSettled, + }) + const result = await ed.act('approve') + expect(act).toHaveBeenCalledWith({ action: 'approve', expectedVersion: 3 }) + expect(result?.doc).toEqual({ title: 'Approved' }) + const s = ed.getState() + expect(s.doc).toEqual({ title: 'Approved' }) + expect(s.baseRevision).toBe(5) + expect(s.pendingVersion).toBe(0) + expect(s.status).toBe('idle') + expect(onSettled).toHaveBeenCalled() + }) + + it('keeps the doc when the document is gone', async () => { + const act = vi.fn().mockResolvedValueOnce({ + doc: null, + state: { label: 'New', published: false, revision: 0, changeSet: null }, + availableActions: [], + }) + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: writeState(cs('review')), + transport: { ...makeTransport(), act }, + }) + const result = await ed.act('reject', { reason: 'No' }) + expect(act).toHaveBeenCalledWith({ + action: 'reject', + reason: 'No', + expectedVersion: 1, + }) + expect(result?.doc).toBeNull() + expect(ed.getState().doc).toEqual(BASE_DOC) + expect(ed.getState().writeState?.label).toBe('New') + }) + + it('records the failed action', async () => { + const err = new Error('CONFLICT') + const act = vi.fn().mockRejectedValueOnce(err) + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + transport: { ...makeTransport(), act }, + }) + expect(await ed.act('discard')).toBeNull() + expect(ed.getState().error).toEqual({ cause: err, action: 'discard' }) + expect(ed.getState().busy).toBe(false) + }) +}) + +describe('load', () => { + it('reloadLatest prefers load and adopts its state', async () => { + const load = vi.fn().mockResolvedValueOnce({ + doc: { title: 'Latest' }, + state: writeState(cs('draft', 2), { revision: 7 }), + availableActions: [{ type: 'discard', label: 'Discard draft' }], + }) + const transport = makeTransport() + const ed = createDocEditorStore({ + initialDoc: BASE_DOC, + state: LIVE, + transport: { ...transport, load }, + normalize: (d) => ({ body: '', ...d }), + }) + await ed.reloadLatest() + expect(transport.reload).not.toHaveBeenCalled() + const s = ed.getState() + expect(s.doc).toEqual({ body: '', title: 'Latest' }) + expect(s.baseline).toBe(s.doc) + expect(s.baseRevision).toBe(7) + expect(s.pendingVersion).toBe(2) + expect(s.availableActions.map((a) => a.type)).toEqual(['discard']) + }) +}) diff --git a/packages/ui-react/src/components/editor/doc-form.tsx b/packages/ui-react/src/components/editor/doc-form.tsx index d8d2e4d8..5780d315 100644 --- a/packages/ui-react/src/components/editor/doc-form.tsx +++ b/packages/ui-react/src/components/editor/doc-form.tsx @@ -8,6 +8,7 @@ import { useForm, useStore } from '@tanstack/react-form' import { canReadField, canWriteField, + docPatch, emptyDoc, isFieldVisible, } from '@tanstack/cms-core' @@ -121,19 +122,7 @@ export interface DocFormApi { setValue: (name: string, value: JsonValue) => void } -const json = (v: JsonValue | undefined) => JSON.stringify(v ?? null) - -/** - * The top-level fields of `doc` whose values differ from `baseline`, compared - * as JSON. A field missing from `doc` is `null` in the patch. - */ -export function docPatch(baseline: Doc, doc: Doc): Doc { - const patch: Doc = {} - for (const key of new Set([...Object.keys(baseline), ...Object.keys(doc)])) { - if (json(doc[key]) !== json(baseline[key])) patch[key] = doc[key] ?? null - } - return patch -} +export { docPatch } const isEmpty = (doc: Doc) => Object.keys(doc).length === 0 diff --git a/packages/ui-react/src/routes/edit.$collection.$id.tsx b/packages/ui-react/src/routes/edit.$collection.$id.tsx index a600835d..3dd18783 100644 --- a/packages/ui-react/src/routes/edit.$collection.$id.tsx +++ b/packages/ui-react/src/routes/edit.$collection.$id.tsx @@ -8,8 +8,6 @@ import { import { adminPath, canAccessCollection, - canReadField, - canWriteField, collectRelations, collections, contentLocales, @@ -17,19 +15,18 @@ import { documentPath, emptyDoc, isCollectionReadOnly, - isFieldVisible, } from '@tanstack/cms-core' import { useStore } from '@tanstack/react-store' import * as api from '@tanstack/cms-api/start' import { + act, createPreviewToken, - discardDraft, getDocEditorMeta, getDocument, listDocumentSummaries, proposeEdit, restoreDocRevision, - saveDoc, + save, } from '@tanstack/cms-api/start' import { routeSession, useCan, useCmsAuth } from '../lib/auth' import { @@ -37,14 +34,21 @@ import { AssigneePanel, CommentsPanel, Diff, - FieldInput, + DocForm, LocaleControls, + useDocForm, } from '../primitives' import type { FieldAccessContext } from '../primitives' import { adminT } from '../lib/i18n' import { fromDatetimeLocalValue, toDatetimeLocalValue } from '../lib/datetime' import { editorError } from '../lib/editor-errors' -import type { Collection, Doc, JsonValue } from '@tanstack/cms-core' +import type { + ActionDescriptor, + Collection, + Doc, + DocEditorSnapshot, + JsonValue, +} from '@tanstack/cms-core' import '../app-renderers' /** Prefill for a new document, used by "Add translation". */ @@ -53,6 +57,25 @@ interface EditSearch { translationOf?: string } +/** What the editor's save buttons pass to `DocForm`'s `submit`. */ +interface SaveMeta { + publish?: boolean + /** Drop the optimistic-concurrency check after a CONFLICT. */ + overwrite?: boolean +} + +/** + * Actions the editor runs with its save buttons (the ones that carry a + * document) or not at all (`schedule` needs a time; the review queue has it). + */ +const SAVE_ACTIONS = new Set(['edit', 'draft', 'submit', 'import', 'schedule']) + +const TONE_CLASSES: Record, string> = { + primary: 'bg-green-600 text-white hover:bg-green-700', + danger: 'text-red-600 ring-1 ring-red-200 hover:bg-red-50', + default: 'text-neutral-700 ring-1 ring-neutral-300 hover:bg-neutral-50', +} + export const Route = createFileRoute('/edit/$collection/$id')({ validateSearch: (search: Record): EditSearch => ({ locale: @@ -76,10 +99,8 @@ export const Route = createFileRoute('/edit/$collection/$id')({ revisions: [], translations: [], references: [], - isPending: false, - pendingVersion: 0, - hasDraft: false, - livePublished: false, + state: null, + availableActions: [], hasCollection: false, } } @@ -122,14 +143,12 @@ export const Route = createFileRoute('/edit/$collection/$id')({ ) return { doc: loaded.doc ?? undefined, - isPending: loaded.isPending, - pendingVersion: loaded.pendingVersion ?? 0, - hasDraft: loaded.pendingSource === 'draft', - livePublished: loaded.livePublished, store, revisions: meta.revisions, translations: meta.translations, references: meta.references, + state: meta.state, + availableActions: meta.availableActions, hasCollection: true, } }, @@ -152,6 +171,27 @@ function safeSitePath(collection: Collection, doc: Doc, id: string) { } function Editor() { + const { collection: collectionName } = Route.useParams() + const { hasCollection } = Route.useLoaderData() + const collection = collections()[collectionName] + if (!hasCollection || !collection) { + return ( + +

+ {adminT('editor.unknownCollection', { name: collectionName })} +

+
+ ) + } + return +} + +/** + * The editor is composition: `DocForm` owns the fields' state and + * validation, and the core editor store owns the baseline, the versions a + * save sends, and where the document stands (`save` / `act` results). + */ +function DocumentEditor({ collection }: { collection: Collection }) { const auth = useCmsAuth() const { ai } = auth const hasTextAi = Boolean(ai?.text) @@ -162,19 +202,14 @@ function Editor() { revisions, translations, references, - hasDraft, - livePublished, - hasCollection, - pendingVersion, + state: loadedState, + availableActions: loadedActions, } = Route.useLoaderData() const canPublish = useCan('publish', collectionName, loaded) const canDelete = useCan('delete', collectionName, loaded) - /** Edits to a live document are drafts until explicitly published. */ - const draftMode = livePublished && canPublish const canWrite = useCan(loaded ? 'update' : 'create', collectionName, loaded) const canCreate = useCan('create', collectionName) const router = useRouter() - const collection = collections()[collectionName] const prefill = Route.useSearch() @@ -182,70 +217,68 @@ function Editor() { // Created once per mount (via useState initializer) so moving between // documents (which remounts via the EditorRoute key) always resets state. const [ed] = useState(() => { - // Defensive initialDoc: if !collection the early-return below fires, but - // hooks must all run before that guard. + const normalize = (d: Doc): Doc => ({ ...emptyDoc(collection), ...d }) const initialDoc: Doc = (() => { - if (!collection) return {} - if (loaded) return { ...emptyDoc(collection), ...loaded } + if (loaded) return normalize(loaded) const seed: Doc = {} if (prefill.locale) seed.locale = prefill.locale if (prefill.translationOf) seed.translationOf = prefill.translationOf - return { ...emptyDoc(collection), ...seed } + return normalize(seed) })() + const ref = { collection: collectionName, id } + + const load = async (): Promise => { + const [fresh, meta] = await Promise.all([ + getDocument({ data: ref }), + getDocEditorMeta({ data: ref }), + ]) + return { + doc: (fresh.doc ?? {}) as Doc, + state: meta.state, + availableActions: meta.availableActions, + } + } return createDocEditorStore({ initialDoc, - baseRevision: - typeof loaded?._revision === 'number' ? loaded._revision : undefined, - pendingVersion, - normalize: collection - ? (d) => ({ ...emptyDoc(collection), ...d }) - : undefined, + ...(loadedState + ? { state: loadedState, availableActions: loadedActions } + : {}), + normalize, transport: { + // `save` merges the patch onto the writer's working copy. save: (args) => - saveDoc({ + save({ data: { - collection: collectionName, - id, - doc: args.doc, + ...ref, + doc: args.patch, expectedRevision: args.expectedRevision, expectedPendingVersion: args.expectedPendingVersion, publish: args.publish, }, }), - reload: async () => { - const fresh = await getDocument({ - data: { collection: collectionName, id }, - }) - return fresh.doc as Doc - }, - discardDraft: () => - discardDraft({ data: { collection: collectionName, id } }).then( - () => undefined, - ), + act: (args) => act({ data: { ...ref, ...args } }), + load, }, onSettled: () => router.invalidate(), }) }) - // Keep pendingVersion in sync when the loader refetches (router.invalidate - // causes a re-render with fresh loader data, but the store was created once). - useEffect(() => { - ed.setPendingVersion(pendingVersion) - }, [ed, pendingVersion]) - // ── Reactive state reads ─────────────────────────────────────────────────── const doc = useStore(ed.store, (s) => s.doc) + const baseline = useStore(ed.store, (s) => s.baseline) const busy = useStore(ed.store, (s) => s.busy) const status = useStore(ed.store, (s) => s.status) + const writeState = useStore(ed.store, (s) => s.writeState) + const actions = useStore(ed.store, (s) => s.availableActions) // Map 'idle' → false to match the original `saved` variable semantics. const saved: false | 'saved' | 'staged' | 'draft' = status === 'idle' ? false : status const errState = useStore(ed.store, (s) => s.error) - // Classify the error the same way the original code did, preserving per-action - // fallback messages. The store stores a `fallbackKey` for actions that need a - // message other than 'editor.saveFailed' (agent.failed, editor.discardFailed, + // Classify the error, preserving per-action fallback messages. The store + // keeps a `fallbackKey` for actions that need a message other than + // 'editor.saveFailed' (agent.failed, editor.discardFailed, // editor.previewLinkFailed, editor.deleteFailed, editor.restoreFailed). const error = errState ? { @@ -256,15 +289,21 @@ function Editor() { : adminT('editor.saveFailed'), ), publish: errState.publish, + fromAction: errState.action !== undefined, } : null - // `useStore` must run unconditionally (Rules of Hooks); gate on canWrite after. - const docDirty = useStore( - ed.store, - (s) => JSON.stringify(s.doc) !== s.cleanJson, - ) - const dirty = canWrite && docDirty + const form = useDocForm({ + collection: collectionName, + value: doc, + baseline, + onChange: (next) => ed.change(next), + onSubmit: (patch, { meta }) => + ed.save({ publish: meta?.publish, overwrite: meta?.overwrite, patch }), + }) + + const dirty = canWrite && form.dirty + const working = busy || form.submitting const dirtyRef = useRef(dirty) dirtyRef.current = dirty @@ -295,23 +334,24 @@ function Editor() { const [confirmingDelete, setConfirmingDelete] = useState(false) const [previewShared, setPreviewShared] = useState(false) - if (!hasCollection || !collection) { - return ( - -

- {adminT('editor.unknownCollection', { name: collectionName })} -

-
- ) - } + const offers = (type: string) => actions.some((a) => a.type === type) + /** Edits to a live document are drafts until explicitly published. */ + const draftMode = offers('draft') && canPublish + const canSave = canWrite && (offers('edit') || offers('submit')) + const decisions = actions.filter((a) => !SAVE_ACTIONS.has(a.type)) + const openDraft = writeState?.changeSet?.source === 'draft' + const revision = + writeState && writeState.revision > 0 + ? writeState.revision + : typeof doc._revision === 'number' + ? doc._revision + : undefined const sitePath = loaded || saved ? safeSitePath(collection, doc, id) : null // Field rules see the stored document (the draft on create), as on the server. const fieldAccess: FieldAccessContext = { session: auth, doc: loaded ?? doc } - const set = (name: string, value: JsonValue) => { - ed.setField(name, value) - } + const set = (name: string, value: JsonValue) => form.setValue(name, value) async function onPropose() { ed.store.setState((s) => ({ ...s, busy: true, error: null })) @@ -331,9 +371,9 @@ function Editor() { } } - /** `overwrite` drops the optimistic-concurrency check after a CONFLICT. */ - async function onSave(publish?: boolean, overwrite?: boolean) { - await ed.save({ publish, overwrite }) + /** Every save goes through the form, so its validators gate it. */ + async function onSave(meta: SaveMeta = {}) { + await form.submit(meta) } async function onReloadLatest() { @@ -342,23 +382,26 @@ function Editor() { // Ctrl/⌘+S never publishes a live document: it saves a draft. saveShortcut.current = () => { - if (canWrite && !busy) - void ed.save({ publish: draftMode ? false : undefined }) + if (canSave && !working) + void onSave({ publish: draftMode ? false : undefined }) } - async function onDiscardDraft() { - // ed.discardDraft() catches errors internally (never re-throws) and sets - // error.cause on the store. We patch in the discard-specific fallback key - // afterward so the UI shows 'editor.discardFailed' instead of the default. - await ed.discardDraft() - const st = ed.getState() - if (st.error && !st.error.fallbackKey) { - ed.store.setState((s) => ({ - ...s, - error: s.error - ? { ...s.error, fallbackKey: 'editor.discardFailed' } - : null, - })) + async function onAct(action: string) { + const result = await ed.act(action) + if (!result) { + if (action === 'discard') { + ed.store.setState((s) => ({ + ...s, + error: s.error + ? { ...s.error, fallbackKey: 'editor.discardFailed' } + : null, + })) + } + return + } + if (result.doc === null) { + leaving.current = true + await router.navigate({ to: adminPath('/content') }) } } @@ -421,25 +464,20 @@ function Editor() { async function onRestoreRevision(revisionId: string) { ed.store.setState((s) => ({ ...s, busy: true, error: null })) try { - const res = await restoreDocRevision({ + await restoreDocRevision({ data: { collection: collectionName, id, revisionId }, }) - const restored = res.doc as Doc - ed.setDoc(restored) - ed.markClean(restored) - ed.setBaseRevision( - typeof restored._revision === 'number' ? restored._revision : undefined, - ) - ed.store.setState((s) => ({ ...s, status: 'saved' })) - await router.invalidate() } catch (e) { ed.store.setState((s) => ({ ...s, + busy: false, error: { cause: e, fallbackKey: 'editor.restoreFailed' }, })) - } finally { - ed.store.setState((s) => ({ ...s, busy: false })) + return } + await ed.reloadLatest() + if (!ed.getState().error) + ed.store.setState((s) => ({ ...s, status: 'saved' })) } const publishAt = typeof doc.publishAt === 'string' ? doc.publishAt : '' @@ -454,6 +492,14 @@ function Editor() { const hasExplicitPublishedField = collection.fields.some( (f) => f.name === 'published' && f.type === 'boolean', ) + const changedFields = proposed + ? collection.fields + .map((f) => f.name) + .filter( + (name) => + JSON.stringify(proposed[name]) !== JSON.stringify(doc[name]), + ) + : undefined return ( @@ -468,14 +514,28 @@ function Editor() { {collection.label} {' '} / {id} - {typeof doc._revision === 'number' && ( + {revision !== undefined && ( - v{doc._revision} + v{revision} )} - {draftMode && (hasDraft || saved === 'draft') && ( - - {adminT('editor.draftBadge')} + {writeState && ( + + {writeState.label} )} {isCollectionReadOnly(collection) && ( @@ -499,7 +559,7 @@ function Editor() { ))} - {canWrite && draftMode && (hasDraft || saved === 'draft') && ( + {decisions.map((action) => ( - )} - {canWrite && draftMode && ( + ))} + {canSave && draftMode && ( )} - {canWrite && ( + {canSave && ( @@ -650,20 +716,27 @@ function Editor() { <> - + {!error.fromAction && ( + + )} )}