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/doc-form-primitive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@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.
73 changes: 73 additions & 0 deletions docs/api/cms-ui-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ Every UI primitive the built-in admin routes use, exported so bespoke domain app
| Export | Use |
| --- | --- |
| `AdminShell`, `CommandPalette` | The admin frame and the ⌘K palette. |
| `DocForm`, `useDocForm`, `docPatch` | The schema-driven document form on TanStack Form (see [`DocForm`](#docform)). |
| `FieldInput`, `RelationPicker`, `ImageField`, `MediaInsert`, `MarkdownEditor`, `LocaleControls` | Field editors. `FieldInputComponentProps` is the `FieldInput` props type. |
| `CollectionSection`, `columnFields`, `defaultSort` | The content list for one collection and its column and sort defaults. |
| `Diff`, `CommentsPanel`, `AssigneePanel` | Review: a proposed edit's diff, the comment thread, the assignee. |
Expand Down Expand Up @@ -384,6 +385,78 @@ type RelationSearch = (

Custom inputs and list cells are props too: `FieldInput` (and its nested fields), `CollectionSection`, and `columnFields(collection, session, renderers)` take `renderers` from `defineRenderers({ inputs, fieldTypes })`, which `/primitives` also exports. Without the prop they use the module bound through `createRoutes(definition, { renderers })`.

### `DocForm`

A `<form>` for one document of a collection, generated from its schema. It keeps the draft in a [TanStack Form](https://tanstack.com/form) instance, renders a control per top-level field in schema order, and calls `onSubmit` with a patch of the fields that changed. It doesn't save anything itself: the submit handler decides where the patch goes.

```tsx validate=type
import { DocForm } from '@tanstack/cms-ui-react/primitives'
import type { Doc } from '@tanstack/cms-core'

export function PostForm({ post, save }: { post: Doc; save: (patch: Doc) => Promise<void> }) {
return (
<DocForm collection="post" defaultValue={post} onSubmit={(patch) => save(patch)}>
{({ dirty, submitting }) => (
<button type="submit" disabled={!dirty || submitting}>
Save
</button>
)}
</DocForm>
)
}
```

| Prop | Type | Description |
| --- | --- | --- |
| `collection` | `string` | The collection's name. An unknown name throws, as for the other primitives. |
| `onSubmit` | `(patch: Doc, context: { doc, baseline, meta }) => unknown` | Receives the top-level fields whose values differ from the baseline, compared as JSON, plus the whole document, the baseline, and the `meta` given to `submit(meta)`. If it throws or rejects, the submit fails: the error is kept and the baseline doesn't move. Otherwise the submitted document becomes the baseline. |
| `value` / `onChange` | `Doc` / `(doc: Doc) => void` | Controlled use. `onChange` gets the whole document after every change. When `value` changes to something other than the form's values, the form adopts it without calling `onChange`. |
| `defaultValue` | `Doc` | The initial document when the form owns its state. |
| `baseline` | `Doc` | The stored document that the patch and `dirty` compare against. Defaults to the initial document. Set it when the parent tracks what is saved; the form then never moves it itself. |
| `fieldRenderers` | `{ [fieldType]: ComponentType<FieldInputComponentProps> }` | Per-form renderers for top-level fields, keyed by field type, built-in types (`text`, `markdown`) included. Each replaces `FieldInput` for that type and gets `FieldInput`'s props, so it can wrap `FieldInput`. Fields nested in `group`, `array`, and `blocks` still render with `FieldInput`. |
| `renderers` | `CmsRenderers` | The app-wide renderers module from `defineRenderers({ inputs, fieldTypes })`, passed to every `FieldInput`, nested fields included. Without it, `FieldInput` uses the module bound through `createRoutes(definition, { renderers })`. `useDocForm` takes it too. |
| `access` | `{ session, doc }` | Field-level access: fields the session can't read are left out, and fields it can't write are read-only. `doc` is the stored document, or `null` for the draft. Without `access`, every field is editable; the server still enforces field rules. |
| `disabled` | `boolean` | Renders every field read-only. |
| `errors` | `Record<string, string>` | Messages by field name, shown under each control (for example the `fieldErrors` of a failed save). |
| `changedFields` | `Array<string>` | Field names to highlight, as `FieldInput`'s `changed` does (for example the fields an agent's proposal changes). |
| `store`, `relationSearch` | | Passed to `FieldInput`: relation titles by collection and id, and the relation search backend. |
| `id`, `className`, `aria-label` | | Set on the `<form>`. `aria-label` defaults to the collection's label. |
| `children` | `ReactNode \| (state) => ReactNode` | Rendered after the fields. The function form gets `{ values, patch, dirty, submitting, error, submit, reset, setValue }`. |

`renderers` and `fieldRenderers` work at different levels. `renderers` is the app's module, keyed by input name (a field's `input`) and by custom field type. `fieldRenderers` is an override for one form, keyed by field type. For each top-level field, `DocForm` uses `fieldRenderers[field.type]` if there is one. Otherwise it renders `FieldInput`, which resolves as usual: the field's named input, then its custom type's input (each from `renderers`, then the bound module), then the built-in control. A `renderers.fieldTypes` input replaces only the control under `FieldInput`'s label and error message, and it can't target built-in types. A `fieldRenderers` entry replaces the whole field, for any type.

Fields hidden by `showWhen` aren't rendered, and their stored values stay in the document. There is no client-side validation yet: put a save's field errors in `errors`.

To keep the form's state in the parent (for example to put the buttons in a header), call `useDocForm` with the same options and pass the result to `DocForm` as `form`:

```tsx validate=type
import { DocForm, useDocForm } from '@tanstack/cms-ui-react/primitives'
import type { Doc } from '@tanstack/cms-core'

export function PostEditor({ post, save }: { post: Doc; save: (patch: Doc, publish: boolean) => Promise<void> }) {
const editor = useDocForm<{ publish: boolean }>({
collection: 'post',
defaultValue: post,
onSubmit: (patch, { meta }) => save(patch, meta?.publish ?? false),
})
return (
<>
<header>
<button type="button" disabled={!editor.dirty} onClick={() => editor.reset()}>
Revert
</button>
<button type="button" onClick={() => void editor.submit({ publish: true })}>
Publish
</button>
</header>
<DocForm form={editor} />
</>
)
}
```

`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.

---

## `@tanstack/cms-ui-react/virtual-routes`
Expand Down
30 changes: 30 additions & 0 deletions docs/schema/collections-and-fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,36 @@ export const invoice = defineCollection({
- Filters and sorts on a field the session can't read, including nested paths like `pricing.cost`, fail with `FORBIDDEN`.
- API keys can additionally be scoped to a list of collections.

## Editing documents in your own UI

The admin's edit screen is generated from these definitions, and a bespoke app can generate the same form. `DocForm` from `@tanstack/cms-ui-react/primitives` takes a collection name, renders a control for each field in schema order, and applies the rules above: fields hidden by `showWhen` aren't shown, and with `access` the session's field rules hide or lock fields. The draft lives in a TanStack Form instance. On submit, your handler gets a patch of the fields that changed, and you decide where it goes:

```tsx validate=type
import { DocForm } from '@tanstack/cms-ui-react/primitives'
import { useCmsAuth } from '@tanstack/cms-ui-react'
import type { Doc } from '@tanstack/cms-core'

export function InvoiceForm({ invoice, save }: { invoice: Doc; save: (patch: Doc) => Promise<void> }) {
const session = useCmsAuth()
return (
<DocForm
collection="invoice"
defaultValue={invoice}
access={{ session, doc: invoice }}
onSubmit={(patch) => save(patch)}
>
{({ dirty, submitting }) => (
<button type="submit" disabled={!dirty || submitting}>
Save
</button>
)}
</DocForm>
)
}
```

To change how a field type looks, pass `fieldRenderers`, keyed by field type, for example `fieldRenderers={{ number: Stepper }}`. Each renderer receives the props of `FieldInput`, which renders every other type. See the [`DocForm` reference](../api/cms-ui-react#docform) for controlled use, `useDocForm`, and submit metadata.

## Hooks

A hook is the engine asking, just before a commit, "anything you want to make us aware of before we go in?" Hooks may rewrite the document or veto the write by throwing. Anything that reacts to the result after the commit is an [event handler](../architecture/events-and-hooks) instead. Every hook may be async; the engine awaits it. Keep each one under about 50ms: outside production the engine warns once per hook that runs longer.
Expand Down
Loading
Loading