@crpt/react-utils
Version:
A useful kit for daily using
55 lines (40 loc) • 1.83 kB
JavaScript
import { assign, find, has, isArray, isEmpty, isString } from 'lodash';
import { CHILDREN, contentShorthands } from '../constants';
import { isValidChildren } from './childrenUtils';
import { getPropWith, resetProp } from './propsUtils';
export var defaults = {
shorthand: contentShorthands,
updateProps: function updateProps(propValue, propName, target) {
resetProp(target, propName, CHILDREN, propValue);
}
};
/**
* getChildren
* @param {object} target
* @param {object} options
* @param {array} args
*/
var getChildren = function getChildren(target, options) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var currArgs = isEmpty(args) ? [target] : args;
var _assign = assign(defaults, options),
getDefault = _assign.getDefault,
shorthand = _assign.shorthand,
updateProps = _assign.updateProps;
var propName = find([isArray(shorthand) && find(shorthand, function (value) {
return has(target, value);
}), isString(shorthand) && shorthand].filter(isString));
var children = typeof shorthand === 'function' ? getPropWith.apply(undefined, [target, shorthand].concat(currArgs)) : getPropWith.apply(undefined, [target, propName].concat(currArgs));
children = isArray(children) ? children.filter(Boolean) : children;
var isEmptyChildren = [isArray(children) && isEmpty(children), Boolean(children) === false].find(Boolean);
if (isEmptyChildren && typeof getDefault === 'function') {
children = getDefault.apply(undefined, currArgs);
}
if (children && typeof updateProps === 'function') {
updateProps.apply(undefined, [children, propName, target].concat(currArgs));
}
return isValidChildren(children) ? children : null;
};
export default getChildren;