@talend/react-cmf
Version:
A framework built on top of best react libraries
113 lines (108 loc) • 3.01 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.attachRef = attachRef;
exports.attachRefs = attachRefs;
exports.defaultState = exports.default = void 0;
exports.settingsReducers = settingsReducers;
var _invariant = _interopRequireDefault(require("invariant"));
var _constant = _interopRequireDefault(require("../constant"));
var _lodash = require("lodash");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* @module react-cmf/lib/reducers/settingsReducers
*/
/* eslint no-underscore-dangle: ["error", {"allow": ["_ref"] }] */
const defaultState = exports.defaultState = {
initialized: false,
contentTypes: {},
actions: {},
props: {},
routes: {}
};
/**
* if an object try to find _ref property and resolve it
*/
function attachRef(refs, obj) {
if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
return obj;
}
let props = {
...obj
};
if (props._ref) {
(0, _invariant.default)(refs[props._ref], `CMF/Settings: Reference '${props._ref}' not found`);
props = {
...refs[props._ref],
...obj
};
delete props._ref;
}
return props;
}
function attachRefs(refs, props) {
const attachedProps = attachRef(refs, props);
Object.keys(attachedProps).forEach(key => {
attachedProps[key] = attachRef(refs, attachedProps[key]);
});
return attachedProps;
}
/**
* attach reference to produce a ready to use freezed object
* @param {object} originalSettings the full settings with `props` and `ref` attribute
* @return {object} frozen settings with ref computed
*/
function prepareSettings({
views,
props,
ref,
...rest
}) {
const settings = {
props: {},
...rest
};
if (views) {
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.warn('settings.view is deprecated, please use settings.props');
}
Object.keys(views).forEach(id => {
settings.props[id] = attachRefs(ref, views[id]);
});
}
if (props) {
Object.keys(props).forEach(id => {
settings.props[id] = attachRefs(ref, props[id]);
});
}
if (typeof settings.freeze === 'function') {
settings.freeze();
}
return settings;
}
/**
* handle actions related to the settings
* @param {object} state initial state
* @param {object} action redux aciton
* @return {object} new state
*/
function settingsReducers(state = defaultState, action) {
switch (action.type) {
case _constant.default.REQUEST_OK:
return {
...state,
initialized: true,
...prepareSettings(action.settings)
};
case _constant.default.REQUEST_KO:
// eslint-disable-next-line no-console
console.error(`Settings can't be loaded ${(0, _lodash.get)(action, 'error.message')}`, action.error);
return state;
default:
return state;
}
}
var _default = exports.default = settingsReducers;
//# sourceMappingURL=settingsReducers.js.map
;