From 4c69bb96a6322d62963a51ea0b06fec82100fa84 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 6 Nov 2026 14:26:26 +0000 Subject: [PATCH] feat(core,ui-react): client-side, schema-derived validation in DocForm and the admin editor (5c) (#45) Chain step 23 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: jherr --- .changeset/doc-form-validation.md | 16 ++ .changeset/schema-issues.md | 5 + docs/api/cms-core.md | 23 ++ docs/api/cms-ui-react.md | 54 +++- docs/schema/collections-and-fields.md | 5 +- examples/blog/e2e/editor.spec.ts | 49 ++++ packages/core/src/index.ts | 5 + packages/core/src/lib/validation.ts | 130 +++++++++ packages/core/src/server/store/internal.ts | 87 ++---- packages/core/tests/validation.test.ts | 175 ++++++++++++ .../src/components/editor/doc-form.tsx | 126 ++++++++- .../src/components/editor/field-input.tsx | 3 +- packages/ui-react/src/lib/editor-errors.ts | 31 ++- packages/ui-react/src/primitives.ts | 3 + .../src/routes/edit.$collection.$id.tsx | 14 +- packages/ui-react/tests/doc-form.test.tsx | 252 ++++++++++++++++++ 16 files changed, 885 insertions(+), 93 deletions(-) create mode 100644 .changeset/doc-form-validation.md create mode 100644 .changeset/schema-issues.md create mode 100644 packages/core/src/lib/validation.ts create mode 100644 packages/core/tests/validation.test.ts diff --git a/.changeset/doc-form-validation.md b/.changeset/doc-form-validation.md new file mode 100644 index 00000000..748f8001 --- /dev/null +++ b/.changeset/doc-form-validation.md @@ -0,0 +1,16 @@ +--- +'@tanstack/cms-ui-react': minor +--- + +`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`. + +- Messages in `errors` (a save's `fieldErrors`) still replace the form's own. +- Fields that aren't rendered, and fields the session can't write, aren't checked. +- Custom `validate`, `unique`, relation targets, hooks and access stay server-side. +- `validate: false` turns the schema checks off. +- `fieldValidators: { [name]: fn | false }` replaces a field's check. Each function receives `{ value, doc, field, schemaError }`. +- `useDocForm` returns `fieldErrors` and `validatorsFor(name)`, which gives the `validators` for your own `form.Field`. + +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. + +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. diff --git a/.changeset/schema-issues.md b/.changeset/schema-issues.md new file mode 100644 index 00000000..5daab8ba --- /dev/null +++ b/.changeset/schema-issues.md @@ -0,0 +1,5 @@ +--- +'@tanstack/cms-core': minor +--- + +`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. diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 8d9d735d..562fe0c5 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -729,6 +729,29 @@ const result = schemaFor(post).safeParse({ ...emptyDoc(post), title: 'Hello', ta if (!result.success) console.log(result.error.issues) ``` +### `schemaIssues(collection, doc)` + +```ts +function schemaIssues(collection: Collection, doc: Record): Array +interface SchemaIssue { path: Array; message: string } +``` + +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. + +```ts validate=type +import { defineCollection, emptyDoc, schemaIssues } from '@tanstack/cms-core' + +const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text', required: true }], +}) + +schemaIssues(post, { ...emptyDoc(post), title: '' }) +// → [{ path: ['title'], message: 'Title is required' }] +``` + ### `blocksSchema()`, `aiBlocksSchema()`, `normalizeBlocks(raw)` ```ts diff --git a/docs/api/cms-ui-react.md b/docs/api/cms-ui-react.md index a014b29b..67fa96c1 100644 --- a/docs/api/cms-ui-react.md +++ b/docs/api/cms-ui-react.md @@ -417,15 +417,61 @@ export function PostForm({ post, save }: { post: Doc; save: (patch: Doc) => Prom | `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). | +| `validate` | `boolean` | Checks fields against the collection schema on blur and on submit (see [Validation](#validation)). Default `true`. `useDocForm` takes it too. | +| `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. | +| `errors` | `Record` | Messages by field name, shown under each control in place of the form's own (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 }`. | +| `children` | `ReactNode \| (state) => ReactNode` | Rendered after the fields. The function form gets `{ values, patch, dirty, submitting, error, fieldErrors, 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`. +Fields hidden by `showWhen` aren't rendered, and their stored values stay in the document. + +#### Validation + +`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`. + +Some rules need the server, so they still surface as a save's errors: + +- custom `validate` functions and Standard Schemas; +- `unique`; +- relation targets that must exist; +- `preValidate` hooks; +- access. + +Put the save's `fieldErrors` in `errors`. A message in `errors` replaces the form's own for that field. + +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. + +`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: + +```tsx validate=type +import { isSafeRedirectTarget } from '@tanstack/cms-core' +import { DocForm } from '@tanstack/cms-ui-react/primitives' +import type { Doc } from '@tanstack/cms-core' + +export function RedirectForm({ redirect, save }: { redirect: Doc; save: (patch: Doc) => Promise }) { + return ( + + schemaError ?? + (isSafeRedirectTarget(value) ? undefined : 'Must be a path starting with / or an http(s) URL'), + }} + onSubmit={(patch) => save(patch)} + > + + + ) +} +``` + +When you render `editor.form.Field` yourself instead of `DocForm`, pass `validators={editor.validatorsFor(name)}` to get the same checks. 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`: @@ -455,7 +501,7 @@ 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 (also exported from `@tanstack/cms-core`). +`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`). #### With the core editor store diff --git a/docs/schema/collections-and-fields.md b/docs/schema/collections-and-fields.md index 650b93f0..ec7eb708 100644 --- a/docs/schema/collections-and-fields.md +++ b/docs/schema/collections-and-fields.md @@ -374,6 +374,8 @@ export const event = defineCollection({ Failures throw a `CmsError` with code `VALIDATION_FAILED` (HTTP 422) and `details: Array<{ path: Array, message: string }>`, which the admin maps back onto the fields. +`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`. + ## Conditional fields 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({ ## 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: +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: ```tsx validate=type import { DocForm } from '@tanstack/cms-ui-react/primitives' @@ -781,6 +783,7 @@ These client-safe helpers from `@tanstack/cms-core` read the registered config: | `blockTypes()` / `blockTypeMap()` | The block palette as an array / keyed by `type` | | `schemaFor(collection)` | Zod object for a full document, including system metadata | | `scalarSchemaFor(collection)` | Zod object without `blocks` fields (for AI structured output) | +| `schemaIssues(collection, doc)` | The `{ path, message }` issues a write would report from the schema (see [Validation](#validation)) | | `emptyDoc(collection)` / `emptyBlock(type)` / `emptyArrayItem(field)` | New values with every field defaulted | | `fillDerivedFields(collection, doc)` | Fills empty `slug` fields from their source | | `slugify(text, { nested? })` | Lowercase kebab-case (`"Héllo, World!"` → `"hello-world"`); with `nested`, per `/` segment | diff --git a/examples/blog/e2e/editor.spec.ts b/examples/blog/e2e/editor.spec.ts index 7aa4a767..4dc0c02b 100644 --- a/examples/blog/e2e/editor.spec.ts +++ b/examples/blog/e2e/editor.spec.ts @@ -117,6 +117,55 @@ test('validation errors appear next to the field', async ({ ) }) +test('a save the schema rejects stays in the browser until it is fixed', async ({ + page, + context, +}) => { + await signInAs(context, 'admin') + const id = 'e2e-client-check' + const created = await page.request.post('/api/cms/v1/ops/createDoc', { + data: { + collection: 'redirect', + id, + doc: { from: '/e2e-client', to: '/post/hello-world', permanent: true }, + }, + }) + expect(created.status()).toBe(200) + + await open(page, `/edit/redirect/${id}`) + const sent: Array = [] + page.on('request', (request) => { + if (request.method() === 'POST' && request.postData()?.includes(id)) { + sent.push(request.url()) + } + }) + const to = page.getByRole('textbox', { name: /^To \(path or URL\)/ }) + const error = page.locator('[data-field-error="to"]') + + await to.fill('') + await to.blur() + await expect(error).toHaveText('To (path or URL) is required') + + await page.getByRole('button', { name: SAVE }).click() + await expect(page.getByRole('alert')).toContainText( + 'Fix the highlighted fields', + ) + await expect(error).toHaveText('To (path or URL) is required') + expect(sent).toEqual([]) + expect((await getDoc(page.request, 'redirect', id)).to).toBe( + '/post/hello-world', + ) + + await to.fill('/post/fixed') + await to.blur() + await expect(error).toHaveCount(0) + await expect(page.getByRole('alert')).toHaveCount(0) + await page.getByRole('button', { name: SAVE }).click() + await expect(page.getByText(/(Saved|Published) ✓/).first()).toBeVisible() + expect(sent.length).toBeGreaterThan(0) + expect((await getDoc(page.request, 'redirect', id)).to).toBe('/post/fixed') +}) + test('scheduling stores the local time as UTC', async ({ page, context }) => { await signInAs(context, 'admin') await createDocument(page, 'post', 'E2E scheduled') diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b956d92e..52bfbb5b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -438,6 +438,11 @@ export type { CreateDocEditorOptions, } from './lib/doc-editor' +// The schema's document checks (client-safe): the write path runs them, and +// so can a form before it saves. +export { schemaIssues } from './lib/validation' +export type { SchemaIssue } from './lib/validation' + // Lightweight, framework-agnostic feature flags (client-safe). Resolve on the // server from the request session, ship the booleans, read them via the store. export { flagEnabled, resolveFlags, createFlagsStore } from './flags' diff --git a/packages/core/src/lib/validation.ts b/packages/core/src/lib/validation.ts new file mode 100644 index 00000000..07be7d76 --- /dev/null +++ b/packages/core/src/lib/validation.ts @@ -0,0 +1,130 @@ +/** + * The document checks the schema alone decides. The server's write path runs + * them on every write, and form validation in the browser runs the same + * functions, so the two can't disagree. + */ +import { contentLocales } from '../config' +import { isLocalizedValue, primaryLocaleValue } from '../i18n' +import { + blockTypeMap, + fillDerivedFields, + isFieldVisible, + schemaFor, +} from '../schema' +import type { Collection, Doc, Field, JsonValue } from '../schema' + +/** A failed check: the value's path from the document root, and why. */ +export interface SchemaIssue { + path: Array + message: string +} + +/** A field's value somewhere in a document. */ +export interface FieldValueVisit { + field: Field + value: JsonValue | undefined + path: Array +} + +/** Whether a value counts as "empty" for a `required` check. */ +export function isEmptyFieldValue(v: JsonValue | undefined): boolean { + if (v === undefined || v === null || v === '') return true + if (Array.isArray(v)) return v.length === 0 + return false +} + +/** + * Every field value a document shows, at any depth (groups, array items, + * blocks), parents before their sub-fields. A field hidden by `showWhen` is + * skipped with everything under it. A localized value is its default + * locale's entry: a missing translation falls back on read. + */ +export function visibleFieldValues( + fields: ReadonlyArray, + doc: Record | undefined, +): Array { + const out: Array = [] + const walk = ( + list: ReadonlyArray, + value: Record | undefined, + path: Array, + ): void => { + for (const f of list) { + if (f.showWhen && !isFieldVisible(f, value as Doc | undefined)) continue + let v = value?.[f.name] as JsonValue | undefined + const at = [...path, f.name] + if (f.localized && isLocalizedValue(v)) { + v = primaryLocaleValue(v, contentLocales()?.defaultLocale ?? 'en') as + | JsonValue + | undefined + } + out.push({ field: f, value: v, path: at }) + if (f.type === 'group' && f.fields && v && typeof v === 'object') { + walk(f.fields, v as Record, at) + } + if (f.type === 'array' && f.fields && Array.isArray(v)) { + for (const [i, item] of v.entries()) { + walk(f.fields, item as Record, [...at, String(i)]) + } + } + if (f.type === 'blocks' && Array.isArray(v)) { + const types = blockTypeMap() + for (const [i, block] of v.entries()) { + if (!block || typeof block !== 'object' || Array.isArray(block)) + continue + const b = block as Record + const typeName = + typeof b._type === 'string' + ? b._type + : typeof b.type === 'string' + ? b.type + : undefined + const bt = typeName ? types[typeName] : undefined + if (bt) walk(bt.fields, b, [...at, String(i)]) + } + } + } + } + walk(fields, doc, []) + return out +} + +/** + * `required` on a visible conditional field. The Zod schema relaxes it, + * because only the sibling values decide whether the field is shown. + */ +export function conditionalRequiredIssue( + visit: FieldValueVisit, +): SchemaIssue | undefined { + const { field, value, path } = visit + if (!field.showWhen || field.required !== true) return undefined + if (!isEmptyFieldValue(value)) return undefined + return { path, message: `${field.label} is required` } +} + +/** + * What the server's schema checks report for a document: types, `required`, + * `min`/`max`, formats (slug, email, url, color), options, and `required` on + * visible conditional fields, after the same derived-field fill (a slug from + * its source field). The rules only the server can run aren't here: custom + * `validate`, relation targets, `unique`, hooks, and access. + */ +export function schemaIssues( + collection: Collection, + doc: Record, +): Array { + const filled = fillDerivedFields(collection, doc) + const parsed = schemaFor(collection).safeParse(filled) + const issues: Array = parsed.success + ? [] + : parsed.error.issues.map((i) => ({ + path: i.path.map(String), + message: i.message, + })) + const checked = parsed.success ? (parsed.data as Doc) : filled + for (const visit of visibleFieldValues(collection.fields, checked)) { + const issue = conditionalRequiredIssue(visit) + if (issue) issues.push(issue) + } + return issues +} diff --git a/packages/core/src/server/store/internal.ts b/packages/core/src/server/store/internal.ts index faed3618..9fbaa9f0 100644 --- a/packages/core/src/server/store/internal.ts +++ b/packages/core/src/server/store/internal.ts @@ -6,16 +6,17 @@ * Server-only. */ import { randomUUID } from 'node:crypto' -import { cmsLogger, contentLocales, getCmsConfig } from '../../config' +import { cmsLogger, getCmsConfig } from '../../config' import { CmsError } from '../../errors' import { - blockTypeMap, fillDerivedFields, isCollectionReadOnly, - isFieldVisible, schemaFor, } from '../../schema' -import { isLocalizedValue, primaryLocaleValue } from '../../i18n' +import { + conditionalRequiredIssue, + visibleFieldValues, +} from '../../lib/validation' import { stampContentVersion, upgradeStoredDoc } from '../content-migrations' import { denormalize } from '../indexing' import { commitEvents, emitCmsEvent, stayedLive } from '../events' @@ -258,17 +259,11 @@ export function isScalarField(field: Field | undefined): boolean { return SCALAR_TYPES.has(field.type) } -/** Whether a value counts as "empty" for a `required` check. */ -function isEmptyFieldValue(v: JsonValue | undefined): boolean { - if (v === undefined || v === null || v === '') return true - if (Array.isArray(v)) return v.length === 0 - return false -} - /** - * Server-side field rules the Zod schema can't express: custom `validate` - * functions / Standard Schemas (at any depth), relation targets that must - * exist (at any depth), and top-level `unique`. + * Field rules the Zod schema can't express: `required` on visible conditional + * fields, custom `validate` functions / Standard Schemas (at any depth), and + * the server-only relation targets that must exist (at any depth) and + * top-level `unique`. */ export async function checkFieldRules( storage: StorageOps, @@ -279,65 +274,15 @@ export async function checkFieldRules( ): Promise { const issues: Array = [] const ctx = { doc, id, collection: collection.name } - const walk = async ( - fields: ReadonlyArray, - value: Record | undefined, - path: Array, - ): Promise => { - for (const f of fields) { - let v = value?.[f.name] as JsonValue | undefined - const at = [...path, f.name] - // A hidden conditional field is not validated at all: skip its - // `required`, `validate`, and any nested sub-field checks. - if (f.showWhen && !isFieldVisible(f, value as Doc | undefined)) continue - // A localized field validates against its default (primary) locale: a - // missing non-default translation is allowed (it falls back on read). - if (f.localized && isLocalizedValue(v)) { - v = primaryLocaleValue(v, contentLocales()?.defaultLocale ?? 'en') as - | JsonValue - | undefined - } - // `required` for conditional fields is enforced here (the base Zod - // schema relaxed it so a hidden field can never block a save). - if (f.showWhen && f.required === true && isEmptyFieldValue(v)) { - issues.push({ path: at, message: `${f.label} is required` }) - } - if (f.validate && options?.validators !== false) { - const message = await runValidator(f.validate, v, ctx) - if (message) issues.push({ path: at, message }) - } - if (f.type === 'group' && f.fields && v && typeof v === 'object') { - await walk(f.fields, v as Record, at) - } - if (f.type === 'array' && f.fields && Array.isArray(v)) { - for (const [i, item] of v.entries()) { - await walk(f.fields, item as Record, [ - ...at, - String(i), - ]) - } - } - if (f.type === 'blocks' && Array.isArray(v)) { - const types = blockTypeMap() - for (const [i, block] of v.entries()) { - if (!block || typeof block !== 'object' || Array.isArray(block)) - continue - const b = block as Record - const typeName = - typeof b._type === 'string' - ? b._type - : typeof b.type === 'string' - ? b.type - : undefined - const bt = typeName ? types[typeName] : undefined - if (bt) { - await walk(bt.fields, b, [...at, String(i)]) - } - } - } + for (const visit of visibleFieldValues(collection.fields, doc)) { + const required = conditionalRequiredIssue(visit) + if (required) issues.push(required) + const { field: f, value: v, path: at } = visit + if (f.validate && options?.validators !== false) { + const message = await runValidator(f.validate, v, ctx) + if (message) issues.push({ path: at, message }) } } - await walk(collection.fields, doc, []) issues.push(...(await relationIssues(storage, collection, doc))) issues.push(...(await uniqueIssues(storage, collection, id, doc))) issues.push(...(await locatorIssues(storage, collection, id, doc))) diff --git a/packages/core/tests/validation.test.ts b/packages/core/tests/validation.test.ts new file mode 100644 index 00000000..c481d513 --- /dev/null +++ b/packages/core/tests/validation.test.ts @@ -0,0 +1,175 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { defineCms, emptyDoc, schemaIssues } from '../src/index' +import { closeStore, commitDocument } from '../src/server' +import type { Collection, Doc } from '../src/index' + +const dirs: Array = [] + +afterEach(async () => { + await closeStore() + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +const offer: Collection = { + name: 'offer', + label: 'Offers', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text', required: true, max: 12 }, + { name: 'handle', label: 'Handle', type: 'slug', required: true }, + { name: 'contact', label: 'Contact', type: 'email' }, + { name: 'brand', label: 'Brand', type: 'color' }, + { name: 'seats', label: 'Seats', type: 'number', min: 1, max: 5 }, + { + name: 'kind', + label: 'Kind', + type: 'select', + options: ['internal', 'external'], + required: true, + }, + { + name: 'href', + label: 'Link', + type: 'url', + required: true, + showWhen: { field: 'kind', equals: 'external' }, + }, + { + name: 'tags', + label: 'Tags', + type: 'multiselect', + options: ['a', 'b', 'c'], + max: 2, + }, + { + name: 'cta', + label: 'CTA', + type: 'group', + fields: [ + { name: 'style', label: 'Style', type: 'text' }, + { + name: 'variant', + label: 'Variant', + type: 'text', + required: true, + showWhen: { field: 'style', equals: 'button' }, + }, + ], + }, + { + name: 'code', + label: 'Code', + type: 'text', + validate: (v) => (v === 'nope' ? 'Not that code' : undefined), + }, + ], +} + +function setup() { + const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-validation-')) + dirs.push(dataDir) + defineCms({ dataDir, collections: [offer], blockTypes: [] }) +} + +const valid: Doc = { + ...emptyDoc(offer), + title: 'Spring', + handle: 'spring', + kind: 'internal', + seats: 2, +} + +async function serverIssues(id: string, doc: Doc) { + try { + await commitDocument('offer', id, doc) + return [] + } catch (e) { + const err = e as { + code: string + details: Array<{ path: Array; message: string }> + } + expect(err.code).toBe('VALIDATION_FAILED') + return err.details + } +} + +describe('schemaIssues', () => { + it('accepts a valid document', () => { + setup() + expect(schemaIssues(offer, valid)).toEqual([]) + }) + + it('reports the server messages for the built-in rules', () => { + setup() + expect( + schemaIssues(offer, { + ...valid, + title: '', + contact: 'nobody', + brand: 'blue', + seats: 9, + tags: ['a', 'b', 'c'], + }), + ).toEqual([ + { path: ['title'], message: 'Title is required' }, + { path: ['contact'], message: 'Enter a valid email address' }, + { path: ['brand'], message: 'Enter a hex color like #1d4ed8' }, + { path: ['seats'], message: 'Too big: expected number to be <=5' }, + { path: ['tags'], message: 'Too big: expected array to have <=2 items' }, + ]) + }) + + it('fills derived fields first, as the server does', () => { + setup() + expect(schemaIssues(offer, { ...valid, handle: '' })).toEqual([]) + expect(schemaIssues(offer, { ...valid, title: '', handle: '' })).toEqual([ + { path: ['title'], message: 'Title is required' }, + { path: ['handle'], message: 'Handle is required' }, + ]) + }) + + it('checks required on visible conditional fields only', () => { + setup() + expect(schemaIssues(offer, { ...valid, href: '' })).toEqual([]) + expect(schemaIssues(offer, { ...valid, kind: 'external' })).toEqual([ + { path: ['href'], message: 'Link is required' }, + ]) + expect( + schemaIssues(offer, { ...valid, cta: { style: 'button', variant: '' } }), + ).toEqual([{ path: ['cta', 'variant'], message: 'Variant is required' }]) + }) + + it('leaves custom validate to the server', () => { + setup() + expect(schemaIssues(offer, { ...valid, code: 'nope' })).toEqual([]) + }) + + it('agrees with a server write', async () => { + setup() + const cases: Array = [ + valid, + { ...valid, title: '' }, + { ...valid, title: 'A title far too long' }, + { ...valid, handle: 'Not A Slug' }, + { ...valid, handle: '', title: 'Derived Handle' }, + { ...valid, contact: 'x@' }, + { ...valid, seats: 0 }, + { ...valid, kind: 'other' }, + { ...valid, tags: ['a', 'z'] }, + { ...valid, kind: 'external', href: '' }, + { ...valid, kind: 'external', href: 'https://example.com' }, + { ...valid, kind: 'external', href: 'ftp://example.com' }, + { ...valid, cta: { style: 'button', variant: '' } }, + { ...valid, cta: { style: 'plain', variant: '' } }, + ] + for (const [i, doc] of cases.entries()) { + const server = await serverIssues(`o${i}`, doc) + expect(schemaIssues(offer, doc), JSON.stringify(doc)).toEqual( + server.map(({ path, message }) => ({ path, message })), + ) + } + }) +}) diff --git a/packages/ui-react/src/components/editor/doc-form.tsx b/packages/ui-react/src/components/editor/doc-form.tsx index 5780d315..da633d12 100644 --- a/packages/ui-react/src/components/editor/doc-form.tsx +++ b/packages/ui-react/src/components/editor/doc-form.tsx @@ -11,8 +11,10 @@ import { docPatch, emptyDoc, isFieldVisible, + schemaIssues, } from '@tanstack/cms-core' import { requireCollection } from '../../lib/collection' +import { fieldErrorsFromIssues } from '../../lib/editor-errors' import { FieldInput } from './field-input' import type { FieldAccessContext, @@ -47,6 +49,30 @@ export interface DocFormSubmitContext { meta: TMeta | undefined } +/** What a `fieldValidators` entry receives. */ +export interface DocFormFieldValidatorArgs { + value: JsonValue | undefined + /** The whole document being validated. */ + doc: Doc + field: Field + /** + * The schema check's message for this field, or `undefined` when it passes + * or `validate` is `false`. + */ + schemaError: string | undefined +} + +/** Returns the field's message, or nothing when the value is fine. */ +export type DocFormFieldValidator = ( + args: DocFormFieldValidatorArgs, +) => string | null | undefined + +/** The validators `useDocForm` gives a top-level field's `form.Field`. */ +export interface DocFormFieldValidators { + /** TanStack Form also runs `onBlur` validators on submit. */ + onBlur: (props: { value: unknown }) => string | undefined +} + export interface UseDocFormOptions { /** The collection's name, as for every primitive. */ collection: string @@ -70,6 +96,18 @@ export interface UseDocFormOptions { * bound through `createRoutes(definition, { renderers })`. */ renderers?: CmsRenderers + /** + * Check each field against the collection schema on blur and on submit, + * with the rules the server applies (`schemaIssues` from core). A submit + * that fails them doesn't call `onSubmit`. `false` turns the schema checks + * off; `fieldValidators` still run. Default `true`. + */ + validate?: boolean + /** + * Checks by top-level field name, run instead of the schema check, whose + * message they receive as `schemaError`. `false` turns a field's checks off. + */ + fieldValidators?: Readonly> /** * Receives the changed top-level fields. A throw or rejection marks the * submit failed and keeps the baseline; otherwise the submitted document @@ -115,8 +153,20 @@ export interface DocFormApi { submitting: boolean /** What the last failed submit threw, or `null`. */ error: unknown - /** Calls `onSubmit` with the patch. Resolves `true` when it succeeded. */ + /** The fields' validation messages, by top-level field name. */ + fieldErrors: Record + /** + * Validates the fields, then calls `onSubmit` with the patch. Resolves + * `true` when it succeeded, and `false` when validation or `onSubmit` + * failed. + */ submit: (meta?: TMeta) => Promise + /** + * The `validators` for a top-level field's `form.Field`, or `undefined` + * when it has none. `DocForm` attaches them; pass them yourself when you + * render `api.form.Field`. + */ + validatorsFor: (name: string) => DocFormFieldValidators | undefined /** Back to the baseline, or to `doc`, which also becomes the baseline. */ reset: (doc?: Doc) => void setValue: (name: string, value: JsonValue) => void @@ -199,7 +249,54 @@ export function useDocForm( const values = useStore(form.store, (s) => s.values) as Doc const submitting = useStore(form.store, (s) => s.isSubmitting) + const fieldMeta = useStore(form.store, (s) => s.fieldMeta) const patch = useMemo(() => docPatch(baseline, values), [baseline, values]) + const fieldErrors = useMemo(() => { + const out: Record = {} + for (const [name, meta] of Object.entries(fieldMeta)) { + const message = firstError(meta?.errors ?? []) + if (message) out[name] = message + } + return out + }, [fieldMeta]) + + // Every field's validator checks the same values on submit: parse once. + const checked = useRef<{ + values: unknown + collection: Collection + errors: Record + } | null>(null) + const schemaErrors = (doc: Doc) => { + const last = checked.current + if (last && last.values === doc && last.collection === collection) { + return last.errors + } + const errors = fieldErrorsFromIssues(schemaIssues(collection, doc)) + checked.current = { values: doc, collection, errors } + return errors + } + + const validatorsFor = (name: string): DocFormFieldValidators | undefined => { + const { validate = true, fieldValidators } = optionsRef.current + const custom = fieldValidators?.[name] + const field = collection.fields.find((f) => f.name === name) + if (!field || custom === false || (!validate && !custom)) return undefined + return { + onBlur: ({ value }) => { + const doc = form.state.values as Doc + const schemaError = validate ? schemaErrors(doc)[name] : undefined + if (!custom) return schemaError + return ( + custom({ + value: value as JsonValue | undefined, + doc, + field, + schemaError, + }) || undefined + ) + }, + } + } return { form, @@ -211,10 +308,16 @@ export function useDocForm( dirty: !isEmpty(patch), submitting, error, + fieldErrors, + validatorsFor, submit: async (meta) => { metaRef.current = meta setError(null) try { + // Re-check first: a value set without a blur may have fixed (or + // broken) a field, and a form already marked invalid would skip its + // first submit's validation. + await form.validateAllFields('blur') await form.handleSubmit() return form.state.isSubmitSuccessful } catch (e) { @@ -245,6 +348,7 @@ export type DocFormState = Pick< | 'dirty' | 'submitting' | 'error' + | 'fieldErrors' | 'submit' | 'reset' | 'setValue' @@ -344,6 +448,7 @@ function DocFormView({ dirty: api.dirty, submitting: api.submitting, error: api.error, + fieldErrors: api.fieldErrors, submit: api.submit, reset: api.reset, setValue: api.setValue, @@ -369,9 +474,24 @@ function DocFormView({ const writable = !access || canWriteField(f, access.session, accessDoc) return ( - + {(field) => ( -
+
{ + const next = e.relatedTarget as Node | null + if (!e.currentTarget.contains(next)) field.handleBlur() + }} + > ) : null + // One tree with or without a message: an error appearing on blur must not + // remount the control the user is moving into. if (!props.disabled) { - if (!errorMessage) return return (
diff --git a/packages/ui-react/src/lib/editor-errors.ts b/packages/ui-react/src/lib/editor-errors.ts index 5d9fa053..b1f63c49 100644 --- a/packages/ui-react/src/lib/editor-errors.ts +++ b/packages/ui-react/src/lib/editor-errors.ts @@ -41,6 +41,24 @@ function issuesFromMessage(message: string): Array { }) } +/** Issues keyed by top-level field name, nested paths folded into the message. */ +export function fieldErrorsFromIssues( + issues: ReadonlyArray, +): Record { + const fieldErrors: Record = {} + for (const issue of issues) { + const [name, ...rest] = issue.path + if (!name) continue + const text = rest.length + ? `${rest.join('.')}: ${issue.message}` + : issue.message + fieldErrors[name] = fieldErrors[name] + ? `${fieldErrors[name]}; ${text}` + : text + } + return fieldErrors +} + export function editorError(e: unknown, fallback: string): EditorError { const message = e instanceof Error && e.message ? e.message : fallback const raw = e as { code?: unknown; details?: unknown } | null @@ -53,16 +71,5 @@ export function editorError(e: unknown, fallback: string): EditorError { const issues = isIssueList(raw?.details) ? raw.details : issuesFromMessage(message) - const fieldErrors: Record = {} - for (const issue of issues) { - const [name, ...rest] = issue.path - if (!name) continue - const text = rest.length - ? `${rest.join('.')}: ${issue.message}` - : issue.message - fieldErrors[name] = fieldErrors[name] - ? `${fieldErrors[name]}; ${text}` - : text - } - return { message, code, fieldErrors } + return { message, code, fieldErrors: fieldErrorsFromIssues(issues) } } diff --git a/packages/ui-react/src/primitives.ts b/packages/ui-react/src/primitives.ts index 5ee09455..a07ca499 100644 --- a/packages/ui-react/src/primitives.ts +++ b/packages/ui-react/src/primitives.ts @@ -45,6 +45,9 @@ export type { DocFormApi, DocFormFieldRenderer, DocFormFieldRenderers, + DocFormFieldValidator, + DocFormFieldValidatorArgs, + DocFormFieldValidators, DocFormInstance, DocFormProps, DocFormState, diff --git a/packages/ui-react/src/routes/edit.$collection.$id.tsx b/packages/ui-react/src/routes/edit.$collection.$id.tsx index 3dd18783..c2cb89c3 100644 --- a/packages/ui-react/src/routes/edit.$collection.$id.tsx +++ b/packages/ui-react/src/routes/edit.$collection.$id.tsx @@ -333,6 +333,9 @@ function DocumentEditor({ collection }: { collection: Collection }) { const [proposed, setProposed] = useState(null) const [confirmingDelete, setConfirmingDelete] = useState(false) const [previewShared, setPreviewShared] = useState(false) + /** The last save stopped at the form's own checks. */ + const [blocked, setBlocked] = useState(false) + const invalid = blocked && Object.keys(form.fieldErrors).length > 0 const offers = (type: string) => actions.some((a) => a.type === type) /** Edits to a live document are drafts until explicitly published. */ @@ -373,7 +376,8 @@ function DocumentEditor({ collection }: { collection: Collection }) { /** Every save goes through the form, so its validators gate it. */ async function onSave(meta: SaveMeta = {}) { - await form.submit(meta) + const saved = await form.submit(meta) + setBlocked(!saved && !form.form.state.isFieldsValid) } async function onReloadLatest() { @@ -749,6 +753,14 @@ function DocumentEditor({ collection }: { collection: Collection }) {
)} + {!error && invalid && ( +
+ {adminT('editor.fieldErrors')} +
+ )} { }) }) +describe('DocForm validation', () => { + const fieldError = (container: HTMLElement, name: string) => + container.querySelector(`[data-field-error="${name}"]`)?.textContent ?? null + + function SaveButton() { + return + } + + const save = () => + act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + }) + + it('checks a field against the schema on blur', () => { + const { container } = render( + {}} />, + ) + fireEvent.change(labelInput(), { target: { value: '' } }) + expect(fieldError(container, 'label')).toBeNull() + fireEvent.focusOut(labelInput()) + expect(fieldError(container, 'label')).toBe('Label is required') + + fireEvent.change(labelInput(), { target: { value: 'Guides' } }) + fireEvent.focusOut(labelInput()) + expect(fieldError(container, 'label')).toBeNull() + }) + + it('blocks a failing submit, then submits once the field is fixed', async () => { + const onSubmit = vi.fn() + const { container } = render( + + {({ fieldErrors }) => ( + <> + {JSON.stringify(fieldErrors)} + + + )} + , + ) + const url = () => screen.getByLabelText('External URL') + fireEvent.change(url(), { target: { value: 'not a url' } }) + await save() + expect(onSubmit).not.toHaveBeenCalled() + const message = 'Enter an http(s) URL or a path starting with /' + expect(fieldError(container, 'externalUrl')).toBe(message) + expect(screen.getByTestId('errors').textContent).toBe( + JSON.stringify({ externalUrl: message }), + ) + + fireEvent.change(url(), { target: { value: 'https://example.com' } }) + await save() + expect(onSubmit).toHaveBeenCalledTimes(1) + expect(onSubmit.mock.calls[0]![0]).toEqual({ + externalUrl: 'https://example.com', + }) + expect(fieldError(container, 'externalUrl')).toBeNull() + }) + + it('keeps the control the user is in when its error appears', () => { + const { container } = render( + {}} />, + ) + const input = labelInput() + fireEvent.change(input, { target: { value: '' } }) + fireEvent.focusOut(input) + expect(fieldError(container, 'label')).toBe('Label is required') + expect(labelInput()).toBe(input) + }) + + it('checks an array when focus leaves it, not when it moves between its inputs', () => { + const menu: Collection = { + name: 'menu', + label: 'Menus', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { + name: 'items', + label: 'Items', + type: 'array', + fields: [ + { name: 'name', label: 'Name', type: 'text', required: true }, + { name: 'href', label: 'Href', type: 'text' }, + ], + }, + ], + } + defineCms({ collections: [link, menu], blockTypes: [] }) + const { container } = render( + {}} + />, + ) + const name = screen.getByLabelText('Name*') + const href = screen.getByLabelText('Href') + fireEvent.focusOut(name, { relatedTarget: href }) + expect(fieldError(container, 'items')).toBeNull() + fireEvent.focusOut(href, { relatedTarget: screen.getByLabelText('Title') }) + expect(fieldError(container, 'items')).toBe('0.name: Name is required') + }) + + it('re-checks values set without a blur before it submits', async () => { + const onSubmit = vi.fn() + let submitted: Array = [] + function Editor() { + const editor = useDocForm({ + collection: 'link', + defaultValue: stored, + onSubmit, + }) + return ( + <> + + + + + + ) + } + render() + const click = (name: string) => + act(async () => { + fireEvent.click(screen.getByRole('button', { name })) + }) + await click('Clear') + await click('Submit') + await click('Fix') + await click('Submit') + expect(submitted).toEqual([false, true]) + expect(onSubmit).toHaveBeenCalledTimes(1) + expect(onSubmit.mock.calls[0]![0]).toEqual({ label: 'Fixed' }) + }) + + it('skips fields hidden by showWhen and fields the session cannot write', async () => { + const onSubmit = vi.fn() + render( + + + , + ) + fireEvent.change(labelInput(), { target: { value: 'Guides' } }) + await save() + expect(onSubmit).toHaveBeenCalledTimes(1) + }) + + it('shows the errors prop over its own message', () => { + const { container } = render( + {}} + />, + ) + fireEvent.change(labelInput(), { target: { value: '' } }) + fireEvent.focusOut(labelInput()) + expect(fieldError(container, 'label')).toBe('Taken on the server') + }) + + it('turns the schema checks off with validate={false}', async () => { + const onSubmit = vi.fn() + const { container } = render( + + + , + ) + fireEvent.change(labelInput(), { target: { value: '' } }) + fireEvent.focusOut(labelInput()) + expect(fieldError(container, 'label')).toBeNull() + await save() + expect(onSubmit).toHaveBeenCalledWith({ label: '' }, expect.anything()) + }) + + it('runs fieldValidators in place of a field’s schema check', async () => { + const onSubmit = vi.fn() + const seen: Array = [] + const { container } = render( + { + seen.push([field.name, doc.clicks, schemaError]) + if (schemaError) return `${schemaError}, please` + return value === 'Docs!' ? 'No exclamation marks' : undefined + }, + externalUrl: false, + }} + onSubmit={onSubmit} + > + + , + ) + fireEvent.change(labelInput(), { target: { value: '' } }) + fireEvent.focusOut(labelInput()) + expect(fieldError(container, 'label')).toBe('Label is required, please') + expect(seen[0]).toEqual(['label', 3, 'Label is required']) + + fireEvent.change(labelInput(), { target: { value: 'Docs!' } }) + await save() + expect(fieldError(container, 'label')).toBe('No exclamation marks') + expect(onSubmit).not.toHaveBeenCalled() + + fireEvent.change(screen.getByRole('combobox'), { + target: { value: 'external' }, + }) + fireEvent.change(screen.getByLabelText('External URL'), { + target: { value: 'not a url' }, + }) + fireEvent.change(labelInput(), { target: { value: 'Docs' } }) + await save() + expect(onSubmit).toHaveBeenCalledTimes(1) + }) +}) + describe('DocForm renderers', () => { const product: Collection = { name: 'product',