|
| 1 | +import { createFactory, PropTypes } from 'react'; |
| 2 | + |
| 3 | +import parser from './parser'; |
| 4 | + |
| 5 | +const contextTypes = { |
| 6 | + urls: PropTypes.object, |
| 7 | +}; |
| 8 | + |
| 9 | +/** |
| 10 | + * Create decorator to connect a React component to the URLs |
| 11 | + * @param {Function} mapURLToProps Map function for URLs |
| 12 | + * @returns {Function} Decorator function |
| 13 | + */ |
| 14 | +function connectURL(mapURLToProps = null) { |
| 15 | + /** |
| 16 | + * URL decorator function |
| 17 | + * @param {Class} Target Component to decorate |
| 18 | + * @returns {Class} Decorated component |
| 19 | + */ |
| 20 | + function decorator(Target) { |
| 21 | + /** |
| 22 | + * Wrapper component |
| 23 | + * @param {Object} props Component properties |
| 24 | + * @param {Object} context Application context |
| 25 | + * @returns {VDOM} Rendered component |
| 26 | + */ |
| 27 | + function Connected(props, context) { |
| 28 | + /** |
| 29 | + * Get specified URL given the received options |
| 30 | + * @param {String} name URL name |
| 31 | + * @param {Object} opts URL parameters |
| 32 | + * @returns {String} Parsed URL |
| 33 | + */ |
| 34 | + function getURL(name, opts = undefined) { |
| 35 | + return parser(context.urls, name, opts); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Get mapped (or not) properties |
| 40 | + * @returns {Object} Child properties |
| 41 | + */ |
| 42 | + function getProps() { |
| 43 | + if (mapURLToProps) { |
| 44 | + return Object.assign(mapURLToProps(getURL, props), props); |
| 45 | + } |
| 46 | + return Object.assign({}, props, { getURL }); |
| 47 | + } |
| 48 | + |
| 49 | + return createFactory(Target)(getProps()); |
| 50 | + } |
| 51 | + |
| 52 | + Connected.contextTypes = contextTypes; |
| 53 | + |
| 54 | + return Connected; |
| 55 | + } |
| 56 | + |
| 57 | + return decorator; |
| 58 | +} |
| 59 | + |
| 60 | +export default connectURL; |
0 commit comments