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

✅ Improve type support #65

Merged
merged 5 commits into from
Jul 15, 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
39 changes: 22 additions & 17 deletions docs/api/use-form-handler/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,42 +23,49 @@ Coming soon...
<script setup lang="ts">
import { useFormHandler } from 'vue-form-handler'

const successFn = (result: Record<string, any>) => { console.log(result) }
const errorFn = (result: Record<string, string | undefined>) => { console.warn(result) }
const successFn = (result: Record<string, any>) => {
console.log(result)
}
const errorFn = (result: Record<string, string | undefined>) => {
console.warn(result)
}
const { build, handleSubmit, values, formState } = useFormHandler()

const form = build({
name: {
required: true,
pattern: {
value: /^[a-zA-Z]+$/,
message: 'Only letters are allowed'
}
message: 'Only letters are allowed',
},
},
email: {
required: true,
pattern: {
value: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
message: 'Please enter a valid email'
}
message: 'Please enter a valid email',
},
},
password: {
required: true,
pattern: {
value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/,
message: 'Password must contain at least 8 characters, one uppercase, one lowercase and one number'
}
message:
'Password must contain at least 8 characters, one uppercase, one lowercase and one number',
},
},
passwordConfirmation: {
required: true,
pattern: {
value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/,
message: 'Password must contain at least 8 characters, one uppercase, one lowercase and one number'
message:
'Password must contain at least 8 characters, one uppercase, one lowercase and one number',
},
validate: {
match: (value: string) => value === values.password || 'Passwords do not match'
}
}
match: (value: string) =>
value === values.password || 'Passwords do not match',
},
},
})
</script>
```
Expand All @@ -68,9 +75,7 @@ Notice how the template looks much cleaner with this approach, and this helps us
## Type Declarations

```ts
export interface Build<T = Record<string, RegisterOptions>> {
(configuration: T | Ref<T> | ComputedRef<T>): ComputedRef<
Record<keyof T, RegisterReturn>
>
}
export type Build = <T extends Record<string, RegisterOptions>>(
configuration: T | Ref<T> | ComputedRef<T>
) => ComputedRef<Record<keyof T, Readonly<RegisterReturn>>>
```
1 change: 0 additions & 1 deletion src/test/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ describe('useFormHandler()', () => {
})

expect(form.value.field.name).toBe('field')
expect(form.value.field.error).toBeUndefined()
expect(form.value.field.onBlur).toBeDefined()
expect(form.value.field.isDirty).toBeUndefined()
expect(form.value.field.isTouched).toBeUndefined()
Expand Down
1 change: 0 additions & 1 deletion src/test/register.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ describe('register()', () => {
const { values, register } = useFormHandler()
const field = register('field')
expect(field.name).toBe('field')
expect(field.error).toBeUndefined()
expect(field.onBlur).toBeDefined()
expect(field.isDirty).toBeUndefined()
expect(field.isTouched).toBeUndefined()
Expand Down
3 changes: 0 additions & 3 deletions src/types/baseControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ export interface BaseControlProps {
/** Name of the control */
name: string

/** Current error of the control */
error: string | undefined

/** Value binding for native inputs */
ref: (fieldRef: any) => void

Expand Down
8 changes: 3 additions & 5 deletions src/types/formHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,9 @@ export type HandleSubmit = (
errorFn?: HandleSubmitErrorFn
) => void

export interface Build<T = Record<string, RegisterOptions>> {
(configuration: T | Ref<T> | ComputedRef<T>): ComputedRef<
Record<keyof T, RegisterReturn>
>
}
export type Build = <T extends Record<string, RegisterOptions>>(
configuration: T | Ref<T> | ComputedRef<T>
) => ComputedRef<Record<keyof T, Readonly<RegisterReturn>>>

export interface InterceptorParams {
/** Name of the field that is currently about to be set*/
Expand Down
12 changes: 5 additions & 7 deletions src/useFormHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
ValidationsConfiguration,
Unregister,
FieldReference,
RegisterOptions,
RegisterReturn,
} from './types'
import {
Expand All @@ -44,7 +43,7 @@ import {
refFn,
transformValidations,
} from './logic'
import { isNativeControl } from './utils'
import { isNativeControl, objectKeys } from './utils'

export const initialState = () => ({
touched: {},
Expand Down Expand Up @@ -271,7 +270,6 @@ export const useFormHandler: UseFormHandler = ({
return {
name,
modelValue: values[name],
error: formState.errors[name],
'onUpdate:modelValue': async (value: any) =>
await handleChange(name, value),
ref: refFn(name, _refs, values),
Expand Down Expand Up @@ -305,12 +303,12 @@ export const useFormHandler: UseFormHandler = ({
}

const build: Build = (configuration) => {
const staticConfig = unref(configuration) as Record<string, RegisterOptions>
const staticConfig = unref(configuration)
return computed(() =>
Object.keys(staticConfig).reduce((acc, key) => {
acc[key] = register(key, staticConfig[key])
objectKeys(staticConfig).reduce((acc, key) => {
acc[key] = register(String(key), staticConfig[key])
return acc
}, {} as Record<string, RegisterReturn>)
}, {} as Record<keyof typeof staticConfig, Readonly<RegisterReturn>>)
)
}

Expand Down
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export { default as min } from './min'
export { default as minLength } from './minLength'
export { default as pattern } from './pattern'
export { default as required } from './required'
export { default as objectKeys } from './objectKeys'
1 change: 1 addition & 0 deletions src/utils/objectKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default <T extends object>(obj: T) => Object.keys(obj) as (keyof T)[]
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"noImplicitAny": true,
"types": ["vitest/importMeta"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts"],
"include": ["src/**/*.ts", "src/**/*.d.ts", "./*d.ts"],
"references": [
{
"path": "./tsconfig.node.json"
Expand Down
5 changes: 5 additions & 0 deletions vue.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { ComputedRef, Ref } from '@vue/runtime-core'

declare module '@vue/runtime-core' {
export function unref<T>(ref: T | Ref<T> | ComputedRef<T>): T
}