UNPKG

unstated-enhancers

Version:
91 lines (90 loc) 3.47 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var subscribe_gate_1 = require("./subscribe-gate"); var isObject = function (value) { return value && typeof value === 'object' && value.constructor === Object; }; var makeContainers = function (containers, config) { var keys = Object.keys(config); var inject = {}; for (var index in keys) { inject[keys[index]] = containers[index]; } return inject; }; var mapCombinedContainersAuto = function (config, options) { if (config === void 0) { config = {}; } var containers = {}; var keys = Object.keys(config); keys.forEach(function (key) { containers[key] = config[key]; if (config[key].ctx) { var _keys = Object.keys(config[key].ctx); _keys.forEach(function (_key) { var name = _key; if (options.concatCombinedContainerNames) { name = name.charAt(0).toUpperCase() + name.slice(1); name = key + name; } containers[name] = config[key].ctx[_key]; }); } }); return containers; }; var connect = function (config, mapStateToProps, mapActionsToProps, options) { if (config === void 0) { config = {}; } if (options === void 0) { options = {}; } if (!isObject(config) || Object.keys(config).length === 0) { throw new Error('Connect needs an object with containers'); } var _containers = Object.values(config); var injected; var isMapped = false; var mapCombinedContainers = typeof options.mapCombinedContainers === 'boolean' ? mapCombinedContainersAuto : options.mapCombinedContainers; var loading = options.loading; return function (Component) { return function (props) { return (React.createElement(subscribe_gate_1.default, { to: _containers, loading: loading }, function () { var containers = []; for (var _i = 0; _i < arguments.length; _i++) { containers[_i] = arguments[_i]; } var mappedState; var mappedActions; if (!injected) { injected = makeContainers(containers, config); } if (mapCombinedContainers && !isMapped) { injected = mapCombinedContainers(injected, options); isMapped = true; } if (mapStateToProps) { mappedState = mapStateToProps(injected); } if (mapActionsToProps) { mappedActions = mapActionsToProps(injected); } var newProps = props; if (mappedState) { newProps = __assign(__assign({}, props), mappedState); } if (mappedActions) { newProps = __assign(__assign({}, newProps), mappedActions); } return React.createElement(Component, __assign({}, newProps, { containers: injected })); })); }; }; }; exports.default = connect;