-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (97 loc) · 2.45 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
import React from 'react'
import stateEnhancer from '@app-elements/with-state'
import requestEnhancer from '@app-elements/with-request'
import constToCamel from '@wasmuth/const-to-camel'
import camelToConst from '@wasmuth/camel-to-const'
const CALLED = {}
const buildActionsAndReducer = (withActions, store, componentName) => {
const actionTypes = Object.keys(withActions).map(camelToConst)
function reducer (action, state) {
if (actionTypes.includes(action.type)) {
const args = action.payload.args || []
const fnRef = constToCamel(action.type)
return {
...state,
...withActions[fnRef].apply(null, [state, ...(args || [])])
}
}
return state
}
const actions = {}
Object.keys(withActions).forEach(type => {
actions[type] = (...args) =>
store.dispatch({
type: camelToConst(type),
payload: { args },
meta: { componentName }
})
})
return {
reducer,
actions
}
}
const connect = ({
name,
withActions,
withState,
withRequest,
getStoreRef,
...rest
}) => PassedComponent => {
class Connect extends React.Component {
constructor (props, context) {
super(props, context)
if (context.store) {
if (withActions) {
if (!CALLED[name]) {
const { reducer, actions } = buildActionsAndReducer(
withActions,
context.store,
name
)
context.store.addReducer(reducer)
this._actions = actions
CALLED[name] = actions
} else {
this._actions = CALLED[name]
}
}
if (getStoreRef) {
getStoreRef(context.store)
}
}
this.state = { ...this.state }
}
render () {
return (
<PassedComponent
{...this.state}
{...this.props}
{...rest}
{...this._actions}
/>
)
}
}
const passedComponentName = PassedComponent.displayName ||
PassedComponent.name ||
name ||
'PassedComponent'
Connect.displayName = `connect(${passedComponentName})`
let enhanced = Connect
if (withRequest != null) {
enhanced = requestEnhancer({
name: enhanced.displayName,
...withRequest // { endpoint, parse }
})(enhanced)
}
if (withState != null) {
enhanced = stateEnhancer({
name: enhanced.displayName,
mapper: withState
})(enhanced)
}
return enhanced
}
export default connect