-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
useInput.ts
176 lines (159 loc) · 5.93 KB
1
import { ReactElement, useEffect, useId } from 'react';
2
import {
3
4
5
6
7
8
9
ControllerFieldState,
ControllerRenderProps,
useController,
UseControllerProps,
UseControllerReturn,
UseFormStateReturn,
} from 'react-hook-form';
10
import get from 'lodash/get';
11
12
13
import { useRecordContext } from '../controller';
import { composeValidators, Validator } from './validate';
14
import isRequired from './isRequired';
15
import { useFormGroupContext } from './useFormGroupContext';
16
import { useFormGroups } from './useFormGroups';
17
import { useApplyInputDefaultValues } from './useApplyInputDefaultValues';
18
import { useEvent } from '../util';
19
import { useWrappedSource } from '../core';
20
21
// replace null or undefined values by empty string to avoid controlled/uncontrolled input warning
22
const defaultFormat = (value: any) => (value == null ? '' : value);
23
24
// parse empty string into null as it's more suitable for a majority of backends
const defaultParse = (value: string) => (value === '' ? null : value);
25
26
27
28
export const useInput = <ValueType = any>(
props: InputProps<ValueType>
): UseInputValue => {
29
30
const {
defaultValue,
31
format = defaultFormat,
32
33
34
id,
isRequired: isRequiredOption,
name,
35
36
onBlur: initialOnBlur,
onChange: initialOnChange,
37
parse: parseProp = defaultParse,
38
39
40
41
source,
validate,
...options
} = props;
42
const finalSource = useWrappedSource(source);
43
const finalName = name || finalSource;
44
const formGroupName = useFormGroupContext();
45
const formGroups = useFormGroups();
46
const record = useRecordContext();
47
48
// @ts-ignore
const parse = useEvent(parseProp);
49
const defaultId = useId();
50
51
if (!finalName && process.env.NODE_ENV === 'development') {
52
console.warn(
53
'Input components require either a source or a name prop.'
54
55
56
);
}
57
useEffect(() => {
58
if (!formGroups || formGroupName == null) {
59
60
return;
}
61
62
formGroups.registerField(finalSource, formGroupName);
63
64
return () => {
65
formGroups.unregisterField(finalSource, formGroupName);
66
};
67
}, [formGroups, formGroupName, finalSource]);
68
69
70
71
72
const sanitizedValidate = Array.isArray(validate)
? composeValidators(validate)
: validate;
73
// Fetch the defaultValue from the record if available or apply the provided defaultValue.
74
// This ensures dynamically added inputs have their value set correctly (ArrayInput for example).
75
// We don't do this for the form level defaultValues so that it works as it should in react-hook-form
76
// (i.e. field level defaultValue override form level defaultValues for this field).
77
78
79
80
81
const {
field: controllerField,
fieldState,
formState,
} = useController({
82
name: finalName,
83
defaultValue: get(record, finalSource, defaultValue),
84
85
86
rules: {
validate: async (value, values) => {
if (!sanitizedValidate) return true;
87
88
const error = await sanitizedValidate(value, values, {
...props,
89
finalSource,
90
});
91
92
if (!error) return true;
93
94
95
96
97
98
99
// react-hook-form expects errors to be plain strings but our validators can return objects
// that have message and args.
// To avoid double translation for users that validate with a schema instead of our validators
// we use a special format for our validators errors.
// The ValidationError component will check for this format and extract the message and args
// to translate.
return `@@react-admin@@${JSON.stringify(error)}`;
100
},
101
},
102
103
...options,
});
104
105
// Because our forms may receive an asynchronously loaded record for instance,
106
107
108
// they may reset their default values which would override the input default value.
// This hook ensures that the input default value is applied when a new record is loaded but has
// no value for the input.
109
useApplyInputDefaultValues({ inputProps: props });
110
111
const onBlur = useEvent((...event: any[]) => {
112
controllerField.onBlur();
113
114
115
116
117
118
if (initialOnBlur) {
initialOnBlur(...event);
}
});
const onChange = useEvent((...event: any[]) => {
119
120
121
122
123
const eventOrValue = (
props.type === 'checkbox' && event[0]?.target?.value === 'on'
? event[0].target.checked
: event[0]?.target?.value ?? event[0]
) as any;
124
controllerField.onChange(parse ? parse(eventOrValue) : eventOrValue);
125
126
127
if (initialOnChange) {
initialOnChange(...event);
}
128
129
});
130
131
const field = {
...controllerField,
132
value: format ? format(controllerField.value) : controllerField.value,
133
134
onBlur,
onChange,
135
136
};
137
return {
138
id: id || defaultId,
139
140
141
field,
fieldState,
formState,
142
isRequired: isRequiredOption || isRequired(validate),
143
144
};
};
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
export type InputProps<ValueType = any> = Omit<
UseControllerProps,
'name' | 'defaultValue' | 'rules'
> &
Partial<UseControllerReturn> & {
alwaysOn?: any;
defaultValue?: any;
format?: (value: ValueType) => any;
id?: string;
isRequired?: boolean;
label?: string | ReactElement | false;
helperText?: string | ReactElement | false;
name?: string;
onBlur?: (...event: any[]) => void;
onChange?: (...event: any[]) => void;
parse?: (value: any) => ValueType;
162
type?: string;
163
164
165
resource?: string;
source: string;
validate?: Validator | Validator[];
166
167
readOnly?: boolean;
disabled?: boolean;
168
169
170
171
172
173
174
175
176
};
export type UseInputValue = {
id: string;
isRequired: boolean;
field: ControllerRenderProps;
formState: UseFormStateReturn<Record<string, string>>;
fieldState: ControllerFieldState;
};