-
Notifications
You must be signed in to change notification settings - Fork 7
/
provider.js
93 lines (82 loc) · 2.82 KB
/
provider.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
import React, { forwardRef, Component } from 'react';
import PropTypes from 'prop-types';
import { diRegistry } from './constants';
import { Context } from './context';
import { addInjectableToMap, getDisplayName, findInjectable } from './utils';
import { globalDi } from './global';
export class DiProvider extends Component {
static contextType = Context;
static propTypes = {
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
global: PropTypes.bool,
target: PropTypes.oneOfType([
PropTypes.func,
PropTypes.arrayOf(PropTypes.func),
]),
use: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.func, PropTypes.object])
).isRequired,
};
componentDidCatch(err) {
globalDi._remove(this.props.use);
throw err;
}
componentWillUnmount() {
globalDi._remove(this.props.use);
}
value = undefined;
getValue() {
if (this.value) return this.value;
const { use, target, global } = this.props;
const { getDependencies } = this.context;
// create a map of dependency real -> replacements for fast lookup
const replacementMap = use.reduce((acc, inj) => {
addInjectableToMap(acc, inj);
return acc;
}, new Map());
// supports global di if needed
globalDi._fromProvider(use, { global });
// support single or multiple targets
const targets = target && (Array.isArray(target) ? target : [target]);
this.value = {
getDependencies(realDeps, targetChild) {
// First we collect dependencies from parent provider(s) (if any)
const dependencies = getDependencies(realDeps, targetChild);
// If no target or target is in the array of targets, map use
if (!targets || targets.includes(targetChild)) {
return dependencies.map((dep) => {
// dep can be either the original or a replacement
// if another provider at the top has already swapped it
// so we check if here we need to inject a different one
// or return the original / parent replacement
const real = diRegistry.has(dep) ? diRegistry.get(dep).from : dep;
const replacedInj = findInjectable(
replacementMap,
real,
targetChild
);
return replacedInj ? replacedInj.value : dep;
});
}
return dependencies;
},
};
return this.value;
}
render() {
return (
<Context.Provider value={this.getValue()}>
{this.props.children}
</Context.Provider>
);
}
}
export function withDi(Comp, deps, target = null) {
const WrappedComponent = forwardRef((props, ref) => (
<DiProvider use={deps} target={target}>
<Comp ref={ref} {...props} />
</DiProvider>
));
WrappedComponent.displayName = getDisplayName(Comp, 'withDi');
return WrappedComponent;
}