Skip to content

Latest commit

 

History

History
176 lines (159 loc) · 5.93 KB

useInput.ts

File metadata and controls

176 lines (159 loc) · 5.93 KB
 
Apr 29, 2024
Apr 29, 2024
1
import { ReactElement, useEffect, useId } from 'react';
Aug 9, 2019
Aug 9, 2019
2
import {
Jan 20, 2022
Jan 20, 2022
3
4
5
6
7
8
9
ControllerFieldState,
ControllerRenderProps,
useController,
UseControllerProps,
UseControllerReturn,
UseFormStateReturn,
} from 'react-hook-form';
Dec 7, 2021
Dec 7, 2021
10
import get from 'lodash/get';
Jan 20, 2022
Jan 20, 2022
11
12
13
import { useRecordContext } from '../controller';
import { composeValidators, Validator } from './validate';
Aug 9, 2019
Aug 9, 2019
14
import isRequired from './isRequired';
Jan 19, 2021
Jan 19, 2021
15
import { useFormGroupContext } from './useFormGroupContext';
Jan 11, 2022
Jan 11, 2022
16
import { useFormGroups } from './useFormGroups';
Jan 20, 2022
Jan 20, 2022
17
import { useApplyInputDefaultValues } from './useApplyInputDefaultValues';
Apr 11, 2023
Apr 11, 2023
18
import { useEvent } from '../util';
Jan 11, 2024
Jan 11, 2024
19
import { useWrappedSource } from '../core';
Aug 9, 2019
Aug 9, 2019
20
Oct 14, 2022
Oct 14, 2022
21
// replace null or undefined values by empty string to avoid controlled/uncontrolled input warning
Oct 13, 2022
Oct 13, 2022
22
const defaultFormat = (value: any) => (value == null ? '' : value);
Oct 14, 2022
Oct 14, 2022
23
24
// parse empty string into null as it's more suitable for a majority of backends
const defaultParse = (value: string) => (value === '' ? null : value);
Oct 13, 2022
Oct 13, 2022
25
Apr 7, 2023
Apr 7, 2023
26
27
28
export const useInput = <ValueType = any>(
props: InputProps<ValueType>
): UseInputValue => {
Jan 20, 2022
Jan 20, 2022
29
30
const {
defaultValue,
Oct 13, 2022
Oct 13, 2022
31
format = defaultFormat,
Jan 20, 2022
Jan 20, 2022
32
33
34
id,
isRequired: isRequiredOption,
name,
Apr 11, 2023
Apr 11, 2023
35
36
onBlur: initialOnBlur,
onChange: initialOnChange,
Jun 17, 2024
Jun 17, 2024
37
parse: parseProp = defaultParse,
Jan 20, 2022
Jan 20, 2022
38
39
40
41
source,
validate,
...options
} = props;
Jan 11, 2024
Jan 11, 2024
42
const finalSource = useWrappedSource(source);
Jan 11, 2024
Jan 11, 2024
43
const finalName = name || finalSource;
Jan 19, 2021
Jan 19, 2021
44
const formGroupName = useFormGroupContext();
Jan 11, 2022
Jan 11, 2022
45
const formGroups = useFormGroups();
Dec 7, 2021
Dec 7, 2021
46
const record = useRecordContext();
Jun 17, 2024
Jun 17, 2024
47
48
// @ts-ignore
const parse = useEvent(parseProp);
Apr 29, 2024
Apr 29, 2024
49
const defaultId = useId();
Jan 19, 2021
Jan 19, 2021
50
Aug 30, 2024
Aug 30, 2024
51
if (!finalName && process.env.NODE_ENV === 'development') {
Jan 11, 2024
Jan 11, 2024
52
console.warn(
Aug 30, 2024
Aug 30, 2024
53
'Input components require either a source or a name prop.'
Jan 11, 2024
Jan 11, 2024
54
55
56
);
}
Jan 19, 2021
Jan 19, 2021
57
useEffect(() => {
Jan 18, 2022
Jan 18, 2022
58
if (!formGroups || formGroupName == null) {
Jan 19, 2021
Jan 19, 2021
59
60
return;
}
Jan 18, 2022
Jan 18, 2022
61
Jan 11, 2024
Jan 11, 2024
62
formGroups.registerField(finalSource, formGroupName);
Jan 19, 2021
Jan 19, 2021
63
64
return () => {
Jan 11, 2024
Jan 11, 2024
65
formGroups.unregisterField(finalSource, formGroupName);
Jan 19, 2021
Jan 19, 2021
66
};
Jan 11, 2024
Jan 11, 2024
67
}, [formGroups, formGroupName, finalSource]);
Aug 9, 2019
Aug 9, 2019
68
69
70
71
72
const sanitizedValidate = Array.isArray(validate)
? composeValidators(validate)
: validate;
Jan 20, 2022
Jan 20, 2022
73
// Fetch the defaultValue from the record if available or apply the provided defaultValue.
Feb 7, 2022
Feb 7, 2022
74
// This ensures dynamically added inputs have their value set correctly (ArrayInput for example).
Jan 24, 2022
Jan 24, 2022
75
// We don't do this for the form level defaultValues so that it works as it should in react-hook-form
Feb 7, 2022
Feb 7, 2022
76
// (i.e. field level defaultValue override form level defaultValues for this field).
May 23, 2024
May 23, 2024
77
78
79
80
81
const {
field: controllerField,
fieldState,
formState,
} = useController({
Sep 25, 2023
Sep 25, 2023
82
name: finalName,
Jan 11, 2024
Jan 11, 2024
83
defaultValue: get(record, finalSource, defaultValue),
Sep 25, 2023
Sep 25, 2023
84
85
86
rules: {
validate: async (value, values) => {
if (!sanitizedValidate) return true;
Aug 19, 2024
Aug 19, 2024
87
88
const error = await sanitizedValidate(value, values, {
...props,
Aug 19, 2024
Aug 19, 2024
89
finalSource,
Aug 19, 2024
Aug 19, 2024
90
});
Sep 25, 2023
Sep 25, 2023
91
Jan 20, 2022
Jan 20, 2022
92
if (!error) return true;
Aug 17, 2023
Aug 17, 2023
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)}`;
Jan 20, 2022
Jan 20, 2022
100
},
Aug 9, 2019
Aug 9, 2019
101
},
Jan 20, 2022
Jan 20, 2022
102
103
...options,
});
Aug 9, 2019
Aug 9, 2019
104
Feb 7, 2022
Feb 7, 2022
105
// Because our forms may receive an asynchronously loaded record for instance,
Jan 25, 2022
Jan 25, 2022
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.
Jun 7, 2023
Jun 7, 2023
109
useApplyInputDefaultValues({ inputProps: props });
Aug 9, 2019
Aug 9, 2019
110
Apr 11, 2023
Apr 11, 2023
111
const onBlur = useEvent((...event: any[]) => {
May 15, 2023
May 15, 2023
112
controllerField.onBlur();
Apr 11, 2023
Apr 11, 2023
113
114
115
116
117
118
if (initialOnBlur) {
initialOnBlur(...event);
}
});
const onChange = useEvent((...event: any[]) => {
May 23, 2024
May 23, 2024
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;
Apr 11, 2023
Apr 11, 2023
124
controllerField.onChange(parse ? parse(eventOrValue) : eventOrValue);
May 15, 2023
May 15, 2023
125
126
127
if (initialOnChange) {
initialOnChange(...event);
}
Apr 11, 2023
Apr 11, 2023
128
129
});
Jan 20, 2022
Jan 20, 2022
130
131
const field = {
...controllerField,
Jan 20, 2022
Jan 20, 2022
132
value: format ? format(controllerField.value) : controllerField.value,
Apr 11, 2023
Apr 11, 2023
133
134
onBlur,
onChange,
Jan 20, 2022
Jan 20, 2022
135
136
};
Aug 9, 2019
Aug 9, 2019
137
return {
Apr 30, 2024
Apr 30, 2024
138
id: id || defaultId,
Jan 20, 2022
Jan 20, 2022
139
140
141
field,
fieldState,
formState,
Feb 5, 2021
Feb 5, 2021
142
isRequired: isRequiredOption || isRequired(validate),
Aug 9, 2019
Aug 9, 2019
143
144
};
};
Feb 8, 2022
Feb 8, 2022
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;
May 11, 2022
May 11, 2022
162
type?: string;
Feb 8, 2022
Feb 8, 2022
163
164
165
resource?: string;
source: string;
validate?: Validator | Validator[];
Jun 24, 2024
Jun 24, 2024
166
167
readOnly?: boolean;
disabled?: boolean;
Feb 8, 2022
Feb 8, 2022
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;
};