Skip to content

Commit

Permalink
Merge pull request #63 from dbssman/feature/60-add-context-provider-a…
Browse files Browse the repository at this point in the history
…s-composable

💉 Add context provider and tests
  • Loading branch information
dbssman authored May 1, 2023
2 parents 47a263a + 333fe12 commit 5455ecb
Show file tree
Hide file tree
Showing 8 changed files with 234 additions and 4 deletions.
1 change: 1 addition & 0 deletions docs/.vitepress/config.cts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export default defineConfig({
{ text: 'values', link: '/api/use-form-handler/values' },
],
},
{ text: `useFormContext`, link: '/api/use-form-context' },
{ text: `FormHandler`, link: '/api/form-handler' },
],
},
Expand Down
124 changes: 124 additions & 0 deletions docs/api/use-form-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# useFormContext

`useFormContext` is a composable to access all the exposed functionalities of `useFormHandler` in any descendant of the handlers subtree is used. By this we avoid drilling the things we need down.

## How it works

`useFormContext` makes use of the [Vue 3 Provide/Inject](https://vuejs.org/guide/components/provide-inject.html) feature to directly provide the exposed features of `useFormHandler` to all the subtree.

As you can imagine, `useFormContext` and `useFormHandler` share the same return, nevertheless, the ancestor who consumes useFormHandler will rule things like `initialValues`, `validationMode`....

## Example:

```vue
<!-- Parent.vue component -->
<template>
<form @submit.prevent="handleSubmit(successFn)">
<input v-bind="register('firstName')" />
<input v-bind="register('lastName')" />
<Child></Child>
<button type="submit">Submit</button>
</form>
</template>
<script setup lang="ts">
import { useFormHandler } from 'vue-form-handler'
import Child from './Child.vue'
const { handleSubmit, register } = useFormHandler();
const successFn = (form: Record<string, any>) => {
console.log({ form })
}
</script>
```

```vue
<!-- Child.vue component -->
<template>
<input v-bind="register('anotherField')" />
<GrandChild></GrandChild>
</template>
<script setup lang="ts">
import { useFormContext } from 'vue-form-handler'
import GrandChild from './GrandChild.vue'
const { register } = useFormContext()
</script>
```

```vue
<!-- GrandChild.vue component -->
<template>
<input v-bind="register('anotherField2')" />
</template>
<script setup lang="ts">
import { useFormContext } from 'vue-form-handler'
const { register } = useFormContext()
</script>
```

Feel free to play with it, you can also combine `register` and `build` approaches for the same form, within the same and in different files

::: warning
Be aware that for a basic and usual functionality, We provide with a default key, If you have more than one `useFormHandler` usage in the same tree, the `injection keys` will collide, so you'll need to pass a specific one to `useFormHandler` and then to its consequent consumer, i.e:

:::details
```vue
<!-- Parent.vue component -->
<template>
<div>
<form @submit.prevent="handleSubmit(successFn)">
<input v-bind="register('firstName')" />
<input v-bind="register('lastName')" />
<Child></Child>
<button type="submit">Submit</button>
</form>
<form @submit.prevent="handleSubmit2(successFn)">
<input v-bind="register2('firstName')" />
<input v-bind="register2('lastName')" />
<AnotherChild></AnotherChild>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script setup lang="ts">
import { useFormHandler } from 'vue-form-handler'
import Child from './Child.vue'
import AnotherChild from './AnotherChild.vue'
const { handleSubmit, register } = useFormHandler({ injectionKey: 'form1' });
const { handleSubmit: handleSubmit2, register: register2 } = useFormHandler({ injectionKey: 'form2' });
const successFn = (form: Record<string, any>) => {
console.log({ form })
}
</script>
```

```vue
<!-- Child.vue component -->
<template>
<input v-bind="register('anotherField')" />
</template>
<script setup lang="ts">
import { useFormContext } from 'vue-form-handler'
const { register } = useFormContext('form1')
</script>
```

```vue
<!-- AnotherChild.vue component -->
<template>
<input v-bind="register('anotherField')" />
</template>
<script setup lang="ts">
import { useFormContext } from 'vue-form-handler'
const { register } = useFormContext('form2')
</script>
```
:::

::: tip
Please refer to [Working with Symbol Keys](https://vuejs.org/guide/components/provide-inject.html#working-with-symbol-keys) for a quick read and understanding how provide/inject is intended to be used, and a correct way of defining your keys, as passing plain strings might not be the best approach, but rather using `Symbol`
:::
2 changes: 2 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ export const BaseInputEmits: BaseControlEmits = [
'blur',
'clear',
]

export const defaultInjectionKey = Symbol('formHandler')
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './FormHandler'
export * from './useFormHandler'
export * from './useFormContext'
export * from './types'
export * from './constants'
78 changes: 78 additions & 0 deletions src/test/context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { defineComponent } from '@vue/runtime-core'
import { mount } from '@vue/test-utils'
import { expect, it, describe } from 'vitest'
import {
useFormContext,
useFormHandler,
FormHandler,
InjectionKey,
} from '../index'

describe('useFormContext', () => {
const registerComponents = (injectionKey?: InjectionKey) => {
const Child = defineComponent({
template: `<template>
{{props}}
</template>`,
setup() {
const props = useFormContext(injectionKey)
return {
props,
}
},
})
const Parent = defineComponent({
template: `<template>
<Child></Child>
</template>`,
components: { Child },
setup() {
useFormHandler({ injectionKey })
},
})

return Parent
}
it('should provide values and formState', () => {
expect(FormHandler).toBeTruthy()
const Parent = registerComponents()
const wrapper = mount(Parent, {
slots: {
default: `<template #default="props">
{{props}}
</template>
`,
},
})
expect(wrapper.html()).toContain('values')
expect(wrapper.html()).toContain('formState')
})
it('should work with string injection keys', () => {
expect(FormHandler).toBeTruthy()
const Parent = registerComponents('test')
const wrapper = mount(Parent, {
slots: {
default: `<template #default="props">
{{props}}
</template>
`,
},
})
expect(wrapper.html()).toContain('values')
expect(wrapper.html()).toContain('formState')
})
it('should work with Symbol injection keys', () => {
expect(FormHandler).toBeTruthy()
const Parent = registerComponents(Symbol('test'))
const wrapper = mount(Parent, {
slots: {
default: `<template #default="props">
{{props}}
</template>
`,
},
})
expect(wrapper.html()).toContain('values')
expect(wrapper.html()).toContain('formState')
})
})
5 changes: 5 additions & 0 deletions src/types/formHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ export type FormValidation = (
values: Record<string, any>
) => Promise<boolean> | boolean

export type InjectionKey = string | Symbol

export interface FormHandlerParams {
/** Values to initialize the form */
initialValues?:
Expand All @@ -142,6 +144,9 @@ export interface FormHandlerParams {

/** Validation behavior options */
validationMode?: 'onChange' | 'onBlur' | 'onSubmit' | 'always'

/** Injection key to override the default */
injectionKey?: InjectionKey
}
export interface FormHandlerReturn {
/** Current form state */
Expand Down
7 changes: 7 additions & 0 deletions src/useFormContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { inject } from '@vue/runtime-core'
import { defaultInjectionKey } from './constants'
import { FormHandlerReturn, InjectionKey } from './types'

export const useFormContext = (
key: InjectionKey = defaultInjectionKey
): FormHandlerReturn => inject(key) as FormHandlerReturn
20 changes: 16 additions & 4 deletions src/useFormHandler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Build } from './types/formHandler'
import { Build, FormHandlerReturn } from './types/formHandler'
import { NativeValidations } from './types/validations'
import { DEFAULT_FIELD_VALUE } from './constants'
import { DEFAULT_FIELD_VALUE, defaultInjectionKey } from './constants'
import {
ModifiedValues,
TriggerValidation,
Expand All @@ -27,7 +27,14 @@ import {
RegisterOptions,
RegisterReturn,
} from './types'
import { computed, reactive, readonly, unref, watch } from '@vue/runtime-core'
import {
computed,
provide,
reactive,
readonly,
unref,
watch,
} from '@vue/runtime-core'
import { isEqual } from 'lodash-es'
import {
getNativeFieldValue,
Expand All @@ -53,6 +60,7 @@ export const useFormHandler: UseFormHandler = ({
interceptor,
validate,
validationMode = 'onChange',
injectionKey = defaultInjectionKey,
} = {}) => {
const values: Record<string, any> = reactive({ ...unref(initialValues) })
const formState = reactive<FormState>({ ...initialState() })
Expand Down Expand Up @@ -332,7 +340,7 @@ export const useFormHandler: UseFormHandler = ({
{ deep: true }
)

return {
const toExpose: FormHandlerReturn = {
clearError,
clearField,
formState: readonly(formState),
Expand All @@ -348,4 +356,8 @@ export const useFormHandler: UseFormHandler = ({
unregister,
values: readonly(values),
}

provide(injectionKey, toExpose)

return toExpose
}

1 comment on commit 5455ecb

@vercel
Copy link

@vercel vercel bot commented on 5455ecb May 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.