-
Notifications
You must be signed in to change notification settings - Fork 24
/
enhanceComponent.ts
74 lines (58 loc) · 1.53 KB
/
enhanceComponent.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
import { Component, ComponentClass, PropTypes, StatelessComponent } from 'react';
import { Action, Dispatch, Store } from 'redux';
import { createEagerElement } from 'recompose';
type Context<S> = {
store: Store<S>
};
export interface Wrapper {
(type: string): string
};
export interface Selector<P, S> {
(state : P): S
};
type Props<P, S> = {
wrapper: Wrapper,
selector: Selector<P, S>
};
const contextDefintion = { store: PropTypes.object.isRequired };
export default <P, S> (
EnhanceableComponent : ComponentClass<any> | StatelessComponent<any>
) : ComponentClass<Props<P, S>> =>
class PrismEnhancedComponent extends Component<Props<P, S>, void> {
static childContextTypes = contextDefintion;
static contextTypes = contextDefintion;
static propTypes = {
wrapper: PropTypes.func.isRequired,
selector: PropTypes.func.isRequired
};
context: Context<P>;
getChildContext() {
const {
selector,
wrapper
} = this.props;
const {
store
} = this.context;
const dispatch : Dispatch<S> = (action : Action) =>
store.dispatch({
...action,
type: wrapper(action.type)
});
const getState = (state : S) => selector(store.getState());
return {
store: {
...store,
dispatch,
getState
}
};
}
render() {
const { selector, wrapper, ...rest } = this.props;
return createEagerElement(
EnhanceableComponent,
rest
);
}
}