-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
decorator.js
66 lines (59 loc) · 1.59 KB
/
decorator.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
// @flow
import type { Decorator, FormApi } from 'final-form'
import type { GetInputs, FindInput } from './types'
import getAllInputs from './getAllInputs'
import defaultFindInput from './findInput'
const noop = () => {}
const createDecorator = (
getInputs?: GetInputs,
findInput?: FindInput
): Decorator => (form: FormApi) => {
const focusOnFirstError = (errors: Object) => {
if (!getInputs) {
getInputs = getAllInputs
}
if (!findInput) {
findInput = defaultFindInput
}
const firstInput = findInput(getInputs(), errors)
if (firstInput) {
firstInput.focus()
}
}
// Save original submit function
const originalSubmit = form.submit
// Subscribe to errors, and keep a local copy of them
let state: { errors?: Object, submitErrors?: Object } = {}
const unsubscribe = form.subscribe(
nextState => {
state = nextState
},
{ errors: true, submitErrors: true }
)
// What to do after submit
const afterSubmit = () => {
const { errors, submitErrors } = state
if (errors && Object.keys(errors).length) {
focusOnFirstError(errors)
} else if (submitErrors && Object.keys(submitErrors).length) {
focusOnFirstError(submitErrors)
}
}
// Rewrite submit function
form.submit = () => {
const result = originalSubmit.call(form)
if (result && typeof result.then === 'function') {
// async
result.then(afterSubmit, noop)
} else {
// sync
afterSubmit()
}
return result
}
return () => {
unsubscribe()
form.submit = originalSubmit
}
}
export default createDecorator