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

[0.5.x] Fix incorrectly reported valid inputs #60

Merged
merged 3 commits into from
Jan 8, 2024
Merged
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: 2 additions & 0 deletions packages/alpine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ export default function (Alpine: TAlpine) {
form.hasErrors = validator.hasErrors()

form.errors = toSimpleValidationErrors(validator.errors())

state.valid = validator.valid()
})

/**
Expand Down
88 changes: 65 additions & 23 deletions packages/core/src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,43 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
*/
let validating = false

const setValidating = (value: boolean) => {
/**
* Set the validating inputs.
*
* Returns an array of listeners that should be invoked once all state
* changes have taken place.
*/
const setValidating = (value: boolean): (() => void)[] => {
if (value !== validating) {
validating = value

listeners.validatingChanged.forEach(callback => callback())
return listeners.validatingChanged
}

return []
}

/**
* Inputs that have been validated.
*/
let validated: Array<string> = []

const setValidated = (value: Array<string>) => {
/**
* Set the validated inputs.
*
* Returns an array of listeners that should be invoked once all state
* changes have taken place.
*/
const setValidated = (value: Array<string>): (() => void)[] => {
const uniqueNames = [...new Set(value)]

if (validated.length !== uniqueNames.length || ! uniqueNames.every(name => validated.includes(name))) {
validated = uniqueNames

listeners.validatedChanged.forEach(callback => callback())
return listeners.validatedChanged
}

return []
}

/**
Expand All @@ -62,37 +78,59 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
*/
let touched: Array<string> = []

const setTouched = (value: Array<string>) => {
/**
* Set the touched inputs.
*
* Returns an array of listeners that should be invoked once all state
* changes have taken place.
*/
const setTouched = (value: Array<string>): (() => void)[] => {
const uniqueNames = [...new Set(value)]

if (touched.length !== uniqueNames.length || ! uniqueNames.every(name => touched.includes(name))) {
touched = uniqueNames

listeners.touchedChanged.forEach(callback => callback())
return listeners.touchedChanged
}

return []
}

/**
* Validation errors state.
*/
let errors: ValidationErrors = {}

const setErrors = (value: ValidationErrors|SimpleValidationErrors) => {
/**
* Set the input errors.
*
* Returns an array of listeners that should be invoked once all state
* changes have taken place.
*/
const setErrors = (value: ValidationErrors|SimpleValidationErrors): (() => void)[] => {
const prepared = toValidationErrors(value)

if (! isequal(errors, prepared)) {
errors = prepared

listeners.errorsChanged.forEach(callback => callback())
return listeners.errorsChanged
}

return []
}

const forgetError = (name: string|NamedInputEvent) => {
/**
* Forget the given input's errors.
*
* Returns an array of listeners that should be invoked once all state
* changes have taken place.
*/
const forgetError = (name: string|NamedInputEvent): (() => void)[] => {
const newErrors = { ...errors }

delete newErrors[resolveName(name)]

setErrors(newErrors)
return setErrors(newErrors)
}

/**
Expand Down Expand Up @@ -163,19 +201,23 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
validate,
timeout: config.timeout ?? 5000,
onValidationError: (response, axiosError) => {
setValidated([...validated, ...validate])

setErrors(merge(omit({ ...errors }, validate), response.data.errors))
[
...setValidated([...validated, ...validate]),
...setErrors(merge(omit({ ...errors }, validate), response.data.errors)),
].forEach(listener => listener())

return config.onValidationError
? config.onValidationError(response, axiosError)
: Promise.reject(axiosError)
},
onSuccess: () => {
setValidated([...validated, ...validate])
setValidated([...validated, ...validate]).forEach(listener => listener())
},
onPrecognitionSuccess: (response) => {
setErrors(omit({ ...errors }, validate))
[
...setValidated([...validated, ...validate]),
...setErrors(omit({ ...errors }, validate)),
].forEach(listener => listener())

return config.onPrecognitionSuccess
? config.onPrecognitionSuccess(response)
Expand Down Expand Up @@ -203,12 +245,12 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
return true
},
onStart: () => {
setValidating(true);
setValidating(true).forEach(listener => listener());

(config.onStart ?? (() => null))()
},
onFinish: () => {
setValidating(false)
setValidating(false).forEach(listener => listener())

oldTouched = validatingTouched!

Expand Down Expand Up @@ -240,7 +282,7 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
name = resolveName(name)

if (get(oldData, name) !== value) {
setTouched([name, ...touched])
setTouched([name, ...touched]).forEach(listener => listener())
}

if (touched.length === 0) {
Expand Down Expand Up @@ -272,7 +314,7 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
? input
: [resolveName(input)]

setTouched([...touched, ...inputs])
setTouched([...touched, ...inputs]).forEach(listener => listener())

return form
},
Expand All @@ -281,18 +323,18 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
errors: () => errors,
hasErrors,
setErrors(value) {
setErrors(value)
setErrors(value).forEach(listener => listener())

return form
},
forgetError(name) {
forgetError(name)
forgetError(name).forEach(listener => listener())

return form
},
reset(...names) {
if (names.length === 0) {
setTouched([])
setTouched([]).forEach(listener => listener())
} else {
const newTouched = [...touched]

Expand All @@ -304,7 +346,7 @@ export const createValidator = (callback: ValidationCallback, initialData: Recor
set(oldData, name, get(initialData, name))
})

setTouched(newTouched)
setTouched(newTouched).forEach(listener => listener())
}

return form
Expand Down
26 changes: 26 additions & 0 deletions packages/core/tests/validator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,29 @@ it('can validate without needing to specify a field', async () => {
validator.touch(['name', 'framework']).validate()
expect(requests).toBe(1)
})

it('marks fields as valid on precognition success', async () => {
expect.assertions(5)

let requests = 0
axios.request.mockImplementation(() => {
requests++

return Promise.resolve({ headers: { precognition: 'true', 'precognition-success': 'true' }, status: 204, data: '' })
})
const validator = createValidator((client) => client.post('/foo', {}))
let valid = null
validator.setErrors({name: 'Required'}).touch('name').on('errorsChanged', () => {
valid = validator.valid()
})

expect(validator.valid()).toStrictEqual([])
expect(valid).toBeNull()

validator.validate()
await vi.runAllTimersAsync()

expect(requests).toBe(1)
expect(validator.valid()).toStrictEqual(['name'])
expect(valid).toStrictEqual(['name'])
})
2 changes: 2 additions & 0 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ export const useForm = <Data extends Record<string, unknown>>(method: RequestMet

// @ts-expect-error
setErrors(toSimpleValidationErrors(validator.current!.errors()))

setValid(validator.current!.valid())
})
}

Expand Down
3 changes: 3 additions & 0 deletions packages/vue/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export const useForm = <Data extends Record<string, unknown>>(method: RequestMet

// @ts-expect-error
form.errors = toSimpleValidationErrors(validator.errors())

// @ts-expect-error
valid.value = validator.valid()
})

/**
Expand Down