UNPKG

1.82 kBJavaScriptView Raw
1import {
2 isArray,
3 isFunction,
4 extend,
5 forEach,
6} from 'angular';
7import invariant from 'invariant';
8
9export default function connect({
10 mapStateToScope,
11 mapDispatchToScope,
12}, directiveDef) {
13 invariant(isFunction(directiveDef) || isArray(directiveDef),
14 'invalid definition of angular directive definition. Should be array or function');
15 invariant(isFunction(mapStateToScope), 'should be function with store state as param');
16 invariant(isFunction(mapDispatchToScope), 'should be function with store dispatch, state as param');
17
18 const directiveFun = isFunction(directiveDef) ? directiveDef : directiveDef[directiveDef.length - 1];
19 const directiveDependency = isArray(directiveDef) && directiveDef.length >= 2 ?
20 directiveDef.slice(0, directiveDef.length - 2) : [];
21
22 const wrappedDirectiveDependency = directiveDependency.concat('ngStore');
23
24 const wrappedDirectiveFun = (...args) => {
25 const ngStore = args[args.length - 1];
26 const dirApi = directiveFun(...args);
27
28 invariant(isFunction(dirApi.link), 'directive link must be defined as a function');
29
30 function wrappedLink($scope, $element, $attrs, ...more) {
31 const $nuScope = $scope;
32
33 function mapState() {
34 forEach(mapStateToScope(ngStore.getState), (val, key) => {
35 $nuScope[key] = val;
36 });
37 }
38
39 const unsubscribe = ngStore.subscribe(mapState);
40 $nuScope.$on('$destroy', unsubscribe);
41 mapState();
42
43 forEach(mapDispatchToScope(ngStore.dispatch, ngStore.getState), (val, key) => {
44 $nuScope[key] = val;
45 });
46
47 return dirApi.link($nuScope, $element, $attrs, ...more);
48 }
49
50 return extend({}, dirApi, {
51 link: wrappedLink,
52 });
53 };
54
55 const finalDirDef = wrappedDirectiveDependency.concat(wrappedDirectiveFun);
56
57 return finalDirDef;
58}