-
-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathautoform-hooks.js
101 lines (91 loc) · 2.29 KB
/
autoform-hooks.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
// Manages all hooks, supporting append/replace, get
export const Hooks = {
form: {}
}
// The names of all supported hooks, excluding "before" and "after".
const hookNames = [
'formToDoc',
'formToModifier',
'docToForm',
'onSubmit',
'onSuccess',
'onError',
'beginSubmit',
'endSubmit'
]
Hooks.getDefault = function () {
const hooks = {
before: {},
after: {}
}
hookNames.forEach(function (hookName) {
hooks[hookName] = []
})
return hooks
}
Hooks.global = Hooks.getDefault()
Hooks.addHooksToList = function addHooksToList (hooksList, hooks, replace) {
// Add before hooks
hooks.before &&
Object.entries(hooks.before).forEach(function autoFormBeforeHooksEach ([
type,
func
]) {
if (typeof func !== 'function') {
throw new Error(
'AutoForm before hook must be a function, not ' + typeof func
)
}
hooksList.before[type] =
!replace && hooksList.before[type] ? hooksList.before[type] : []
hooksList.before[type].push(func)
})
// Add after hooks
hooks.after &&
Object.entries(hooks.after).forEach(function autoFormAfterHooksEach ([
type,
func
]) {
if (typeof func !== 'function') {
throw new Error(
'AutoForm after hook must be a function, not ' + typeof func
)
}
hooksList.after[type] =
!replace && hooksList.after[type] ? hooksList.after[type] : []
hooksList.after[type].push(func)
})
// Add all other hooks
hookNames.forEach(function autoFormHooksEach (name) {
if (hooks[name]) {
if (typeof hooks[name] !== 'function') {
throw new Error(
'AutoForm ' +
name +
' hook must be a function, not ' +
typeof hooks[name]
)
}
if (replace) {
hooksList[name] = []
}
hooksList[name].push(hooks[name])
}
})
}
Hooks.getHooks = function getHooks (formId, type, subtype) {
let f, g
if (subtype) {
f =
(Hooks.form[formId] &&
Hooks.form[formId][type] &&
Hooks.form[formId][type][subtype]) ||
[]
g = (Hooks.global[type] && Hooks.global[type][subtype]) || []
}
else {
f = (Hooks.form[formId] && Hooks.form[formId][type]) || []
g = Hooks.global[type] || []
}
return f.concat(g)
}