Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Form)!: include nested state in submit data #3028

Draft
wants to merge 3 commits into
base: v3
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/3.components/form.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ This will give you access to the following:
| Name | Type |
| ---- | ---- |
| `submit()`{lang="ts-type"} | `Promise<void>`{lang="ts-type"} <br> <div class="text-[var(--ui-text-toned)] mt-1"><p>Triggers form submission.</p> |
| `validate(path?: string \| string[], opts: { silent?: boolean })`{lang="ts-type"} | `Promise<T>`{lang="ts-type"} <br> <div class="text-[var(--ui-text-toned)] mt-1"><p>Triggers form validation. Will raise any errors unless `opts.silent` is set to true.</p> |
| `validate(opts: { name?: string \| string[], silent?: boolean, nested?: boolean, transform?: boolean })`{lang="ts-type"} | `Promise<T>`{lang="ts-type"} <br> <div class="text-[var(--ui-text-toned)] mt-1"><p>Triggers form validation. Will raise any errors unless `opts.silent` is set to true.</p> |
| `clear(path?: string)`{lang="ts-type"} | `void` <br> <div class="text-[var(--ui-text-toned)] mt-1"><p>Clears form errors associated with a specific path. If no path is provided, clears all form errors.</p> |
| `getErrors(path?: string)`{lang="ts-type"} | `FormError[]`{lang="ts-type"} <br> <div class="text-[var(--ui-text-toned)] mt-1"><p>Retrieves form errors associated with a specific path. If no path is provided, returns all form errors.</p></div> |
| `setErrors(errors: FormError[], path?: string)`{lang="ts-type"} | `void` <br> <div class="text-[var(--ui-text-toned)] mt-1"><p>Sets form errors for a given path. If no path is provided, overrides all errors.</p> |
Expand Down
15 changes: 9 additions & 6 deletions src/runtime/components/Form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const parentBus = inject(

provide(formBusInjectionKey, bus)

const nestedForms = ref<Map<string | number, { validate: () => any }>>(new Map())
const nestedForms = ref<Map<string | number, { validate: typeof _validate }>>(new Map())

onMounted(async () => {
bus.on(async (event) => {
Expand Down Expand Up @@ -120,12 +120,12 @@ async function getErrors(): Promise<FormErrorWithId[]> {
return resolveErrorIds(errs)
}

async function _validate(opts: { name?: string | string[], silent?: boolean, nested?: boolean } = { silent: false, nested: true }): Promise<T | false> {
async function _validate(opts: { name?: string | string[], silent?: boolean, nested?: boolean, transform?: boolean } = { silent: false, nested: true, transform: false }): Promise<T | false> {
const names = opts.name && !Array.isArray(opts.name) ? [opts.name] : opts.name as string[]

const nestedValidatePromises = !names && opts.nested
? Array.from(nestedForms.value.values()).map(
({ validate }) => validate().then(() => undefined).catch((error: Error) => {
({ validate }) => validate(opts).then(() => undefined).catch((error: Error) => {
if (!(error instanceof FormValidationException)) {
throw error
}
Expand All @@ -150,13 +150,17 @@ async function _validate(opts: { name?: string | string[], silent?: boolean, nes
errors.value = await getErrors()
}

const childErrors = (await Promise.all(nestedValidatePromises)).filter(val => val)
const childErrors = (await Promise.all(nestedValidatePromises)).filter(val => val !== undefined)

if (errors.value.length + childErrors.length > 0) {
if (opts.silent) return false
throw new FormValidationException(formId, errors.value, childErrors)
}

if (opts.transform) {
Object.assign(props.state, parsedValue.value)
}

return props.state as T
}

Expand All @@ -169,8 +173,7 @@ async function onSubmitWrapper(payload: Event) {
const event = payload as FormSubmitEvent<any>

try {
await _validate({ nested: true })
event.data = props.schema ? parsedValue.value : props.state
event.data = await _validate({ nested: true, transform: true })
await props.onSubmit?.(event)
} catch (error) {
if (!(error instanceof FormValidationException)) {
Expand Down
8 changes: 4 additions & 4 deletions src/runtime/types/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { GetObjectField } from './utils'
import type { Struct as SuperstructSchema } from 'superstruct'

export interface Form<T> {
validate (opts?: { name: string | string[], silent?: false, nested?: boolean }): Promise<T | false>
validate (opts?: { name?: string | string[], silent?: boolean, nested?: boolean, transform?: boolean }): Promise<T | false>
clear (path?: string): void
errors: Ref<FormError[]>
setErrors (errs: FormError[], path?: string): void
Expand Down Expand Up @@ -43,7 +43,7 @@ export type FormSubmitEvent<T> = SubmitEvent & { data: T }

export type FormValidationError = {
errors: FormErrorWithId[]
childrens: FormValidationError[]
childrens?: FormValidationError[]
}

export type FormErrorEvent = SubmitEvent & FormValidationError
Expand Down Expand Up @@ -93,9 +93,9 @@ export interface ValidateReturnSchema<T> {
export class FormValidationException extends Error {
formId: string | number
errors: FormErrorWithId[]
childrens: FormValidationException[]
childrens?: FormValidationException[]

constructor(formId: string | number, errors: FormErrorWithId[], childErrors: FormValidationException[]) {
constructor(formId: string | number, errors: FormErrorWithId[], childErrors?: FormValidationException[]) {
super('Form validation exception')
this.formId = formId
this.errors = errors
Expand Down
9 changes: 9 additions & 0 deletions test/components/Form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,15 @@ describe('Form', () => {
expect(nestedField.text()).toBe('Required')
})

test('submit event contains nested attributes', async () => {
state.email = '[email protected]'
state.password = 'strongpassword'
state.nested.field = 'nested'

await form.value.submit()
expect(wrapper.setupState.onSubmit).toHaveBeenCalledWith(expect.objectContaining({ data: { email: '[email protected]', password: 'strongpassword', nested: { field: 'nested' } } }))
})

test('submit works when child is disabled', async () => {
await form.value.submit()
expect(wrapper.setupState.onError).toHaveBeenCalledTimes(1)
Expand Down
Loading