react-f0rm 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as FieldPath, N as Name, F as Form$1, V as ValidationMode, P as PathValueOf, b as FieldError, c as Path, O as Options } from './form-DHKns6j_.js';
2
- export { d as FieldErrorEntry, e as FieldState, H as HandleSubmitOptions, f as PathValue, R as ReValidateMode, g as ResetFieldOptions, h as ResetOptions, S as SetFieldOptions, i as SetFocusOptions, j as SetServerErrorsOptions, k as VALIDATION_OUTCOME, l as ValidateResult, m as ValidationOutcome, n as changeValue, o as changeValueByPath, p as clearErrors, q as createForm, r as ensureValidate, s as getDirtyFields, t as getError, u as getErrorByPath, v as getErrors, w as getFieldErrors, x as getFieldErrorsByPath, y as getFieldState, z as getFirstError, A as getTouchedFields, B as getValue, C as getValueByPath, D as getValues, E as handleSubmit, G as hasErrors, I as hasTouched, J as hasTouchedByPath, K as incrementSubmitCount, L as isDirty, M as isTouched, Q as removeField, T as removeFieldByPath, U as reset, W as resetField, X as setDisabled, Y as setError, Z as setErrorByPath, _ as setFocus, $ as setInitialValues, a0 as setIsSubmitting, a1 as setServerErrors, a2 as setSubmitSuccessful, a3 as setTouched, a4 as setTouchedByPath, a5 as setValidatingByPath, a6 as setValue, a7 as setValueByPath, a8 as trigger, a9 as unsetValidatingByPath, aa as validate } from './form-DHKns6j_.js';
3
- import { V as Validator } from './validate-BoNZhOMY.js';
1
+ import { a as FieldPath, N as Name, F as Form$1, V as ValidationMode, P as PathValueOf, b as FieldError, c as Path, O as Options } from './form-B2pyaLdK.js';
2
+ export { d as FieldErrorEntry, e as FieldState, f as FormValidateFn, g as FormValidateMeta, H as HandleSubmitOptions, h as PathValue, R as ReValidateMode, i as ResetFieldOptions, j as ResetOptions, S as SetFieldOptions, k as SetFocusOptions, l as SetServerErrorsOptions, m as VALIDATION_OUTCOME, n as ValidateResult, o as ValidationOutcome, p as changeValue, q as changeValueByPath, r as clearErrors, s as createForm, t as ensureValidate, u as getDirtyFields, v as getError, w as getErrorByPath, x as getErrors, y as getFieldErrors, z as getFieldErrorsByPath, A as getFieldState, B as getFirstError, C as getTouchedFields, D as getValue, E as getValueByPath, G as getValues, I as handleSubmit, J as hasErrors, K as hasTouched, L as hasTouchedByPath, M as incrementSubmitCount, Q as isDirty, T as isTouched, U as removeField, W as removeFieldByPath, X as reset, Y as resetField, Z as setDisabled, _ as setError, $ as setErrorByPath, a0 as setFocus, a1 as setInitialValues, a2 as setIsSubmitting, a3 as setServerErrors, a4 as setSubmitSuccessful, a5 as setTouched, a6 as setTouchedByPath, a7 as setValidatingByPath, a8 as setValue, a9 as setValueByPath, aa as trigger, ab as unsetValidatingByPath, ac as validate } from './form-B2pyaLdK.js';
3
+ import { V as Validator } from './validate-BhOEz8BS.js';
4
4
  import * as React from 'react';
5
5
  import { ReactNode } from 'react';
6
6
  import { EventEmitter } from '@for-fun/event-emitter';
@@ -258,6 +258,17 @@ declare function useDirtyFields(form: Form$1): Record<string, boolean>;
258
258
  declare function useTouchedFields(form: Form$1): string[];
259
259
  declare function useHasErrors(form: Form$1): boolean;
260
260
  declare function useIsSubmitting(form: Form$1): boolean;
261
+ /**
262
+ * Get whether the form accepts a submit right now:
263
+ * `!isSubmitting && !hasErrors`. This is the single flag a submit
264
+ * button's `disabled` prop wants — it is `false` for the whole async
265
+ * `onSubmit` span (not just the validation pass) and whenever any field
266
+ * holds an error (client validation or server backfill), replacing the
267
+ * hand-rolled `useHasErrors(form) || useIsSubmitting(form)` pair.
268
+ * Deliberately no dirty or validating semantics: an untouched-but-clean
269
+ * form can submit.
270
+ */
271
+ declare function useCanSubmit(form: Form$1): boolean;
261
272
  declare function useSubmitCount(form: Form$1): number;
262
273
 
