Skip to content

Commit 133db06

Browse files
cursoragentjherr
andcommitted
Merge #45 (cursor/client-validation-d21e) 66b3f69 into the integration rehearsal
Co-authored-by: jherr <jherr@pobox.com>
2 parents ca85559 + 66b3f69 commit 133db06

16 files changed

Lines changed: 885 additions & 93 deletions

File tree

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@tanstack/cms-ui-react': minor
3+
---
4+
5+
`DocForm` and `useDocForm` validate in the browser. Each field is checked against the collection schema when it loses focus and again on submit, with core's `schemaIssues`: the rules the server's write path runs. A submit that fails them doesn't call `onSubmit`, and `submit()` resolves `false`.
6+
7+
- Messages in `errors` (a save's `fieldErrors`) still replace the form's own.
8+
- Fields that aren't rendered, and fields the session can't write, aren't checked.
9+
- Custom `validate`, `unique`, relation targets, hooks and access stay server-side.
10+
- `validate: false` turns the schema checks off.
11+
- `fieldValidators: { [name]: fn | false }` replaces a field's check. Each function receives `{ value, doc, field, schemaError }`.
12+
- `useDocForm` returns `fieldErrors` and `validatorsFor(name)`, which gives the `validators` for your own `form.Field`.
13+
14+
A field counts as blurred when focus leaves it, not when focus moves between the inputs of one array or group. `FieldInput` keeps its control mounted when an error appears or clears, so the input being typed in isn't replaced.
15+
16+
The admin's edit route gets the checks through `DocForm`. A save they block shows the inline errors and a "Fix the highlighted fields" alert, and sends nothing.

‎.changeset/schema-issues.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/cms-core': minor
3+
---
4+
5+
`schemaIssues(collection, doc)` returns what the server's schema checks report for a document, as `{ path, message }` issues, without saving it. It covers types, `required`, `min`/`max`, formats, options, and `required` on visible conditional fields, after the same derived-field fill as a write. Custom `validate`, relation targets, `unique`, hooks and access stay server-side. The write path runs the same functions, so a form that checks with it before saving agrees with the server.

‎docs/api/cms-core.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,29 @@ const result = schemaFor(post).safeParse({ ...emptyDoc(post), title: 'Hello', ta
729729
if (!result.success) console.log(result.error.issues)
730730
```
731731

732+
### `schemaIssues(collection, doc)`
733+
734+
```ts
735+
function schemaIssues(collection: Collection, doc: Record<string, unknown>): Array<SchemaIssue>
736+
interface SchemaIssue { path: Array<string>; message: string }
737+
```
738+
739+
What a write would report from the schema, without saving. It fills derived fields as a write does, parses with `schemaFor`, and adds `required` on the fields that `showWhen` shows. The write path runs the same functions, so the issues match a save's `VALIDATION_FAILED` details. Custom `validate`, relation targets, `unique`, hooks and access aren't included: only the server runs them. Client-safe; `DocForm` uses it to validate before a save.
740+
741+
```ts validate=type
742+
import { defineCollection, emptyDoc, schemaIssues } from '@tanstack/cms-core'
743+
744+
const post = defineCollection({
745+
name: 'post',
746+
label: 'Posts',
747+
titleField: 'title',
748+
fields: [{ name: 'title', label: 'Title', type: 'text', required: true }],
749+
})
750+
751+
schemaIssues(post, { ...emptyDoc(post), title: '' })
752+
// → [{ path: ['title'], message: 'Title is required' }]
753+
```
754+
732755
### `blocksSchema()`, `aiBlocksSchema()`, `normalizeBlocks(raw)`
733756

734757
```ts

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

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -417,15 +417,61 @@ export function PostForm({ post, save }: { post: Doc; save: (patch: Doc) => Prom
417417
| `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. |
418418
| `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. |
419419
| `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). |
420+
| `validate` | `boolean` | Checks fields against the collection schema on blur and on submit (see [Validation](#validation)). Default `true`. `useDocForm` takes it too. |
421+
| `fieldValidators` | `{ [fieldName]: ((args) => string \| undefined) \| false }` | Per-field checks run instead of the schema check, or `false` to turn a field's checks off. `useDocForm` takes it too. |
422+
| `errors` | `Record<string, string>` | Messages by field name, shown under each control in place of the form's own (for example the `fieldErrors` of a failed save). |
421423
| `changedFields` | `Array<string>` | Field names to highlight, as `FieldInput`'s `changed` does (for example the fields an agent's proposal changes). |
422424
| `store`, `relationSearch` | | Passed to `FieldInput`: relation titles by collection and id, and the relation search backend. |
423425
| `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 }`. |
426+
| `children` | `ReactNode \| (state) => ReactNode` | Rendered after the fields. The function form gets `{ values, patch, dirty, submitting, error, fieldErrors, submit, reset, setValue }`. |
425427
426428
`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.
427429
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`.
430+
Fields hidden by `showWhen` aren't rendered, and their stored values stay in the document.
431+
432+
#### Validation
433+
434+
`DocForm` checks each field when it loses focus and again on submit, with the rules the server applies to a write: types, `required`, `min`/`max`, the `slug`, `email`, `url` and `color` formats, select options, and `required` on fields that `showWhen` shows. The checks are `schemaIssues(collection, doc)` from `@tanstack/cms-core`, the functions the server's write path runs, so the form and the server can't disagree about them. A submit that fails them doesn't call `onSubmit`, and `submit()` resolves `false`.
435+
436+
Some rules need the server, so they still surface as a save's errors:
437+
438+
- custom `validate` functions and Standard Schemas;
439+
- `unique`;
440+
- relation targets that must exist;
441+
- `preValidate` hooks;
442+
- access.
443+
444+
Put the save's `fieldErrors` in `errors`. A message in `errors` replaces the form's own for that field.
445+
446+
Fields that aren't rendered (hidden by `showWhen` or by read access) and fields the session can't write aren't checked: the user couldn't fix them.
447+
448+
`validate={false}` turns the schema checks off. `fieldValidators` replaces them for single fields. Each entry gets `{ value, doc, field, schemaError }` and returns a message, or nothing when the value is fine; `false` turns that field's checks off:
449+
450+
```tsx validate=type
451+
import { isSafeRedirectTarget } from '@tanstack/cms-core'
452+
import { DocForm } from '@tanstack/cms-ui-react/primitives'
453+
import type { Doc } from '@tanstack/cms-core'
454+
455+
export function RedirectForm({ redirect, save }: { redirect: Doc; save: (patch: Doc) => Promise<void> }) {
456+
return (
457+
<DocForm
458+
collection="redirect"
459+
defaultValue={redirect}
460+
fieldValidators={{
461+
// Keep the schema's message, and run the field's server rule early.
462+
to: ({ value, schemaError }) =>
463+
schemaError ??
464+
(isSafeRedirectTarget(value) ? undefined : 'Must be a path starting with / or an http(s) URL'),
465+
}}
466+
onSubmit={(patch) => save(patch)}
467+
>
468+
<button type="submit">Save</button>
469+
</DocForm>
470+
)
471+
}
472+
```
473+
474+
When you render `editor.form.Field` yourself instead of `DocForm`, pass `validators={editor.validatorsFor(name)}` to get the same checks.
429475

430476
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`:
431477

@@ -455,7 +501,7 @@ export function PostEditor({ post, save }: { post: Doc; save: (patch: Doc, publi
455501
}
456502
```
457503

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 (also exported from `@tanstack/cms-core`).
504+
`useDocForm` returns `{ form, collection, values, baseline, patch, dirty, submitting, error, fieldErrors, submit, reset, setValue, validatorsFor }`. `form` is the TanStack Form instance, for `form.Field` and `form.Subscribe`. `submit(meta?)` validates the fields, then resolves `true` when `onSubmit` succeeded, and `false` when a field failed its checks or `onSubmit` threw. `fieldErrors` holds the form's own messages by field name. `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`).
459505

460506
#### With the core editor store
461507

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,8 @@ export const event = defineCollection({
374374

375375
Failures throw a `CmsError` with code `VALIDATION_FAILED` (HTTP 422) and `details: Array<{ path: Array<string>, message: string }>`, which the admin maps back onto the fields.
376376

377+
`schemaIssues(collection, doc)` runs the schema layer without saving, plus `required` on the fields that `showWhen` shows. It returns the same `{ path, message }` issues a write would. The admin's edit form and [`DocForm`](../api/cms-ui-react#validation) run it on blur and before every save, so the user sees schema errors on the fields they can edit before anything is sent. `validate` runs only on the server: a function may use server-only code, and it gets the document's `id`. To check a rule in the browser too, pass it to `DocForm`'s `fieldValidators`.
378+
377379
## Conditional fields
378380

379381
A field can declare `showWhen` to appear only when a *sibling* field matches. The condition is declarative (and serializable), so it works the same in the admin form and on the server:
@@ -451,7 +453,7 @@ export const invoice = defineCollection({
451453

452454
## Editing documents in your own UI
453455

454-
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:
456+
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, with `access` the session's field rules hide or lock fields, and the schema's checks run on blur and before each submit. 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:
455457

456458
```tsx validate=type
457459
import { DocForm } from '@tanstack/cms-ui-react/primitives'
@@ -781,6 +783,7 @@ These client-safe helpers from `@tanstack/cms-core` read the registered config:
781783
| `blockTypes()` / `blockTypeMap()` | The block palette as an array / keyed by `type` |
782784
| `schemaFor(collection)` | Zod object for a full document, including system metadata |
783785
| `scalarSchemaFor(collection)` | Zod object without `blocks` fields (for AI structured output) |
786+
| `schemaIssues(collection, doc)` | The `{ path, message }` issues a write would report from the schema (see [Validation](#validation)) |
784787
| `emptyDoc(collection)` / `emptyBlock(type)` / `emptyArrayItem(field)` | New values with every field defaulted |
785788
| `fillDerivedFields(collection, doc)` | Fills empty `slug` fields from their source |
786789
| `slugify(text, { nested? })` | Lowercase kebab-case (`"Héllo, World!"` → `"hello-world"`); with `nested`, per `/` segment |

‎examples/blog/e2e/editor.spec.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,55 @@ test('validation errors appear next to the field', async ({
117117
)
118118
})
119119

120+
test('a save the schema rejects stays in the browser until it is fixed', async ({
121+
page,
122+
context,
123+
}) => {
124+
await signInAs(context, 'admin')
125+
const id = 'e2e-client-check'
126+
const created = await page.request.post('/api/cms/v1/ops/createDoc', {
127+
data: {
128+
collection: 'redirect',
129+
id,
130+
doc: { from: '/e2e-client', to: '/post/hello-world', permanent: true },
131+
},
132+
})
133+
expect(created.status()).toBe(200)
134+
135+
await open(page, `/edit/redirect/${id}`)
136+
const sent: Array<string> = []
137+
page.on('request', (request) => {
138+
if (request.method() === 'POST' && request.postData()?.includes(id)) {
139+
sent.push(request.url())
140+
}
141+
})
142+
const to = page.getByRole('textbox', { name: /^To \(path or URL\)/ })
143+
const error = page.locator('[data-field-error="to"]')
144+
145+
await to.fill('')
146+
await to.blur()
147+
await expect(error).toHaveText('To (path or URL) is required')
148+
149+
await page.getByRole('button', { name: SAVE }).click()
150+
await expect(page.getByRole('alert')).toContainText(
151+
'Fix the highlighted fields',
152+
)
153+
await expect(error).toHaveText('To (path or URL) is required')
154+
expect(sent).toEqual([])
155+
expect((await getDoc(page.request, 'redirect', id)).to).toBe(
156+
'/post/hello-world',
157+
)
158+
159+
await to.fill('/post/fixed')
160+
await to.blur()
161+
await expect(error).toHaveCount(0)
162+
await expect(page.getByRole('alert')).toHaveCount(0)
163+
await page.getByRole('button', { name: SAVE }).click()
164+
await expect(page.getByText(/(Saved|Published) ✓/).first()).toBeVisible()
165+
expect(sent.length).toBeGreaterThan(0)
166+
expect((await getDoc(page.request, 'redirect', id)).to).toBe('/post/fixed')
167+
})
168+
120169
test('scheduling stores the local time as UTC', async ({ page, context }) => {
121170
await signInAs(context, 'admin')
122171
await createDocument(page, 'post', 'E2E scheduled')

‎packages/core/src/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,11 @@ export type {
438438
CreateDocEditorOptions,
439439
} from './lib/doc-editor'
440440

441+
// The schema's document checks (client-safe): the write path runs them, and
442+
// so can a form before it saves.
443+
export { schemaIssues } from './lib/validation'
444+
export type { SchemaIssue } from './lib/validation'
445+
441446
// Lightweight, framework-agnostic feature flags (client-safe). Resolve on the
442447
// server from the request session, ship the booleans, read them via the store.
443448
export { flagEnabled, resolveFlags, createFlagsStore } from './flags'
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/**
2+
* The document checks the schema alone decides. The server's write path runs
3+
* them on every write, and form validation in the browser runs the same
4+
* functions, so the two can't disagree.
5+
*/
6+
import { contentLocales } from '../config'
7+
import { isLocalizedValue, primaryLocaleValue } from '../i18n'
8+
import {
9+
blockTypeMap,
10+
fillDerivedFields,
11+
isFieldVisible,
12+
schemaFor,
13+
} from '../schema'
14+
import type { Collection, Doc, Field, JsonValue } from '../schema'
15+
16+
/** A failed check: the value's path from the document root, and why. */
17+
export interface SchemaIssue {
18+
path: Array<string>
19+
message: string
20+
}
21+
22+
/** A field's value somewhere in a document. */
23+
export interface FieldValueVisit {
24+
field: Field
25+
value: JsonValue | undefined
26+
path: Array<string>
27+
}
28+
29+
/** Whether a value counts as "empty" for a `required` check. */
30+
export function isEmptyFieldValue(v: JsonValue | undefined): boolean {
31+
if (v === undefined || v === null || v === '') return true
32+
if (Array.isArray(v)) return v.length === 0
33+
return false
34+
}
35+
36+
/**
37+
* Every field value a document shows, at any depth (groups, array items,
38+
* blocks), parents before their sub-fields. A field hidden by `showWhen` is
39+
* skipped with everything under it. A localized value is its default
40+
* locale's entry: a missing translation falls back on read.
41+
*/
42+
export function visibleFieldValues(
43+
fields: ReadonlyArray<Field>,
44+
doc: Record<string, unknown> | undefined,
45+
): Array<FieldValueVisit> {
46+
const out: Array<FieldValueVisit> = []
47+
const walk = (
48+
list: ReadonlyArray<Field>,
49+
value: Record<string, unknown> | undefined,
50+
path: Array<string>,
51+
): void => {
52+
for (const f of list) {
53+
if (f.showWhen && !isFieldVisible(f, value as Doc | undefined)) continue
54+
let v = value?.[f.name] as JsonValue | undefined
55+
const at = [...path, f.name]
56+
if (f.localized && isLocalizedValue(v)) {
57+
v = primaryLocaleValue(v, contentLocales()?.defaultLocale ?? 'en') as
58+
| JsonValue
59+
| undefined
60+
}
61+
out.push({ field: f, value: v, path: at })
62+
if (f.type === 'group' && f.fields && v && typeof v === 'object') {
63+
walk(f.fields, v as Record<string, unknown>, at)
64+
}
65+
if (f.type === 'array' && f.fields && Array.isArray(v)) {
66+
for (const [i, item] of v.entries()) {
67+
walk(f.fields, item as Record<string, unknown>, [...at, String(i)])
68+
}
69+
}
70+
if (f.type === 'blocks' && Array.isArray(v)) {
71+
const types = blockTypeMap()
72+
for (const [i, block] of v.entries()) {
73+
if (!block || typeof block !== 'object' || Array.isArray(block))
74+
continue
75+
const b = block as Record<string, unknown>
76+
const typeName =
77+
typeof b._type === 'string'
78+
? b._type
79+
: typeof b.type === 'string'
80+
? b.type
81+
: undefined
82+
const bt = typeName ? types[typeName] : undefined
83+
if (bt) walk(bt.fields, b, [...at, String(i)])
84+
}
85+
}
86+
}
87+
}
88+
walk(fields, doc, [])
89+
return out
90+
}
91+
92+
/**
93+
* `required` on a visible conditional field. The Zod schema relaxes it,
94+
* because only the sibling values decide whether the field is shown.
95+
*/
96+
export function conditionalRequiredIssue(
97+
visit: FieldValueVisit,
98+
): SchemaIssue | undefined {
99+
const { field, value, path } = visit
100+
if (!field.showWhen || field.required !== true) return undefined
101+
if (!isEmptyFieldValue(value)) return undefined
102+
return { path, message: `${field.label} is required` }
103+
}
104+
105+
/**
106+
* What the server's schema checks report for a document: types, `required`,
107+
* `min`/`max`, formats (slug, email, url, color), options, and `required` on
108+
* visible conditional fields, after the same derived-field fill (a slug from
109+
* its source field). The rules only the server can run aren't here: custom
110+
* `validate`, relation targets, `unique`, hooks, and access.
111+
*/
112+
export function schemaIssues(
113+
collection: Collection,
114+
doc: Record<string, unknown>,
115+
): Array<SchemaIssue> {
116+
const filled = fillDerivedFields(collection, doc)
117+
const parsed = schemaFor(collection).safeParse(filled)
118+
const issues: Array<SchemaIssue> = parsed.success
119+
? []
120+
: parsed.error.issues.map((i) => ({
121+
path: i.path.map(String),
122+
message: i.message,
123+
}))
124+
const checked = parsed.success ? (parsed.data as Doc) : filled
125+
for (const visit of visibleFieldValues(collection.fields, checked)) {
126+
const issue = conditionalRequiredIssue(visit)
127+
if (issue) issues.push(issue)
128+
}
129+
return issues
130+
}

0 commit comments

Comments
 (0)