diff --git a/.changeset/doc-form-primitive.md b/.changeset/doc-form-primitive.md new file mode 100644 index 00000000..92cf5c4d --- /dev/null +++ b/.changeset/doc-form-primitive.md @@ -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. diff --git a/docs/api/cms-ui-react.md b/docs/api/cms-ui-react.md index 8f29912e..dfc3708f 100644 --- a/docs/api/cms-ui-react.md +++ b/docs/api/cms-ui-react.md @@ -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. | @@ -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 `
` 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 }) { + return ( + save(patch)}> + {({ dirty, submitting }) => ( + + )} + + ) +} +``` + +| 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 }` | 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` | Messages by field name, shown under each control (for example the `fieldErrors` of a failed save). | +| `changedFields` | `Array` | 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 ``. `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 }) { + const editor = useDocForm<{ publish: boolean }>({ + collection: 'post', + defaultValue: post, + onSubmit: (patch, { meta }) => save(patch, meta?.publish ?? false), + }) + return ( + <> +
+ + +
+ + + ) +} +``` + +`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` diff --git a/docs/schema/collections-and-fields.md b/docs/schema/collections-and-fields.md index b666d1bc..00eac9cd 100644 --- a/docs/schema/collections-and-fields.md +++ b/docs/schema/collections-and-fields.md @@ -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 }) { + const session = useCmsAuth() + return ( + save(patch)} + > + {({ dirty, submitting }) => ( + + )} + + ) +} +``` + +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. diff --git a/packages/ui-react/src/components/editor/doc-form.tsx b/packages/ui-react/src/components/editor/doc-form.tsx new file mode 100644 index 00000000..d8d2e4d8 --- /dev/null +++ b/packages/ui-react/src/components/editor/doc-form.tsx @@ -0,0 +1,419 @@ +/** + * The schema-driven document form: TanStack Form state for one collection's + * fields, rendered with `FieldInput` (or a renderer per field type), and + * submitted as a patch against the stored document. + */ +import { useEffect, useMemo, useRef, useState } from 'react' +import { useForm, useStore } from '@tanstack/react-form' +import { + canReadField, + canWriteField, + emptyDoc, + isFieldVisible, +} from '@tanstack/cms-core' +import { requireCollection } from '../../lib/collection' +import { FieldInput } from './field-input' +import type { + FieldAccessContext, + FieldInputComponentProps, +} from './field-input' +import type { RelationSearch } from './relation-picker' +import type { CmsRenderers } from '../../lib/renderers' +import type { ComponentType, ReactNode } from 'react' +import type { + Collection, + Doc, + Field, + FieldType, + JsonValue, +} from '@tanstack/cms-core' + +/** A top-level field renderer. It receives the same props as `FieldInput`. */ +export type DocFormFieldRenderer = ComponentType + +/** Field renderers keyed by field type (`text`, `markdown`, a custom type). */ +export type DocFormFieldRenderers = Partial< + Record +> + +/** What `onSubmit` receives besides the patch. */ +export interface DocFormSubmitContext { + /** The whole document as submitted. */ + doc: Doc + /** The document the patch was computed against. */ + baseline: Doc + /** The argument given to `submit(meta)`; `undefined` for a form submit. */ + meta: TMeta | undefined +} + +export interface UseDocFormOptions { + /** The collection's name, as for every primitive. */ + collection: string + /** + * The document being edited, when the parent owns it. The form adopts any + * `value` that differs from its own values. Pair it with `onChange`. + */ + value?: Doc + /** The initial document when the form owns it. */ + defaultValue?: Doc + /** + * The stored document that the patch and `dirty` compare against. Defaults + * to the initial document, and then to each successfully submitted one. + */ + baseline?: Doc + /** Called with the whole document after every change. */ + onChange?: (doc: Doc) => void + /** + * The app's renderers module (`defineRenderers({ inputs, fieldTypes })`), + * passed to every `FieldInput`. Without it, `FieldInput` uses the module + * bound through `createRoutes(definition, { renderers })`. + */ + renderers?: CmsRenderers + /** + * Receives the changed top-level fields. A throw or rejection marks the + * submit failed and keeps the baseline; otherwise the submitted document + * becomes the baseline, unless the `baseline` prop is set. + */ + onSubmit: ( + patch: Doc, + context: DocFormSubmitContext, + ) => unknown | Promise +} + +/** + * Form values are typed as plain records: TanStack Form's deep field-name + * types don't terminate on the recursive `JsonValue`. + */ +type DocFormValues = Record + +function useDocTanStackForm( + defaultValues: Doc, + onSubmit: (doc: Doc) => Promise, +) { + return useForm({ + defaultValues: defaultValues as DocFormValues, + onSubmit: ({ value }) => onSubmit(value as Doc), + }) +} + +/** The TanStack Form instance behind a document form. */ +export type DocFormInstance = ReturnType + +export interface DocFormApi { + /** The TanStack Form instance, for `form.Field`, `form.Subscribe`, and so on. */ + form: DocFormInstance + /** The resolved collection definition. */ + collection: Collection + /** The `renderers` option, for `DocForm` to pass to `FieldInput`. */ + renderers: CmsRenderers | undefined + values: Doc + baseline: Doc + /** The top-level fields whose values differ from the baseline. */ + patch: Doc + dirty: boolean + submitting: boolean + /** What the last failed submit threw, or `null`. */ + error: unknown + /** Calls `onSubmit` with the patch. Resolves `true` when it succeeded. */ + submit: (meta?: TMeta) => Promise + /** Back to the baseline, or to `doc`, which also becomes the baseline. */ + reset: (doc?: Doc) => void + 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 +} + +const isEmpty = (doc: Doc) => Object.keys(doc).length === 0 + +/** + * The headless half of `DocForm`: TanStack Form state for one collection's + * document, with the patch, dirty state, and submit. Render it with + * ``, or read `api.form` directly. + */ +export function useDocForm( + options: UseDocFormOptions, +): DocFormApi { + const collection = requireCollection(options.collection) + const normalize = (doc: Doc | undefined): Doc => ({ + ...emptyDoc(collection), + ...doc, + }) + + const optionsRef = useRef(options) + optionsRef.current = options + const metaRef = useRef(undefined) + + const [initial] = useState(() => + normalize(options.value ?? options.defaultValue ?? options.baseline), + ) + const [ownBaseline, setOwnBaseline] = useState(() => + options.baseline ? normalize(options.baseline) : initial, + ) + const baselineProp = options.baseline + const baseline = useMemo( + () => (baselineProp ? normalize(baselineProp) : ownBaseline), + [baselineProp, ownBaseline, collection], + ) + const baselineRef = useRef(baseline) + baselineRef.current = baseline + + const [error, setError] = useState(null) + + const form = useDocTanStackForm(initial, async (doc) => { + const base = baselineRef.current + await optionsRef.current.onSubmit(docPatch(base, doc), { + doc, + baseline: base, + meta: metaRef.current, + }) + if (!optionsRef.current.baseline) setOwnBaseline(doc) + }) + + // Every change to the values reaches `onChange`, including changes made + // through `api.form`; adopting the parent's `value` doesn't echo back. + const adopting = useRef(false) + const lastValues = useRef(form.state.values) + useEffect(() => { + const subscription = form.store.subscribe(() => { + const values = form.state.values + if (values === lastValues.current) return + lastValues.current = values + if (!adopting.current) optionsRef.current.onChange?.(values as Doc) + }) + return () => subscription.unsubscribe() + }, [form]) + + const value = options.value + useEffect(() => { + if (value === undefined) return + const next = normalize(value) + if (isEmpty(docPatch(form.state.values as Doc, next))) return + adopting.current = true + try { + form.reset(next, { keepDefaultValues: true }) + } finally { + adopting.current = false + } + }, [form, value]) + + const values = useStore(form.store, (s) => s.values) as Doc + const submitting = useStore(form.store, (s) => s.isSubmitting) + const patch = useMemo(() => docPatch(baseline, values), [baseline, values]) + + return { + form, + collection, + renderers: options.renderers, + values, + baseline, + patch, + dirty: !isEmpty(patch), + submitting, + error, + submit: async (meta) => { + metaRef.current = meta + setError(null) + try { + await form.handleSubmit() + return form.state.isSubmitSuccessful + } catch (e) { + setError(e) + return false + } finally { + metaRef.current = undefined + } + }, + reset: (doc) => { + if (doc) { + const next = normalize(doc) + if (!optionsRef.current.baseline) setOwnBaseline(next) + form.reset(next, { keepDefaultValues: true }) + } else { + form.reset(baselineRef.current, { keepDefaultValues: true }) + } + }, + setValue: (name, next) => form.setFieldValue(name, next), + } +} + +/** The values a `DocForm` hands to its `children` render function. */ +export type DocFormState = Pick< + DocFormApi, + | 'values' + | 'patch' + | 'dirty' + | 'submitting' + | 'error' + | 'submit' + | 'reset' + | 'setValue' +> + +interface DocFormViewProps { + /** + * Per-form renderers keyed by field type, built-in types included. They + * replace `FieldInput` for that type; every other field renders with + * `FieldInput`, which resolves `renderers`. + */ + fieldRenderers?: DocFormFieldRenderers + /** Overrides the `renderers` given to `useDocForm`. */ + renderers?: CmsRenderers + /** + * Field-level access: fields the session can't read are hidden, and fields + * it can't write are read-only. Without it every field is editable. + */ + access?: FieldAccessContext + /** Render every field read-only. */ + disabled?: boolean + /** Messages per field name (for example a save's `fieldErrors`). */ + errors?: Readonly> + /** Field names to mark as changed (`FieldInput`'s `changed` ring). */ + changedFields?: ReadonlyArray + /** Related documents for relation titles, by collection then id. */ + store?: Record> + /** Search backend for relation fields. Default: `listDocumentSummaries`. */ + relationSearch?: RelationSearch + id?: string + className?: string + 'aria-label'?: string + /** Rendered after the fields, typically the submit buttons. */ + children?: ReactNode | ((state: DocFormState) => ReactNode) +} + +export type DocFormProps = DocFormViewProps & + ({ form: DocFormApi } | (UseDocFormOptions & { form?: never })) + +/** + * A `` with a control for each field of the collection, in schema + * order, skipping fields hidden by `showWhen` or by field read access. + * + * Pass `collection`, `onSubmit`, and `value`/`onChange` or `defaultValue`, or + * pass `form` from `useDocForm` to keep the form's state in the parent. + */ +export function DocForm(props: DocFormProps) { + if (props.form) return + return ( + & UseDocFormOptions)} + /> + ) +} + +function OwnedDocForm( + props: DocFormViewProps & UseDocFormOptions, +) { + const api = useDocForm(props) + return +} + +function rendererFor( + field: Field, + renderers: DocFormFieldRenderers | undefined, +): DocFormFieldRenderer { + const type = field.type as string + if (renderers && Object.hasOwn(renderers, type)) { + return renderers[type] ?? FieldInput + } + return FieldInput +} + +function DocFormView({ + api, + fieldRenderers, + access, + disabled, + errors, + changedFields, + store, + relationSearch, + renderers, + id, + className, + 'aria-label': ariaLabel, + children, +}: DocFormViewProps & { api: DocFormApi }) { + const { form, collection, values } = api + const accessDoc = access ? (access.doc ?? values) : null + const fields = collection.fields + .filter((f) => !access || canReadField(f, access.session, accessDoc)) + .filter((f) => isFieldVisible(f, values)) + const state: DocFormState = { + values, + patch: api.patch, + dirty: api.dirty, + submitting: api.submitting, + error: api.error, + submit: api.submit, + reset: api.reset, + setValue: api.setValue, + } + return ( + { + e.preventDefault() + e.stopPropagation() + void api.submit() + }} + > +
+ {fields.map((f) => { + const Renderer = rendererFor(f, fieldRenderers) + const writable = + !access || canWriteField(f, access.session, accessDoc) + return ( + + {(field) => ( +
+ field.handleChange(v)} + /> +
+ )} +
+ ) + })} +
+ {typeof children === 'function' ? children(state) : children} + + ) +} + +function firstError(errors: ReadonlyArray): string | undefined { + const first = errors.find((e) => e != null && e !== '') + if (first === undefined) return undefined + if (typeof first === 'string') return first + if (first && typeof first === 'object' && 'message' in first) { + return String((first as { message: unknown }).message) + } + return String(first) +} diff --git a/packages/ui-react/src/primitives.ts b/packages/ui-react/src/primitives.ts index e3d43076..5ee09455 100644 --- a/packages/ui-react/src/primitives.ts +++ b/packages/ui-react/src/primitives.ts @@ -40,6 +40,18 @@ export type { FieldInputComponentProps, } from './components/editor/field-input' +export { DocForm, docPatch, useDocForm } from './components/editor/doc-form' +export type { + DocFormApi, + DocFormFieldRenderer, + DocFormFieldRenderers, + DocFormInstance, + DocFormProps, + DocFormState, + DocFormSubmitContext, + UseDocFormOptions, +} from './components/editor/doc-form' + export { RELATION_PAGE_SIZE, RelationPicker, diff --git a/packages/ui-react/tests/doc-form.test.tsx b/packages/ui-react/tests/doc-form.test.tsx new file mode 100644 index 00000000..c26ad65e --- /dev/null +++ b/packages/ui-react/tests/doc-form.test.tsx @@ -0,0 +1,425 @@ +// @vitest-environment happy-dom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useState } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { defineCms, defineFieldType } from '@tanstack/cms-core' +import { DocForm, docPatch, useDocForm } from '../src/primitives' +import { sessionFor } from './render' +import type { Collection, Doc, FieldInputProps } from '@tanstack/cms-core' +import type { + CmsRenderers, + DocFormFieldRenderer, + FieldInputComponentProps, +} from '../src/primitives' + +const link: Collection = { + name: 'link', + label: 'Links', + titleField: 'label', + fields: [ + { name: 'label', label: 'Label', type: 'text', required: true }, + { + name: 'linkType', + label: 'Link type', + type: 'select', + options: ['internal', 'external'], + }, + { + name: 'externalUrl', + label: 'External URL', + type: 'url', + showWhen: { field: 'linkType', equals: 'external' }, + }, + { name: 'clicks', label: 'Clicks', type: 'number' }, + { + name: 'notes', + label: 'Notes', + type: 'text', + access: { read: ['editor', 'admin'], write: ['admin'] }, + }, + ], +} + +beforeEach(() => { + defineCms({ collections: [link], blockTypes: [] }) +}) + +afterEach(cleanup) + +const stored: Doc = { + label: 'Docs', + linkType: 'internal', + externalUrl: '', + clicks: 3, + notes: 'n', + _revision: 2, +} + +const labelInput = () => screen.getByLabelText('Label*') as HTMLInputElement + +const fieldNames = (container: HTMLElement) => + [...container.querySelectorAll('[data-doc-form-field]')].map((el) => + el.getAttribute('data-doc-form-field'), + ) + +describe('docPatch', () => { + it('keeps the top-level fields whose JSON differs', () => { + expect( + docPatch( + { a: 1, b: { c: [1] }, d: 'x', e: 'gone' }, + { a: 1, b: { c: [1, 2] }, d: 'y', f: true }, + ), + ).toEqual({ b: { c: [1, 2] }, d: 'y', e: null, f: true }) + expect(docPatch({ a: null }, {})).toEqual({}) + }) +}) + +describe('DocForm', () => { + it('renders the collection by name, in schema order, honouring showWhen and field access', () => { + const { container } = render( + {}} />, + ) + expect(fieldNames(container)).toEqual([ + 'label', + 'linkType', + 'clicks', + 'notes', + ]) + + fireEvent.change(screen.getByRole('combobox'), { + target: { value: 'external' }, + }) + expect(fieldNames(container)).toEqual([ + 'label', + 'linkType', + 'externalUrl', + 'clicks', + 'notes', + ]) + cleanup() + const editor = render( + {}} + />, + ) + expect(fieldNames(editor.container)).toContain('notes') + const notes = editor.container.querySelector( + '[data-doc-form-field="notes"] fieldset', + ) as HTMLFieldSetElement + expect(notes.disabled).toBe(true) + cleanup() + const author = render( + {}} + />, + ) + expect(fieldNames(author.container)).not.toContain('notes') + }) + + it('throws for an unknown collection name, like the other primitives', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + expect(() => + render( {}} />), + ).toThrow('Unknown collection: "nope"') + }) + + it('submits only the changed fields, then treats the submitted doc as the baseline', async () => { + const onSubmit = vi.fn() + const onChange = vi.fn() + render( + + {({ dirty, patch }) => ( + <> + {String(dirty)} + {JSON.stringify(patch)} + + + )} + , + ) + expect(screen.getByTestId('dirty').textContent).toBe('false') + + fireEvent.change(labelInput(), { target: { value: 'Guides' } }) + expect(onChange).toHaveBeenLastCalledWith( + expect.objectContaining({ label: 'Guides', clicks: 3, _revision: 2 }), + ) + expect(screen.getByTestId('dirty').textContent).toBe('true') + expect(screen.getByTestId('patch').textContent).toBe('{"label":"Guides"}') + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + }) + expect(onSubmit).toHaveBeenCalledTimes(1) + const [patch, context] = onSubmit.mock.calls[0]! + expect(patch).toEqual({ label: 'Guides' }) + expect(context.doc).toMatchObject({ label: 'Guides', _revision: 2 }) + expect(context.baseline).toMatchObject({ label: 'Docs' }) + expect(context.meta).toBeUndefined() + expect(screen.getByTestId('dirty').textContent).toBe('false') + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + }) + expect(onSubmit.mock.calls[1]![0]).toEqual({}) + }) + + it('keeps the baseline and reports the error when onSubmit throws', async () => { + const failure = new Error('CONFLICT') + render( + Promise.reject(failure)} + > + {({ dirty, error }) => ( + <> + {String(dirty)} + + {error instanceof Error ? error.message : ''} + + + + )} + , + ) + fireEvent.change(labelInput(), { target: { value: 'Guides' } }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + }) + expect(screen.getByTestId('error').textContent).toBe('CONFLICT') + expect(screen.getByTestId('dirty').textContent).toBe('true') + }) + + it('is controlled by value/onChange and adopts outside changes without echoing them', async () => { + const changes: Array = [] + const submitted: Array = [] + let setOutside!: (doc: Doc) => void + function Parent() { + const [doc, setDoc] = useState(stored) + setOutside = setDoc + return ( + <> + {String(doc.label)} + { + changes.push(next) + setDoc(next) + }} + onSubmit={(patch) => { + submitted.push(patch) + }} + > + + + + ) + } + render() + fireEvent.change(labelInput(), { target: { value: 'Guides' } }) + expect(screen.getByTestId('parent').textContent).toBe('Guides') + expect(changes).toHaveLength(1) + + act(() => setOutside({ ...stored, label: 'From agent', clicks: 9 })) + expect(labelInput().value).toBe('From agent') + expect(changes).toHaveLength(1) + + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + }) + expect(submitted).toEqual([{ label: 'From agent', clicks: 9 }]) + }) + + it('uses a renderer per field type and FieldInput for the rest', () => { + const NumberStepper: DocFormFieldRenderer = ({ + field, + value, + onChange, + }: FieldInputComponentProps) => ( + + ) + const onChange = vi.fn() + render( + {}} + />, + ) + fireEvent.click(screen.getByRole('button', { name: 'Clicks: 3' })) + expect(onChange).toHaveBeenLastCalledWith( + expect.objectContaining({ clicks: 4 }), + ) + expect(labelInput()).toBeTruthy() + }) + + it('shows field errors and changed rings passed as props', () => { + const { container } = render( + {}} + />, + ) + expect( + container.querySelector('[data-field-error="label"]')?.textContent, + ).toBe('Label is required.') + const clicks = screen.getByLabelText('Clicks') as HTMLInputElement + expect(clicks.className).toContain('border-indigo-400') + }) + + it('renders a parent-held useDocForm and passes submit(meta) through', async () => { + const onSubmit = vi.fn() + let submitResult: boolean | undefined + function Editor() { + const editor = useDocForm<{ publish: boolean }>({ + collection: 'link', + defaultValue: stored, + onSubmit, + }) + return ( + <> + + + + + ) + } + render() + const publish = screen.getByRole('button', { + name: 'Publish', + }) as HTMLButtonElement + expect(publish.disabled).toBe(true) + + fireEvent.change(labelInput(), { target: { value: 'Reverted' } }) + fireEvent.click(screen.getByRole('button', { name: 'Revert' })) + expect(labelInput().value).toBe('Docs') + expect(publish.disabled).toBe(true) + + fireEvent.change(labelInput(), { target: { value: 'Live' } }) + await act(async () => { + fireEvent.click(publish) + }) + expect(onSubmit).toHaveBeenCalledWith( + { label: 'Live' }, + expect.objectContaining({ meta: { publish: true } }), + ) + expect(submitResult).toBe(true) + }) +}) + +describe('DocForm renderers', () => { + const product: Collection = { + name: 'product', + label: 'Products', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'rating', label: 'Rating', type: 'rating' }, + { name: 'sku', label: 'SKU', type: 'text', input: 'sku' }, + ], + } + const doc: Doc = { title: 'Lamp', rating: 3, sku: 'L-1' } + + beforeEach(() => { + defineCms({ + collections: [product], + blockTypes: [], + fieldTypes: [ + defineFieldType({ name: 'rating', schema: () => z.number().min(0) }), + ], + }) + }) + + const Sku = ({ value }: FieldInputProps) => ( + {String(value)} + ) + const Stars = ({ value }: FieldInputProps) => ( + {'★'.repeat(Number(value))} + ) + const renderers: CmsRenderers = { + inputs: { sku: Sku }, + fieldTypes: { rating: { input: Stars } }, + } + + it('passes renderers to FieldInput for named inputs and custom field types', () => { + render( + {}} + />, + ) + expect(screen.getByLabelText('sku input').textContent).toBe('L-1') + expect(screen.getByLabelText('stars input').textContent).toBe('★★★') + expect(screen.getByLabelText('Title')).toBeTruthy() + }) + + it('puts fieldRenderers first, then FieldInput with renderers', () => { + const seen: Array = [] + const Rating: DocFormFieldRenderer = (props) => { + seen.push(props.renderers) + return {String(props.value)} + } + render( + {}} + />, + ) + expect(screen.getByLabelText('rating override').textContent).toBe('3') + expect(screen.queryByLabelText('stars input')).toBeNull() + expect(screen.getByLabelText('sku input')).toBeTruthy() + expect(seen.at(-1)).toBe(renderers) + }) + + it('takes renderers from useDocForm when DocForm renders a parent-held form', () => { + function Editor() { + const editor = useDocForm({ + collection: 'product', + defaultValue: doc, + renderers, + onSubmit: () => {}, + }) + return + } + render() + expect(screen.getByLabelText('stars input')).toBeTruthy() + }) +}) diff --git a/packages/ui-react/tests/s1-primitives-boundary.test.ts b/packages/ui-react/tests/s1-primitives-boundary.test.ts index 00c632eb..d246845c 100644 --- a/packages/ui-react/tests/s1-primitives-boundary.test.ts +++ b/packages/ui-react/tests/s1-primitives-boundary.test.ts @@ -29,6 +29,9 @@ describe('Seam S1 — Canned Admin is built only on public Headless UI Primitive expect(primitives.columnFields).toBeTypeOf('function') expect(primitives.defaultSort).toBeTypeOf('function') expect(primitives.FieldInput).toBeTypeOf('function') + expect(primitives.DocForm).toBeTypeOf('function') + expect(primitives.useDocForm).toBeTypeOf('function') + expect(primitives.docPatch).toBeTypeOf('function') expect(primitives.RelationPicker).toBeTypeOf('function') expect(primitives.ImageField).toBeTypeOf('function') expect(primitives.MediaInsert).toBeTypeOf('function') diff --git a/starters/runtime-tables/CMS-INTEGRATION.md b/starters/runtime-tables/CMS-INTEGRATION.md index 83e8e0f0..eef923d2 100644 --- a/starters/runtime-tables/CMS-INTEGRATION.md +++ b/starters/runtime-tables/CMS-INTEGRATION.md @@ -6,7 +6,7 @@ Catalog row #12 (class) · [README](./README.md) · [`starters/catalog.json`](.. Tables defined at runtime. A proposed table is stored as a `schemaDefinition` document and staged for review. Once it's approved, the starter re-registers the CMS with that table as a real collection. The new collection then shows up immediately in validation, the ops/MCP surface, admin columns, and search. Forms and tables are generated from the collection metadata. -**CMS features it relies on:** `stageWrite`/`approve` for schema changes, re-running `defineCms` with dynamic `defineCollection`s, `schemaFor`, the `list_collections` agent tool, FTS search, and `FieldInput`/`columnFields` from `/primitives`. +**CMS features it relies on:** `stageWrite`/`approve` for schema changes, re-running `defineCms` with dynamic `defineCollection`s, `schemaFor`, the `list_collections` agent tool, FTS search, and `DocForm`/`columnFields` from `/primitives`. ## Files @@ -41,7 +41,7 @@ Tables defined at runtime. A proposed table is stored as a `schemaDefinition` do ### Admin UI and UI primitives -- `GeneratedRuntimeForm` renders a `FieldInput` per field. +- `GeneratedRuntimeForm` renders the runtime table's collection with `DocForm`, which generates a control per field and submits only the changed fields. - `GeneratedRuntimeTableView` renders the title field plus `columnFields(collection.name)`. - `schemaFor(collection)` checks that Zod validation picks up runtime fields. diff --git a/starters/runtime-tables/src/generated-views.tsx b/starters/runtime-tables/src/generated-views.tsx index 05247444..a538659a 100644 --- a/starters/runtime-tables/src/generated-views.tsx +++ b/starters/runtime-tables/src/generated-views.tsx @@ -1,35 +1,44 @@ /** * Metadata-generated forms and views for Class #12 (`runtime-tables`). * - * Seam S1 + S6: Uses `@tanstack/cms-ui-react/primitives` (`FieldInput`, + * Seam S1 + S6: Uses `@tanstack/cms-ui-react/primitives` (`DocForm`, * `columnFields`) to generate forms and table/kanban views dynamically from * runtime collection metadata, with zero imports from themed public rendering * or bespoke domain views. */ -import { FieldInput, columnFields } from '@tanstack/cms-ui-react/primitives' +import { collections } from '@tanstack/cms-core' +import { DocForm, columnFields } from '@tanstack/cms-ui-react/primitives' import type { Collection, Doc } from '@tanstack/cms-core' +/** + * A form for one row of a runtime table, generated from the approved + * collection. `onSubmit` receives only the fields the user changed. + */ export function GeneratedRuntimeForm({ collection, - values, - onChange, + value, + onSubmit, }: { - collection: Collection - values: Doc - onChange: (field: string, value: unknown) => void + /** The runtime table's collection name. */ + collection: string + /** The stored row; omit it for a new row. */ + value?: Doc + onSubmit: (patch: Doc, doc: Doc) => void | Promise }) { + const label = collections()[collection]?.label ?? collection return ( -
- {collection.fields.map((field) => ( - onChange(field.name, val)} - /> - ))} - + onSubmit(patch, doc)} + > + {({ submitting }) => ( + + )} + ) } diff --git a/starters/runtime-tables/tests/seam.test.ts b/starters/runtime-tables/tests/seam.test.ts index 9e4a6bfa..944749ba 100644 --- a/starters/runtime-tables/tests/seam.test.ts +++ b/starters/runtime-tables/tests/seam.test.ts @@ -1,6 +1,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, describe, expect, it } from 'vitest' import { collections, schemaFor } from '@tanstack/cms-core' import { @@ -121,8 +123,25 @@ describe('starter-runtime-tables — Class #12 (Seam S1, S2, S3, S6) acceptance expect(search.total).toBe(1) expect(search.items[0]?.values?.dealSize).toBe(120000) + // S1: The generated form is the schema-driven DocForm primitive over the runtime fields + const formHtml = renderToStaticMarkup( + createElement(GeneratedRuntimeForm, { + collection: 'dealTrack', + value: { + company: 'Acme Robotics', + stage: 'qualified', + dealSize: 45000, + }, + onSubmit: () => {}, + }), + ) + expect(formHtml).toContain('aria-label="Generated form for Deal Tracker"') + for (const name of ['company', 'stage', 'dealSize']) { + expect(formHtml).toContain(`data-doc-form-field="${name}"`) + } + expect(formHtml).toContain('value="Acme Robotics"') + // S6: Generated views use only Headless UI Primitives - expect(GeneratedRuntimeForm).toBeTypeOf('function') expect(GeneratedRuntimeTableView).toBeTypeOf('function') }) })