/
form-control.tsx
269 lines (243 loc) · 7.43 KB
/
form-control.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { createContext } from "@chakra-ui/react-context"
import { PropGetter } from "@chakra-ui/react-types"
import { mergeRefs } from "@chakra-ui/react-use-merge-refs"
import {
chakra,
forwardRef,
HTMLChakraProps,
omitThemingProps,
SystemStyleObject,
ThemingProps,
useMultiStyleConfig,
} from "@chakra-ui/system"
import { cx, dataAttr } from "@chakra-ui/shared-utils"
import { useCallback, useId, useState } from "react"
const [FormControlStylesProvider, useFormControlStyles] = createContext<
Record<string, SystemStyleObject>
>({
name: `FormControlStylesContext`,
errorMessage: `useFormControlStyles returned is 'undefined'. Seems you forgot to wrap the components in "<FormControl />" `,
})
export { useFormControlContext, useFormControlStyles }
export interface FormControlOptions {
/**
* If `true`, the form control will be required. This has 2 side effects:
* - The `FormLabel` will show a required indicator
* - The form element (e.g, Input) will have `aria-required` set to `true`
*/
isRequired?: boolean
/**
* If `true`, the form control will be disabled. This has 2 side effects:
* - The `FormLabel` will have `data-disabled` attribute
* - The form element (e.g, Input) will be disabled
*/
isDisabled?: boolean
/**
* If `true`, the form control will be invalid. This has 2 side effects:
* - The `FormLabel` and `FormErrorIcon` will have `data-invalid` set to `true`
* - The form element (e.g, Input) will have `aria-invalid` set to `true`
*/
isInvalid?: boolean
/**
* If `true`, the form control will be readonly
*/
isReadOnly?: boolean
}
interface FormControlContext extends FormControlOptions {
/**
* The label text used to inform users as to what information is
* requested for a text field.
*/
label?: string
/**
* The custom `id` to use for the form control. This is passed directly to the form element (e.g, Input).
* - The form element (e.g. Input) gets the `id`
* - The form label id: `form-label-${id}`
* - The form error text id: `form-error-text-${id}`
* - The form helper text id: `form-helper-text-${id}`
*/
id?: string
}
type FormControlProviderContext = Omit<
ReturnType<typeof useFormControlProvider>,
"getRootProps" | "htmlProps"
>
const [FormControlProvider, useFormControlContext] =
createContext<FormControlProviderContext>({
strict: false,
name: "FormControlContext",
})
function useFormControlProvider(props: FormControlContext) {
const {
id: idProp,
isRequired,
isInvalid,
isDisabled,
isReadOnly,
...htmlProps
} = props
// Generate all the required ids
const uuid = useId()
const id = idProp || `field-${uuid}`
const labelId = `${id}-label`
const feedbackId = `${id}-feedback`
const helpTextId = `${id}-helptext`
/**
* Track whether the `FormErrorMessage` has been rendered.
* We use this to append its id the `aria-describedby` of the `input`.
*/
const [hasFeedbackText, setHasFeedbackText] = useState(false)
/**
* Track whether the `FormHelperText` has been rendered.
* We use this to append its id the `aria-describedby` of the `input`.
*/
const [hasHelpText, setHasHelpText] = useState(false)
// Track whether the form element (e.g, `input`) has focus.
const [isFocused, setFocus] = useState(false)
const getHelpTextProps = useCallback<PropGetter>(
(props = {}, forwardedRef = null) => ({
id: helpTextId,
...props,
/**
* Notify the field context when the help text is rendered on screen,
* so we can apply the correct `aria-describedby` to the field (e.g. input, textarea).
*/
ref: mergeRefs(forwardedRef, (node) => {
if (!node) return
setHasHelpText(true)
}),
}),
[helpTextId],
)
const getLabelProps = useCallback<PropGetter>(
(props = {}, forwardedRef = null) => ({
...props,
ref: forwardedRef,
"data-focus": dataAttr(isFocused),
"data-disabled": dataAttr(isDisabled),
"data-invalid": dataAttr(isInvalid),
"data-readonly": dataAttr(isReadOnly),
id: props.id ?? labelId,
htmlFor: props.htmlFor ?? id,
}),
[id, isDisabled, isFocused, isInvalid, isReadOnly, labelId],
)
const getErrorMessageProps = useCallback<PropGetter>(
(props = {}, forwardedRef = null) => ({
id: feedbackId,
...props,
/**
* Notify the field context when the error message is rendered on screen,
* so we can apply the correct `aria-describedby` to the field (e.g. input, textarea).
*/
ref: mergeRefs(forwardedRef, (node) => {
if (!node) return
setHasFeedbackText(true)
}),
"aria-live": "polite",
}),
[feedbackId],
)
const getRootProps = useCallback<PropGetter>(
(props = {}, forwardedRef = null) => ({
...props,
...htmlProps,
ref: forwardedRef,
role: "group",
}),
[htmlProps],
)
const getRequiredIndicatorProps = useCallback<PropGetter>(
(props = {}, forwardedRef = null) => ({
...props,
ref: forwardedRef,
role: "presentation",
"aria-hidden": true,
children: props.children || "*",
}),
[],
)
return {
isRequired: !!isRequired,
isInvalid: !!isInvalid,
isReadOnly: !!isReadOnly,
isDisabled: !!isDisabled,
isFocused: !!isFocused,
onFocus: () => setFocus(true),
onBlur: () => setFocus(false),
hasFeedbackText,
setHasFeedbackText,
hasHelpText,
setHasHelpText,
id,
labelId,
feedbackId,
helpTextId,
htmlProps,
getHelpTextProps,
getErrorMessageProps,
getRootProps,
getLabelProps,
getRequiredIndicatorProps,
}
}
export interface FormControlProps
extends HTMLChakraProps<"div">,
ThemingProps<"FormControl">,
FormControlContext {}
/**
* FormControl provides context such as
* `isInvalid`, `isDisabled`, and `isRequired` to form elements.
*
* This is commonly used in form elements such as `input`,
* `select`, `textarea`, etc.
*
* @see Docs https://chakra-ui.com/docs/components/form-control
*/
export const FormControl = forwardRef<FormControlProps, "div">(
function FormControl(props, ref) {
const styles = useMultiStyleConfig("Form", props)
const ownProps = omitThemingProps(props)
const {
getRootProps,
htmlProps: _,
...context
} = useFormControlProvider(ownProps)
const className = cx("chakra-form-control", props.className)
return (
<FormControlProvider value={context}>
<FormControlStylesProvider value={styles}>
<chakra.div
{...getRootProps({}, ref)}
className={className}
__css={styles["container"]}
/>
</FormControlStylesProvider>
</FormControlProvider>
)
},
)
FormControl.displayName = "FormControl"
export interface HelpTextProps extends HTMLChakraProps<"div"> {}
/**
* FormHelperText
*
* Assistive component that conveys additional guidance
* about the field, such as how it will be used and what
* types in values should be provided.
*/
export const FormHelperText = forwardRef<HelpTextProps, "div">(
function FormHelperText(props, ref) {
const field = useFormControlContext()
const styles = useFormControlStyles()
const className = cx("chakra-form__helper-text", props.className)
return (
<chakra.div
{...field?.getHelpTextProps(props, ref)}
__css={styles.helperText}
className={className}
/>
)
},
)
FormHelperText.displayName = "FormHelperText"