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(#4075): mark whole form dirty is validate called #4083

Merged
merged 2 commits into from
Dec 8, 2023
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
59 changes: 58 additions & 1 deletion packages/ui/src/components/va-form/VaForm.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ export const ValidateAndResetValidation: StoryFn = () => ({
components: { VaForm, VaInput, VaButton },
template: `
<va-form ref="form">
<va-input data-testid="input" :rules="[false]"/>
<va-input data-testid="input" :rules="[false]" stateful />
</va-form>
<va-button @click="$refs.form.validate()">
Validate
Expand Down Expand Up @@ -539,3 +539,60 @@ export const FormDataInitialValue = () => ({
</va-button>
`,
})

export const DirtyForm: StoryFn = () => ({
components: { VaForm, VaInput, VaButton },

setup () {
const { isDirty } = useForm('form')

return {
isDirty,
}
},

template: `
<p id="form-dirty">[form-dirty]: {{ isDirty }}</p>
<p id="input-dirty">[input-dirty]: {{ $refs.input?.isDirty }}</p>
<va-form ref="form">
<va-input data-testid="input" :rules="[false]" stateful ref="input" />
</va-form>
<va-button @click="$refs.form.validate()">
Validate
</va-button>
<va-button @click="$refs.form.resetValidation()">
Reset validation
</va-button>
`,
})

DirtyForm.play = async ({ canvasElement, step }) => {
const canvas = within(canvasElement)
const input = canvas.getByTestId('input')
const validateButton = canvas.getByRole('button', { name: 'Validate' }) as HTMLElement
const resetButton = canvas.getByRole('button', { name: 'Reset validation' }) as HTMLElement

await step('Validates input with error', async () => {
await userEvent.click(validateButton)
expect(input.getAttribute('aria-invalid')).toEqual('true')
expect(canvasElement.querySelector('#form-dirty')?.innerHTML.includes('true')).toBeTruthy()
expect(canvasElement.querySelector('#input-dirty')?.innerHTML.includes('false')).toBeTruthy()
})

await step('Reset inputs validation', async () => {
await userEvent.click(resetButton)
expect(input.getAttribute('aria-invalid')).toEqual('false')
})

await step('Validates input on input error', async () => {
await userEvent.type(input, 'Hello')
expect(input.getAttribute('aria-invalid')).toEqual('true')
expect(canvasElement.querySelector('#form-dirty')?.innerHTML.includes('false')).toBeTruthy()
expect(canvasElement.querySelector('#input-dirty')?.innerHTML.includes('true')).toBeTruthy()
})

await step('Reset inputs validation', async () => {
await userEvent.click(resetButton)
expect(input.getAttribute('aria-invalid')).toEqual('false')
})
}
2 changes: 2 additions & 0 deletions packages/ui/src/components/va-input/VaInput.vue
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ export default defineComponent({
})

const {
isDirty,
computedError,
computedErrorMessages,
listeners: { onBlur, onFocus },
Expand Down Expand Up @@ -240,6 +241,7 @@ export default defineComponent({

fieldListeners: createFieldListeners(emit),
filterSlots,
isDirty,
reset,
focus,
blur,
Expand Down
2 changes: 2 additions & 0 deletions packages/ui/src/composables/useForm/useFormChild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const useFormChild = (context: FormFiled) => {

if (!formContext) {
return {
isFormDirty: ref(false),
isFormImmediate: ref(false),
doShowError: ref(true),
doShowErrorMessages: ref(true),
Expand All @@ -26,6 +27,7 @@ export const useFormChild = (context: FormFiled) => {
})

return {
isFormDirty: formContext.isFormDirty,
isFormImmediate: formContext.immediate,
doShowError: formContext.doShowError,
doShowErrorMessages: formContext.doShowErrorMessages,
Expand Down
12 changes: 10 additions & 2 deletions packages/ui/src/composables/useForm/useFormParent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const createFormContext = <Names extends string>(options: FormParentOptio
doShowError: computed(() => !options.hideErrors),
doShowErrorMessages: computed(() => !options.hideErrorMessages),
doShowLoading: computed(() => !options.hideLoading),
isFormDirty: ref(false),
registerField: (uid: number, field: FormFiled) => {
fields.value.set(uid, field as FormFiled<Names>)
},
Expand All @@ -34,7 +35,7 @@ export const useFormParent = <Names extends string = string>(options: FormParent

provide(FormServiceKey, formContext)

const { fields } = formContext
const { fields, isFormDirty } = formContext

const fieldNames = computed(() => fields.value.map((field) => unref(field.name)).filter(Boolean) as Names[])
const fieldsNamed = computed(() => fields.value.reduce((acc, field) => {
Expand All @@ -47,31 +48,38 @@ export const useFormParent = <Names extends string = string>(options: FormParent
}, {} as Record<Names, FormFiled['value']>))
const isValid = computed(() => fields.value.every((field) => unref(field.isValid)))
const isLoading = computed(() => fields.value.some((field) => unref(field.isLoading)))
const isDirty = computed(() => fields.value.some((field) => unref(field.isLoading)))
const isDirty = computed({
get () { return fields.value.some((field) => unref(field.isLoading)) || isFormDirty.value },
set (v) { isFormDirty.value = v },
})
const errorMessages = computed(() => fields.value.map((field) => unref(field.errorMessages)).flat())
const errorMessagesNamed = computed(() => fields.value.reduce((acc, field) => {
if (unref(field.name)) { acc[unref(field.name) as Names] = unref(field.errorMessages) }
return acc
}, {} as Record<Names, any>))

const validate = () => {
isDirty.value = true
// Validate each filed to get the error messages
return fields.value.reduce((acc, field) => {
return field.validate() && acc
}, true)
}

const validateAsync = () => {
isDirty.value = true
return Promise.all(fields.value.map((field) => field.validateAsync())).then((results) => {
return results.every(Boolean)
})
}

const reset = () => {
isDirty.value = false
fields.value.forEach((field) => field.reset())
}

const resetValidation = () => {
isDirty.value = false
fields.value.forEach((field) => field.resetValidation())
}

Expand Down
12 changes: 10 additions & 2 deletions packages/ui/src/composables/useValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export const useValidation = <V, P extends ExtractPropTypes<typeof useValidation
const resetValidation = () => {
computedError.value = false
computedErrorMessages.value = []
isDirty.value = false
}

const processResults = (results: any[]) => {
Expand Down Expand Up @@ -193,6 +194,7 @@ export const useValidation = <V, P extends ExtractPropTypes<typeof useValidation
doShowError,
doShowLoading,
isFormImmediate,
isFormDirty,
} = useFormChild({
isDirty,
isValid: computed(() => !computedError.value),
Expand All @@ -202,7 +204,11 @@ export const useValidation = <V, P extends ExtractPropTypes<typeof useValidation
validateAsync,
resetValidation,
focus,
reset,
reset: () => {
reset()
resetValidation()
isDirty.value = false
},
value: computed(() => options.value || props.modelValue),
name: toRef(props, 'name'),
})
Expand All @@ -212,7 +218,9 @@ export const useValidation = <V, P extends ExtractPropTypes<typeof useValidation
computedError: computed(() => {
// Hide error if component haven't been interacted yet
// Ignore dirty state if immediateValidation is true
if (!immediateValidation.value && !isDirty.value) { return false }
if (!isFormDirty.value) {
if (!immediateValidation.value && !isDirty.value) { return false }
}

return doShowError.value ? computedError.value : false
}),
Expand Down
Loading