This repository has been archived by the owner on Jun 5, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
compose.ts
82 lines (49 loc) · 1.98 KB
/
compose.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
/* IMPORT */
import {StoreClass, StoreLike, StoreType} from './types';
import Store from './store';
import {DUMMY_OBJ, isNativeClass} from './utils';
/* HELPERS */
function extendEval<ParentStore extends StoreClass<any, any, any>> ( ParentStore: ParentStore, stores: { [index: string]: StoreLike } ) { //URL: https://github.com/microsoft/TypeScript/issues/17088
let result;
return eval (`
result = class ComposedStore extends ParentStore {
constructor ( ...args ) {
super ( ...args );
linkStores ( this, stores );
}
};
`);
return result;
}
function extendJS<ParentStore extends StoreClass<any, any, any>> ( ParentStore: ParentStore, stores: { [index: string]: StoreLike } ) {
return class ComposedStore extends ParentStore {
constructor ( ...args ) {
super ( ...args );
linkStores ( this, stores );
}
};
}
function linkStores<ParentStore extends StoreType<any, any, any>> ( parent: ParentStore, children: { [index: string]: StoreLike } ) {
for ( let name in children ) {
const store = children[name],
instance = store instanceof Store ? store : new store (); //FIXME: Use `getStoreInstance` instead, how can we do it while supporting nested `<Provider>`?
instance.ctx = parent;
parent[name] = instance;
const _setState = instance.setState;
instance.setState = function setState () {
return _setState.apply ( instance, arguments ).then ( () => parent.setState ( DUMMY_OBJ ) );
};
}
}
/* COMPOSE */
function compose<ParentStore extends StoreClass<any, any, any>> ( stores: { [index: string]: StoreLike } ) {
return function ( ParentStore: ParentStore ) {
const ComposedStore = isNativeClass ( ParentStore ) ? extendEval ( ParentStore, stores ) : extendJS ( ParentStore, stores );
try {
Object.defineProperty ( ComposedStore, 'name', { value: ParentStore.name } );
} catch {}
return ComposedStore as ParentStore; //TSC
};
}
/* EXPORT */
export default compose;