|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +function getDisplayName(WrappedComponent) { |
| 4 | + return WrappedComponent.displayName || WrappedComponent.name || 'Component'; |
| 5 | +} |
| 6 | + |
| 7 | +function enhance (name, fn) { |
| 8 | + fn.displayName = name; |
| 9 | + return React.forwardRef(fn); |
| 10 | +} |
| 11 | + |
| 12 | +function withName (Component, props) { |
| 13 | + Component.displayName = getDisplayName(Component); |
| 14 | + return <Component {...props} />; |
| 15 | +} |
| 16 | + |
| 17 | +const drop = (a, i = 1) => (a && a.length) ? a.slice(i, a.length) : []; |
| 18 | +const head = a => (a && a.length) ? a[0] : undefined; |
| 19 | + |
| 20 | +export function withContextConsumer (Component, contexts) { |
| 21 | + return enhance(`WithContextConsumer(${getDisplayName(Component)})`, (props, ref) => { |
| 22 | + const applyConsumer = (contextEntries, contextProps = {}) => { |
| 23 | + if (contextEntries.length !== 0) { |
| 24 | + const [contextName, ContextComponent] = head(contextEntries); |
| 25 | + return ( |
| 26 | + <ContextComponent.Consumer> |
| 27 | + {context => ( |
| 28 | + applyConsumer( |
| 29 | + drop(contextEntries), |
| 30 | + { [contextName]: context, ...contextProps }, |
| 31 | + ) |
| 32 | + )} |
| 33 | + </ContextComponent.Consumer> |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + return withName(Component, {...props, ...contextProps, ref}) |
| 38 | + }; |
| 39 | + |
| 40 | + return applyConsumer(Object.entries(contexts)); |
| 41 | + }); |
| 42 | +} |
| 43 | + |
| 44 | +export function withContextProvider (Component, getContexts) { |
| 45 | + return enhance(`WithContextProvider(${getDisplayName(Component)})`, (props, ref) => { |
| 46 | + const contexts = getContexts(props); |
| 47 | + const applyProvider = (contexts) => { |
| 48 | + if (contexts.length !== 0) { |
| 49 | + const { context: ContextComponent, value } = head(contexts); |
| 50 | + return ( |
| 51 | + <ContextComponent.Provider value={value}> |
| 52 | + {applyProvider(drop(contexts))} |
| 53 | + </ContextComponent.Provider> |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + return withName(Component, {...props, ref}); |
| 58 | + }; |
| 59 | + |
| 60 | + return applyProvider(contexts); |
| 61 | + }); |
| 62 | +} |
0 commit comments