diff --git a/docs/guide/pages-routing/actions-and-forms.md b/docs/guide/pages-routing/actions-and-forms.md index ff46fa30a..dfcf47a46 100644 --- a/docs/guide/pages-routing/actions-and-forms.md +++ b/docs/guide/pages-routing/actions-and-forms.md @@ -153,7 +153,7 @@ The types are inferred from your action's `withValidator()` schema in the compan | Property / Method | Purpose | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data` / `setData` | Current form values, typed to match the action's body schema. | -| `errors` | Field-level validation errors, keys typed to body field names. | +| `errors` | Field-level validation errors, keyed by body field and by nested paths such as `profile.name` or `contacts.0.email`. | | `error` | Action error, or `null`. | | `throwOnError` (option) | Set to `false` to keep authentication and server failures in `form.error` instead of throwing them. | | `post`, `put`, `patch`, `delete` | Submit the form with that method. In React these are native form action callbacks. | @@ -163,11 +163,11 @@ The types are inferred from your action's `withValidator()` schema in the compan | `recentlySuccessful` | `true` for 2 seconds after a successful submission. Useful for flash messages. | | `reset(...fields)` | Reset form data to the current defaults (last submitted values after success). Field names autocomplete. Pass `{ initial: true }` first to reset to the values passed to `useForm`. | | `resetOnSuccess` (option) | When `true`, a successful submit resets defaults to the mount-time values, and form data too unless it was edited during the submit. Useful for create forms that should clear after save. | -| `setError(field, message)` | Set a client-side validation error on a field. | -| `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. | +| `setError(field, message)` | Set a client-side validation error on a field, including a nested path such as `profile.name`. | +| `clearErrors(...fields)` | Clear validation errors. Field names autocomplete. Clearing a parent field also clears the errors of its nested fields. | | `clearError()` | Clear `error`. | -Use `setError()` for client-side validation. Editing a field clears its error automatically. +Use `setError()` for client-side validation. Editing a value clears its error and the errors of the nested values that changed with it. Fields you did not change keep their errors. For a native React form, use `form.post`, `form.put`, `form.patch`, or `form.delete` as a native form action. For an awaitable mutation, use `action()`. In Vue, Svelte, and Solid, form submissions return `Promise`; catch thrown errors or use your framework's error handling. diff --git a/packages/react/src/runtime/use-form.ts b/packages/react/src/runtime/use-form.ts index fdf55b190..fa078e31e 100644 --- a/packages/react/src/runtime/use-form.ts +++ b/packages/react/src/runtime/use-form.ts @@ -9,12 +9,15 @@ import { } from 'react'; import { VoidActionError, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, isCallSiteActionError, isEqualFormValue, + omitFormErrors, parseFormResetArgs, submitAction, type FormResetOptions, @@ -191,23 +194,20 @@ export function useForm( const setData = useCallback( (field: string, value: unknown) => { - const previousValue = dataRef.current[field]; - dataRef.current = { ...dataRef.current, [field]: value }; - setDataState(dataRef.current); - if (isEqualFormValue(previousValue, value)) { - return; - } + const previous = dataRef.current; + const next = { ...previous, [field]: value }; + dataRef.current = next; + setDataState(next); const target = callbackOutcomeRef.current ?? outcome; setErrorEdits((prev) => { const current = resolveOutcomeErrors(target, prev); - if (!(field in current)) { + const affected = changedFormErrorKeys(current, previous, next); + if (affected.length === 0) { return prev; } - const next = { ...current }; - delete next[field]; return { ...(prev?.source === target ? prev : { source: target }), - errors: next, + errors: omitFormErrors(current, affected), }; }); }, @@ -236,15 +236,14 @@ export function useForm( const clearErrors = useCallback( (...fields: ReadonlyArray) => { const target = callbackOutcomeRef.current ?? outcome; + const data = dataRef.current; setErrorEdits((prev) => { const base = prev?.source === target ? prev : { source: target }; if (fields.length === 0) { return { ...base, errors: EMPTY_ERRORS }; } - const next = { ...resolveOutcomeErrors(target, prev) }; - for (const field of fields) { - delete next[field]; - } + const current = resolveOutcomeErrors(target, prev); + const next = omitFormErrors(current, formErrorKeysWithin(current, fields, data)); return { ...base, errors: next }; }); }, diff --git a/packages/react/test/unit/use-form.test.ts b/packages/react/test/unit/use-form.test.ts index 8bca58a20..75df0caaf 100644 --- a/packages/react/test/unit/use-form.test.ts +++ b/packages/react/test/unit/use-form.test.ts @@ -22,6 +22,12 @@ import { useIslandForm, type IslandFormReturn } from '../../src/runtime/use-isla declare module 'void/routes' { interface PageActionMap { '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/__form-callbacks/notes': { actions: { create: { body: { title: string } } } }; + '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/__form-nested/contacts': { + body: { + profile: { name: string; email: string }; + contacts: Array<{ email: string }>; + }; + }; } } @@ -247,6 +253,60 @@ describe('useForm callbacks', () => { expect(formRef.current!.error).toBe(actionError); }); + it('clears only the errors of the fields a change touched', async () => { + type NestedForm = ReturnType>; + const formRef: { current: NestedForm | null } = { current: null }; + function App() { + formRef.current = useForm('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/__form-nested/contacts', { + profile: { name: '', email: '' }, + contacts: [{ email: '' }, { email: '' }], + }); + return null; + } + const router = routerWithVisit( + vi.fn(async () => ({ + errors: { + 'profile.name': 'Required name', + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', + title: 'Unrelated', + }, + })), + ); + await mountApp(createElement(RouterContext.Provider, { value: router }, createElement(App))); + const form = () => formRef.current!; + const submit = () => + act(async () => { + startTransition(() => { + form().post(new FormData()); + }); + }); + + await submit(); + await act(async () => { + form().setData('profile', { name: 'Alex', email: '' }); + }); + expect(form().errors['profile.name']).toBeUndefined(); + expect(form().errors['profile.email']).toBe('Required email'); + + await act(async () => { + form().setData('contacts', [{ email: '' }, { email: 'alex@example.com' }]); + }); + expect(form().errors['contacts.0.email']).toBe('First email'); + expect(form().errors['contacts.1.email']).toBeUndefined(); + + await act(async () => { + form().clearErrors('profile'); + }); + expect(form().errors).toEqual({ 'contacts.0.email': 'First email', title: 'Unrelated' }); + + await act(async () => { + form().clearErrors('contacts'); + }); + expect(form().errors).toEqual({ title: 'Unrelated' }); + }); + it('fires onSuccess on each successful submit', async () => { const onSuccess = vi.fn(); const { formRef } = await mountForm( @@ -803,3 +863,54 @@ describe('useForm state derivation and error management', () => { } }); }); + +declare module 'void/routes' { + interface PageActionMap { + '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/__form-optional/contacts': { + body: { contacts: Array<{ email: string } | undefined> }; + }; + } +} + +describe('error isolation', () => { + it.each([ + { + name: 'changes one row while an array-level and two row-level errors exist', + initial: [{ email: '' }, { email: '' }], + updated: [{ email: 'fixed@example.com' }, { email: '' }], + initialErrors: { + contacts: 'At least one valid email required', + 'contacts.0.email': 'First email required', + 'contacts.1.email': 'Second email required', + }, + expectedErrors: { 'contacts.1.email': 'Second email required' }, + }, + { + name: 'clears the array-level count error after adding an undefined slot', + initial: [undefined], + updated: [undefined, undefined], + initialErrors: { contacts: 'Add a second row' }, + expectedErrors: {}, + }, + ])('$name', async ({ initial, updated, initialErrors, expectedErrors }) => { + type OptionalForm = ReturnType>; + const formRef: { current: OptionalForm | null } = { current: null }; + function App() { + formRef.current = useForm('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/__form-optional/contacts', { contacts: initial }); + return null; + } + const router = routerWithVisit(async () => ({ errors: initialErrors })); + await mountApp(createElement(RouterContext.Provider, { value: router }, createElement(App))); + await act(async () => { + startTransition(() => { + formRef.current!.post(new FormData()); + }); + }); + expect(formRef.current!.errors).toEqual(initialErrors); + await act(async () => { + formRef.current!.setData('contacts', updated); + }); + expect(formRef.current!.data.contacts).toEqual(updated); + expect(formRef.current!.errors).toEqual(expectedErrors); + }); +}); diff --git a/packages/react/test/unit/use-form.typecheck.ts b/packages/react/test/unit/use-form.typecheck.ts index cad0ce449..91a9d8d91 100644 --- a/packages/react/test/unit/use-form.typecheck.ts +++ b/packages/react/test/unit/use-form.typecheck.ts @@ -1,13 +1,43 @@ -import { VoidActionError } from 'void/pages-client'; +import { VoidActionError, type FormState } from 'void/pages-client'; import { useForm } from '../../src/runtime/use-form.ts'; +export function checkGenericFieldHelpers( + form: FormState, + field: keyof T & string, +): string | undefined { + form.setError(field, 'Client-side'); + form.clearErrors(field); + return form.errors[field]; +} + declare module 'void/routes' { interface PageActionMap { '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/__form-options/notes': { actions: { create: { body: { title: string } } } }; '/__form-options/notes/:id': { body: { title: string }; params: { id: string } }; + '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/__form-options/nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('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/__form-options/nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.setError('profile.name', 'Required name'); + form.setError('contacts.0.email', 'Required email'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFormOptions(): void { useForm( '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/__form-options/notes?create', diff --git a/packages/solid/src/runtime/use-form.ts b/packages/solid/src/runtime/use-form.ts index 3f8cb3aff..966a62090 100644 --- a/packages/solid/src/runtime/use-form.ts +++ b/packages/solid/src/runtime/use-form.ts @@ -2,12 +2,15 @@ import { createSignal, createMemo, useContext } from 'solid-js'; import { createStore, reconcile } from 'solid-js/store'; import { VoidActionError, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, isCallSiteActionError, isEqualFormValue, + omitFormErrors, parseFormResetArgs, submitAction, type FormResetOptions, @@ -88,8 +91,18 @@ export function useForm( }); function setData(field: string, value: unknown) { + // The store can merge the new value into the existing object. Snapshot that field + // before the write and compare against what the store actually kept. + const previous = { ...data }; + if (Object.hasOwn(previous, field)) { + previous[field] = cloneFormValue(previous[field]); + } setDataStore(field, value); - clearErrors(field); + const current = errors(); + const affected = changedFormErrorKeys(current, previous, data); + if (affected.length > 0) { + replaceErrors(omitFormErrors(current, affected)); + } } function reset(...args: ReadonlyArray) { @@ -105,15 +118,12 @@ export function useForm( } function clearErrors(...fields: ReadonlyArray) { - if (fields.length === 0) { - replaceErrors({}); - } else { - const next = { ...errors() }; - for (const field of fields) { - delete next[field]; - } - replaceErrors(next); - } + const current = errors(); + replaceErrors( + fields.length === 0 + ? {} + : omitFormErrors(current, formErrorKeysWithin(current, fields, data)), + ); } function setFieldError(field: string, message: string) { diff --git a/packages/solid/test/unit/form-errors.test.ts b/packages/solid/test/unit/form-errors.test.ts index e6098acd4..cdc19bf15 100644 --- a/packages/solid/test/unit/form-errors.test.ts +++ b/packages/solid/test/unit/form-errors.test.ts @@ -10,6 +10,7 @@ vi.mock('solid-js/store', () => ); type TestForm = { + data: Readonly>; errors: Record; setData(field: string, value: unknown): void; setError(field: string, message: string): void; @@ -20,17 +21,17 @@ const useForm = typedUseForm as unknown as ( defaults: Record, ) => TestForm; -function createForm() { - const [serverErrors, setServerErrors] = createSignal({ - email: 'Invalid email', - name: 'Required', - }); +function createForm( + server: Record = { email: 'Invalid email', name: 'Required' }, + defaults: Record = { email: '', name: '' }, +) { + const [serverErrors, setServerErrors] = createSignal(server); let form!: TestForm; const dispose = createRoot((dispose) => { createComponent(ErrorsContext.Provider, { value: serverErrors, get children() { - form = useForm('/test', { email: '', name: '' }); + form = useForm('/test', defaults); return null; }, }); @@ -66,6 +67,56 @@ describe('useForm router errors', () => { } }); + it('clears only the errors of the fields a change touched', () => { + const { form, dispose } = createForm( + { + 'profile.name': 'Required name', + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', + name: 'Unrelated', + }, + { + profile: { name: '', email: '' }, + contacts: [{ email: '' }, { email: '' }], + }, + ); + try { + form.setData('profile', { name: 'Alex', email: '' }); + expect(form.errors).toEqual({ + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + 'contacts.1.email': 'Second email', + name: 'Unrelated', + }); + + form.setData('contacts', [{ email: '' }, { email: 'alex@example.com' }]); + expect(form.errors).toEqual({ + 'profile.email': 'Required email', + 'contacts.0.email': 'First email', + name: 'Unrelated', + }); + + form.clearErrors('profile'); + expect(form.errors).toEqual({ 'contacts.0.email': 'First email', name: 'Unrelated' }); + + form.setError('profile.name', 'Required name'); + expect(form.errors).toEqual({ + 'profile.name': 'Required name', + 'contacts.0.email': 'First email', + name: 'Unrelated', + }); + + form.clearErrors('contacts'); + expect(form.errors).toEqual({ 'profile.name': 'Required name', name: 'Unrelated' }); + + form.clearErrors(); + expect(form.errors).toEqual({}); + } finally { + dispose(); + } + }); + it('shows new server results after earlier errors were cleared', () => { const { form, setServerErrors, dispose } = createForm(); try { @@ -78,3 +129,45 @@ describe('useForm router errors', () => { } }); }); + +it('keeps an untouched row error when clearing its parent array error', () => { + const { form, dispose } = createForm( + { + contacts: 'At least one valid email required', + 'contacts.0.email': 'First email required', + 'contacts.1.email': 'Second email required', + }, + { contacts: [{ email: '' }, { email: '' }] }, + ); + try { + form.setData('contacts', [{ email: 'fixed@example.com' }, { email: '' }]); + expect(form.errors).toEqual({ 'contacts.1.email': 'Second email required' }); + } finally { + dispose(); + } +}); + +it('clears an array count error after adding an undefined entry', () => { + const { form, dispose } = createForm({ contacts: 'Add a second row' }, { contacts: [undefined] }); + try { + form.setData('contacts', [undefined, undefined]); + expect(form.data.contacts).toEqual([undefined, undefined]); + expect(form.errors).toEqual({}); + } finally { + dispose(); + } +}); + +it('keeps a nested error for an optional key preserved by the store merge', () => { + const { form, dispose } = createForm( + { 'profile.nickname': 'Nickname unavailable' }, + { profile: { name: '', nickname: 'Reserved name' } }, + ); + try { + form.setData('profile', { name: 'Alex' }); + expect(form.data.profile).toEqual({ name: 'Alex', nickname: 'Reserved name' }); + expect(form.errors).toEqual({ 'profile.nickname': 'Nickname unavailable' }); + } finally { + dispose(); + } +}); diff --git a/packages/solid/test/unit/form-errors.typecheck.ts b/packages/solid/test/unit/form-errors.typecheck.ts index 5849df88e..b302da404 100644 --- a/packages/solid/test/unit/form-errors.typecheck.ts +++ b/packages/solid/test/unit/form-errors.typecheck.ts @@ -4,9 +4,30 @@ import { useForm } from '../../src/runtime/use-form.ts'; declare module 'void/routes' { interface PageActionMap { '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/__form-errors/solid': { body: { email: string } }; + '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/__form-errors/solid-nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('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/__form-errors/solid-nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.setData('contacts', [{ email: 'alex@example.com' }]); + form.setError('profile.name', 'Required name'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFieldErrors(): void { const form = useForm('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/__form-errors/solid', { email: '' }); form.setError('email', 'Invalid email'); diff --git a/packages/svelte/src/runtime/use-form.svelte.ts b/packages/svelte/src/runtime/use-form.svelte.ts index f01e7533d..b40a7c2be 100644 --- a/packages/svelte/src/runtime/use-form.svelte.ts +++ b/packages/svelte/src/runtime/use-form.svelte.ts @@ -1,7 +1,9 @@ import { getContext, untrack } from 'svelte'; import { VoidActionError, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, @@ -51,33 +53,32 @@ export function useForm( let latestRequestId = 0; let dataSnapshot = cloneFormValue(initialDefaults); + function clearEditedErrors(current: Record) { + for (const key of changedFormErrorKeys(errors, dataSnapshot, current)) { + delete errors[key]; + } + dataSnapshot = current; + } + $effect(() => { // Read nested values even after an earlier edit, without subscribing to errors. const current = cloneFormValue(data); - untrack(() => { - for (const key of new Set([...Object.keys(dataSnapshot), ...Object.keys(current)])) { - if (!isEqualFormValue(current[key], dataSnapshot[key])) { - delete errors[key]; - } - } - dataSnapshot = current; - }); + untrack(() => clearEditedErrors(current)); }); - // An input handler may validate its new value before the change effect runs. - function snapshotField(field: string) { - untrack(() => { - dataSnapshot = { ...dataSnapshot, [field]: cloneFormValue(data[field]) }; - }); + // An input handler can validate before the effect runs. Clear older errors for + // pending edits before writing the new one. + function clearPendingEditErrors() { + untrack(() => clearEditedErrors(cloneFormValue(data))); } - // Handlers may also write `form.errors.field` directly, which needs the same snapshot. + // Handlers may also write `form.errors.field` directly. // The view is derived because setError and clearErrors replace `errors`. const errorsView = $derived( new Proxy(errors, { set(target, field, message) { if (typeof field === 'string') { - snapshotField(field); + clearPendingEditErrors(); } return Reflect.set(target, field, message); }, @@ -105,14 +106,14 @@ export function useForm( if (fields.length === 0) { errors = {}; } else { - for (const field of fields) { - delete errors[field]; + for (const key of formErrorKeysWithin(errors, fields, data)) { + delete errors[key]; } } } function setError(field: string, message: string) { - snapshotField(field); + clearPendingEditErrors(); errors = { ...errors, [field]: message }; } @@ -156,9 +157,8 @@ export function useForm( ? getValidationErrors(result.error.body) : null; if (validationErrors) { - for (const [field, message] of Object.entries(validationErrors)) { - setError(field, message); - } + clearPendingEditErrors(); + errors = { ...errors, ...validationErrors }; } else { error = result.error; } diff --git a/packages/svelte/test/unit/form-errors.typecheck.ts b/packages/svelte/test/unit/form-errors.typecheck.ts index 024ba82b0..be7220ce2 100644 --- a/packages/svelte/test/unit/form-errors.typecheck.ts +++ b/packages/svelte/test/unit/form-errors.typecheck.ts @@ -4,9 +4,30 @@ import { useForm } from '../../src/runtime/use-form.svelte.ts'; declare module 'void/routes' { interface PageActionMap { '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/__form-errors/svelte': { body: { email: string } }; + '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/__form-errors/svelte-nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('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/__form-errors/svelte-nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.errors['contacts.0.email'] = 'Required email'; + form.setError('profile.name', 'Required name'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFieldErrors(): void { const form = useForm('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/__form-errors/svelte', { email: '' }); form.setError('email', 'Invalid email'); diff --git a/packages/svelte/test/unit/use-form.test.ts b/packages/svelte/test/unit/use-form.test.ts index 714c6d1be..7f4b28bbb 100644 --- a/packages/svelte/test/unit/use-form.test.ts +++ b/packages/svelte/test/unit/use-form.test.ts @@ -18,6 +18,7 @@ type TestForm = { readonly pending: boolean; readonly wasSuccessful: boolean; setError(field: string, message: string): void; + clearErrors(...fields: Array): void; reset(): void; post(): Promise; }; @@ -154,6 +155,46 @@ describe('useForm field errors', () => { expect({ ...form.errors }).toEqual({ name: 'Name invalid' }); }); + it('clears only the errors of the fields a change touched', () => { + const form = mountForm({ + profile: { name: '', email: '' }, + contacts: [{ email: '' }, { email: '' }], + }); + form.setError('profile.name', 'Required name'); + form.setError('profile.email', 'Required email'); + form.setError('contacts.0.email', 'First email'); + form.setError('contacts.1.email', 'Second email'); + form.setError('name', 'Unrelated'); + svelte.flushSync(); + + form.data.profile = { name: 'Alex', email: '' }; + svelte.flushSync(); + expect(form.errors['profile.name']).toBeUndefined(); + expect(form.errors['profile.email']).toBe('Required email'); + + form.data.contacts = [{ email: '' }, { email: 'alex@example.com' }]; + svelte.flushSync(); + expect(form.errors['contacts.0.email']).toBe('First email'); + expect(form.errors['contacts.1.email']).toBeUndefined(); + + form.clearErrors('profile'); + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'contacts.0.email': 'First email', name: 'Unrelated' }); + + form.clearErrors('contacts'); + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ name: 'Unrelated' }); + }); + + it('keeps an error set for a field whose name contains a dot', () => { + const form = mountForm({ 'email.work': '' }); + + form.data['email.work'] = 'alice@example.com'; + form.setError('email.work', 'Invalid email'); + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'email.work': 'Invalid email' }); + }); + it('clears an error written before the field edit in the same handler', () => { const form = mountForm({ email: '' }); @@ -391,3 +432,46 @@ describe('useIslandForm edits made during a submit', () => { expect(form.data.title).toBe('Sent'); }); }); + +it('clears the array-level count error after adding an undefined slot', () => { + const form = mountForm({ contacts: [undefined] }); + form.setError('contacts', 'Add a second row'); + (form.data.contacts as Array).push(undefined); + svelte.flushSync(); + expect((form.data.contacts as Array).length).toBe(2); + expect(form.errors.contacts).toBeUndefined(); +}); + +it('clears the object-level error after removing an undefined key', () => { + const form = mountForm({ profile: { option: undefined } }); + form.setError('profile', 'Remove the option field'); + delete (form.data.profile as Record).option; + svelte.flushSync(); + expect(Object.hasOwn(form.data.profile as object, 'option')).toBe(false); + expect(form.errors.profile).toBeUndefined(); +}); + +it('clears stale errors for other edits in the same batch as validation', () => { + const form = mountForm({ contacts: [{ email: '' }, { email: '' }] }); + form.setError('contacts.0.email', 'First email required'); + const contacts = form.data.contacts as Array<{ email: string }>; + contacts[0].email = 'first@example.com'; + contacts[1].email = 'invalid'; + form.setError('contacts.1.email', 'Second email invalid'); + svelte.flushSync(); + + expect({ ...form.errors }).toEqual({ 'contacts.1.email': 'Second email invalid' }); +}); + +it('preserves a separate literal dotted error when editing or clearing its prefix', () => { + const form = mountForm({ email: '', 'email.work': '' }); + form.setError('email', 'Personal email is required'); + form.setError('email.work', 'Work email is required'); + form.data.email = 'new@example.com'; + svelte.flushSync(); + expect({ ...form.errors }).toEqual({ 'email.work': 'Work email is required' }); + + form.setError('email', 'Invalid email'); + form.clearErrors('email'); + expect({ ...form.errors }).toEqual({ 'email.work': 'Work email is required' }); +}); diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index f2039b7a3..115bebe23 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -645,10 +645,15 @@ export function initIslands( } export { + changedFormErrorKeys, + formErrorKeysWithin, formErrorMessage, formRetryMessage, formSubmissionBlocked, + omitFormErrors, scheduleFormRetry, + type FormErrorPath, + type FormErrors, type FormModel, type FormMethod, type FormState, diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts index f5d0772da..64ae4b650 100644 --- a/packages/void/src/pages/form-presentation.ts +++ b/packages/void/src/pages/form-presentation.ts @@ -1,6 +1,7 @@ import type { RouteUrl } from 'void/routes'; import type { VoidActionError } from './action-result.ts'; import type { FormResetOptions } from './form-reset.ts'; +import { isEqualFormValue, isPlainObject } from './form-value-equality.ts'; import type { VisitOptions } from './navigation-engine.ts'; export type FormMethod = 'post' | 'put' | 'patch' | 'delete'; @@ -20,8 +21,28 @@ export type FormStatus = { readonly wasSuccessful: boolean; readonly recentlySuccessful: boolean; }; +/** + * A body field plus the dotted nested paths a validator reports for it, such as `profile.name` + * or `contacts.0.email`. The recursion is capped so a recursive body type stays cheap to check. + */ +export type FormErrorPath = []> = Depth['length'] extends 6 + ? never + : T extends ReadonlyArray + ? `${number}` | `${number}.${FormErrorPath}` + : T extends object + ? { + [K in keyof T & string]: T[K] extends (...args: Array) => unknown + ? never + : K | `${K}.${FormErrorPath}`; + }[keyof T & string] + : never; +/** + * A body field or one of its nested paths. `keyof TData & string` keeps top-level names usable in + * generic callers, where TypeScript cannot resolve the `FormErrorPath` conditional. + */ +type FormFieldPath = FormErrorPath | (keyof TData & string); /** Field-keyed validation messages; a field without an error is absent. */ -export type FormErrors = Partial>; +export type FormErrors = Partial, string>>; /** * How an adapter's apps change `data` and `errors`, following its framework's idiom. * `'in-place'`: apps edit them directly (Vue, Svelte). @@ -40,8 +61,8 @@ export type FormState = FormStatus & Readonly<{ reset(options: FormResetOptions, ...fields: ReadonlyArray): void; reset(...fields: ReadonlyArray): void; - setError(field: keyof TData & string, message: string): void; - clearErrors(...fields: ReadonlyArray): void; + setError(field: FormFieldPath, message: string): void; + clearErrors(...fields: ReadonlyArray>): void; clearError(): void; }>; /** @@ -61,6 +82,96 @@ export type IslandFormState = FormStatus & delete(url: RouteUrl): Promise; }>; +function hasFormField(value: unknown, field: string): value is Record { + return (isPlainObject(value) || Array.isArray(value)) && Object.hasOwn(value, field); +} + +// A literal key can contain dots. Prefer the longest own key before treating dots as path +// separators. Check both snapshots so deleting a literal key still identifies the same field. +function formValuePath(field: string, previous: unknown, next = previous): Array { + const path: Array = []; + for (;;) { + let key = field; + while (!hasFormField(previous, key) && !hasFormField(next, key)) { + const dot = key.lastIndexOf('.'); + if (dot === -1) { + break; + } + key = key.slice(0, dot); + } + path.push(key); + if (key === field) { + return path; + } + previous = hasFormField(previous, key) ? previous[key] : undefined; + next = hasFormField(next, key) ? next[key] : undefined; + field = field.slice(key.length + 1); + } +} + +function formValueChanged(previous: unknown, next: unknown, path: ReadonlyArray): boolean { + for (const key of path) { + if (Object.is(previous, next)) { + return false; + } + if (!hasFormField(previous, key)) { + if (hasFormField(next, key)) { + return true; + } + // Replacing a container invalidates descendant errors even when the + // specific field was missing, for example a required field in an empty object. + return !( + (isPlainObject(previous) && isPlainObject(next)) || + (Array.isArray(previous) && Array.isArray(next)) + ); + } + if (!hasFormField(next, key)) { + return true; + } + previous = previous[key]; + next = next[key]; + } + return !isEqualFormValue(previous, next); +} + +/** The exact error keys whose field values changed, including affected parent fields. */ +export function changedFormErrorKeys( + errors: Readonly>, + previous: unknown, + next: unknown, +): Array { + return Object.keys(errors).filter((key) => + formValueChanged(previous, next, formValuePath(key, previous, next)), + ); +} + +/** The error keys on explicitly cleared fields and their descendants. */ +export function formErrorKeysWithin( + errors: Readonly>, + fields: ReadonlyArray, + data: unknown, +): Array { + const paths = fields.map((field) => formValuePath(field, data)); + return Object.keys(errors).filter((key) => { + const path = formValuePath(key, data); + return paths.some((parent) => parent.every((part, index) => part === path[index])); + }); +} + +/** Remove only the selected error keys. */ +export function omitFormErrors( + errors: Record, + keys: ReadonlyArray, +): Record { + if (keys.length === 0) { + return errors; + } + const next = { ...errors }; + for (const key of keys) { + delete next[key]; + } + return next; +} export function formErrorMessage(form: Pick): string | null { return form.error?.message ?? (Object.values(form.errors).filter(Boolean).join('. ') || null); } diff --git a/packages/void/src/pages/form-value-equality.ts b/packages/void/src/pages/form-value-equality.ts index 363d38461..baeff5c37 100644 --- a/packages/void/src/pages/form-value-equality.ts +++ b/packages/void/src/pages/form-value-equality.ts @@ -1,4 +1,4 @@ -function isPlainObject(value: unknown): value is Record { +export function isPlainObject(value: unknown): value is Record { if (value === null || typeof value !== 'object') { return false; } @@ -17,7 +17,15 @@ export function isEqualFormValue(a: unknown, b: unknown): boolean { return false; } - return a.every((value, index) => isEqualFormValue(value, b[index])); + for (let index = 0; index < a.length; index += 1) { + if ( + Object.hasOwn(a, index) !== Object.hasOwn(b, index) || + !isEqualFormValue(a[index], b[index]) + ) { + return false; + } + } + return true; } if (isPlainObject(a) || isPlainObject(b)) { diff --git a/packages/void/test/unit/form-presentation.test.ts b/packages/void/test/unit/form-presentation.test.ts index 910142197..70dacf4e3 100644 --- a/packages/void/test/unit/form-presentation.test.ts +++ b/packages/void/test/unit/form-presentation.test.ts @@ -1,8 +1,11 @@ -import { afterEach, expect, it, vi } from 'vite-plus/test'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { VoidActionError } from '../../src/pages/action-result.ts'; import { + changedFormErrorKeys, formErrorMessage, formSubmissionBlocked, + formErrorKeysWithin, + omitFormErrors, scheduleFormRetry, } from '../../src/pages/form-presentation.ts'; const error = () => @@ -40,3 +43,102 @@ it('blocks only while pending or until a known retry deadline, without submittin await vi.advanceTimersByTimeAsync(2000); expect(ready).toHaveBeenCalledOnce(); }); + +describe('changedFormErrorKeys', () => { + const errors = { + contacts: 'More contacts required', + 'contacts.0.email': 'First email invalid', + 'contacts.1.email': 'Second email invalid', + 'contacts.1.name': 'Second name required', + }; + const twoContacts = { contacts: [{ email: '' }, { email: '', name: '' }] }; + + it('selects the changed child and its ancestor but keeps unchanged siblings', () => { + expect( + changedFormErrorKeys(errors, twoContacts, { + contacts: [{ email: 'valid@example.com' }, { email: '', name: '' }], + }), + ).toEqual(['contacts', 'contacts.0.email']); + }); + + it('selects the descendants of a removed row', () => { + expect(changedFormErrorKeys(errors, twoContacts, { contacts: [{ email: '' }] })).toEqual([ + 'contacts', + 'contacts.1.email', + 'contacts.1.name', + ]); + }); + + it('clears a missing descendant when its container is replaced', () => { + const errors = { 'profile.name': 'Required' }; + expect(changedFormErrorKeys(errors, { profile: {} }, { profile: null })).toEqual([ + 'profile.name', + ]); + expect(changedFormErrorKeys(errors, { profile: {} }, { profile: { email: '' } })).toEqual([]); + }); + + it('keeps a literal dotted field separate from a nested path', () => { + const before = { email: { personal: '' }, 'email.work': '' }; + const errors = { 'email.personal': 'Invalid', 'email.work': 'Invalid' }; + expect( + changedFormErrorKeys(errors, before, { + ...before, + email: { personal: 'valid@example.com' }, + }), + ).toEqual(['email.personal']); + expect(changedFormErrorKeys(errors, before, { email: before.email })).toEqual(['email.work']); + }); + + it('treats undefined fields and array entries as present', () => { + const before = { profile: { nickname: undefined }, contacts: [undefined] }; + expect( + changedFormErrorKeys( + { profile: 'Invalid', 'profile.nickname': 'Invalid', contacts: 'Too short' }, + before, + { profile: {}, contacts: [undefined, undefined] }, + ), + ).toEqual(['profile', 'profile.nickname', 'contacts']); + expect( + changedFormErrorKeys( + { contacts: 'Invalid', 'contacts.0': 'Invalid' }, + { contacts: new Array(1) }, + { contacts: [undefined] }, + ), + ).toEqual(['contacts', 'contacts.0']); + }); + + it('keeps a non-plain object whole', () => { + const date = new Date(0); + const errors = { date: 'Invalid date' }; + expect(changedFormErrorKeys(errors, { date }, { date })).toEqual([]); + expect(changedFormErrorKeys(errors, { date }, { date: new Date(1) })).toEqual(['date']); + }); +}); + +describe('formErrorKeysWithin', () => { + const data = { email: { personal: '' }, 'email.work': '' }; + const errors = { email: 'Invalid', 'email.personal': 'Required', 'email.work': 'Required' }; + + it('selects a parent and its descendants, preserving flat dotted fields', () => { + expect(formErrorKeysWithin(errors, ['email'], data)).toEqual(['email', 'email.personal']); + expect(formErrorKeysWithin(errors, ['email.work'], data)).toEqual(['email.work']); + }); + + it('finds descendant errors for a missing optional parent', () => { + expect(formErrorKeysWithin({ 'profile.name': 'Required' }, ['profile'], {})).toEqual([ + 'profile.name', + ]); + }); +}); + +describe('omitFormErrors', () => { + const errors = { profile: 'Invalid', 'profile.name': 'Required' }; + + it('removes the exact keys selected for an edit', () => { + expect(omitFormErrors(errors, ['profile'])).toEqual({ 'profile.name': 'Required' }); + }); + + it('returns the same map with no keys to remove', () => { + expect(omitFormErrors(errors, [])).toBe(errors); + }); +}); diff --git a/packages/vue/src/runtime/use-form.ts b/packages/vue/src/runtime/use-form.ts index de1ebfe24..4d2688935 100644 --- a/packages/vue/src/runtime/use-form.ts +++ b/packages/vue/src/runtime/use-form.ts @@ -1,6 +1,8 @@ import { VoidActionError, + changedFormErrorKeys, cloneFormValue, + formErrorKeysWithin, getValidationErrors, interpolateRouteParams, isAbortError, @@ -52,10 +54,8 @@ export function useForm( watch( () => cloneFormValue(data), (val) => { - for (const key of new Set([...Object.keys(dataSnapshot), ...Object.keys(val)])) { - if (!isEqualFormValue(val[key], dataSnapshot[key])) { - delete errors[key]; - } + for (const key of changedFormErrorKeys(errors, dataSnapshot, val)) { + delete errors[key]; } dataSnapshot = val; }, @@ -80,14 +80,10 @@ export function useForm( } function clearErrors(...fields: ReadonlyArray) { - if (fields.length === 0) { - for (const key of Object.keys(errors)) { - delete errors[key]; - } - } else { - for (const field of fields) { - delete errors[field]; - } + const keys = + fields.length === 0 ? Object.keys(errors) : formErrorKeysWithin(errors, fields, data); + for (const key of keys) { + delete errors[key]; } } diff --git a/packages/vue/test/unit/form-errors.typecheck.ts b/packages/vue/test/unit/form-errors.typecheck.ts index ab336a67f..35c64b660 100644 --- a/packages/vue/test/unit/form-errors.typecheck.ts +++ b/packages/vue/test/unit/form-errors.typecheck.ts @@ -4,9 +4,30 @@ import { useForm } from '../../src/runtime/use-form.ts'; declare module 'void/routes' { interface PageActionMap { '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/__form-errors/vue': { body: { email: string } }; + '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/__form-errors/vue-nested': { + body: { profile: { name: string }; contacts: Array<{ email: string }> }; + }; } } +export function checkNestedErrorPaths(): void { + const form = useForm('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/__form-errors/vue-nested', { + profile: { name: '' }, + contacts: [{ email: '' }], + }); + const name: string | undefined = form.errors['profile.name']; + const email: string | undefined = form.errors['contacts.0.email']; + void name; + void email; + form.errors['contacts.0.email'] = 'Required email'; + form.setError('profile.name', 'Required name'); + form.clearErrors('profile', 'contacts', 'contacts.0.email'); + // @ts-expect-error Nested error paths must name a field in the action body. + form.setError('profile.missing', 'Invalid'); + // @ts-expect-error Array segments must be numeric array indices. + form.clearErrors('contacts.first'); +} + export function checkFieldErrors(): void { const form = useForm('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/__form-errors/vue', { email: '' }); form.setError('email', 'Invalid email'); diff --git a/packages/vue/test/unit/use-form.test.ts b/packages/vue/test/unit/use-form.test.ts index 01dbfaef4..0a30f157a 100644 --- a/packages/vue/test/unit/use-form.test.ts +++ b/packages/vue/test/unit/use-form.test.ts @@ -7,6 +7,7 @@ import { useIslandForm } from '../../src/runtime/use-island-form.ts'; type TestForm = { setError(field: string, message: string): void; + clearErrors(...fields: Array): void; readonly errors: Record; data: Record; hasChanges: boolean; @@ -162,6 +163,45 @@ describe('useForm setError', () => { await renderToString(app); }); + it('clears only the errors of the fields a change touched', async () => { + const router = { + visit: async () => ({}), + } as unknown as VoidRouter; + const app = createSSRApp( + defineComponent({ + setup() { + const form = useForm( + '/test', + { profile: { name: '', email: '' }, contacts: [{ email: '' }, { email: '' }] }, + {}, + ); + form.setError('profile.name', 'Required name'); + form.setError('profile.email', 'Required email'); + form.setError('contacts.0.email', 'First email'); + form.setError('contacts.1.email', 'Second email'); + form.setError('name', 'Unrelated'); + + form.data.profile = { name: 'Alex', email: '' }; + expect(form.errors['profile.name']).toBeUndefined(); + expect(form.errors['profile.email']).toBe('Required email'); + + form.data.contacts = [{ email: '' }, { email: 'alex@example.com' }]; + expect(form.errors['contacts.0.email']).toBe('First email'); + expect(form.errors['contacts.1.email']).toBeUndefined(); + + form.clearErrors('profile'); + expect(form.errors).toEqual({ 'contacts.0.email': 'First email', name: 'Unrelated' }); + + form.clearErrors('contacts'); + expect(form.errors).toEqual({ name: 'Unrelated' }); + return () => h('form'); + }, + }), + ); + app.provide('__void_router', router); + await renderToString(app); + }); + it('keeps errors on other fields when one field changes', async () => { const router = { visit: async () => ({}), @@ -420,3 +460,37 @@ describe('useIslandForm edits made during a submit', () => { expect(form.data.title).toBe('Sent'); }); }); + +it('clears the array-level count error after adding an undefined slot', async () => { + const app = createSSRApp( + defineComponent({ + setup() { + const form = useForm('/test', { contacts: [undefined] }); + form.setError('contacts', 'Add a second row'); + (form.data.contacts as Array).push(undefined); + expect((form.data.contacts as Array).length).toBe(2); + expect(form.errors.contacts).toBeUndefined(); + return () => h('form'); + }, + }), + ); + app.provide('__void_router', {}); + await renderToString(app); +}); + +it('clears the object-level error after removing an undefined key', async () => { + const app = createSSRApp( + defineComponent({ + setup() { + const form = useForm('/test', { profile: { option: undefined } }); + form.setError('profile', 'Remove the option field'); + delete (form.data.profile as Record).option; + expect(Object.hasOwn(form.data.profile as object, 'option')).toBe(false); + expect(form.errors.profile).toBeUndefined(); + return () => h('form'); + }, + }), + ); + app.provide('__void_router', {}); + await renderToString(app); +});