/
index.js
333 lines (298 loc) · 8.5 KB
/
index.js
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright © 2022 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React, { useCallback, useEffect, useMemo } from 'react'
import classnames from 'classnames'
import { isPlainObject, pick, isEmpty, at, compact, get, merge } from 'lodash'
import Message from '@ttn-lw/lib/components/message'
import from from '@ttn-lw/lib/from'
import PropTypes from '@ttn-lw/lib/prop-types'
import { useFormContext } from '..'
import Tooltip from './tooltip'
import FieldError from './error'
import style from './field.styl'
export const getPassThroughProps = (props, excludeProps) => {
const rest = {}
for (const property of Object.keys(props)) {
if (!excludeProps[property]) {
rest[property] = props[property]
}
}
return rest
}
const isValueEmpty = value => {
if (value === null || value === undefined) {
return true
}
if (typeof value === 'object') {
return Object.keys(value) === 0
}
if (typeof value === 'string') {
return value === ''
}
return false
}
const extractValue = value => {
let newValue = value
if (typeof value === 'object' && value !== null && 'target' in value) {
const target = value.target
if ('type' in target && target.type === 'checkbox') {
newValue = target.checked
} else if ('value' in target) {
newValue = target.value
}
}
return newValue
}
const defaultValueSetter = ({ setFieldValue, setValues }, { name, names, value }) =>
names.length > 1 ? setValues(values => merge({}, values, value)) : setFieldValue(name, value)
const FormField = props => {
const {
className,
component: Component,
decode,
description,
disabled: inputDisabled,
encode,
fieldWidth,
name,
readOnly,
required,
title,
titleChildren,
tooltipId,
warning,
validate,
valueSetter,
onChange,
onBlur,
} = props
const {
disabled: formDisabled,
validateOnBlur,
setFieldValue,
setFieldTouched,
setValues,
values,
errors: formErrors,
registerField,
unregisterField,
touched: formTouched,
} = useFormContext()
// Generate streamlined `names` variable to handle both composite and simple fields.
const names = useMemo(() => name.split(','), [name])
const isCompositeField = names.length > 1
// Extract field state.
const errors = compact(at(formErrors, names))
const touched = at(formTouched, names).some(Boolean)
const encodedValue = isCompositeField ? pick(values, names) : get(values, name)
// Register field(s) in formiks internal field registry.
useEffect(() => {
for (const name of names) {
registerField(name, { validate })
}
return () => {
for (const name of names) {
unregisterField(name)
}
}
}, [names, registerField, unregisterField, validate])
const handleChange = useCallback(
async (value, enforceValidation = false) => {
const oldValue = encodedValue
const newValue = encode(extractValue(value), oldValue)
let isSyntheticEvent = false
if (isPlainObject(value)) {
// Check if the value is react's synthetic event.
isSyntheticEvent = 'target' in value
// TODO: Remove `await` and event persist when https://github.com/jaredpalmer/formik/issues/2457
// is resolved.
if (typeof value.persist === 'function') {
value.persist()
}
}
// This middleware takes care of updating the form values and allows for more control
// over how the form values are changed if needed. See the default prop to understand
// how the value is set by default.
await valueSetter(
{ setFieldValue, setValues, setFieldTouched },
{ name, names, value: newValue, oldValue },
)
if (enforceValidation) {
for (const name of names) {
setFieldTouched(name, true, true)
}
}
onChange(isSyntheticEvent ? value : encode(value, oldValue))
},
[
encode,
encodedValue,
name,
names,
onChange,
setFieldTouched,
setFieldValue,
setValues,
valueSetter,
],
)
const handleBlur = useCallback(
event => {
if (validateOnBlur) {
const value = extractValue(event)
for (const name of names) {
setFieldTouched(name, !isValueEmpty(value))
}
}
onBlur(event)
},
[validateOnBlur, onBlur, names, setFieldTouched],
)
const value = decode(encodedValue)
const disabled = inputDisabled || formDisabled
const hasTooltip = Boolean(tooltipId)
const hasTitle = Boolean(title)
const showError =
touched &&
!isEmpty(errors) &&
Boolean(errors[0].message?.id || errors[0].id || typeof errors[0] === 'string')
const showWarning = !showError && Boolean(warning)
const error = showError && errors[0]
const showDescription = !showError && !showWarning && Boolean(description)
const tooltipIcon = hasTooltip ? <Tooltip id={tooltipId} glossaryTerm={title} /> : null
const describedBy = showError
? `${name}-field-error`
: showWarning
? `${name}-field-warning`
: showDescription
? `${name}-field-description`
: undefined
const fieldMessage = showError ? (
<div className={style.messages}>
<FieldError content={error} title={title} error id={describedBy} />
</div>
) : showWarning ? (
<div className={style.messages}>
<FieldError content={warning} title={title} warning id={describedBy} />
</div>
) : showDescription ? (
<Message className={style.description} content={description} id={describedBy} />
) : null
const fieldComponentProps = {
value,
error: showError,
warning: showWarning,
name,
id: name,
disabled,
onChange: handleChange,
onBlur: handleBlur,
readOnly,
}
const cls = classnames(
className,
style.field,
from(style, {
error: showError,
warning: showWarning,
[`field-width-${fieldWidth}`]: Boolean(fieldWidth),
required,
readOnly,
hasTooltip,
}),
)
return (
<div className={cls} data-needs-focus={showError} data-test-id="form-field">
{hasTitle && (
<div className={style.label}>
<Message
component="label"
content={title}
className={style.title}
htmlFor={fieldComponentProps.id}
/>
{tooltipIcon}
{titleChildren}
</div>
)}
<div className={style.componentArea}>
<Component
aria-invalid={showError}
aria-describedby={describedBy}
children={!hasTitle && tooltipIcon}
{...fieldComponentProps}
{...getPassThroughProps(props, FormField.propTypes)}
/>
{fieldMessage}
</div>
</div>
)
}
FormField.propTypes = {
className: PropTypes.string,
component: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.shape({
render: PropTypes.func.isRequired,
}),
]).isRequired,
decode: PropTypes.func,
description: PropTypes.message,
disabled: PropTypes.bool,
encode: PropTypes.func,
fieldWidth: PropTypes.oneOf([
'xxs',
'xs',
's',
'm',
'l',
'xl',
'xxl',
'full',
'half',
'third',
'quarter',
]),
name: PropTypes.string.isRequired,
onBlur: PropTypes.func,
onChange: PropTypes.func,
readOnly: PropTypes.bool,
required: PropTypes.bool,
title: PropTypes.message,
titleChildren: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]),
tooltipId: PropTypes.string,
validate: PropTypes.func,
valueSetter: PropTypes.func,
warning: PropTypes.message,
}
FormField.defaultProps = {
className: undefined,
decode: value => value,
description: '',
disabled: false,
encode: value => value,
fieldWidth: undefined,
onBlur: () => null,
onChange: () => null,
readOnly: false,
required: false,
title: undefined,
titleChildren: null,
tooltipId: '',
validate: undefined,
valueSetter: defaultValueSetter,
warning: '',
}
export default FormField