@enact/core
Version:
Enact is an open source JavaScript framework containing everything you need to create a fast, scalable mobile or web application.
96 lines (93 loc) • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hoc = exports["default"] = void 0;
var _util = require("../util");
var _mergeDeepWithKey = _interopRequireDefault(require("ramda/src/mergeDeepWithKey"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
/**
* Provides the {@link core/hoc.hoc} method to create higher-order components (HOCs).
*
* @module core/hoc
* @exports hoc
*/
var mergeFn = function mergeFn(key, defaultValue, userValue) {
// eslint-disable-next-line no-undefined
if (userValue === undefined) {
return defaultValue;
}
return userValue;
};
/**
* Constructs a higher-order component (HOC) using an optional set of default configuration parameters and
* a factory method that accepts instance configuration parameters and a component to wrap. The
* returned function can accept:
* * an instance config and a component constructor to wrap and return a renderable component, or
* * an instance config only and return a decorator function expecting a component constructor
* (like the next bullet), or
* * a component constructor and return a renderable component
*
* Example:
* ```
* const Countable = hoc({prop: 'data-count'}, (config, Wrapped) => {
* return class extends React.Component {
* constructor (props) {
* super(props);
* this.state = {
* count: 0
* };
* },
* inc = () => this.setState({count: this.state.count + 1}),
* render () {
* const props = Object.assign({}, this.props, {
* [config.prop]: this.state.count,
* onClick: this.inc
* });
* return <Wrapped {...props} />
* }
* }
* });
*
* const CountableAsDataNumber({prop: 'data-number'});
* const CountableDiv('div');
* const CountableDivAsDataNumber = CountableAsDataNumber('div');
* ```
*
* @function
* @param {Object} defaultConfig Set of default configuration parameters
* @param {Function} hawk Higher-order component
*
* @returns {Function} HOC Decorator
* @memberof core/hoc
* @public
*/
var hoc = exports.hoc = function hoc(defaultConfig, hawk) {
// normalize arguments to allow defaultConfig to be omitted
var factory = hawk;
var defaults = defaultConfig;
if (!factory && typeof defaultConfig === 'function') {
factory = defaultConfig;
defaults = null;
}
var Component = function Component(config, maybeWrapped) {
if ((0, _util.isRenderable)(config)) {
return factory(defaults, config);
} else {
var cfg = (0, _mergeDeepWithKey["default"])(mergeFn, defaults, config);
if ((0, _util.isRenderable)(maybeWrapped)) {
return factory(cfg, maybeWrapped);
} else {
return function (Wrapped) {
return factory(cfg, Wrapped);
};
}
}
};
if (defaults) {
Component.displayName = 'HOC';
Component.defaultConfig = defaults;
}
return Component;
};
var _default = exports["default"] = hoc;