Skip to content

Commit dd9489a

Browse files
jherrcursoragent
andauthored
feat(ui-react): DocForm, a schema-driven TanStack Form editor primitive in /primitives (5b(i)) (#33) (#33)
Chain step 9 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: Cursor Agent <cursoragent@cursor.com>
1 parent 87b29ae commit dd9489a

10 files changed

Lines changed: 1016 additions & 21 deletions

File tree

‎.changeset/doc-form-primitive.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/cms-ui-react': minor
3+
---
4+
5+
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.

‎docs/api/cms-ui-react.md‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,7 @@ Every UI primitive the built-in admin routes use, exported so bespoke domain app
357357
| Export | Use |
358358
| --- | --- |
359359
| `AdminShell`, `CommandPalette` | The admin frame and the ⌘K palette. |
360+
| `DocForm`, `useDocForm`, `docPatch` | The schema-driven document form on TanStack Form (see [`DocForm`](#docform)). |
360361
| `FieldInput`, `RelationPicker`, `ImageField`, `MediaInsert`, `MarkdownEditor`, `LocaleControls` | Field editors. `FieldInputComponentProps` is the `FieldInput` props type. |
361362
| `CollectionSection`, `columnFields`, `defaultSort` | The content list for one collection and its column and sort defaults. |
362363
| `Diff`, `CommentsPanel`, `AssigneePanel` | Review: a proposed edit's diff, the comment thread, the assignee. |
@@ -384,6 +385,78 @@ type RelationSearch = (
384385

385386
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 })`.
386387

388+
### `DocForm`
389+
390+
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.
391+
392+
```tsx validate=type
393+
import { DocForm } from '@tanstack/cms-ui-react/primitives'
394+
import type { Doc } from '@tanstack/cms-core'
395+
396+
export function PostForm({ post, save }: { post: Doc; save: (patch: Doc) => Promise<void> }) {
397+
return (
398+
<DocForm collection="post" defaultValue={post} onSubmit={(patch) => save(patch)}>
399+
{({ dirty, submitting }) => (
400+
<button type="submit" disabled={!dirty || submitting}>
401+
Save
402+
</button>
403+
)}
404+
</DocForm>
405+
)
406+
}
407+
```
408+
409+
| Prop | Type | Description |
410+
| --- | --- | --- |
411+
| `collection` | `string` | The collection's name. An unknown name throws, as for the other primitives. |
412+
| `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. |
413+
| `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`. |
414+
| `defaultValue` | `Doc` | The initial document when the form owns its state. |
415+
| `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. |
416+
| `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`. |
417+
| `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. |
418+
| `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. |
419+
| `disabled` | `boolean` | Renders every field read-only. |
420+
| `errors` | `Record<string, string>` | Messages by field name, shown under each control (for example the `fieldErrors` of a failed save). |
421+
| `changedFields` | `Array<string>` | Field names to highlight, as `FieldInput`'s `changed` does (for example the fields an agent's proposal changes). |
422+
| `store`, `relationSearch` | | Passed to `FieldInput`: relation titles by collection and id, and the relation search backend. |
423+
| `id`, `className`, `aria-label` | | Set on the `<form>`. `aria-label` defaults to the collection's label. |
424+
| `children` | `ReactNode \| (state) => ReactNode` | Rendered after the fields. The function form gets `{ values, patch, dirty, submitting, error, submit, reset, setValue }`. |
425+
426+
`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.
427+
428+
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`.
429+
430+
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`:
431+
432+
```tsx validate=type
433+
import { DocForm, useDocForm } from '@tanstack/cms-ui-react/primitives'
434+
import type { Doc } from '@tanstack/cms-core'
435+
436+
export function PostEditor({ post, save }: { post: Doc; save: (patch: Doc, publish: boolean) => Promise<void> }) {
437+
const editor = useDocForm<{ publish: boolean }>({
438+
collection: 'post',
439+
defaultValue: post,
440+
onSubmit: (patch, { meta }) => save(patch, meta?.publish ?? false),
441+
})
442+
return (
443+
<>
444+
<header>
445+
<button type="button" disabled={!editor.dirty} onClick={() => editor.reset()}>
446+
Revert
447+
</button>
448+
<button type="button" onClick={() => void editor.submit({ publish: true })}>
449+
Publish
450+
</button>
451+
</header>
452+
<DocForm form={editor} />
453+
</>
454+
)
455+
}
456+
```
457+
458+
`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.
459+
387460
---
388461

389462
## `@tanstack/cms-ui-react/virtual-routes`

‎docs/schema/collections-and-fields.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,36 @@ export const invoice = defineCollection({
446446
- Filters and sorts on a field the session can't read, including nested paths like `pricing.cost`, fail with `FORBIDDEN`.
447447
- API keys can additionally be scoped to a list of collections.
448448

449+
## Editing documents in your own UI
450+
451+
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:
452+
453+
```tsx validate=type
454+
import { DocForm } from '@tanstack/cms-ui-react/primitives'
455+
import { useCmsAuth } from '@tanstack/cms-ui-react'
456+
import type { Doc } from '@tanstack/cms-core'
457+
458+
export function InvoiceForm({ invoice, save }: { invoice: Doc; save: (patch: Doc) => Promise<void> }) {
459+
const session = useCmsAuth()
460+
return (
461+
<DocForm
462+
collection="invoice"
463+
defaultValue={invoice}
464+
access={{ session, doc: invoice }}
465+
onSubmit={(patch) => save(patch)}
466+
>
467+
{({ dirty, submitting }) => (
468+
<button type="submit" disabled={!dirty || submitting}>
469+
Save
470+
</button>
471+
)}
472+
</DocForm>
473+
)
474+
}
475+
```
476+
477+
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.
478+
449479
## Hooks
450480

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

0 commit comments

Comments
 (0)