/
react-jeff.ts
267 lines (238 loc) · 5.57 KB
/
react-jeff.ts
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
import * as React from "react"
/**
* A close enough check to test if a value is a Synthetic Event or not.
* See: https://github.com/reactjs/rfcs/pull/112
*/
function isReactSyntheticEvent(value: any) {
if (typeof value !== "object" || value === null) return false
if (typeof value.bubbles !== "boolean") return false
if (typeof value.cancellable !== "boolean") return false
if (typeof value.defaultPrevented !== "boolean") return false
if (typeof value.eventPhase !== "number") return false
if (typeof value.isTrusted !== "boolean") return false
if (typeof value.timestamp !== "number") return false
if (typeof value.type !== "string") return false
return true
}
/**
* TODO: Document
*/
interface Validation<Val, Err = string> {
(value: Val): Err[] | Promise<Err[]>
}
/**
* An `onSubmit` handler, can return a promise, and can return additional form validation errors
*/
interface SubmitHandler<Err = string> {
(event: React.FormEvent): void | Err[] | Promise<void> | Promise<Err[]>
}
/**
* TODO: Document
*/
export interface FieldOptions<Val, Err = string> {
defaultValue: Val
validations: Array<Validation<Val, Err>>
disabled?: boolean
readOnly?: boolean
}
/**
* TODO: Document
*/
export interface FormOptions<Err = string> {
fields: Array<Field<any, Err>>
onSubmit: SubmitHandler<Err>
}
/**
* TODO: Document
*/
export interface Field<Val, Err = string> {
value: Val
defaultValue: Val
setValue: (value: Val) => any
errors: Err[]
focused: boolean
blurred: boolean
touched: boolean
dirty: boolean
valid: boolean
validating: boolean
disabled: boolean
readOnly: boolean
setDisabled: (disabled: boolean) => void
setReadOnly: (readonly: boolean) => void
reset: () => void
validate: () => Promise<void>
props: {
value: Val
disabled: boolean
readOnly: boolean
onFocus: React.FocusEventHandler<Element>
onBlur: React.FocusEventHandler<Element>
onChange: (value: Val) => void
}
}
/**
* TODO: Document
*/
export interface Form<Err = string> {
errors: Array<Err>
submitted: boolean
focused: boolean
touched: boolean
dirty: boolean
valid: boolean
validating: boolean
reset: () => void
props: {
onSubmit: SubmitHandler<Err>
}
}
/**
* TODO: Document
*/
export function useField<Val, Err = string>(
options: FieldOptions<Val, Err>,
): Field<Val, Err> {
let defaultValue = options.defaultValue
let validations = options.validations || []
let [value, setValue] = React.useState(defaultValue)
let [errors, setErrors] = React.useState<Err[]>([])
let [validating, setValidating] = React.useState(false)
let [focused, setFocused] = React.useState(false)
let [blurred, setBlurred] = React.useState(false)
let [touched, setTouched] = React.useState(false)
let [dirty, setDirty] = React.useState(false)
let [disabled, setDisabled] = React.useState(options.disabled || false)
let [readOnly, setReadOnly] = React.useState(options.readOnly || false)
let onFocus = React.useCallback(() => {
setFocused(true)
setTouched(true)
}, [])
let onBlur = React.useCallback(() => {
setFocused(false)
setBlurred(true)
}, [])
let valueRef = React.useRef<Val>(value)
function reset() {
setValue(defaultValue)
setErrors([])
setValidating(false)
setBlurred(false)
if (!focused) setTouched(false)
setDirty(false)
}
function validate() {
let initValue = valueRef.current
let errorsMap: Err[][] = []
setValidating(true)
let promises = validations.map((validation, index) => {
return Promise.resolve()
.then(() => validation(initValue))
.then(errors => {
errorsMap[index] = errors
if (Object.is(initValue, valueRef.current)) {
setErrors(errorsMap.flat(1))
}
})
})
return Promise.all(promises)
.then(() => {
if (Object.is(initValue, valueRef.current)) {
setValidating(false)
}
})
.catch(err => {
if (Object.is(initValue, valueRef.current)) {
setValidating(false)
}
throw err
})
}
let setValueHandler = (value: Val) => {
valueRef.current = value
setDirty(true)
setValue(value)
setErrors([])
validate()
}
let onChange = (value: Val) => {
if (isReactSyntheticEvent(value)) {
throw new TypeError(
"Expected `field.onChange` to be called with a value, not an event",
)
}
setValueHandler(value)
}
let valid = !errors.length
return {
value,
errors,
defaultValue,
setValue: setValueHandler,
focused,
blurred,
touched,
dirty,
valid,
validating,
disabled,
readOnly,
setDisabled,
setReadOnly,
reset,
validate,
props: {
value,
disabled,
readOnly,
onFocus,
onBlur,
onChange,
},
}
}
/**
* TODO: Document
*/
export function useForm<Err = string>(options: FormOptions<Err>): Form<Err> {
let fields = options.fields
let onSubmit = options.onSubmit
let [submitted, setSubmitted] = React.useState(false)
let focused = fields.some(field => field.focused)
let touched = fields.some(field => field.touched)
let dirty = fields.some(field => field.dirty)
let valid = fields.every(field => field.valid)
let validating = fields.some(field => field.validating)
let errors = fields.reduce(
(errors: Err[], field: Field<any, Err>) => {
return errors.concat(field.errors)
},
[] as Err[],
)
function reset() {
setSubmitted(false)
fields.forEach(field => field.reset())
}
function onSubmitHandler(event: React.FormEvent) {
setSubmitted(true)
let result = onSubmit(event)
// Promise.resolve()
// .then(() => result)
// .then((res: void | Err[]) => {
// // ...
// })
}
return {
errors,
submitted,
focused,
touched,
dirty,
valid,
validating,
reset,
props: {
onSubmit: onSubmitHandler,
},
}
}