Comparing version 0.2.2 to 0.2.3
@@ -501,2 +501,11 @@ 'use strict'; | ||
}; | ||
function conditionalValidator(condition, validator) { | ||
return function (value, getValue) { | ||
if (condition(value, getValue)) { | ||
return validator(value, getValue); | ||
} | ||
return true; | ||
}; | ||
} | ||
var noopValidator = function noopValidator() { | ||
@@ -1125,2 +1134,3 @@ return true; | ||
exports.conditionalValidator = conditionalValidator; | ||
exports.isAtLeast = isAtLeast; | ||
@@ -1127,0 +1137,0 @@ exports.isAtMost = isAtMost; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("derive-state"),t=require("react");function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function i(e,t,r){return(i=o()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var o=new(Function.bind.apply(e,n));return r&&u(o,r.prototype),o}).apply(null,arguments)}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return i(e,arguments,n(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),u(r,e)})(e)}var c=Symbol("is subfield"),s=function(e){return e[c]=!0,e},f=Symbol("path"),l=function(e){if("string"==typeof e)return e;var t=new Proxy({path:""},m(!1)),r=e(t);if(r!==t)throw new Error("You must return a value from the argument in the selector function");return r[f]},p=function(t,r){var n=l(t);return r.has(n)||r.set(n,new e.State),r.get(n)},v=function(e){return"object"==typeof e?e:e(new Proxy({path:""},m(!0))).map((function(e){return e[f]}))},h=function e(t){var r={};if(!t)return r;if("object"!=typeof t)throw new Error("Model must be an object");var n=Array.isArray(t)?function(e){return"["+e+"]"}:function(e){return e};return Object.entries(t).forEach((function(t){var u=t[1],o=n(t[0]);if((g(u)||Array.isArray(u))&&c in u){var i=e(u);Object.entries(i).forEach((function(e){var t=e[0],n=e[1],u=t.startsWith("[")?"":".";r[o+u+t]=n}))}else r[o]=u})),r},d=function(e){var t={};for(var r in e)y(t,r,e[r]);return t},y=function e(t,r,n){if(r.startsWith("[")){var u=r.indexOf("]"),o=Number(r.substring(1,u)),i=r.substring(u+1);return i.length?i.startsWith(".")?(t[o]=t[o]||{},e(t[o],i.slice(1),n)):(t[o]=t[o]||[],e(t[o],i,n)):void(t[o]=n)}switch(b(r)){case"array":var a=r.indexOf("["),c=r.substring(0,a),s=r.substring(a);return t[c]=t[c]||[],e(t[c],s,n);case"object":var f=r.indexOf("."),l=r.substring(0,f),p=r.substring(f+1);return t[l]=t[l]||{},e(t[l],p,n);case"terminal":return void(t[r]=n)}},b=function(e){var t=e.indexOf("."),r=e.indexOf("[");return t<0&&r<0?"terminal":t<0?"array":r<0||t<r?"object":"array"},m=function(e){var t={get:function(r,n,u){if(n===f)return r.path;if("symbol"==typeof n)throw new Error("Can't serialize symbols to keys");var o="number"!=typeof n&&isNaN(n)?r.path.length?r.path+"."+n:n:r.path+"["+n+"]";return e&&0===r.path.length?new Proxy({path:o},t):(r.path=o,u)}};return t},g=function(e){return null!==e&&"object"==typeof e&&e.__proto__===Object.prototype},V=function(e,t){return"function"==typeof e?e(t):"string"==typeof e?Number(t(e)):e},x=function e(t,r){return function(){for(var n=arguments.length,u=new Array(n),o=0;o<n;o++)u[o]=arguments[o];if(r>=t.length)return!0;var i=t[r].apply(t,u),a=function(n){return!0!==n?n:e(t,r+1).apply(void 0,u)};return E(i)?i.then(a):a(i)}},w=function(){return!0},E=function(e){return"object"==typeof e&&!Array.isArray(e)},O=function(e,t){return p(t,e.controlStates)},j=function(t){var r=t.key,n=t.validator$,u=t.value$,o=t.getControlValue$,i=new e.Stateless((function(t){var i=new Set,a=S;n.subscribe((function(e){return a=e}));var c=S;function s(){if(a===S)throw new Error("No validator defined");if(c===S)throw new Error("No validator defined");try{var n=a(c,(function(t){var r=l(t),n=o(r);if(i.has(n)||(i.add(n),e.asStateless(n).subscribe(s)),!n.hasValue())throw new A(r);return n.getValue()}));if("boolean"==typeof n)return t.next(!0!==n&&[]);if(Array.isArray(n))return t.next(n);t.next("pending"),n.then((function(e){return t.next(!0!==e&&(!1===e?[]:e))}))}catch(e){return e instanceof A?console.warn("Setting control "+r+" error to pending, as the validation depends on a field that hasn't been registered yet",e):console.error(e),t.next("pending")}}u.subscribe((function(e){c=e,s()}))})),a=new e.Stateless((function(r){r.next(!1);var n=function(){},o=t.manualError$.subscribe((function(t){r.next(t),n(),n=u.pipe(e.skipSynchronous(),e.take(1),e.map((function(){return!1}))).subscribe(r.next)}));return function(){n(),o()}}));return e.combine({validatorResult:i,manualResult:a}).pipe(e.map((function(e){var t=e.validatorResult,r=e.manualResult;return!1===r||"pending"===r?t:!1===t||"pending"===t?r:[].concat(r,t)})))},A=function(e){var t,r;function n(t){var r;return(r=e.call(this,"Control "+t+" doesn't have any value yet")||this).name="ValueNotThereYetError",Object.setPrototypeOf(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(r),n.prototype),r}return r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,n}(a(Error)),S=Symbol("empty"),M=function(e,n){var u=l(n.key);return t.useEffect((function(){e.registerControl(n)}),[e,n]),{getValue:function(){var t=p(u,e.values);return t.hasValue()?t.getValue():n.initialValue},setValue:function(t){return p(u,e.values).setValue(t)},subscribe:function(t){return p(u,e.values).subscribe(t)},touch:function(){var t=O(e,u);t.value.then((function(e){e.touched||t.setValue(r({},e,{touched:!0}))}),(function(){}))}}},_={},k=e.just(!1),C={};exports.isAtLeast=function(e){return function(t,r){var n=V(e,r);return!(Number(t)<n)||["Expected a value of at least "+n]}},exports.isAtMost=function(e){return function(t,r){var n=V(e,r);return!(Number(t)>n)||["Expected a value of at most "+n]}},exports.isGreaterThan=function(e){return function(t,r){var n=V(e,r);return!(Number(t)<=n)||["Expected a value greater than "+n]}},exports.isInteger=function(e){return parseInt(e)===parseFloat(e)||["Expected an integer"]},exports.isLessThan=function(e){return function(t,r){var n=V(e,r);return!(Number(t)>=n)||["Expected a value less than "+n]}},exports.isNumber=function(e){return!isNaN(e)||["Expected a number"]},exports.isRequired=function(e){return null!=e&&""!==e||["required"]},exports.matches=function(e,t){return function(r){return!!e.test(r)||[null!=t?t:"Invalid value"]}},exports.mergeValidators=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var u=t.map((function(e){return e.apply(void 0,r)})),o=function(e){var t=e.flatMap((function(e){return"boolean"==typeof e?[]:e}));return 0===t.length?!e.some((function(e){return!1===e})):t};return u.some(E)?Promise.all(u).then(o):o(u)}},exports.pipeValidators=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return x(t,0)},exports.readField=function(e,t){try{return p(t,e.values).getValue()}catch(e){return}},exports.readForm=function(e){return d(Object.fromEntries(Array.from(e.values.entries()).map((function(e){var t=e[1];return[e[0],t.hasValue()?t.getValue():void 0]}))))},exports.resetForm=function(e,t){var n=e.values,u=e.initialValues;(t?v(t):Array.from(n.keys())).forEach((function(t){if(n.has(t)&&u.has(t)){n.get(t).setValue(u.get(t).getValue());var o=O(e,t),i=o.getValue();i.touched&&o.setValue(r({},i,{touched:!1}))}}))},exports.setFieldError=function(e,t,r){try{O(e,t).getValue().manualError.emit(r)}catch(e){console.warn("Can't set error: Field not registered",e)}},exports.setFieldValue=function(e,t,r){p(t,e.values).setValue(r)},exports.setFormInitialValue=function(e,t){Object.entries(h(t)).forEach((function(t){var r=t[1];p(t[0],e.initialValues).setValue(r)}))},exports.setFormValue=function(e,t){Object.entries(h(t)).forEach((function(t){var r=t[1];p(t[0],e.values).setValue(r)}))},exports.setInitialValue=function(e,t,r){return p(t,e.initialValues).setValue(r)},exports.subfield=function(e){return Array.isArray(e)?s([].concat(e)):s(r({},e))},exports.touchFields=function(e,t,n){void 0===n&&(n=!0),(t?v(t):e.registeredKeys.getValue()).forEach((function(t){var u=O(e,t),o=u.getValue();o.touched!==n&&u.setValue(r({},o,{touched:n}))}))},exports.useControl=function(e,n){var u=M(e,n),o=u.subscribe,i=function(e,t){if(null==e)return{};var r,n,u={},o=Object.keys(e);for(n=0;n<o.length;n++)t.indexOf(r=o[n])>=0||(u[r]=e[r]);return u}(u,["subscribe"]),a=t.useState(i.getValue),c=a[0],s=a[1];return t.useEffect((function(){return o(s)}),[]),r({},i,{value:c})},exports.useControlSubscription=M,exports.useErrors=function(r,n){var u=n?v(n):[_],o=t.useMemo((function(){return(u[0]===_?r.registeredKeys.pipe(e.map((function(e){return Array.from(e)}))):e.just(u)).pipe(e.switchMap((function(t){return e.combine(Object.fromEntries(t.map((function(t){return[t,O(r,t).pipe(e.map((function(e){return e.touched?e.error$:k})),e.withDefault(k),e.distinctUntilChanged(),e.switchMap((function(e){return e})))]}))))})),e.map((function(e){return Object.fromEntries(Object.entries(e).filter((function(e){return!1!==e[1]})))}))).capture()}),[r].concat(u)),i=t.useState((function(){return o.hasValue()?o.getValue():{}})),a=i[0],c=i[1];return t.useEffect((function(){return o.subscribe((function(e){return c((function(){return e}))})),function(){return o.close()}}),[o]),a},exports.useForm=function(n){var u=t.useRef(null);return u.current||(u.current=function(t){void 0===t&&(t={});var n=new Map;Object.entries(h(t.initialValue||{})).forEach((function(t){n.set(t[0],new e.State(t[1]))}));var u=new Map(Array.from(n.entries()).map((function(t){return[t[0],new e.State(t[1].getValue())]}))),o=new e.State(new Set(u.keys())),i=new Map,a=function(e){return p(e,u)};return{registeredKeys:o,registerControl:function(t){var c=t.initialValue,s=t.validator,f=void 0===s?w:s,v=l(t.key),h=a(v),d=p(v,i);if(!d.hasValue()){var y=o.getValue();y.add(v),o.setValue(y);var b=new e.Stateless;d.setValue({touched:!1,validator:f,manualError:b,error$:j({key:v,validator$:d.pipe(e.map((function(e){return e.validator})),e.withDefault(f),e.distinctUntilChanged()),value$:h,manualError$:b,getControlValue$:a}).capture()})}f!==d.getValue().validator&&d.setValue(r({},d.getValue(),{validator:f}));var m=p(v,n);m.hasValue()&&m.getValue()===c||m.setValue(c);var g=p(v,u);g.hasValue()||g.setValue(c)},initialValues:n,controlStates:i,values:u,dispose:function(){Array.from(n.values()).forEach((function(e){return e.close()})),Array.from(u.values()).forEach((function(e){return e.close()})),Array.from(i.values()).forEach((function(e){e.hasValue()&&e.getValue().error$.close(),e.close()})),o.close(),n.clear(),u.clear(),i.clear()}}}(n)),t.useEffect((function(){return function(){return u.current.dispose()}}),[]),u.current},exports.useFormChanges=function(r,n,u){var o=t.useMemo((function(){return r.registeredKeys.pipe(e.map((function(e){return Array.from(e)})),e.switchMap((function(t){return e.combine(Object.fromEntries(t.map((function(t){return[t,r.values.get(t).pipe(e.withDefault(void 0),e.distinctUntilChanged())]}))))})),e.map((function(e){return n(d(e))})),e.distinctUntilChanged(u)).capture()}),[r]),i=t.useState((function(){return o.hasValue()?o.getValue():{}})),a=i[0],c=i[1];return t.useEffect((function(){return o.subscribe(c),function(){return o.close()}}),[o]),a},exports.useInput=function(e,n){void 0===n&&(n={});var u=n.eventType,o=void 0===u?"input":u,i=n.elementProp,a=void 0===i?"value":i,c=t.useRef(null);return t.useEffect((function(){var t=c.current;if(t){var u=n.initialValue,i=void 0===u?"":u,s=n.validator,f=n.key?l(n.key):t.name;if(f){e.registerControl({initialValue:i,key:f,validator:s});var v=p(f,e.values),h=v.subscribe((function(e){t[a]!==e&&(t[a]=e)})),d=function(){var t=O(e,f);t.getValue().touched||t.setValue(r({},t.getValue(),{touched:!0}))};t.addEventListener("blur",d);var y=function(e){return v.setValue(e.target[a])};return t.addEventListener(o,y),function(){h(),t.removeEventListener("blur",d),t.removeEventListener(o,y)}}console.error("An input is missing its key. Either supply it through useInput `key` option or through the input's name",t,{options:n})}})),c},exports.useIsPristine=function(r){var n=t.useMemo((function(){return r.registeredKeys.pipe(e.switchMap((function(t){return e.combine(Array.from(t).map((function(t){var n=p(t,r.initialValues),u=p(t,r.values);return e.combine({initialValue:n,value:u}).pipe(e.map((function(e){return e.initialValue===e.value})))}))).pipe(e.map((function(e){return e.every((function(e){return e}))})))})),e.distinctUntilChanged()).capture()}),[r]),u=t.useState((function(){return!n.hasValue()||n.getValue()})),o=u[0],i=u[1];return t.useEffect((function(){return n.subscribe(i),function(){return n.close()}}),[n]),o},exports.useIsValid=function(r,n,u){void 0===n&&(n=!1);var o=u?v(u):[C],i=t.useMemo((function(){return(o[0]===C?r.registeredKeys.pipe(e.map((function(e){return Array.from(e)}))):e.just(o)).pipe(e.switchMap((function(t){return e.combine(Object.fromEntries(t.map((function(t){return[t,O(r,t).pipe(e.take(1),e.switchMap((function(e){return e.error$})),e.withDefault(!1))]}))))})),e.map((function(e){return Object.fromEntries(Object.entries(e).filter((function(e){return!1!==e[1]})))})))}),[r].concat(o)),a=t.useMemo((function(){return i.pipe(e.map((function(e){var t=Object.values(e),r=!1;return!t.some((function(e){return"pending"!==e||(r=!0,!1)}))&&(!r||"pending")}))).capture()}),[i]),c=t.useState((function(){return a.hasValue()?a.getValue():n})),s=c[0],f=c[1];return t.useEffect((function(){return a.subscribe(f),function(){return a.close()}}),[a]),s},exports.useWatch=function(e,r){var n=p(r,e.values),u=t.useState((function(){if(n.hasValue())return n.getValue()})),o=u[0],i=u[1];return t.useEffect((function(){return n.subscribe(i)}),[n]),o}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("derive-state"),t=require("react");function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function i(e,t,r){return(i=o()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var o=new(Function.bind.apply(e,n));return r&&u(o,r.prototype),o}).apply(null,arguments)}function a(e){var t="function"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return i(e,arguments,n(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),u(r,e)})(e)}var c=Symbol("is subfield"),s=function(e){return e[c]=!0,e},f=Symbol("path"),l=function(e){if("string"==typeof e)return e;var t=new Proxy({path:""},m(!1)),r=e(t);if(r!==t)throw new Error("You must return a value from the argument in the selector function");return r[f]},p=function(t,r){var n=l(t);return r.has(n)||r.set(n,new e.State),r.get(n)},v=function(e){return"object"==typeof e?e:e(new Proxy({path:""},m(!0))).map((function(e){return e[f]}))},h=function e(t){var r={};if(!t)return r;if("object"!=typeof t)throw new Error("Model must be an object");var n=Array.isArray(t)?function(e){return"["+e+"]"}:function(e){return e};return Object.entries(t).forEach((function(t){var u=t[1],o=n(t[0]);if((g(u)||Array.isArray(u))&&c in u){var i=e(u);Object.entries(i).forEach((function(e){var t=e[0],n=e[1],u=t.startsWith("[")?"":".";r[o+u+t]=n}))}else r[o]=u})),r},d=function(e){var t={};for(var r in e)y(t,r,e[r]);return t},y=function e(t,r,n){if(r.startsWith("[")){var u=r.indexOf("]"),o=Number(r.substring(1,u)),i=r.substring(u+1);return i.length?i.startsWith(".")?(t[o]=t[o]||{},e(t[o],i.slice(1),n)):(t[o]=t[o]||[],e(t[o],i,n)):void(t[o]=n)}switch(b(r)){case"array":var a=r.indexOf("["),c=r.substring(0,a),s=r.substring(a);return t[c]=t[c]||[],e(t[c],s,n);case"object":var f=r.indexOf("."),l=r.substring(0,f),p=r.substring(f+1);return t[l]=t[l]||{},e(t[l],p,n);case"terminal":return void(t[r]=n)}},b=function(e){var t=e.indexOf("."),r=e.indexOf("[");return t<0&&r<0?"terminal":t<0?"array":r<0||t<r?"object":"array"},m=function(e){var t={get:function(r,n,u){if(n===f)return r.path;if("symbol"==typeof n)throw new Error("Can't serialize symbols to keys");var o="number"!=typeof n&&isNaN(n)?r.path.length?r.path+"."+n:n:r.path+"["+n+"]";return e&&0===r.path.length?new Proxy({path:o},t):(r.path=o,u)}};return t},g=function(e){return null!==e&&"object"==typeof e&&e.__proto__===Object.prototype},V=function(e,t){return"function"==typeof e?e(t):"string"==typeof e?Number(t(e)):e},x=function e(t,r){return function(){for(var n=arguments.length,u=new Array(n),o=0;o<n;o++)u[o]=arguments[o];if(r>=t.length)return!0;var i=t[r].apply(t,u),a=function(n){return!0!==n?n:e(t,r+1).apply(void 0,u)};return E(i)?i.then(a):a(i)}},w=function(){return!0},E=function(e){return"object"==typeof e&&!Array.isArray(e)},O=function(e,t){return p(t,e.controlStates)},j=function(t){var r=t.key,n=t.validator$,u=t.value$,o=t.getControlValue$,i=new e.Stateless((function(t){var i=new Set,a=S;n.subscribe((function(e){return a=e}));var c=S;function s(){if(a===S)throw new Error("No validator defined");if(c===S)throw new Error("No validator defined");try{var n=a(c,(function(t){var r=l(t),n=o(r);if(i.has(n)||(i.add(n),e.asStateless(n).subscribe(s)),!n.hasValue())throw new A(r);return n.getValue()}));if("boolean"==typeof n)return t.next(!0!==n&&[]);if(Array.isArray(n))return t.next(n);t.next("pending"),n.then((function(e){return t.next(!0!==e&&(!1===e?[]:e))}))}catch(e){return e instanceof A?console.warn("Setting control "+r+" error to pending, as the validation depends on a field that hasn't been registered yet",e):console.error(e),t.next("pending")}}u.subscribe((function(e){c=e,s()}))})),a=new e.Stateless((function(r){r.next(!1);var n=function(){},o=t.manualError$.subscribe((function(t){r.next(t),n(),n=u.pipe(e.skipSynchronous(),e.take(1),e.map((function(){return!1}))).subscribe(r.next)}));return function(){n(),o()}}));return e.combine({validatorResult:i,manualResult:a}).pipe(e.map((function(e){var t=e.validatorResult,r=e.manualResult;return!1===r||"pending"===r?t:!1===t||"pending"===t?r:[].concat(r,t)})))},A=function(e){var t,r;function n(t){var r;return(r=e.call(this,"Control "+t+" doesn't have any value yet")||this).name="ValueNotThereYetError",Object.setPrototypeOf(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(r),n.prototype),r}return r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,n}(a(Error)),S=Symbol("empty"),M=function(e,n){var u=l(n.key);return t.useEffect((function(){e.registerControl(n)}),[e,n]),{getValue:function(){var t=p(u,e.values);return t.hasValue()?t.getValue():n.initialValue},setValue:function(t){return p(u,e.values).setValue(t)},subscribe:function(t){return p(u,e.values).subscribe(t)},touch:function(){var t=O(e,u);t.value.then((function(e){e.touched||t.setValue(r({},e,{touched:!0}))}),(function(){}))}}},_={},k=e.just(!1),C={};exports.conditionalValidator=function(e,t){return function(r,n){return!e(r,n)||t(r,n)}},exports.isAtLeast=function(e){return function(t,r){var n=V(e,r);return!(Number(t)<n)||["Expected a value of at least "+n]}},exports.isAtMost=function(e){return function(t,r){var n=V(e,r);return!(Number(t)>n)||["Expected a value of at most "+n]}},exports.isGreaterThan=function(e){return function(t,r){var n=V(e,r);return!(Number(t)<=n)||["Expected a value greater than "+n]}},exports.isInteger=function(e){return parseInt(e)===parseFloat(e)||["Expected an integer"]},exports.isLessThan=function(e){return function(t,r){var n=V(e,r);return!(Number(t)>=n)||["Expected a value less than "+n]}},exports.isNumber=function(e){return!isNaN(e)||["Expected a number"]},exports.isRequired=function(e){return null!=e&&""!==e||["required"]},exports.matches=function(e,t){return function(r){return!!e.test(r)||[null!=t?t:"Invalid value"]}},exports.mergeValidators=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var u=t.map((function(e){return e.apply(void 0,r)})),o=function(e){var t=e.flatMap((function(e){return"boolean"==typeof e?[]:e}));return 0===t.length?!e.some((function(e){return!1===e})):t};return u.some(E)?Promise.all(u).then(o):o(u)}},exports.pipeValidators=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return x(t,0)},exports.readField=function(e,t){try{return p(t,e.values).getValue()}catch(e){return}},exports.readForm=function(e){return d(Object.fromEntries(Array.from(e.values.entries()).map((function(e){var t=e[1];return[e[0],t.hasValue()?t.getValue():void 0]}))))},exports.resetForm=function(e,t){var n=e.values,u=e.initialValues;(t?v(t):Array.from(n.keys())).forEach((function(t){if(n.has(t)&&u.has(t)){n.get(t).setValue(u.get(t).getValue());var o=O(e,t),i=o.getValue();i.touched&&o.setValue(r({},i,{touched:!1}))}}))},exports.setFieldError=function(e,t,r){try{O(e,t).getValue().manualError.emit(r)}catch(e){console.warn("Can't set error: Field not registered",e)}},exports.setFieldValue=function(e,t,r){p(t,e.values).setValue(r)},exports.setFormInitialValue=function(e,t){Object.entries(h(t)).forEach((function(t){var r=t[1];p(t[0],e.initialValues).setValue(r)}))},exports.setFormValue=function(e,t){Object.entries(h(t)).forEach((function(t){var r=t[1];p(t[0],e.values).setValue(r)}))},exports.setInitialValue=function(e,t,r){return p(t,e.initialValues).setValue(r)},exports.subfield=function(e){return Array.isArray(e)?s([].concat(e)):s(r({},e))},exports.touchFields=function(e,t,n){void 0===n&&(n=!0),(t?v(t):e.registeredKeys.getValue()).forEach((function(t){var u=O(e,t),o=u.getValue();o.touched!==n&&u.setValue(r({},o,{touched:n}))}))},exports.useControl=function(e,n){var u=M(e,n),o=u.subscribe,i=function(e,t){if(null==e)return{};var r,n,u={},o=Object.keys(e);for(n=0;n<o.length;n++)t.indexOf(r=o[n])>=0||(u[r]=e[r]);return u}(u,["subscribe"]),a=t.useState(i.getValue),c=a[0],s=a[1];return t.useEffect((function(){return o(s)}),[]),r({},i,{value:c})},exports.useControlSubscription=M,exports.useErrors=function(r,n){var u=n?v(n):[_],o=t.useMemo((function(){return(u[0]===_?r.registeredKeys.pipe(e.map((function(e){return Array.from(e)}))):e.just(u)).pipe(e.switchMap((function(t){return e.combine(Object.fromEntries(t.map((function(t){return[t,O(r,t).pipe(e.map((function(e){return e.touched?e.error$:k})),e.withDefault(k),e.distinctUntilChanged(),e.switchMap((function(e){return e})))]}))))})),e.map((function(e){return Object.fromEntries(Object.entries(e).filter((function(e){return!1!==e[1]})))}))).capture()}),[r].concat(u)),i=t.useState((function(){return o.hasValue()?o.getValue():{}})),a=i[0],c=i[1];return t.useEffect((function(){return o.subscribe((function(e){return c((function(){return e}))})),function(){return o.close()}}),[o]),a},exports.useForm=function(n){var u=t.useRef(null);return u.current||(u.current=function(t){void 0===t&&(t={});var n=new Map;Object.entries(h(t.initialValue||{})).forEach((function(t){n.set(t[0],new e.State(t[1]))}));var u=new Map(Array.from(n.entries()).map((function(t){return[t[0],new e.State(t[1].getValue())]}))),o=new e.State(new Set(u.keys())),i=new Map,a=function(e){return p(e,u)};return{registeredKeys:o,registerControl:function(t){var c=t.initialValue,s=t.validator,f=void 0===s?w:s,v=l(t.key),h=a(v),d=p(v,i);if(!d.hasValue()){var y=o.getValue();y.add(v),o.setValue(y);var b=new e.Stateless;d.setValue({touched:!1,validator:f,manualError:b,error$:j({key:v,validator$:d.pipe(e.map((function(e){return e.validator})),e.withDefault(f),e.distinctUntilChanged()),value$:h,manualError$:b,getControlValue$:a}).capture()})}f!==d.getValue().validator&&d.setValue(r({},d.getValue(),{validator:f}));var m=p(v,n);m.hasValue()&&m.getValue()===c||m.setValue(c);var g=p(v,u);g.hasValue()||g.setValue(c)},initialValues:n,controlStates:i,values:u,dispose:function(){Array.from(n.values()).forEach((function(e){return e.close()})),Array.from(u.values()).forEach((function(e){return e.close()})),Array.from(i.values()).forEach((function(e){e.hasValue()&&e.getValue().error$.close(),e.close()})),o.close(),n.clear(),u.clear(),i.clear()}}}(n)),t.useEffect((function(){return function(){return u.current.dispose()}}),[]),u.current},exports.useFormChanges=function(r,n,u){var o=t.useMemo((function(){return r.registeredKeys.pipe(e.map((function(e){return Array.from(e)})),e.switchMap((function(t){return e.combine(Object.fromEntries(t.map((function(t){return[t,r.values.get(t).pipe(e.withDefault(void 0),e.distinctUntilChanged())]}))))})),e.map((function(e){return n(d(e))})),e.distinctUntilChanged(u)).capture()}),[r]),i=t.useState((function(){return o.hasValue()?o.getValue():{}})),a=i[0],c=i[1];return t.useEffect((function(){return o.subscribe(c),function(){return o.close()}}),[o]),a},exports.useInput=function(e,n){void 0===n&&(n={});var u=n.eventType,o=void 0===u?"input":u,i=n.elementProp,a=void 0===i?"value":i,c=t.useRef(null);return t.useEffect((function(){var t=c.current;if(t){var u=n.initialValue,i=void 0===u?"":u,s=n.validator,f=n.key?l(n.key):t.name;if(f){e.registerControl({initialValue:i,key:f,validator:s});var v=p(f,e.values),h=v.subscribe((function(e){t[a]!==e&&(t[a]=e)})),d=function(){var t=O(e,f);t.getValue().touched||t.setValue(r({},t.getValue(),{touched:!0}))};t.addEventListener("blur",d);var y=function(e){return v.setValue(e.target[a])};return t.addEventListener(o,y),function(){h(),t.removeEventListener("blur",d),t.removeEventListener(o,y)}}console.error("An input is missing its key. Either supply it through useInput `key` option or through the input's name",t,{options:n})}})),c},exports.useIsPristine=function(r){var n=t.useMemo((function(){return r.registeredKeys.pipe(e.switchMap((function(t){return e.combine(Array.from(t).map((function(t){var n=p(t,r.initialValues),u=p(t,r.values);return e.combine({initialValue:n,value:u}).pipe(e.map((function(e){return e.initialValue===e.value})))}))).pipe(e.map((function(e){return e.every((function(e){return e}))})))})),e.distinctUntilChanged()).capture()}),[r]),u=t.useState((function(){return!n.hasValue()||n.getValue()})),o=u[0],i=u[1];return t.useEffect((function(){return n.subscribe(i),function(){return n.close()}}),[n]),o},exports.useIsValid=function(r,n,u){void 0===n&&(n=!1);var o=u?v(u):[C],i=t.useMemo((function(){return(o[0]===C?r.registeredKeys.pipe(e.map((function(e){return Array.from(e)}))):e.just(o)).pipe(e.switchMap((function(t){return e.combine(Object.fromEntries(t.map((function(t){return[t,O(r,t).pipe(e.take(1),e.switchMap((function(e){return e.error$})),e.withDefault(!1))]}))))})),e.map((function(e){return Object.fromEntries(Object.entries(e).filter((function(e){return!1!==e[1]})))})))}),[r].concat(o)),a=t.useMemo((function(){return i.pipe(e.map((function(e){var t=Object.values(e),r=!1;return!t.some((function(e){return"pending"!==e||(r=!0,!1)}))&&(!r||"pending")}))).capture()}),[i]),c=t.useState((function(){return a.hasValue()?a.getValue():n})),s=c[0],f=c[1];return t.useEffect((function(){return a.subscribe(f),function(){return a.close()}}),[a]),s},exports.useWatch=function(e,r){var n=p(r,e.values),u=t.useState((function(){if(n.hasValue())return n.getValue()})),o=u[0],i=u[1];return t.useEffect((function(){return n.subscribe(i)}),[n]),o}; | ||
//# sourceMappingURL=formicary.cjs.production.min.js.map |
@@ -497,2 +497,11 @@ import { State, Stateless, map, withDefault, distinctUntilChanged, asStateless, skipSynchronous, take, combine, just, switchMap } from 'derive-state'; | ||
}; | ||
function conditionalValidator(condition, validator) { | ||
return function (value, getValue) { | ||
if (condition(value, getValue)) { | ||
return validator(value, getValue); | ||
} | ||
return true; | ||
}; | ||
} | ||
var noopValidator = function noopValidator() { | ||
@@ -1121,3 +1130,3 @@ return true; | ||
export { isAtLeast, isAtMost, isGreaterThan, isInteger, isLessThan, isNumber, isRequired, matches, mergeValidators, pipeValidators, readField, readForm, resetForm, setFieldError, setFieldValue, setFormInitialValue, setFormValue, setInitialValue, subfield, touchFields, useControl, useControlSubscription, useErrors, useForm, useFormChanges, useInput, useIsPristine, useIsValid, useWatch }; | ||
export { conditionalValidator, isAtLeast, isAtMost, isGreaterThan, isInteger, isLessThan, isNumber, isRequired, matches, mergeValidators, pipeValidators, readField, readForm, resetForm, setFieldError, setFieldValue, setFormInitialValue, setFormValue, setInitialValue, subfield, touchFields, useControl, useControlSubscription, useErrors, useForm, useFormChanges, useInput, useIsPristine, useIsValid, useWatch }; | ||
//# sourceMappingURL=formicary.esm.js.map |
@@ -17,4 +17,5 @@ export { readField } from './commands/readField'; | ||
export { useWatch } from './hooks/useWatch'; | ||
export { FieldValidator as Validator, isAtLeast, isGreaterThan, isInteger, isNumber, isAtMost, isLessThan, isRequired, mergeValidators, pipeValidators, matches, } from './validators'; | ||
export { FieldValidator as Validator, isAtLeast, isGreaterThan, isInteger, isNumber, isAtMost, isLessThan, isRequired, mergeValidators, pipeValidators, matches, conditionalValidator, } from './validators'; | ||
export { FormRef } from './internal/formRef'; | ||
export { subfield } from './internal/subfield'; | ||
export { KeySelector } from './internal/path'; |
@@ -19,3 +19,4 @@ import { KeySelector } from './internal/path'; | ||
export declare const mergeValidators: ValidatorComposer; | ||
export declare function conditionalValidator<T, TValues>(condition: (value: T, getValue: (key: KeySelector<TValues, T>) => any) => boolean, validator: PureValidator<T> | FieldValidator<T, TValues>): FieldValidator<T, TValues>; | ||
export declare const noopValidator: PureValidator<any>; | ||
export {}; |
{ | ||
"version": "0.2.2", | ||
"version": "0.2.3", | ||
"license": "MIT", | ||
@@ -69,2 +69,2 @@ "main": "dist/index.js", | ||
} | ||
} | ||
} |
@@ -94,6 +94,7 @@ # Formicary | ||
Validators are composable. This library exposes two utilities to compose them easily: | ||
Validators are composable. This library exposes some utilities to compose them easily: | ||
- `pipeValidators(...validators)` takes any number of validators and runs them one-by-one, bailing out when one of them reports an error. | ||
- `mergeValidators(...validators)` takes any number of validators and runs them simultaneously, returning the list of all errors reported if there were any. | ||
- `conditionalValidator(conditionFn, validator)` only runs `validator` when conditionFn returns `true`, otherwise it always accepts. | ||
@@ -100,0 +101,0 @@ And it provides a set of useful built-in validators: |
@@ -32,14 +32,21 @@ export { readField } from './commands/readField'; | ||
matches, | ||
conditionalValidator, | ||
} from './validators'; | ||
export { FormRef } from './internal/formRef'; | ||
export { subfield } from './internal/subfield'; | ||
export { KeySelector } from './internal/path'; | ||
/* TODO | ||
- Global validations | ||
- On submit validations | ||
- Context provider | ||
- i18n support (Default validators to give an error type instead of a localised message) | ||
- Derived changes | ||
- Remove/cleanup unused fields (need refcount?) | ||
- getErrors command | ||
=> Investigate scroll into view after touch fields | ||
- Array fields | ||
- Better control of touched | ||
* show error if a dependency causes that field to go on error, even when left untouched | ||
- Global validations | ||
- On submit validations | ||
- Custom typings for FormRef (as an opaque token) | ||
- Default validators to give an error type instead of a localised message | ||
*/ |
@@ -142,2 +142,17 @@ import { KeySelector } from './internal/path'; | ||
export function conditionalValidator<T, TValues>( | ||
condition: ( | ||
value: T, | ||
getValue: (key: KeySelector<TValues, T>) => any | ||
) => boolean, | ||
validator: PureValidator<T> | FieldValidator<T, TValues> | ||
): FieldValidator<T, TValues> { | ||
return (value, getValue) => { | ||
if (condition(value, getValue)) { | ||
return validator(value, getValue); | ||
} | ||
return true; | ||
}; | ||
} | ||
export const noopValidator: PureValidator<any> = () => true; | ||
@@ -144,0 +159,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
322358
3551
266