UNPKG

1.98 kBJavaScriptView Raw
1import has from "lodash-es/has";
2import isSchema from './util/isSchema';
3
4var Condition = /*#__PURE__*/function () {
5 function Condition(refs, options) {
6 this.refs = refs;
7
8 if (typeof options === 'function') {
9 this.fn = options;
10 return;
11 }
12
13 if (!has(options, 'is')) throw new TypeError('`is:` is required for `when()` conditions');
14 if (!options.then && !options.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
15 var is = options.is,
16 then = options.then,
17 otherwise = options.otherwise;
18 var check = typeof is === 'function' ? is : function () {
19 for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
20 values[_key] = arguments[_key];
21 }
22
23 return values.every(function (value) {
24 return value === is;
25 });
26 };
27
28 this.fn = function () {
29 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
30 args[_key2] = arguments[_key2];
31 }
32
33 var options = args.pop();
34 var schema = args.pop();
35 var branch = check.apply(void 0, args) ? then : otherwise;
36 if (!branch) return undefined;
37 if (typeof branch === 'function') return branch(schema);
38 return schema.concat(branch.resolve(options));
39 };
40 }
41
42 var _proto = Condition.prototype;
43
44 _proto.resolve = function resolve(base, options) {
45 var values = this.refs.map(function (ref) {
46 return ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
47 });
48 var schema = this.fn.apply(base, values.concat(base, options));
49 if (schema === undefined || schema === base) return base;
50 if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');
51 return schema.resolve(options);
52 };
53
54 return Condition;
55}();
56
57export default Condition;
\No newline at end of file