wix-style-react
Version:
135 lines (107 loc) • 3.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.children = exports.oneOf = exports.any = exports.multiple = exports.optional = exports.once = void 0;
var _react = require("react");
var validators = {
ONCE: function ONCE(types, i, type) {
return types[i] && types[i].type === type ? i + 1 : false;
},
OPTIONAL: function OPTIONAL(types, i, type) {
return types[i] && types[i].type === type ? i + 1 : i;
},
ANY: function ANY(types) {
return types.length;
},
ONEOF: function ONEOF(types, i, possibleTypes) {
if (!types.length) {
return false;
}
return possibleTypes.includes(types[i].type) ? i + 1 : false;
},
MULTIPLE: function 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 = function error(componentName, rules) {
var orderedTypes = rules.map(function (rule) {
var validation = rule.validation,
type = rule.type;
if (validation === 'ANY') {
return "* (".concat(validation, ")");
}
if (validation === 'ONEOF') {
var types = type.map(function (t) {
return 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 = function once(type) {
return {
validation: 'ONCE',
type: type
};
};
exports.once = once;
var optional = function optional(type) {
return {
validation: 'OPTIONAL',
type: type
};
};
exports.optional = optional;
var multiple = function multiple(type) {
return {
validation: 'MULTIPLE',
type: type
};
};
exports.multiple = multiple;
var any = function any() {
return {
validation: 'ANY'
};
};
exports.any = any;
var 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
};
};
exports.oneOf = oneOf;
var children = function children() {
for (var _len2 = arguments.length, rules = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
rules[_key2] = arguments[_key2];
}
return function (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(function (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);
}
};
};
exports.children = children;