263
274
  /** Subscription granularity for {@link onPathEvent}.
@@ -503,5 +514,5 @@ interface SelectComponent {
503
514
  }
504
515
  declare const Select: SelectComponent;
505
516
 
506
- export { Checkbox, CheckboxGroupContext, CheckboxGroupProvider, Field, FieldError, FieldPath, Form, FormContext, Form$1 as FormInstance, FormProvider, Name, Options, Path, PathValueOf, Select, ValidationMode, Validator, createFormContext, fieldErrorId, subscribe, useCheckboxGroupContext, useDirtyFields, useError, useErrorByPath, useField, useFieldArray, useFieldErrors, useFieldErrorsByPath, useForm, useFormContext, useHasErrors, useIsDirty, useIsSubmitting, useSubmitCount, useTouched, useTouchedByPath, useTouchedFields, useValue, useValueByPath, useWatch };
517
+ export { Checkbox, CheckboxGroupContext, CheckboxGroupProvider, Field, FieldError, FieldPath, Form, FormContext, Form$1 as FormInstance, FormProvider, Name, Options, Path, PathValueOf, Select, ValidationMode, Validator, createFormContext, fieldErrorId, subscribe, useCanSubmit, useCheckboxGroupContext, useDirtyFields, useError, useErrorByPath, useField, useFieldArray, useFieldErrors, useFieldErrorsByPath, useForm, useFormContext, useHasErrors, useIsDirty, useIsSubmitting, useSubmitCount, useTouched, useTouchedByPath, useTouchedFields, useValue, useValueByPath, useWatch };
507
518
  export type { FieldRules, SubscribeEvent, SubscribeOptions, WatchScope };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import*as e from"react";import t,{useCallback as n,useRef as r,useState as o,useEffect as i,useMemo as u,useContext as s,useReducer as a,createContext as c,createElement as l}from"react";function f(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];(e.get(t)||[]).forEach(function(e){return e.apply(void 0,r)})}function d(e,t,n){var r=function(e,t){var n=e.get(t);if(n)return n;var r=new Set;return e.set(t,r),r}(e,t);return r.add(n),function(){return r.delete(n)}}const m=new Map;function h(e){if(Array.isArray(e))return e;const t=m.get(e);if(t)return t;const n=function(e){const t=[];let n="";const r=()=>{t.push(n),n=""};for(let o=0;o<e.length;o++){const i=e[o];if("."===i)""!==n&&r();else if("["===i){""!==n&&r();const i=e[o+1];if('"'===i||"'"===i){const n=e.indexOf(i,o+2);if(-1===n)throw new TypeError(`Unterminated quote in path: ${e}`);if("]"!==e[n+1])throw new TypeError(`Expected "]" after quoted segment in path: ${e}`);t.push(e.slice(o+2,n)),o=n+1}else{const n=e.indexOf("]",o+1);if(-1===n)throw new TypeError(`Unterminated bracket in path: ${e}`);const r=e.slice(o+1,n);t.push(/^-?\d+$/.test(r)?Number(r):r),o=n}}else n+=i}""===n&&0!==t.length||r();return t}(e);return m.set(e,n),n}function y(e,t){return t.reduce((e,t)=>{if(null!=e)return e[t]},e)}function v(e,t){if(!t.length||null==e)return e;const[n,...r]=t;if(r.length){const t=v(e[n],r);return t===e[n]?e:p(e,[n],t)}if(Array.isArray(e)){if(!(n in e))return e;const t=e.slice();return delete t[n],t}if("object"!=typeof e||!(n in e))return e;const o={...e};return delete o[n],o}function p(e,t,n){if(!t.length)return n;const[r,...o]=t;if("number"==typeof r){const t=Array.isArray(e)?e.slice():[];return t[r]=p(t[r],o,n),t}return{...e,[r]:p(e&&e[r],o,n)}}function g(e,t,n,r){if(!t.length)return n;let o=e,i=null,u="";for(let s=0;s<t.length;s++){const a=t[s];if(!r.has(o)){let t;t="number"==typeof a?Array.isArray(o)?o.slice():[]:{...o},r.add(t),0===s?e=t:i[u]=t,o=t}s===t.length-1?o[a]=n:(i=o,u=a,o=o[a])}return e}function b(e){return e&&"function"==typeof e.then}function k(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;const n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!k(e[n],t[n]))return!1;return!0}const r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)return!1;if(Object.getPrototypeOf(t)!==r)return!1;const o=Object.keys(e),i=Object.keys(t);if(o.length!==i.length)return!1;for(const n of o)if(!k(e[n],t[n]))return!1;return!0}function S(e,t,n,r){return new Promise((o,i)=>{if(r())return void i();if(n())return void o();const u=d(e,t,()=>{if(r())return u(),void i();n()&&(u(),o())})})}function E(e){const t=h(e);return{value:t,key:JSON.stringify(t)}}const V=Symbol("validation-outcome");function w(e){return{emitter:new Map,...e,mode:e?.mode??"onSubmit",reValidateMode:e?.reValidateMode??"onChange",disabled:e?.disabled??!1,initialValues:e?.initialValues??{},values:new Map,deleted:new Set,errors:new Map,touched:new Set,validators:new Map,changeHandlers:new Map,validating:new Set,parsedValues:void 0,isSubmitting:!1,submitCount:0,isSubmitSuccessful:void 0}}function O(e){const{initialValues:t,parsedValues:n,values:r,deleted:o}=e,i=new Set;let u=n??t;for(const[e,t]of r)u=g(u,JSON.parse(e),t,i);for(const e of o)u=v(u,JSON.parse(e));return u}function _(e,t){return A(e,E(t))}function A({initialValues:e,parsedValues:t,values:n,deleted:r},o){return n.has(o.key)?n.get(o.key):r.has(o.key)?void 0:y(t??e,o.value)}function x(e,t,n,r){T(e,E(t),n,r)}function T(e,t,n,r){const{emitter:o,values:i,deleted:u}=e;i.set(t.key,n),ue(u,t),Z(e),r?.shouldTouch&&K(e,t),r?.shouldValidate&&e.validators.get(t.key)?.(),f(o,"change",t)}function L(e,t,n){C(e,E(t),n)}function C(e,t,n){const r=e.changeHandlers.get(t.key);r?r(n):T(e,t,n)}function j(e,t){return D(e,E(t))}function D({errors:e},t){return e.get(t.key)?.[0]}const N=[];function M(e,t){return B(e,E(t))}function B({errors:e},t){return e.get(t.key)??N}function $({errors:e}){const t=[];for(const[n,r]of e){const e=JSON.parse(n).join(".");for(const{type:n,message:o}of r)t.push({path:e,type:n,message:o})}return t}function q({errors:e}){return e.values().next().value?.[0]?.message}function H(e,t){const n=E(t),{initialValues:r,values:o,touched:i,validating:u}=e,s=o.get(n.key);return{value:A(e,n),error:D(e,n),errors:B(e,n),isDirty:o.has(n.key)&&y(r,n.value)!==s,isTouched:i.has(n.key),isValidating:u.has(n.key)}}function I({emitter:e,validating:t},n){t.delete(n.key),f(e,"validating",n)}function R({emitter:e,validating:t},n){t.add(n.key),f(e,"validating",n)}function P(e,t,n){U(e,E(t),n)}function U({emitter:e,errors:t},n,r){const o=function(e){if("string"==typeof e)return e?[{type:"custom",message:e}]:void 0;if(me(e))return[e];if(!e)return;const t=[];return e.forEach(e=>{"string"==typeof e&&e?t.push({type:"custom",message:e}):me(e)&&t.push(e)}),t.length?t:void 0}(r);o?t.set(n.key,o):t.delete(n.key),f(e,"errors",n)}function F(e,t){const{emitter:n,errors:r}=e;if(void 0===t)return r.clear(),void f(n,"errors");const o="string"==typeof t||de(t)?[E(t)]:t.map(e=>E(e));for(const{key:e}of o)r.delete(e);for(const e of o)f(n,"errors",e)}function J(e,t,n){n?.keepExisting||F(e);for(const[n,r]of Object.entries(t))P(e,n,(Array.isArray(r)?r:[r]).map(e=>({type:"server",message:e})))}function G(e,t){K(e,E(t))}function K({emitter:e,touched:t},n){t.has(n.key)||(t.add(n.key),f(e,"touched",n))}function W(e,t){return z(e,E(t))}function z({touched:e},t){return e.has(t.key)}function Y(e){let t=!1;return Q(e,()=>{t=!0}),t}function Q({initialValues:e,values:t},n){for(const[r,o]of t){const t=JSON.parse(r);y(e,t)!==o&&n(t.join("."))}}const X=new WeakMap;function Z(e){const t=X.get(e);t&&t.version++}function ee(e){const t={};return Q(e,e=>{t[e]=!0}),t}function te(e){let t=X.get(e);if(t){if(t.version>0){const n=ee(e);(function(e,t){const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(e=>!0===t[e])})(t.result,n)||(t.result=n),t.version=0}}else t={version:0,result:ee(e)},X.set(e,t);return t.result}function ne({touched:e}){return Array.from(e,e=>JSON.parse(e).join("."))}function re({touched:e}){return e.size>0}function oe(e,t){ie(e,E(t))}function ie(e,{key:t,value:n}){const{emitter:r,values:o,touched:i,errors:u,validating:s,deleted:a}=e;o.delete(t),i.delete(t),u.delete(t),s.delete(t),function(e,t){for(let n=1;n<t.length;n++)if(e.has(JSON.stringify(t.slice(0,n))))return!0;const n=`${JSON.stringify(t).slice(0,-1)},`;for(const t of e.keys())if(t.startsWith(n))return!0;return!1}(o,n)||a.add(t),Z(e),f(r,"change"),f(r,"touched"),f(r,"errors"),f(r,"validating")}function ue(e,{key:t}){if(e.size)for(const n of e)(n===t||n.startsWith(`${t.slice(0,-1)},`)||t.startsWith(`${n.slice(0,-1)},`))&&e.delete(n)}function se(e,t){e.initialValues===t||k(e.initialValues,t)||(e.initialValues=t,e.parsedValues=void 0,e.values.clear(),e.deleted.clear(),Z(e),f(e.emitter,"change"))}function ae(e,t,n){const r=n?.keepDirtyValues?Object.keys(te(e)).map(t=>({key:t,value:_(e,t)})):[];e.initialValues=t,e.parsedValues=void 0,n?.keepErrors||F(e);const{emitter:o,touched:i,values:u,deleted:s,validating:a}=e;u.clear(),s.clear(),n?.keepTouched||i.clear(),a.clear(),n?.keepIsSubmitting||(e.isSubmitting=!1),n?.keepSubmitCount||(e.submitCount=0),n?.keepIsSubmitted||(e.isSubmitSuccessful=void 0),Z(e);for(const{key:t,value:n}of r)T(e,E(t),n);f(o,"change"),f(o,"touched"),f(o,"validating"),f(o,"submitting"),f(o,"submitCount"),f(o,"submitSuccessful"),f(o,"reset")}function ce(e,t,n){const r=E(t),{emitter:o,values:i,touched:u,errors:s,deleted:a}=e;if(i.delete(r.key),void 0!==e.parsedValues){e.parsedValues=v(e.parsedValues,r.value);const t=y(e.initialValues,r.value);void 0!==t&&i.set(r.key,t)}n&&"value"in n&&i.set(r.key,n.value),ue(a,r),f(o,"change"),!n?.keepTouched&&u.delete(r.key)&&f(o,"touched",r),!n?.keepErrors&&s.delete(r.key)&&f(o,"errors",r),Z(e)}function le({errors:e}){return e.size>0}async function fe(e,t){const n=()=>S(e.emitter,"validating",()=>!e.validating.size,()=>!1);if(void 0===t){if(e.validators.forEach(e=>e()),await n(),e.validate){const t=await e.validate(O(e));ye(e,t)}return!le(e)}const r="string"==typeof t||de(t)?[E(t).key]:t.map(e=>E(e).key);return r.forEach(t=>e.validators.get(t)?.()),await n(),r.every(t=>!e.errors.has(t))}function de(e){return e.some(e=>"number"==typeof e)}function me(e){return!!e&&"object"==typeof e&&"string"==typeof e.type&&"string"==typeof e.message}function he(e,t,n=[]){Object.entries(t).forEach(([t,r])=>{const o=[...n,...h(t)];"string"==typeof r?r&&P(e,o,r):Array.isArray(r)||me(r)?P(e,o,r):r&&"object"==typeof r&&he(e,r,o)})}function ye(e,t){if(t){if("object"==typeof t&&V in t){const n=t;return n.errors&&he(e,n.errors),void function(e,t){void 0!==t&&t!==e.parsedValues&&(e.parsedValues=t,f(e.emitter,"change"))}(e,n.values)}he(e,t)}}async function ve(e){if(e.validators.forEach(e=>e()),await S(e.emitter,"validating",()=>!e.validating.size,()=>le(e)).catch(()=>{throw new Error(q(e))}),e.validate){const t=await e.validate(O(e));if(ye(e,t),le(e))throw new Error(q(e))}}async function pe(e){return ve(e).catch(e=>e.message)}function ge(e,t){e.isSubmitting=t,f(e.emitter,"submitting")}function be(e){e.submitCount++,f(e.emitter,"submitCount")}function ke(e,t){e.isSubmitSuccessful=t,f(e.emitter,"submitSuccessful")}function Se(e,t){e.disabled=t,f(e.emitter,"disabled")}function Ee(e){if(e.startsWith("["))try{const t=JSON.parse(e);if(Array.isArray(t))return t.join(".")}catch{}return e}function Ve(e,t){const{onSubmit:n,onValidSubmit:r,onInvalidSubmit:o,shouldFocusError:i=!0}=t??{};return async t=>{t&&"function"==typeof t.preventDefault&&t.preventDefault();const u=t?.currentTarget;ge(e,!0),be(e);const s=O(e);if(u&&"function"==typeof u.checkValidity&&!1===u.checkValidity()){if(u.reportValidity(),i&&"function"==typeof u.querySelector){const e=u.querySelector(":invalid");e&&"function"==typeof e.focus&&e.focus()}return ge(e,!1),ke(e,!1),void(o&&o(function(e){const t=[],{elements:n}=e;for(let e=0;e<n.length;e++){const r=n[e];r.name&&"function"==typeof r.checkValidity&&!r.checkValidity()&&t.push({path:Ee(r.name),type:"native",message:r.validationMessage})}return t}(u),s))}if(await pe(e)){if(ge(e,!1),ke(e,!1),i){const t=e.errors.keys().next().value;void 0!==t&&f(e.emitter,"focusError",t)}o&&o($(e),s)}else try{const o=O(e);n&&await n(o,t),r&&await r(o,t),ke(e,!0)}catch{ke(e,!1)}finally{ge(e,!1)}}}function we(e,t,n){const{key:r}=E(t);n?f(e.emitter,"focusError",r,n):f(e.emitter,"focusError",r)}function Oe(e,t){switch(e){case"required":return"This field is required";case"min":return`Must be at least ${t}`;case"max":return`Must be at most ${t}`;case"minLength":return`Must be at least ${t} characters`;case"maxLength":return`Must be at most ${t} characters`;case"pattern":return"Invalid format";default:return"Invalid value"}}var _e,Ae={exports:{}},xe={};var Te,Le,Ce={};var je=(Le||(Le=1,"production"===process.env.NODE_ENV?Ae.exports=function(){if(_e)return xe;_e=1;var e=t,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=e.useState,o=e.useEffect,i=e.useLayoutEffect,u=e.useDebugValue;function s(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!n(e,r)}catch(e){return!0}}var a="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var n=t(),a=r({inst:{value:n,getSnapshot:t}}),c=a[0].inst,l=a[1];return i(function(){c.value=n,c.getSnapshot=t,s(c)&&l({inst:c})},[e,n,t]),o(function(){return s(c)&&l({inst:c}),e(function(){s(c)&&l({inst:c})})},[e]),u(n),n};return xe.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:a,xe}():Ae.exports=(Te||(Te=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch(e){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var n=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},o=n.useState,i=n.useEffect,u=n.useLayoutEffect,s=n.useDebugValue,a=!1,c=!1,l="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,l){a||void 0===n.startTransition||(a=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var f=l();if(!c){var d=l();r(f,d)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),c=!0)}var m=(d=o({inst:{value:f,getSnapshot:l}}))[0].inst,h=d[1];return u(function(){m.value=f,m.getSnapshot=l,e(m)&&h({inst:m})},[t,f,l]),i(function(){return e(m)&&h({inst:m}),t(function(){e(m)&&h({inst:m})})},[t]),s(f),f};Ce.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:l,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Ce)),Ae.exports);function De(e,t){return e.startsWith(`${t.slice(0,-1)},`)}function Ne(e,t,n,r,o){const{key:i}=n;return d(e,t,e=>{(void 0===e||e.key===i||De(i,e.key)||"branch"===r&&De(e.key,i))&&o()})}function Me(e,t,n,r){return d(e,t,e=>{void 0!==e&&e.key!==n||r()})}function Be(e,t){const{name:n,event:r="change",scope:o="branch",callback:i}=t;if(void 0===n)return d(e.emitter,r,i);const u=function(e){return Array.isArray(e)&&e.every(e=>"number"!=typeof e)}(n)?n:[n],s=u.map(t=>{const n=E(t);return"errors"===r||"touched"===r?Me(e.emitter,r,n.key,i):Ne(e.emitter,r,n,o,i)});return 1===s.length?s[0]:()=>s.forEach(e=>e())}function $e(e){const[t]=o(()=>{const t=w(e);return e&&void 0!==e.values&&se(t,e.values),t}),n=e&&e.initialValues,u=e&&e.values,s=r(null);null===s.current&&(s.current={done:!1,source:void 0}),i(()=>{const e=s.current;e.done&&(e.source===n||k(e.source,n))||(e.done=!0,e.source=n,se(t,n))},[t,n]);const a=r(null);return null===a.current&&(a.current={done:!1,source:void 0}),i(()=>{if(void 0===u)return;const e=a.current;e.done&&(e.source===u||k(e.source,u))||(e.done=!0,e.source=u,se(t,u))},[t,u]),t}function qe(e,t){const o=r(null);null===o.current&&(o.current={hasValue:!1});const i=o.current,u=r(t);u.current=t;const s=n(()=>(i.hasValue||(i.value=u.current(),i.hasValue=!0),i.value),[i]),a=n(t=>{i.hasValue=!1;return e(()=>{i.hasValue=!1,t()})},[e,i]);return je.useSyncExternalStore(a,s,s)}function He(e,t,r){return qe(n(n=>d(e,t,n),[e,t]),r)}function Ie(e,t){return Re(e,E(t))}function Re(e,t){const{emitter:r}=e,{key:o}=t;return qe(n(e=>Ne(r,"change",t,"leaf",e),[r,o]),A.bind(null,e,t))}function Pe(e,t){return Ue(e,E(t))}function Ue(e,t){const{emitter:r}=e,{key:o}=t;return qe(n(e=>Me(r,"touched",o,e),[r,o]),z.bind(null,e,t))}function Fe(e,t){return Je(e,E(t))?.message}function Je(e,t){const{emitter:r}=e,{key:o}=t;return qe(n(e=>Me(r,"errors",o,e),[r,o]),D.bind(null,e,t))}function Ge(e,t){return Ke(e,E(t))}function Ke(e,t){const{emitter:r}=e,{key:o}=t;return qe(n(e=>Me(r,"errors",o,e),[r,o]),B.bind(null,e,t))}function We(e){return He(e.emitter,"change",Y.bind(null,e))}function ze(e){return He(e.emitter,"change",te.bind(null,e))}function Ye(e){return He(e.emitter,"touched",ne.bind(null,e))}function Qe(e){return He(e.emitter,"errors",le.bind(null,e))}function Xe(e){return He(e.emitter,"submitting",()=>e.isSubmitting)}function Ze(e){return He(e.emitter,"submitCount",()=>e.submitCount)}function et(e){const t=u(()=>E(h(e)),[e]);return u(()=>t,[t.key])}function tt(e){const t=function(e){const t=r(e);return t.current=e,t}(e);return n((...e)=>t.current(...e),[t])}function nt(e,t){if(!e)return t;const n=function(e){return t=>{if(e.required&&(""===t||null==t))return[{type:"required",message:"string"==typeof e.required?e.required:Oe("required")}];const n=[],r=(t,n)=>e.messages?.[t]??Oe(t,n);if(void 0!==e.min){const o=Number(t);!Number.isNaN(o)&&o<e.min&&n.push({type:"min",message:r("min",e.min)})}if(void 0!==e.max){const o=Number(t);!Number.isNaN(o)&&o>e.max&&n.push({type:"max",message:r("max",e.max)})}return void 0!==e.minLength&&"string"==typeof t&&t.length<e.minLength&&n.push({type:"minLength",message:r("minLength",e.minLength)}),void 0!==e.maxLength&&"string"==typeof t&&t.length>e.maxLength&&n.push({type:"maxLength",message:r("maxLength",e.maxLength)}),e.pattern&&!e.pattern.value.test(t)&&n.push({type:"pattern",message:e.messages?.pattern??e.pattern.message??Oe("pattern")}),n.length?n:void 0}}(e);return t?(e,r)=>{const o=n(e,r),i=e=>{const t=[...o??[]];return Array.isArray(e)?t.push(...e):e&&t.push(e),t.length?t:void 0},u=t(e,r);return b(u)?u.then(i):i(u)}:n}function rt({form:e,name:t,initialValue:n,shouldUnregister:u,validate:a,rules:c,validateDebounce:l,delayError:f,disabled:d,mode:m},h){const y=s(h),v=e||y;if(!v)throw new Error("no form provided");const p=et(t),g=function(e,t,n,o){const u=s(ct),a=n||u;if(!a)throw new Error("no form provided");const c=r(null),l=r(e);l.current=e;const f=r(o?.debounce??0);return f.current=o?.debounce??0,i(()=>{let e=null,n=null,r=!1;const o=()=>{r||(r=!0,R(a,t))},i=()=>{r&&(r=!1,I(a,t))},u=()=>{e=null;const r=l.current;if(!r)return void i();n?.abort(),n=new AbortController;const u=c.current={};let s;try{s=r(A(a,t),{form:a,path:t,signal:n.signal})}catch(e){throw i(),e}if(!b(s))return U(a,t,s),void i();o(),s.then(e=>{u===c.current&&U(a,t,e)}).catch(()=>{}).finally(()=>{u===c.current&&(i(),c.current=null)})};return a.validators.set(t.key,()=>{const t=f.current;if(t>0)return null!==e?clearTimeout(e):o(),void(e=setTimeout(u,t));u()}),()=>{a.validators.delete(t.key),null!==e&&(clearTimeout(e),e=null),i(),n?.abort()}},[a,t.key]),tt(()=>a.validators.get(t.key)?.())}(nt(c,a),p,v,{debounce:l}),k=Ke(v,p),S=function(e,t){const[n,r]=o(e);return i(()=>{if(void 0===t)return;if(0===e.length)return void r(e);if(n.length>0)return void r(e);const o=setTimeout(()=>r(e),t);return()=>clearTimeout(o)},[e,t,n]),void 0===t?e:n}(k,f),E=S[0],V=E?.message,w=Re(v,p),O=He(v.emitter,"disabled",()=>v.disabled),_=m??v.mode;i(()=>{void 0!==n&&void 0===A(v,p)&&T(v,p,n)},[v,p,n]);const x=tt(e=>{T(v,p,e),("onChange"===_||"all"===_||"onTouched"===_&&z(v,p)||k.length>0&&"onChange"===v.reValidateMode)&&g()});i(()=>(v.changeHandlers.set(p.key,x),()=>{v.changeHandlers.get(p.key)===x&&v.changeHandlers.delete(p.key)}),[v,p.key,x]);const L=tt(()=>{K(v,p),("onBlur"===_||"onTouched"===_||"all"===_||k.length>0&&"onBlur"===v.reValidateMode)&&g()});return i(()=>()=>{!1!==u&&ie(v,p)},[p,v,u]),{form:v,value:w,error:V,errorObject:E,errors:S,onChange:x,onBlur:L,name:p.key,disabled:O||!!d}}function ot(e){return rt(e,ct)}let it=0;function ut(){return"_"+ ++it}function st(e,t){const o=s(t),u=e.form||o;if(!u)throw new Error("no form provided");const c=et(e.name),l=r([]),f=n(()=>A(u,c)||[],[u,c]),d=n(e=>{T(u,c,e)},[u,c]),m=n(()=>{const e=f();for(;l.current.length<e.length;)l.current.push(ut());for(;l.current.length>e.length;)l.current.pop();return l.current.map((e,t)=>({id:e,index:t}))},[f]),[h,y]=a(m,void 0,m);i(()=>Ne(u.emitter,"change",c,"branch",y),[u.emitter,c]);return{fields:h,append:tt(e=>{const t=f();l.current.push(ut()),d([...t,e])}),prepend:tt(e=>{const t=f();l.current.unshift(ut()),d([e,...t])}),insert:tt((e,t)=>{const n=f();l.current.splice(e,0,ut());const r=[...n.slice(0,e),t,...n.slice(e)];d(r)}),remove:tt(e=>{const t=f();l.current.splice(e,1);const n=t.filter((t,n)=>n!==e);d(n)}),swap:tt((e,t)=>{const n=f();[l.current[e],l.current[t]]=[l.current[t],l.current[e]];const r=[...n];[r[e],r[t]]=[r[t],r[e]],d(r)}),move:tt((e,t)=>{const n=f(),[r]=l.current.splice(e,1);l.current.splice(t,0,r);const o=[...n],[i]=o.splice(e,1);o.splice(t,0,i),d(o)}),replace:tt(e=>{l.current=e.map(()=>ut()),d([...e])}),update:tt((e,t)=>{const n=f();if(e<0||e>=n.length)return;const r=[...n];r[e]=t,d(r)})}}function at(e){return st(e,ct)}const ct=c(null),lt=ct.Provider;function ft(){const e=s(ct);if(!e)throw new Error("no form provided");return e}function dt(){const e=c(null);return{context:e,FormProvider:function({form:t,children:n}){return l(e.Provider,{value:t},n)},useFormContext:function(){const t=s(e);if(!t)throw new Error("no form provided");return t},useField:function(t){return rt(t,e)},useFieldArray:function(t){return st(t,e)}}}const mt=c(null),ht=mt.Provider;function yt(){const e=s(mt);if(!e)throw new Error("no group provided");return e}function vt({form:t,context:n,initialValues:r,values:o,onSubmit:i,onValidSubmit:u,onInvalidSubmit:s,shouldFocusError:a,...c}){const l=$e({initialValues:r,values:o}),f=t||l,d=Ve(f,{onSubmit:i,onValidSubmit:u,onInvalidSubmit:s,shouldFocusError:a}),{Provider:m}=n??ct;return e.createElement(m,{value:f},e.createElement("form",{...c,noValidate:!0,onSubmit:d}))}function pt(e){return e.replace(/["'[\],\s]+/g,"-").replace(/^-+|-+$/g,"")||"field"}function gt(e,t,n){return{"aria-invalid":!!e||n["aria-invalid"],"aria-describedby":e?[n["aria-describedby"],pt(t)].filter(Boolean).join(" "):n["aria-describedby"]}}function bt(e){return pt(E(e).key)}const kt=e.forwardRef(({validate:t,eventToValue:n,initialValue:r,name:o,asProps:i,renderError:u,as:s,valueToProps:a,form:c,shouldUnregister:l,rules:f,validateDebounce:m,disabled:h,delayError:y,mode:v,...p},g)=>{const b=e.useRef(null),[k,S]=e.useState(0),E=e.useCallback(e=>{b.current=e,function(e,t){"function"==typeof e?e(t):e&&(e.current=t)}(g,e)},[g]),{value:V,onChange:w,onBlur:O,error:_,form:A,name:x,disabled:T}=ot({name:o,form:c,initialValue:r,shouldUnregister:l,rules:f,validateDebounce:m,delayError:y,disabled:h,mode:v,validate:(...e)=>{const n=b.current;if(!n||"function"!=typeof n.checkValidity||(n.setCustomValidity(""),!1!==n.checkValidity()))return t?t(...e):void 0;S(e=>e+1)}}),L=s||"input";e.useEffect(()=>{const e=b.current;e&&"function"==typeof e.setCustomValidity&&("string"==typeof _?(e.setCustomValidity(_),e.reportValidity()):e.setCustomValidity(""))},[_]),e.useEffect(()=>{k>0&&b.current?.reportValidity()},[k]),e.useEffect(()=>d(A.emitter,"focusError",(e,t)=>{if(e!==x)return;const n=b.current;n&&"function"==typeof n.focus&&(n.focus(),t?.shouldSelect&&"function"==typeof n.select&&n.select())}),[A,x]);const C=n??(e=>e.target.value),j=pt(x);return e.createElement(e.Fragment,null,e.createElement(L,{...p,name:x,onBlur:O,...i,...a?a(V):{value:V},...gt(_,x,p),disabled:T,onChange:e=>w(C(e)),ref:E}),_&&u?e.createElement("span",{id:j,role:"alert"},u(_,j)):null)}),St=e.forwardRef(({name:t,form:n,initialValue:r,shouldUnregister:o,validate:i,rules:u,validateDebounce:s,disabled:a,delayError:c,mode:l,...f},d)=>{const{value:m,onChange:h,onBlur:y,error:v,name:p,disabled:g}=ot({name:t,form:n,initialValue:r,shouldUnregister:o,validate:i,rules:u,validateDebounce:s,delayError:c,disabled:a,mode:l});return e.createElement("input",{...f,name:p,onBlur:y,type:"checkbox",checked:!!m,...gt(v,p,f),disabled:g,onChange:e=>h(e.target.checked),ref:d})});function Et(e,t){return e?Array.isArray(t)?t:[]:t??""}const Vt=e.forwardRef(({name:t,multiple:n,children:r,form:o,initialValue:i,shouldUnregister:u,validate:s,rules:a,validateDebounce:c,disabled:l,delayError:f,mode:d,...m},h)=>{const{value:y,onChange:v,onBlur:p,error:g,name:b,disabled:k}=ot({name:t,form:o,initialValue:i,shouldUnregister:u,validate:s,rules:a,validateDebounce:c,delayError:f,disabled:l,mode:d});return e.createElement("select",{...m,name:b,onBlur:p,multiple:n,value:Et(n,y),...gt(g,b,m),disabled:k,onChange:e=>v(n?Array.from(e.target.selectedOptions,e=>e.value):e.target.value),ref:h},r)});export{St as Checkbox,mt as CheckboxGroupContext,ht as CheckboxGroupProvider,kt as Field,vt as Form,ct as FormContext,lt as FormProvider,Vt as Select,V as VALIDATION_OUTCOME,L as changeValue,C as changeValueByPath,F as clearErrors,w as createForm,dt as createFormContext,ve as ensureValidate,bt as fieldErrorId,te as getDirtyFields,j as getError,D as getErrorByPath,$ as getErrors,M as getFieldErrors,B as getFieldErrorsByPath,H as getFieldState,q as getFirstError,ne as getTouchedFields,_ as getValue,A as getValueByPath,O as getValues,Ve as handleSubmit,le as hasErrors,W as hasTouched,z as hasTouchedByPath,be as incrementSubmitCount,Y as isDirty,re as isTouched,oe as removeField,ie as removeFieldByPath,ae as reset,ce as resetField,Se as setDisabled,P as setError,U as setErrorByPath,we as setFocus,se as setInitialValues,ge as setIsSubmitting,J as setServerErrors,ke as setSubmitSuccessful,G as setTouched,K as setTouchedByPath,R as setValidatingByPath,x as setValue,T as setValueByPath,Be as subscribe,fe as trigger,I as unsetValidatingByPath,yt as useCheckboxGroupContext,ze as useDirtyFields,Fe as useError,Je as useErrorByPath,ot as useField,at as useFieldArray,Ge as useFieldErrors,Ke as useFieldErrorsByPath,$e as useForm,ft as useFormContext,Qe as useHasErrors,We as useIsDirty,Xe as useIsSubmitting,Ze as useSubmitCount,Pe as useTouched,Ue as useTouchedByPath,Ye as useTouchedFields,Ie as useValue,Re as useValueByPath,He as useWatch,pe as validate};
1
+ import*as e from"react";import t,{useCallback as n,useRef as r,useState as o,useEffect as i,useMemo as u,useContext as s,useReducer as a,createContext as c,createElement as l}from"react";function f(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];(e.get(t)||[]).forEach(function(e){return e.apply(void 0,r)})}function d(e,t,n){var r=function(e,t){var n=e.get(t);if(n)return n;var r=new Set;return e.set(t,r),r}(e,t);return r.add(n),function(){return r.delete(n)}}const m=new Map;function h(e){if(Array.isArray(e))return e;const t=m.get(e);if(t)return t;const n=function(e){const t=[];let n="";const r=()=>{t.push(n),n=""};for(let o=0;o<e.length;o++){const i=e[o];if("."===i)""!==n&&r();else if("["===i){""!==n&&r();const i=e[o+1];if('"'===i||"'"===i){const n=e.indexOf(i,o+2);if(-1===n)throw new TypeError(`Unterminated quote in path: ${e}`);if("]"!==e[n+1])throw new TypeError(`Expected "]" after quoted segment in path: ${e}`);t.push(e.slice(o+2,n)),o=n+1}else{const n=e.indexOf("]",o+1);if(-1===n)throw new TypeError(`Unterminated bracket in path: ${e}`);const r=e.slice(o+1,n);t.push(/^-?\d+$/.test(r)?Number(r):r),o=n}}else n+=i}""===n&&0!==t.length||r();return t}(e);return m.set(e,n),n}function v(e,t){return t.reduce((e,t)=>{if(null!=e)return e[t]},e)}function y(e,t){if(!t.length||null==e)return e;const[n,...r]=t;if(r.length){const t=y(e[n],r);return t===e[n]?e:p(e,[n],t)}if(Array.isArray(e)){if(!(n in e))return e;const t=e.slice();return delete t[n],t}if("object"!=typeof e||!(n in e))return e;const o={...e};return delete o[n],o}function p(e,t,n){if(!t.length)return n;const[r,...o]=t;if("number"==typeof r){const t=Array.isArray(e)?e.slice():[];return t[r]=p(t[r],o,n),t}return{...e,[r]:p(e&&e[r],o,n)}}function g(e,t,n,r){if(!t.length)return n;let o=e,i=null,u="";for(let s=0;s<t.length;s++){const a=t[s];if(!r.has(o)){let t;t="number"==typeof a?Array.isArray(o)?o.slice():[]:{...o},r.add(t),0===s?e=t:i[u]=t,o=t}s===t.length-1?o[a]=n:(i=o,u=a,o=o[a])}return e}function b(e){return e&&"function"==typeof e.then}function k(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;const n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!k(e[n],t[n]))return!1;return!0}const r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)return!1;if(Object.getPrototypeOf(t)!==r)return!1;const o=Object.keys(e),i=Object.keys(t);if(o.length!==i.length)return!1;for(const n of o)if(!k(e[n],t[n]))return!1;return!0}function S(e,t,n,r){return new Promise((o,i)=>{if(r())return void i();if(n())return void o();const u=d(e,t,()=>{if(r())return u(),void i();n()&&(u(),o())})})}function E(e){const t=h(e);return{value:t,key:JSON.stringify(t)}}const w=Symbol("validation-outcome");function V(e){return{emitter:new Map,...e,mode:e?.mode??"onSubmit",reValidateMode:e?.reValidateMode??"onChange",disabled:e?.disabled??!1,initialValues:e?.initialValues??{},values:new Map,deleted:new Set,errors:new Map,touched:new Set,validators:new Map,changeHandlers:new Map,validating:new Set,parsedValues:void 0,isSubmitting:!1,submitCount:0,isSubmitSuccessful:void 0}}function O(e){const{initialValues:t,parsedValues:n,values:r,deleted:o}=e,i=new Set;let u=n??t;for(const[e,t]of r)u=g(u,JSON.parse(e),t,i);for(const e of o)u=y(u,JSON.parse(e));return u}function _(e,t){return A(e,E(t))}function A({initialValues:e,parsedValues:t,values:n,deleted:r},o){return n.has(o.key)?n.get(o.key):r.has(o.key)?void 0:v(t??e,o.value)}function x(e,t,n,r){T(e,E(t),n,r)}function T(e,t,n,r){const{emitter:o,values:i,deleted:u}=e;i.set(t.key,n),ue(u,t),Z(e),r?.shouldTouch&&G(e,t),r?.shouldValidate&&e.validators.get(t.key)?.(),f(o,"change",t)}function C(e,t,n){L(e,E(t),n)}function L(e,t,n){const r=e.changeHandlers.get(t.key);r?r(n):T(e,t,n)}function j(e,t){return D(e,E(t))}function D({errors:e},t){return e.get(t.key)?.[0]}const N=[];function M(e,t){return B(e,E(t))}function B({errors:e},t){return e.get(t.key)??N}function P({errors:e}){const t=[];for(const[n,r]of e){const e=JSON.parse(n).join(".");for(const{type:n,message:o}of r)t.push({path:e,type:n,message:o})}return t}function $({errors:e}){return e.values().next().value?.[0]?.message}function q(e,t){const n=E(t),{initialValues:r,values:o,touched:i,validating:u}=e,s=o.get(n.key);return{value:A(e,n),error:D(e,n),errors:B(e,n),isDirty:o.has(n.key)&&v(r,n.value)!==s,isTouched:i.has(n.key),isValidating:u.has(n.key)}}function H({emitter:e,validating:t},n){t.delete(n.key),f(e,"validating",n)}function I({emitter:e,validating:t},n){t.add(n.key),f(e,"validating",n)}function R(e,t,n){U(e,E(t),n)}function U({emitter:e,errors:t},n,r){const o=function(e){if("string"==typeof e)return e?[{type:"custom",message:e}]:void 0;if(me(e))return[e];if(!e)return;const t=[];return e.forEach(e=>{"string"==typeof e&&e?t.push({type:"custom",message:e}):me(e)&&t.push(e)}),t.length?t:void 0}(r);o?t.set(n.key,o):t.delete(n.key),f(e,"errors",n)}function F(e,t){const{emitter:n,errors:r}=e;if(void 0===t)return r.clear(),void f(n,"errors");const o="string"==typeof t||de(t)?[E(t)]:t.map(e=>E(e));for(const{key:e}of o)r.delete(e);for(const e of o)f(n,"errors",e)}function J(e,t,n){n?.keepExisting||F(e);for(const[n,r]of Object.entries(t))R(e,n,(Array.isArray(r)?r:[r]).map(e=>({type:"server",message:e})))}function W(e,t){G(e,E(t))}function G({emitter:e,touched:t},n){t.has(n.key)||(t.add(n.key),f(e,"touched",n))}function K(e,t){return z(e,E(t))}function z({touched:e},t){return e.has(t.key)}function Y(e){let t=!1;return Q(e,()=>{t=!0}),t}function Q({initialValues:e,values:t},n){for(const[r,o]of t){const t=JSON.parse(r);v(e,t)!==o&&n(t.join("."))}}const X=new WeakMap;function Z(e){const t=X.get(e);t&&t.version++}function ee(e){const t={};return Q(e,e=>{t[e]=!0}),t}function te(e){let t=X.get(e);if(t){if(t.version>0){const n=ee(e);(function(e,t){const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(e=>!0===t[e])})(t.result,n)||(t.result=n),t.version=0}}else t={version:0,result:ee(e)},X.set(e,t);return t.result}function ne({touched:e}){return Array.from(e,e=>JSON.parse(e).join("."))}function re({touched:e}){return e.size>0}function oe(e,t){ie(e,E(t))}function ie(e,{key:t,value:n}){const{emitter:r,values:o,touched:i,errors:u,validating:s,deleted:a}=e;o.delete(t),i.delete(t),u.delete(t),s.delete(t),function(e,t){for(let n=1;n<t.length;n++)if(e.has(JSON.stringify(t.slice(0,n))))return!0;const n=`${JSON.stringify(t).slice(0,-1)},`;for(const t of e.keys())if(t.startsWith(n))return!0;return!1}(o,n)||a.add(t),Z(e),f(r,"change"),f(r,"touched"),f(r,"errors"),f(r,"validating")}function ue(e,{key:t}){if(e.size)for(const n of e)(n===t||n.startsWith(`${t.slice(0,-1)},`)||t.startsWith(`${n.slice(0,-1)},`))&&e.delete(n)}function se(e,t){e.initialValues===t||k(e.initialValues,t)||(e.initialValues=t,e.parsedValues=void 0,e.values.clear(),e.deleted.clear(),Z(e),f(e.emitter,"change"))}function ae(e,t,n){const r=n?.keepDirtyValues?Object.keys(te(e)).map(t=>({key:t,value:_(e,t)})):[];e.initialValues=t,e.parsedValues=void 0,n?.keepErrors||F(e);const{emitter:o,touched:i,values:u,deleted:s,validating:a}=e;u.clear(),s.clear(),n?.keepTouched||i.clear(),a.clear(),n?.keepIsSubmitting||(e.isSubmitting=!1),n?.keepSubmitCount||(e.submitCount=0),n?.keepIsSubmitted||(e.isSubmitSuccessful=void 0),Z(e);for(const{key:t,value:n}of r)T(e,E(t),n);f(o,"change"),f(o,"touched"),f(o,"validating"),f(o,"submitting"),f(o,"submitCount"),f(o,"submitSuccessful"),f(o,"reset")}function ce(e,t,n){const r=E(t),{emitter:o,values:i,touched:u,errors:s,deleted:a}=e;if(i.delete(r.key),void 0!==e.parsedValues){e.parsedValues=y(e.parsedValues,r.value);const t=v(e.initialValues,r.value);void 0!==t&&i.set(r.key,t)}n&&"value"in n&&i.set(r.key,n.value),ue(a,r),f(o,"change"),!n?.keepTouched&&u.delete(r.key)&&f(o,"touched",r),!n?.keepErrors&&s.delete(r.key)&&f(o,"errors",r),Z(e)}function le({errors:e}){return e.size>0}async function fe(e,t){const n=()=>S(e.emitter,"validating",()=>pe(e),()=>!1);if(void 0===t)return e.validators.forEach(e=>e()),await n(),e.validate&&await ke(e),!le(e);const r="string"==typeof t||de(t)?[E(t).key]:t.map(e=>E(e).key);return r.forEach(t=>e.validators.get(t)?.()),await n(),r.every(t=>!e.errors.has(t))}function de(e){return e.some(e=>"number"==typeof e)}function me(e){return!!e&&"object"==typeof e&&"string"==typeof e.type&&"string"==typeof e.message}function he(e,t,n=[]){Object.entries(t).forEach(([t,r])=>{const o=[...n,...h(t)];"string"==typeof r?r&&R(e,o,r):Array.isArray(r)||me(r)?R(e,o,r):r&&"object"==typeof r&&he(e,r,o)})}function ve(e,t){if(t){if("object"==typeof t&&w in t){const n=t;return n.errors&&he(e,n.errors),void function(e,t){void 0!==t&&t!==e.parsedValues&&(e.parsedValues=t,f(e.emitter,"change"))}(e,n.values)}he(e,t)}}const ye="__form_validate__";function pe(e){for(const t of e.validating)if(t!==ye)return!1;return!0}const ge=Symbol("form-validate-settled"),be=new WeakMap;function ke(e){const t=e.validate;if(!t)return Promise.resolve();const n=e.validateDebounce??0;if(n<=0){const n=new AbortController;return Promise.resolve(t(O(e),{form:e,signal:n.signal})).then(t=>{ve(e,t)})}const r=function(e){let t=be.get(e);return t||(t={timer:null,controller:null,round:null,marked:!1,waiters:[]},be.set(e,t)),t}(e);return null!==r.timer?clearTimeout(r.timer):(r.marked=!0,e.validating.add(ye),f(e.emitter,"validating")),r.timer=setTimeout(()=>{r.timer=null;const t=r.round={};(function(e,t,n){const r=e.validate;if(!r)return Promise.resolve();t.controller?.abort();const o=t.controller=new AbortController;let i;try{i=Promise.resolve(r(O(e),{form:e,signal:o.signal}))}catch(e){i=Promise.reject(e)}return i.then(r=>{t.round===n&&ve(e,r)},e=>{if(t.round===n)throw e})})(e,r,t).then(()=>Se(e,r,t,ge),n=>Se(e,r,t,n))},n),new Promise((e,t)=>{r.waiters.push({resolve:e,reject:t})})}function Se(e,t,n,r){if(t.round!==n)return;if(t.round=null,null!==t.timer)return;t.marked&&(t.marked=!1,e.validating.delete(ye),f(e.emitter,"validating"));const o=t.waiters;t.waiters=[];for(const e of o)r===ge?e.resolve():e.reject(r)}async function Ee(e){if(e.validators.forEach(e=>e()),await S(e.emitter,"validating",()=>pe(e),()=>le(e)).catch(()=>{throw new Error($(e))}),e.validate&&(await ke(e),le(e)))throw new Error($(e))}async function we(e){return Ee(e).catch(e=>e.message)}function Ve(e,t){e.isSubmitting=t,f(e.emitter,"submitting")}function Oe(e){e.submitCount++,f(e.emitter,"submitCount")}function _e(e,t){e.isSubmitSuccessful=t,f(e.emitter,"submitSuccessful")}function Ae(e,t){e.disabled=t,f(e.emitter,"disabled")}function xe(e){if(e.startsWith("["))try{const t=JSON.parse(e);if(Array.isArray(t))return t.join(".")}catch{}return e}function Te(e,t){const{onSubmit:n,onValidSubmit:r,onInvalidSubmit:o,shouldFocusError:i=!0}=t??{};return async t=>{t&&"function"==typeof t.preventDefault&&t.preventDefault();const u=t?.currentTarget;Ve(e,!0),Oe(e);const s=O(e);if(u&&"function"==typeof u.checkValidity&&!1===u.checkValidity()){if(u.reportValidity(),i&&"function"==typeof u.querySelector){const e=u.querySelector(":invalid");e&&"function"==typeof e.focus&&e.focus()}return Ve(e,!1),_e(e,!1),void(o&&o(function(e){const t=[],{elements:n}=e;for(let e=0;e<n.length;e++){const r=n[e];r.name&&"function"==typeof r.checkValidity&&!r.checkValidity()&&t.push({path:xe(r.name),type:"native",message:r.validationMessage})}return t}(u),s))}if(await we(e)){if(Ve(e,!1),_e(e,!1),i){const t=e.errors.keys().next().value;void 0!==t&&f(e.emitter,"focusError",t)}o&&o(P(e),s)}else try{const o=O(e);n&&await n(o,t),r&&await r(o,t),_e(e,!0)}catch{_e(e,!1)}finally{Ve(e,!1)}}}function Ce(e,t,n){const{key:r}=E(t);n?f(e.emitter,"focusError",r,n):f(e.emitter,"focusError",r)}function Le(e,t){switch(e){case"required":return"This field is required";case"min":return`Must be at least ${t}`;case"max":return`Must be at most ${t}`;case"minLength":return`Must be at least ${t} characters`;case"maxLength":return`Must be at most ${t} characters`;case"pattern":return"Invalid format";default:return"Invalid value"}}var je,De={exports:{}},Ne={};var Me,Be,Pe={};var $e=(Be||(Be=1,"production"===process.env.NODE_ENV?De.exports=function(){if(je)return Ne;je=1;var e=t,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=e.useState,o=e.useEffect,i=e.useLayoutEffect,u=e.useDebugValue;function s(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!n(e,r)}catch(e){return!0}}var a="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var n=t(),a=r({inst:{value:n,getSnapshot:t}}),c=a[0].inst,l=a[1];return i(function(){c.value=n,c.getSnapshot=t,s(c)&&l({inst:c})},[e,n,t]),o(function(){return s(c)&&l({inst:c}),e(function(){s(c)&&l({inst:c})})},[e]),u(n),n};return Ne.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:a,Ne}():De.exports=(Me||(Me=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch(e){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var n=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},o=n.useState,i=n.useEffect,u=n.useLayoutEffect,s=n.useDebugValue,a=!1,c=!1,l="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,l){a||void 0===n.startTransition||(a=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var f=l();if(!c){var d=l();r(f,d)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),c=!0)}var m=(d=o({inst:{value:f,getSnapshot:l}}))[0].inst,h=d[1];return u(function(){m.value=f,m.getSnapshot=l,e(m)&&h({inst:m})},[t,f,l]),i(function(){return e(m)&&h({inst:m}),t(function(){e(m)&&h({inst:m})})},[t]),s(f),f};Pe.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:l,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Pe)),De.exports);function qe(e,t){return e.startsWith(`${t.slice(0,-1)},`)}function He(e,t,n,r,o){const{key:i}=n;return d(e,t,e=>{(void 0===e||e.key===i||qe(i,e.key)||"branch"===r&&qe(e.key,i))&&o()})}function Ie(e,t,n,r){return d(e,t,e=>{void 0!==e&&e.key!==n||r()})}function Re(e,t){const{name:n,event:r="change",scope:o="branch",callback:i}=t;if(void 0===n)return d(e.emitter,r,i);const u=function(e){return Array.isArray(e)&&e.every(e=>"number"!=typeof e)}(n)?n:[n],s=u.map(t=>{const n=E(t);return"errors"===r||"touched"===r?Ie(e.emitter,r,n.key,i):He(e.emitter,r,n,o,i)});return 1===s.length?s[0]:()=>s.forEach(e=>e())}function Ue(e){const[t]=o(()=>{const t=V(e);return e&&void 0!==e.values&&se(t,e.values),t}),n=e&&e.initialValues,u=e&&e.values,s=r(null);null===s.current&&(s.current={done:!1,source:void 0}),i(()=>{const e=s.current;e.done&&(e.source===n||k(e.source,n))||(e.done=!0,e.source=n,se(t,n))},[t,n]);const a=r(null);return null===a.current&&(a.current={done:!1,source:void 0}),i(()=>{if(void 0===u)return;const e=a.current;e.done&&(e.source===u||k(e.source,u))||(e.done=!0,e.source=u,se(t,u))},[t,u]),t}function Fe(e,t){const o=r(null);null===o.current&&(o.current={hasValue:!1});const i=o.current,u=r(t);u.current=t;const s=n(()=>(i.hasValue||(i.value=u.current(),i.hasValue=!0),i.value),[i]),a=n(t=>{i.hasValue=!1;return e(()=>{i.hasValue=!1,t()})},[e,i]);return $e.useSyncExternalStore(a,s,s)}function Je(e,t,r){return Fe(n(n=>d(e,t,n),[e,t]),r)}function We(e,t){return Ge(e,E(t))}function Ge(e,t){const{emitter:r}=e,{key:o}=t;return Fe(n(e=>He(r,"change",t,"leaf",e),[r,o]),A.bind(null,e,t))}function Ke(e,t){return ze(e,E(t))}function ze(e,t){const{emitter:r}=e,{key:o}=t;return Fe(n(e=>Ie(r,"touched",o,e),[r,o]),z.bind(null,e,t))}function Ye(e,t){return Qe(e,E(t))?.message}function Qe(e,t){const{emitter:r}=e,{key:o}=t;return Fe(n(e=>Ie(r,"errors",o,e),[r,o]),D.bind(null,e,t))}function Xe(e,t){return Ze(e,E(t))}function Ze(e,t){const{emitter:r}=e,{key:o}=t;return Fe(n(e=>Ie(r,"errors",o,e),[r,o]),B.bind(null,e,t))}function et(e){return Je(e.emitter,"change",Y.bind(null,e))}function tt(e){return Je(e.emitter,"change",te.bind(null,e))}function nt(e){return Je(e.emitter,"touched",ne.bind(null,e))}function rt(e){return Je(e.emitter,"errors",le.bind(null,e))}function ot(e){return Je(e.emitter,"submitting",()=>e.isSubmitting)}function it(e){const{emitter:t}=e;return Fe(n(e=>{const n=d(t,"errors",e),r=d(t,"submitting",e);return()=>{n(),r()}},[t]),()=>!e.isSubmitting&&!le(e))}function ut(e){return Je(e.emitter,"submitCount",()=>e.submitCount)}function st(e){const t=u(()=>E(h(e)),[e]);return u(()=>t,[t.key])}function at(e){const t=function(e){const t=r(e);return t.current=e,t}(e);return n((...e)=>t.current(...e),[t])}function ct(e,t){if(!e)return t;const n=function(e){return t=>{if(e.required&&(""===t||null==t))return[{type:"required",message:"string"==typeof e.required?e.required:Le("required")}];const n=[],r=(t,n)=>e.messages?.[t]??Le(t,n);if(void 0!==e.min){const o=Number(t);!Number.isNaN(o)&&o<e.min&&n.push({type:"min",message:r("min",e.min)})}if(void 0!==e.max){const o=Number(t);!Number.isNaN(o)&&o>e.max&&n.push({type:"max",message:r("max",e.max)})}return void 0!==e.minLength&&"string"==typeof t&&t.length<e.minLength&&n.push({type:"minLength",message:r("minLength",e.minLength)}),void 0!==e.maxLength&&"string"==typeof t&&t.length>e.maxLength&&n.push({type:"maxLength",message:r("maxLength",e.maxLength)}),e.pattern&&!e.pattern.value.test(t)&&n.push({type:"pattern",message:e.messages?.pattern??e.pattern.message??Le("pattern")}),n.length?n:void 0}}(e);return t?(e,r)=>{const o=n(e,r),i=e=>{const t=[...o??[]];return Array.isArray(e)?t.push(...e):e&&t.push(e),t.length?t:void 0},u=t(e,r);return b(u)?u.then(i):i(u)}:n}function lt({form:e,name:t,initialValue:n,shouldUnregister:u,validate:a,rules:c,validateDebounce:l,delayError:f,disabled:d,mode:m},h){const v=s(h),y=e||v;if(!y)throw new Error("no form provided");const p=st(t),g=function(e,t,n,o){const u=s(yt),a=n||u;if(!a)throw new Error("no form provided");const c=r(null),l=r(e);l.current=e;const f=r(o?.debounce??0);return f.current=o?.debounce??0,i(()=>{let e=null,n=null,r=!1;const o=()=>{r||(r=!0,I(a,t))},i=()=>{r&&(r=!1,H(a,t))},u=()=>{e=null;const r=l.current;if(!r)return void i();n?.abort(),n=new AbortController;const u=c.current={};let s;try{s=r(A(a,t),{form:a,path:t,signal:n.signal})}catch(e){throw i(),e}if(!b(s))return U(a,t,s),void i();o(),s.then(e=>{u===c.current&&U(a,t,e)}).catch(()=>{}).finally(()=>{u===c.current&&(i(),c.current=null)})};return a.validators.set(t.key,()=>{const t=f.current;if(t>0)return null!==e?clearTimeout(e):o(),void(e=setTimeout(u,t));u()}),()=>{a.validators.delete(t.key),null!==e&&(clearTimeout(e),e=null),i(),n?.abort()}},[a,t.key]),at(()=>a.validators.get(t.key)?.())}(ct(c,a),p,y,{debounce:l}),k=Ze(y,p),S=function(e,t){const[n,r]=o(e);return i(()=>{if(void 0===t)return;if(0===e.length)return void r(e);if(n.length>0)return void r(e);const o=setTimeout(()=>r(e),t);return()=>clearTimeout(o)},[e,t,n]),void 0===t?e:n}(k,f),E=S[0],w=E?.message,V=Ge(y,p),O=Je(y.emitter,"disabled",()=>y.disabled),_=m??y.mode;i(()=>{void 0!==n&&void 0===A(y,p)&&T(y,p,n)},[y,p,n]);const x=at(e=>{T(y,p,e),("onChange"===_||"all"===_||"onTouched"===_&&z(y,p)||k.length>0&&"onChange"===y.reValidateMode)&&g()});i(()=>(y.changeHandlers.set(p.key,x),()=>{y.changeHandlers.get(p.key)===x&&y.changeHandlers.delete(p.key)}),[y,p.key,x]);const C=at(()=>{G(y,p),("onBlur"===_||"onTouched"===_||"all"===_||k.length>0&&"onBlur"===y.reValidateMode)&&g()});return i(()=>()=>{!1!==u&&ie(y,p)},[p,y,u]),{form:y,value:V,error:w,errorObject:E,errors:S,onChange:x,onBlur:C,name:p.key,disabled:O||!!d}}function ft(e){return lt(e,yt)}let dt=0;function mt(){return"_"+ ++dt}function ht(e,t){const o=s(t),u=e.form||o;if(!u)throw new Error("no form provided");const c=st(e.name),l=r([]),f=n(()=>A(u,c)||[],[u,c]),d=n(e=>{T(u,c,e)},[u,c]),m=n(()=>{const e=f();for(;l.current.length<e.length;)l.current.push(mt());for(;l.current.length>e.length;)l.current.pop();return l.current.map((e,t)=>({id:e,index:t}))},[f]),[h,v]=a(m,void 0,m);i(()=>He(u.emitter,"change",c,"branch",v),[u.emitter,c]);return{fields:h,append:at(e=>{const t=f();l.current.push(mt()),d([...t,e])}),prepend:at(e=>{const t=f();l.current.unshift(mt()),d([e,...t])}),insert:at((e,t)=>{const n=f();l.current.splice(e,0,mt());const r=[...n.slice(0,e),t,...n.slice(e)];d(r)}),remove:at(e=>{const t=f();l.current.splice(e,1);const n=t.filter((t,n)=>n!==e);d(n)}),swap:at((e,t)=>{const n=f();[l.current[e],l.current[t]]=[l.current[t],l.current[e]];const r=[...n];[r[e],r[t]]=[r[t],r[e]],d(r)}),move:at((e,t)=>{const n=f(),[r]=l.current.splice(e,1);l.current.splice(t,0,r);const o=[...n],[i]=o.splice(e,1);o.splice(t,0,i),d(o)}),replace:at(e=>{l.current=e.map(()=>mt()),d([...e])}),update:at((e,t)=>{const n=f();if(e<0||e>=n.length)return;const r=[...n];r[e]=t,d(r)})}}function vt(e){return ht(e,yt)}const yt=c(null),pt=yt.Provider;function gt(){const e=s(yt);if(!e)throw new Error("no form provided");return e}function bt(){const e=c(null);return{context:e,FormProvider:function({form:t,children:n}){return l(e.Provider,{value:t},n)},useFormContext:function(){const t=s(e);if(!t)throw new Error("no form provided");return t},useField:function(t){return lt(t,e)},useFieldArray:function(t){return ht(t,e)}}}const kt=c(null),St=kt.Provider;function Et(){const e=s(kt);if(!e)throw new Error("no group provided");return e}function wt({form:t,context:n,initialValues:r,values:o,onSubmit:i,onValidSubmit:u,onInvalidSubmit:s,shouldFocusError:a,...c}){const l=Ue({initialValues:r,values:o}),f=t||l,d=Te(f,{onSubmit:i,onValidSubmit:u,onInvalidSubmit:s,shouldFocusError:a}),{Provider:m}=n??yt;return e.createElement(m,{value:f},e.createElement("form",{...c,noValidate:!0,onSubmit:d}))}function Vt(e){return e.replace(/["'[\],\s]+/g,"-").replace(/^-+|-+$/g,"")||"field"}function Ot(e,t,n){return{"aria-invalid":!!e||n["aria-invalid"],"aria-describedby":e?[n["aria-describedby"],Vt(t)].filter(Boolean).join(" "):n["aria-describedby"]}}function _t(e){return Vt(E(e).key)}const At=e.forwardRef(({validate:t,eventToValue:n,initialValue:r,name:o,asProps:i,renderError:u,as:s,valueToProps:a,form:c,shouldUnregister:l,rules:f,validateDebounce:m,disabled:h,delayError:v,mode:y,...p},g)=>{const b=e.useRef(null),[k,S]=e.useState(0),E=e.useCallback(e=>{b.current=e,function(e,t){"function"==typeof e?e(t):e&&(e.current=t)}(g,e)},[g]),{value:w,onChange:V,onBlur:O,error:_,form:A,name:x,disabled:T}=ft({name:o,form:c,initialValue:r,shouldUnregister:l,rules:f,validateDebounce:m,delayError:v,disabled:h,mode:y,validate:(...e)=>{const n=b.current;if(!n||"function"!=typeof n.checkValidity||(n.setCustomValidity(""),!1!==n.checkValidity()))return t?t(...e):void 0;S(e=>e+1)}}),C=s||"input";e.useEffect(()=>{const e=b.current;e&&"function"==typeof e.setCustomValidity&&("string"==typeof _?(e.setCustomValidity(_),e.reportValidity()):e.setCustomValidity(""))},[_]),e.useEffect(()=>{k>0&&b.current?.reportValidity()},[k]),e.useEffect(()=>d(A.emitter,"focusError",(e,t)=>{if(e!==x)return;const n=b.current;n&&"function"==typeof n.focus&&(n.focus(),t?.shouldSelect&&"function"==typeof n.select&&n.select())}),[A,x]);const L=n??(e=>e.target.value),j=Vt(x);return e.createElement(e.Fragment,null,e.createElement(C,{...p,name:x,onBlur:O,...i,...a?a(w):{value:w},...Ot(_,x,p),disabled:T,onChange:e=>V(L(e)),ref:E}),_&&u?e.createElement("span",{id:j,role:"alert"},u(_,j)):null)}),xt=e.forwardRef(({name:t,form:n,initialValue:r,shouldUnregister:o,validate:i,rules:u,validateDebounce:s,disabled:a,delayError:c,mode:l,...f},d)=>{const{value:m,onChange:h,onBlur:v,error:y,name:p,disabled:g}=ft({name:t,form:n,initialValue:r,shouldUnregister:o,validate:i,rules:u,validateDebounce:s,delayError:c,disabled:a,mode:l});return e.createElement("input",{...f,name:p,onBlur:v,type:"checkbox",checked:!!m,...Ot(y,p,f),disabled:g,onChange:e=>h(e.target.checked),ref:d})});function Tt(e,t){return e?Array.isArray(t)?t:[]:t??""}const Ct=e.forwardRef(({name:t,multiple:n,children:r,form:o,initialValue:i,shouldUnregister:u,validate:s,rules:a,validateDebounce:c,disabled:l,delayError:f,mode:d,...m},h)=>{const{value:v,onChange:y,onBlur:p,error:g,name:b,disabled:k}=ft({name:t,form:o,initialValue:i,shouldUnregister:u,validate:s,rules:a,validateDebounce:c,delayError:f,disabled:l,mode:d});return e.createElement("select",{...m,name:b,onBlur:p,multiple:n,value:Tt(n,v),...Ot(g,b,m),disabled:k,onChange:e=>y(n?Array.from(e.target.selectedOptions,e=>e.value):e.target.value),ref:h},r)});export{xt as Checkbox,kt as CheckboxGroupContext,St as CheckboxGroupProvider,At as Field,wt as Form,yt as FormContext,pt as FormProvider,Ct as Select,w as VALIDATION_OUTCOME,C as changeValue,L as changeValueByPath,F as clearErrors,V as createForm,bt as createFormContext,Ee as ensureValidate,_t as fieldErrorId,te as getDirtyFields,j as getError,D as getErrorByPath,P as getErrors,M as getFieldErrors,B as getFieldErrorsByPath,q as getFieldState,$ as getFirstError,ne as getTouchedFields,_ as getValue,A as getValueByPath,O as getValues,Te as handleSubmit,le as hasErrors,K as hasTouched,z as hasTouchedByPath,Oe as incrementSubmitCount,Y as isDirty,re as isTouched,oe as removeField,ie as removeFieldByPath,ae as reset,ce as resetField,Ae as setDisabled,R as setError,U as setErrorByPath,Ce as setFocus,se as setInitialValues,Ve as setIsSubmitting,J as setServerErrors,_e as setSubmitSuccessful,W as setTouched,G as setTouchedByPath,I as setValidatingByPath,x as setValue,T as setValueByPath,Re as subscribe,fe as trigger,H as unsetValidatingByPath,it as useCanSubmit,Et as useCheckboxGroupContext,tt as useDirtyFields,Ye as useError,Qe as useErrorByPath,ft as useField,vt as useFieldArray,Xe as useFieldErrors,Ze as useFieldErrorsByPath,Ue as useForm,gt as useFormContext,rt as useHasErrors,et as useIsDirty,ot as useIsSubmitting,ut as useSubmitCount,Ke as useTouched,ze as useTouchedByPath,nt as useTouchedFields,We as useValue,Ge as useValueByPath,Je as useWatch,we as validate};
2
2
  //# sourceMappingURL=index.mjs.map