-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.tsx
288 lines (266 loc) · 8.13 KB
/
form.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { forwardRef, ReactNode, useRef } from 'react'
import {
Control,
Controller,
FieldErrors,
FieldPath,
FieldValues,
useFormState,
} from 'react-hook-form'
import { generalFormErrorKey } from '../lib/schemas'
import { Button, ButtonProps } from './Button'
import { DropdownItem, DropdownSelect } from './DropdownSelect'
import { IconOkCircle } from './icons'
import { LoadingAnimation } from './LoadingAnimation'
export function FormLabel({
...props
}: React.ComponentPropsWithoutRef<'label'>): JSX.Element {
return (
<label
className="block text-left text-sm uppercase tracking-widest text-gray-400"
{...props}
>
{props.children}
</label>
)
}
type FormSubmitPropsShared<TFieldValues extends FieldValues> = {
control: Control<TFieldValues>
isLoading: boolean
/** By default, we don't allow submitting initially without changes to trigger validation. This can be disabled herewith. */
isInitiallySubmittable?: boolean
}
type FormSubmitProps<TFieldValues extends FieldValues> =
FormSubmitPropsShared<TFieldValues> & {
icon?: ButtonProps['icon']
isBig?: boolean
children?: ReactNode
}
export function useIsSubmitEnabled<TFieldValues extends FieldValues>(
props: FormSubmitPropsShared<TFieldValues>,
) {
const { isValid, isValidating, submitCount, isDirty, isSubmitting } =
useFormState({ control: props.control })
const isValidForm = !!isValid && !isValidating
/** Even an invalid form can be submitted if it has not been submitted yet and if it is initially submittable. */
const isInitialSubmit = !!props.isInitiallySubmittable && submitCount === 0
const isEnabled =
((isValidForm && !!isDirty) || isInitialSubmit) && !isSubmitting
return isEnabled
}
export function FormSubmit<TFieldValues extends FieldValues>(
props: FormSubmitProps<TFieldValues>,
): JSX.Element {
const isEnabled = useIsSubmitEnabled(props)
return (
<Button
disabled={!isEnabled}
isSubmit={true}
icon={props.icon ?? <IconOkCircle />}
showLoading={props.isLoading}
isBig={props.isBig}
>
{props.children ?? <span>Save</span>}
<input className="hidden" type="submit" />
</Button>
)
}
type InputProps = React.ComponentPropsWithoutRef<'input'> & {
small?: boolean
hasLabel?: boolean
validationErrorMessage: string | undefined
/** This is used in forms that should submit on blur. */
blurOnEnterPressed?: boolean
isSpecial?: boolean
isLoading?: boolean
icon?: ReactNode
textAlignCenter?: boolean
hideBottomBorderForSpecial?: boolean
}
/**
* Additional props:
* - small?: boolean
* - hasLabel?: boolean
* - validationErrorMessage: string | undefined
* - blurOnEnterPressed?: boolean
* - isSpecial?: boolean
* - isLoading?: boolean
* - icon?: ReactNode
* - textAlignCenter?: boolean
* - hideBottomBorderForSpecial?: boolean
*/
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
small = false,
hasLabel = true,
validationErrorMessage = undefined,
blurOnEnterPressed = false,
isSpecial = false,
isLoading = false,
textAlignCenter = false,
hideBottomBorderForSpecial = false,
icon,
...props
},
ref,
): JSX.Element {
return (
<div className="relative">
{/* flex & items-center for the loading animation */}
<div className="flex items-center">
<input
type={props.type ?? 'text'}
className={
`${textAlignCenter ? 'text-center' : 'text-left'}` +
' relative block w-full disabled:cursor-not-allowed ' +
(isSpecial
? `${
hideBottomBorderForSpecial ? 'border-none' : 'border-b-2'
} border-l-0 border-r-0 border-t-0 border-dtertiary bg-transparent outline-none focus:border-dprimary focus:ring-0 ${
small ? 'p-3 px-8' : 'p-6 px-12'
}`
: 'rounded-md placeholder:text-indigo-300 hover:shadow-md disabled:bg-gray-100' +
// only show margin when there is a label
` ${hasLabel && !small && 'mt-1'}` +
` ${small ? 'px-2 py-1.5 text-xs' : 'text-sm'}` +
` ${
!props.required
? 'border-gray-300 focus:border-dprimary focus:ring-dprimary'
: 'border-dsecondary focus:border-dsecondary focus:ring-dsecondary'
}`)
}
// TODO Ideally, this is set on the form element and not the single inputs, but not sure about the implementation for that.
onKeyDown={
!blurOnEnterPressed
? undefined
: (e) => {
if (e.key === 'Enter') {
e.currentTarget.blur()
}
}
}
{...props}
ref={ref}
/>
{isLoading ? (
<div className="absolute">
<LoadingAnimation size="small" />
</div>
) : (
<div className="absolute">{icon}</div>
)}
</div>
{!!validationErrorMessage && (
<div className="absolute mt-1">
<FormError message={validationErrorMessage} />
</div>
)}
</div>
)
})
export const InputCheckbox = forwardRef<
HTMLInputElement,
React.ComponentPropsWithoutRef<'input'>
>(function InputCheckbox(props, ref): JSX.Element {
// remove `children` from props to not spread it onto `input`
const { children, ...rest } = props
return (
<div className="inline-flex items-center">
<input
type="checkbox"
className="h-4 w-4 rounded border-gray-300 text-dprimary focus:ring-dprimary"
{...rest}
ref={ref}
/>
<label htmlFor={props.name} className="ml-2 block text-sm">
{children}
</label>
</div>
)
})
function FormError({ message }: { message: string | undefined }): JSX.Element {
return (
<p className="animate-fade-in text-sm text-yellow-500">
{message ?? <span className="opacity-0"> </span>}
</p>
)
}
export function FormFieldError<TFieldValues extends FieldValues>({
fieldName,
errors,
noMargin,
}: {
fieldName: keyof FieldErrors<TFieldValues> | typeof generalFormErrorKey
errors: FieldErrors<TFieldValues>
noMargin?: boolean
}): JSX.Element {
const errorForField = errors[fieldName]
return (
<div className={!noMargin ? 'mt-12' : ''}>
<FormError
message={
typeof errorForField?.message === 'string'
? errorForField.message
: undefined
}
/>
</div>
)
}
export function Form(
props: React.ComponentPropsWithoutRef<'form'>,
): JSX.Element {
return (
<form className={props.className ?? 'inline-block w-full'} {...props}>
{props.children}
</form>
)
}
export function FormSelect<TFieldValues extends FieldValues>({
control,
name,
items,
unselectedLabel,
validationErrorMessage,
}: {
control: Control<TFieldValues>
name: FieldPath<TFieldValues>
items: DropdownItem[]
unselectedLabel: string
validationErrorMessage?: string
}): JSX.Element {
/**
* Hack, as the form who is using this `FormSelect`'s `onChange` is not triggered by Headless UI.
* See https://github.com/react-hook-form/react-hook-form/discussions/9359#discussioncomment-4131515
*/
const refSelect = useRef<HTMLSelectElement | null>(null)
return (
<div className="relative">
<select className="hidden" ref={refSelect} />
<Controller
name={name}
control={control}
render={({ field: fieldSelection }) => (
<>
<DropdownSelect
unselectedLabel={unselectedLabel}
selectedItemIdExternal={fieldSelection.value ?? null}
items={items}
onChangeSelection={(selectedItemId) => {
fieldSelection.onChange(selectedItemId)
if (refSelect.current) {
refSelect.current.dispatchEvent(
new Event('change', { bubbles: true }),
)
}
}}
/>
</>
)}
/>
<div className="absolute mt-2">
<FormError message={validationErrorMessage} />
</div>
</div>
)
}