wix-style-react
Version:
wix-style-react
91 lines (90 loc) • 2.7 kB
JavaScript
;
exports.__esModule = true;
exports.optional = exports.oneOf = exports.once = exports.multiple = exports.children = exports.any = void 0;
var _react = require("react");
var validators = {
ONCE: (types, i, type) => types[i] && types[i].type === type ? i + 1 : false,
OPTIONAL: (types, i, type) => types[i] && types[i].type === type ? i + 1 : i,
ANY: types => types.length,
ONEOF: (types, i, possibleTypes) => {
if (!types.length) {
return false;
}
return possibleTypes.includes(types[i].type) ? i + 1 : false;
},
MULTIPLE: (types, i, type) => {
if (!types[i] || types[i].type !== type) {
return false;
}
while (types[i] && types[i].type === type) {
++i;
}
return i;
}
};
var error = (componentName, rules) => {
var orderedTypes = rules.map(rule => {
var {
validation,
type
} = rule;
if (validation === 'ANY') {
return "* (".concat(validation, ")");
}
if (validation === 'ONEOF') {
var types = type.map(t => t.name).join(', ');
return "".concat(validation, "(").concat(types, ")");
}
return "".concat(type.name, " (").concat(validation, ")");
}).join(', ');
return new Error("".concat(componentName, " should have children of the following types in this order: ").concat(orderedTypes));
};
var once = type => ({
validation: 'ONCE',
type
});
exports.once = once;
var optional = type => ({
validation: 'OPTIONAL',
type
});
exports.optional = optional;
var multiple = type => ({
validation: 'MULTIPLE',
type
});
exports.multiple = multiple;
var any = () => ({
validation: 'ANY'
});
exports.any = any;
var oneOf = exports.oneOf = function oneOf() {
for (var _len = arguments.length, types = new Array(_len), _key = 0; _key < _len; _key++) {
types[_key] = arguments[_key];
}
return {
validation: 'ONEOF',
type: types
};
};
var children = exports.children = function children() {
for (var _len2 = arguments.length, rules = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
rules[_key2] = arguments[_key2];
}
return (props, propName, componentName) => {
if (!rules || rules.length === 0) {
return new Error("".concat(componentName, " should have at least a single child declaration rule"));
}
var childrenAsArray = _react.Children.toArray(props[propName]);
var result = rules.reduce((acc, curr) => {
if (acc === false) {
return acc;
}
return validators[curr.validation](childrenAsArray, acc, curr.type);
}, 0);
if (result === false || childrenAsArray[result]) {
return error(componentName, rules);
}
};
};
//# sourceMappingURL=CompositeValidation.js.map