Skip to content

Commit

Permalink
feat: form transform value
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <i@innei.in>
  • Loading branch information
Innei committed Mar 24, 2024
1 parent d6d0b50 commit 661fe5c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
14 changes: 10 additions & 4 deletions src/components/ui/form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,16 @@ export const Form = forwardRef<
},
getCurrentValues: () => {
return Object.fromEntries(
Object.entries(jotaiStore.get(fieldsAtom)).map(([key, value]) => [
key,
(value as any as Field).$ref?.value,
]),
Object.entries(jotaiStore.get(fieldsAtom)).map(([key, value]) => {
const nextValue = (value as any as Field).$ref?.value

return [
key,
(value as Field).transform
? (value as Field).transform?.(nextValue)
: nextValue,
]
}),
)
},
addField: (name: string, field: Field) => {
Expand Down
5 changes: 3 additions & 2 deletions src/components/ui/form/FormInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { useForm, useFormConfig } from './FormContext'
export const FormInput: FC<
DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> &
FormFieldBaseProps<string>
> = memo(({ className, rules, onKeyDown, ...rest }) => {
> = memo(({ className, rules, onKeyDown, transform, ...rest }) => {
const FormCtx = useForm()
if (!FormCtx) throw new Error('FormInput must be used inside <FormContext />')
const { showErrorMessage } = useFormConfig()
Expand Down Expand Up @@ -44,12 +44,13 @@ export const FormInput: FC<
addField(name, {
rules,
$ref: inputRef.current,
transform,
})

return () => {
removeField(name)
}
}, [rest.name, rules])
}, [rest.name, rules, transform])

const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
Expand Down
7 changes: 6 additions & 1 deletion src/components/ui/form/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ export interface Rule<T = unknown> {
type ValidateStatus = 'error' | 'success'
export interface Field {
rules: (Rule<any> & { status?: ValidateStatus })[]
/**
* `getCurrentValues` will return the transformed value
* @param value field value
*/
transform?: <X, T = string>(value: T) => X

$ref: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null
}

export type FormFieldBaseProps<T> = {
export interface FormFieldBaseProps<T> extends Pick<Field, 'transform'> {
rules?: Rule<T>[]
}

0 comments on commit 661fe5c

Please sign in to comment.