@tanstack/form-core
Advanced tools
Comparing version 0.0.5 to 0.0.6
@@ -37,2 +37,3 @@ /** | ||
} | ||
class FormApi { | ||
@@ -316,3 +317,2 @@ // // This carries the context for nested fields | ||
exports.FormApi = FormApi; | ||
exports.getDefaultFormState = getDefaultFormState; | ||
//# sourceMappingURL=FormApi.js.map |
@@ -22,3 +22,2 @@ /** | ||
exports.FormApi = FormApi.FormApi; | ||
exports.getDefaultFormState = FormApi.getDefaultFormState; | ||
exports.FieldApi = FieldApi.FieldApi; | ||
@@ -25,0 +24,0 @@ exports.functionalUpdate = utils.functionalUpdate; |
@@ -102,2 +102,3 @@ /** | ||
} | ||
class FormApi { | ||
@@ -720,3 +721,3 @@ // // This carries the context for nested fields | ||
export { FieldApi, FormApi, functionalUpdate, getBy, getDefaultFormState, setBy }; | ||
export { FieldApi, FormApi, functionalUpdate, getBy, setBy }; | ||
//# sourceMappingURL=index.js.map |
@@ -11,3 +11,3 @@ { | ||
"name": "node_modules/.pnpm/@tanstack+store@0.0.1-beta.84/node_modules/@tanstack/store/build/esm/index.js", | ||
"uid": "3676-13" | ||
"uid": "dff6-13" | ||
}, | ||
@@ -18,15 +18,15 @@ { | ||
{ | ||
"uid": "3676-15", | ||
"uid": "dff6-15", | ||
"name": "utils.ts" | ||
}, | ||
{ | ||
"uid": "3676-17", | ||
"uid": "dff6-17", | ||
"name": "FormApi.ts" | ||
}, | ||
{ | ||
"uid": "3676-21", | ||
"uid": "dff6-21", | ||
"name": "FieldApi.ts" | ||
}, | ||
{ | ||
"uid": "3676-23", | ||
"uid": "dff6-23", | ||
"name": "index.ts" | ||
@@ -37,3 +37,3 @@ } | ||
{ | ||
"uid": "3676-19", | ||
"uid": "dff6-19", | ||
"name": "\u0000rollupPluginBabelHelpers.js" | ||
@@ -47,44 +47,44 @@ } | ||
"nodeParts": { | ||
"3676-13": { | ||
"dff6-13": { | ||
"renderedLength": 1288, | ||
"gzipLength": 497, | ||
"brotliLength": 0, | ||
"mainUid": "3676-12" | ||
"mainUid": "dff6-12" | ||
}, | ||
"3676-15": { | ||
"dff6-15": { | ||
"renderedLength": 1944, | ||
"gzipLength": 684, | ||
"brotliLength": 0, | ||
"mainUid": "3676-14" | ||
"mainUid": "dff6-14" | ||
}, | ||
"3676-17": { | ||
"renderedLength": 10266, | ||
"gzipLength": 2308, | ||
"dff6-17": { | ||
"renderedLength": 10267, | ||
"gzipLength": 2309, | ||
"brotliLength": 0, | ||
"mainUid": "3676-16" | ||
"mainUid": "dff6-16" | ||
}, | ||
"3676-19": { | ||
"dff6-19": { | ||
"renderedLength": 353, | ||
"gzipLength": 227, | ||
"brotliLength": 0, | ||
"mainUid": "3676-18" | ||
"mainUid": "dff6-18" | ||
}, | ||
"3676-21": { | ||
"dff6-21": { | ||
"renderedLength": 10602, | ||
"gzipLength": 2507, | ||
"brotliLength": 0, | ||
"mainUid": "3676-20" | ||
"mainUid": "dff6-20" | ||
}, | ||
"3676-23": { | ||
"dff6-23": { | ||
"renderedLength": 0, | ||
"gzipLength": 0, | ||
"brotliLength": 0, | ||
"mainUid": "3676-22" | ||
"mainUid": "dff6-22" | ||
} | ||
}, | ||
"nodeMetas": { | ||
"3676-12": { | ||
"dff6-12": { | ||
"id": "/node_modules/.pnpm/@tanstack+store@0.0.1-beta.84/node_modules/@tanstack/store/build/esm/index.js", | ||
"moduleParts": { | ||
"index.production.js": "3676-13" | ||
"index.production.js": "dff6-13" | ||
}, | ||
@@ -94,13 +94,13 @@ "imported": [], | ||
{ | ||
"uid": "3676-16" | ||
"uid": "dff6-16" | ||
}, | ||
{ | ||
"uid": "3676-20" | ||
"uid": "dff6-20" | ||
} | ||
] | ||
}, | ||
"3676-14": { | ||
"dff6-14": { | ||
"id": "/packages/form-core/src/utils.ts", | ||
"moduleParts": { | ||
"index.production.js": "3676-15" | ||
"index.production.js": "dff6-15" | ||
}, | ||
@@ -110,20 +110,20 @@ "imported": [], | ||
{ | ||
"uid": "3676-22" | ||
"uid": "dff6-22" | ||
}, | ||
{ | ||
"uid": "3676-16" | ||
"uid": "dff6-16" | ||
} | ||
] | ||
}, | ||
"3676-16": { | ||
"dff6-16": { | ||
"id": "/packages/form-core/src/FormApi.ts", | ||
"moduleParts": { | ||
"index.production.js": "3676-17" | ||
"index.production.js": "dff6-17" | ||
}, | ||
"imported": [ | ||
{ | ||
"uid": "3676-12" | ||
"uid": "dff6-12" | ||
}, | ||
{ | ||
"uid": "3676-14" | ||
"uid": "dff6-14" | ||
} | ||
@@ -133,10 +133,10 @@ ], | ||
{ | ||
"uid": "3676-22" | ||
"uid": "dff6-22" | ||
} | ||
] | ||
}, | ||
"3676-18": { | ||
"dff6-18": { | ||
"id": "\u0000rollupPluginBabelHelpers.js", | ||
"moduleParts": { | ||
"index.production.js": "3676-19" | ||
"index.production.js": "dff6-19" | ||
}, | ||
@@ -146,17 +146,17 @@ "imported": [], | ||
{ | ||
"uid": "3676-20" | ||
"uid": "dff6-20" | ||
} | ||
] | ||
}, | ||
"3676-20": { | ||
"dff6-20": { | ||
"id": "/packages/form-core/src/FieldApi.ts", | ||
"moduleParts": { | ||
"index.production.js": "3676-21" | ||
"index.production.js": "dff6-21" | ||
}, | ||
"imported": [ | ||
{ | ||
"uid": "3676-18" | ||
"uid": "dff6-18" | ||
}, | ||
{ | ||
"uid": "3676-12" | ||
"uid": "dff6-12" | ||
} | ||
@@ -166,20 +166,20 @@ ], | ||
{ | ||
"uid": "3676-22" | ||
"uid": "dff6-22" | ||
} | ||
] | ||
}, | ||
"3676-22": { | ||
"dff6-22": { | ||
"id": "/packages/form-core/src/index.ts", | ||
"moduleParts": { | ||
"index.production.js": "3676-23" | ||
"index.production.js": "dff6-23" | ||
}, | ||
"imported": [ | ||
{ | ||
"uid": "3676-16" | ||
"uid": "dff6-16" | ||
}, | ||
{ | ||
"uid": "3676-20" | ||
"uid": "dff6-20" | ||
}, | ||
{ | ||
"uid": "3676-14" | ||
"uid": "dff6-14" | ||
} | ||
@@ -186,0 +186,0 @@ ], |
import type { DeepKeys, DeepValue, RequiredByKey, Updater } from './utils'; | ||
import type { FormApi, ValidationError } from './FormApi'; | ||
import { Store } from '@tanstack/store'; | ||
export declare type ValidationCause = 'change' | 'blur' | 'submit'; | ||
export declare type FieldOptions<TData, TFormData> = { | ||
export type ValidationCause = 'change' | 'blur' | 'submit'; | ||
export interface FieldOptions<TData, TFormData> { | ||
name: unknown extends TFormData ? string : DeepKeys<TFormData>; | ||
defaultValue?: TData; | ||
form?: FormApi<TFormData>; | ||
validate?: (value: TData, fieldApi: FieldApi<TData, TFormData>) => ValidationError; | ||
@@ -16,4 +15,7 @@ validateAsync?: (value: TData, fieldApi: FieldApi<TData, TFormData>) => ValidationError | Promise<ValidationError>; | ||
defaultMeta?: Partial<FieldMeta>; | ||
} | ||
export type FieldApiOptions<TData, TFormData> = FieldOptions<TData, TFormData> & { | ||
form: FormApi<TFormData>; | ||
}; | ||
export declare type FieldMeta = { | ||
export type FieldMeta = { | ||
isTouched: boolean; | ||
@@ -24,11 +26,11 @@ touchedError?: ValidationError; | ||
}; | ||
export declare type UserChangeProps<TData> = { | ||
export type UserChangeProps<TData> = { | ||
onChange?: (updater: Updater<TData>) => void; | ||
onBlur?: (event: any) => void; | ||
}; | ||
export declare type UserInputProps = { | ||
export type UserInputProps = { | ||
onChange?: (event: any) => void; | ||
onBlur?: (event: any) => void; | ||
}; | ||
export declare type ChangeProps<TData> = { | ||
export type ChangeProps<TData> = { | ||
value: TData; | ||
@@ -38,3 +40,3 @@ onChange: (updater: Updater<TData>) => void; | ||
}; | ||
export declare type InputProps = { | ||
export type InputProps = { | ||
value: string; | ||
@@ -44,4 +46,3 @@ onChange: (event: any) => void; | ||
}; | ||
export declare type FieldApiOptions<TData, TFormData> = RequiredByKey<FieldOptions<TData, TFormData>, 'form'>; | ||
export declare type FieldState<TData> = { | ||
export type FieldState<TData> = { | ||
value: TData; | ||
@@ -48,0 +49,0 @@ meta: FieldMeta; |
@@ -1,6 +0,10 @@ | ||
import type { FormEvent } from 'react'; | ||
import { Store } from '@tanstack/store'; | ||
import type { DeepKeys, DeepValue, Updater } from './utils'; | ||
import type { FieldApi, FieldMeta, ValidationCause } from './FieldApi'; | ||
export declare type FormOptions<TData> = { | ||
export interface Register { | ||
} | ||
export type FormSubmitEvent = Register extends { | ||
FormSubmitEvent: infer E; | ||
} ? E : Event; | ||
export type FormOptions<TData> = { | ||
defaultValues?: TData; | ||
@@ -11,3 +15,2 @@ defaultState?: Partial<FormState<TData>>; | ||
validate?: (values: TData, formApi: FormApi<TData>) => Promise<any>; | ||
debugForm?: boolean; | ||
defaultValidatePristine?: boolean; | ||
@@ -18,6 +21,6 @@ defaultValidateOn?: ValidationCause; | ||
}; | ||
export declare type FieldInfo<TFormData> = { | ||
export type FieldInfo<TFormData> = { | ||
instances: Record<string, FieldApi<any, TFormData>>; | ||
} & ValidationMeta; | ||
export declare type ValidationMeta = { | ||
export type ValidationMeta = { | ||
validationCount?: number; | ||
@@ -29,4 +32,4 @@ validationAsyncCount?: number; | ||
}; | ||
export declare type ValidationError = undefined | false | null | string; | ||
export declare type FormState<TData> = { | ||
export type ValidationError = undefined | false | null | string; | ||
export type FormState<TData> = { | ||
values: TData; | ||
@@ -48,3 +51,2 @@ isFormValidating: boolean; | ||
}; | ||
export declare function getDefaultFormState<TData>(defaultState: Partial<FormState<TData>>): FormState<TData>; | ||
export declare class FormApi<TFormData> { | ||
@@ -62,5 +64,3 @@ options: FormOptions<TFormData>; | ||
validateForm: () => Promise<ValidationError>; | ||
handleSubmit: (e: FormEvent & { | ||
__handled?: boolean; | ||
}) => Promise<void>; | ||
handleSubmit: (e: FormSubmitEvent) => Promise<void>; | ||
getFieldValue: <TField extends DeepKeys<TFormData>>(field: TField) => DeepValue<TFormData, TField>; | ||
@@ -70,3 +70,3 @@ getFieldMeta: <TField extends DeepKeys<TFormData>>(field: TField) => FieldMeta; | ||
setFieldMeta: <TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<FieldMeta>) => void; | ||
setFieldValue: <TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<DeepValue<TFormData, TField>, DeepValue<TFormData, TField>>, opts?: { | ||
setFieldValue: <TField extends DeepKeys<TFormData>>(field: TField, updater: Updater<DeepValue<TFormData, TField>>, opts?: { | ||
touch?: boolean; | ||
@@ -73,0 +73,0 @@ }) => void; |
@@ -1,16 +0,16 @@ | ||
export declare type UpdaterFn<TInput, TOutput = TInput> = (input: TInput) => TOutput; | ||
export declare type Updater<TInput, TOutput = TInput> = TOutput | UpdaterFn<TInput, TOutput>; | ||
export type UpdaterFn<TInput, TOutput = TInput> = (input: TInput) => TOutput; | ||
export type Updater<TInput, TOutput = TInput> = TOutput | UpdaterFn<TInput, TOutput>; | ||
export declare function functionalUpdate<TInput, TOutput = TInput>(updater: Updater<TInput, TOutput>, input: TInput): TOutput; | ||
export declare function getBy(obj: any, path: any): any; | ||
export declare function setBy(obj: any, _path: any, updater: Updater<any>): any; | ||
export declare type RequiredByKey<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>; | ||
declare type ComputeRange<N extends number, Result extends Array<unknown> = []> = Result['length'] extends N ? Result : ComputeRange<N, [...Result, Result['length']]>; | ||
declare type Index40 = ComputeRange<40>[number]; | ||
declare type IsTuple<T> = T extends readonly any[] & { | ||
export type RequiredByKey<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>; | ||
type ComputeRange<N extends number, Result extends Array<unknown> = []> = Result['length'] extends N ? Result : ComputeRange<N, [...Result, Result['length']]>; | ||
type Index40 = ComputeRange<40>[number]; | ||
type IsTuple<T> = T extends readonly any[] & { | ||
length: infer Length; | ||
} ? Length extends Index40 ? T : never : never; | ||
declare type AllowedIndexes<Tuple extends ReadonlyArray<any>, Keys extends number = never> = Tuple extends readonly [] ? Keys : Tuple extends readonly [infer _, ...infer Tail] ? AllowedIndexes<Tail, Keys | Tail['length']> : Keys; | ||
export declare type DeepKeys<T> = unknown extends T ? keyof T : object extends T ? string : T extends readonly any[] & IsTuple<T> ? AllowedIndexes<T> | DeepKeysPrefix<T, AllowedIndexes<T>> : T extends any[] ? never & 'Dynamic length array indexing is not supported' : T extends Date ? never : T extends object ? (keyof T & string) | DeepKeysPrefix<T, keyof T> : never; | ||
declare type DeepKeysPrefix<T, TPrefix> = TPrefix extends keyof T & (number | string) ? `${TPrefix}.${DeepKeys<T[TPrefix]> & string}` : never; | ||
export declare type DeepValue<T, TProp> = T extends Record<string | number, any> ? TProp extends `${infer TBranch}.${infer TDeepProp}` ? DeepValue<T[TBranch], TDeepProp> : T[TProp & string] : never; | ||
type AllowedIndexes<Tuple extends ReadonlyArray<any>, Keys extends number = never> = Tuple extends readonly [] ? Keys : Tuple extends readonly [infer _, ...infer Tail] ? AllowedIndexes<Tail, Keys | Tail['length']> : Keys; | ||
export type DeepKeys<T> = unknown extends T ? keyof T : object extends T ? string : T extends readonly any[] & IsTuple<T> ? AllowedIndexes<T> | DeepKeysPrefix<T, AllowedIndexes<T>> : T extends any[] ? never & 'Dynamic length array indexing is not supported' : T extends Date ? never : T extends object ? (keyof T & string) | DeepKeysPrefix<T, keyof T> : never; | ||
type DeepKeysPrefix<T, TPrefix> = TPrefix extends keyof T & (number | string) ? `${TPrefix}.${DeepKeys<T[TPrefix]> & string}` : never; | ||
export type DeepValue<T, TProp> = T extends Record<string | number, any> ? TProp extends `${infer TBranch}.${infer TDeepProp}` ? DeepValue<T[TBranch], TDeepProp> : T[TProp & string] : never; | ||
export {}; |
@@ -155,2 +155,3 @@ /** | ||
} | ||
class FormApi { | ||
@@ -777,3 +778,2 @@ // // This carries the context for nested fields | ||
exports.getBy = getBy; | ||
exports.getDefaultFormState = getDefaultFormState; | ||
exports.setBy = setBy; | ||
@@ -780,0 +780,0 @@ |
@@ -21,3 +21,3 @@ /** | ||
* @license MIT | ||
*/class e{listeners=new Set;batching=!1;queue=[];constructor(t,e){this.state=t,this.options=e}subscribe=t=>{this.listeners.add(t);const e=this.options?.onSubscribe?.(t,this);return()=>{this.listeners.delete(t),e?.()}};setState=t=>{const e=this.state;this.state=this.options?.updateFn?this.options.updateFn(e)(t):t(e),this.state!==e&&(this.options?.onUpdate?.(this.state,e),this.queue.push((()=>{this.listeners.forEach((t=>t(this.state,e)))})),this.#t())};#t=()=>{this.batching||(this.queue.forEach((t=>t())),this.queue=[])};batch=t=>{this.batching=!0,t(),this.batching=!1,this.#t()}}function i(t,e){return"function"==typeof t?t(e):t}function s(t,e){if(!e)throw new Error("A path string is required to use getBy");return u(e).reduce(((t,e)=>{if(void 0!==t)return t[e]}),t)}function a(t,e,s){const a=u(e);return function t(e){if(!a.length)return i(s,e);const n=a.shift();if("string"==typeof n)return"object"==typeof e?{...e,[n]:t(e[n])}:{[n]:t()};if("number"==typeof n){if(Array.isArray(e)){const i=e.slice(0,n);return[...i.length?i:new Array(n),t(e[n]),...e.slice(n+1)]}return[...new Array(n),t()]}throw new Error("Uh oh!")}(t)}const n=/^(\d*)$/gm,o=/\.(\d*)\./gm,l=/^(\d*)\./gm,h=/\.(\d*$)/gm,r=/\.{2,}/gm;function u(t){return t.replace("[",".").replace("]","").replace(n,"__int__$1").replace(o,".__int__$1.").replace(l,"__int__$1.").replace(h,".__int__$1").replace(r,".").split(".").map((t=>0===t.indexOf("__int__")?parseInt(t.substring("__int__".length),10):t))}function d(t){return{values:{},fieldMeta:{},canSubmit:!0,isFieldsValid:!1,isFieldsValidating:!1,isFormValid:!1,isFormValidating:!1,isSubmitted:!1,isSubmitting:!1,isTouched:!1,isValid:!1,isValidating:!1,submissionAttempts:0,formValidationCount:0,...t}}var c=0;function f(t){return"__private_"+c+++"_"+t}function v(t,e){if(!Object.prototype.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}let m=0;var p=f("updateStore"),g=f("leaseValidateAsync");class V{constructor(t){var i;this.options={},this.mount=()=>{const t=this.getInfo();t.instances[this.uid]=this;const e=this.form.store.subscribe((()=>{v(this,p)[p]()}));return()=>{e(),delete t.instances[this.uid],Object.keys(t.instances).length||delete this.form.fieldInfo[this.name]}},Object.defineProperty(this,p,{writable:!0,value:()=>{this.store.batch((()=>{const t=this.getValue(),e=this.getMeta();t!==this.state.value&&this.store.setState((e=>({...e,value:t}))),e!==this.state.meta&&this.store.setState((t=>({...t,meta:e})))}))}}),this.update=t=>{var e,i,s,a;this.options={validatePristine:null!=(e=this.form.options.defaultValidatePristine)&&e,validateOn:null!=(i=this.form.options.defaultValidateOn)?i:"change",validateAsyncOn:null!=(s=this.form.options.defaultValidateAsyncOn)?s:"blur",validateAsyncDebounceMs:null!=(a=this.form.options.defaultValidateAsyncDebounceMs)?a:0,...t},void 0===this.state.value&&void 0!==this.options.defaultValue&&this.setValue(this.options.defaultValue),void 0===this.getMeta()&&this.setMeta(this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,e)=>this.form.setFieldValue(this.name,t,e),this.getMeta=()=>this.form.getFieldMeta(this.name),this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=t=>this.form.pushFieldValue(this.name,t),this.insertValue=(t,e)=>this.form.insertFieldValue(this.name,t,e),this.removeValue=t=>this.form.spliceFieldValue(this.name,t),this.swapValues=(t,e)=>this.form.swapFieldValues(this.name,t,e),this.getSubField=t=>new V({name:this.name+"."+t,form:this.form}),this.validateSync=async(t=this.state.value)=>{const{validate:e}=this.options;if(!e)return;const i=(this.getInfo().validationCount||0)+1;this.getInfo().validationCount=i;const s=y(e(t,this));this.state.meta.error!==s&&this.setMeta((t=>({...t,error:s}))),this.state.meta.error&&this.cancelValidateAsync()},Object.defineProperty(this,g,{writable:!0,value:()=>{const t=(this.getInfo().validationAsyncCount||0)+1;return this.getInfo().validationAsyncCount=t,t}}),this.cancelValidateAsync=()=>{v(this,g)[g](),this.setMeta((t=>({...t,isValidating:!1})))},this.validateAsync=async(t=this.state.value)=>{const{validateAsync:e,validateAsyncDebounceMs:i}=this.options;if(!e)return;!0!==this.state.meta.isValidating&&this.setMeta((t=>({...t,isValidating:!0})));const s=v(this,g)[g](),a=()=>s===this.getInfo().validationAsyncCount;if(this.getInfo().validationPromise||(this.getInfo().validationPromise=new Promise(((t,e)=>{this.getInfo().validationResolve=t,this.getInfo().validationReject=e}))),i>0&&await new Promise((t=>setTimeout(t,i))),a())try{const i=await e(t,this);if(a()){var n,o;const t=y(i);this.setMeta((e=>({...e,isValidating:!1,error:t}))),null==(n=(o=this.getInfo()).validationResolve)||n.call(o,t)}}catch(t){var l,h;if(a())throw null==(l=(h=this.getInfo()).validationReject)||l.call(h,t),t}finally{a()&&(this.setMeta((t=>({...t,isValidating:!1}))),delete this.getInfo().validationPromise)}return this.getInfo().validationPromise},this.shouldValidate=(t,e)=>{const{validateOn:i,validateAsyncOn:s}=this.options,a=function(t){return t?b[t]:3}(e);return Object.keys(b).some((e=>t?s:i===e&&a>=b[e]))},this.validate=async(t,e)=>{if(this.options.validatePristine||this.state.meta.isTouched)return this.shouldValidate(!1,t)&&this.validateSync(e),this.state.meta.error?this.state.meta.error:this.shouldValidate(!0,t)?this.validateAsync(e):void 0},this.getChangeProps=(t={})=>({...t,value:this.state.value,onChange:e=>{this.setValue(e),null==t.onChange||t.onChange(e)},onBlur:e=>{this.setMeta((t=>({...t,isTouched:!0}))),this.validate("blur"),null==t.onBlur||t.onBlur(e)}}),this.getInputProps=(t={})=>({...t,value:String(this.state.value),onChange:e=>{this.setValue(e.target.value),null==t.onChange||t.onChange(e.target.value)},onBlur:this.getChangeProps(t).onBlur}),this.form=t.form,this.uid=m++;let s="";this.form.fieldName&&(s=this.form.fieldName+"."),this.name=s+t.name,this.store=new e({value:this.getValue(),meta:null!=(i=this.getMeta())?i:{isValidating:!1,isTouched:!1,...this.options.defaultMeta}},{onUpdate:t=>{t.meta.touchedError=t.meta.isTouched?t.meta.error:void 0;const e=this.state;this.state=t,t.value!==e.value&&this.validate("change",t.value)}}),this.state=this.store.state,this.update(t)}}const b={change:0,blur:1,submit:2};function y(t){if(t)return"string"!=typeof t?"Invalid Form Values":t}t.FieldApi=V,t.FormApi=class{constructor(t){var n,o;this.options={},this.fieldInfo={},this.validationMeta={},this.update=t=>{this.store.batch((()=>{t.defaultState&&t.defaultState!==this.options.defaultState&&this.store.setState((e=>({...e,...t.defaultState}))),t.defaultValues!==this.options.defaultValues&&this.store.setState((e=>({...e,values:t.defaultValues})))})),this.options=t},this.reset=()=>this.store.setState((()=>d(this.options.defaultValues))),this.validateAllFields=async()=>{const t=[];return this.store.batch((()=>{Object.values(this.fieldInfo).forEach((e=>{Object.values(e.instances).forEach((e=>{e.state.meta.isTouched||(e.setMeta((t=>({...t,isTouched:!0}))),e.options.validate&&t.push(e.validate()))}))}))})),Promise.all(t)},this.validateForm=async()=>{const{validate:t}=this.options;if(!t)return;this.store.setState((t=>({...t,isValidating:!0,formValidationCount:t.formValidationCount+1})));const e=this.state.formValidationCount,i=()=>e===this.state.formValidationCount;this.validationMeta.validationPromise||(this.validationMeta.validationPromise=new Promise(((t,e)=>{this.validationMeta.validationResolve=t,this.validationMeta.validationReject=e})));return(async()=>{try{const a=await t(this.state.values,this);var e,s;if(i())this.store.setState((t=>({...t,isValidating:!1,error:a?"string"==typeof a?a:"Invalid Form Values":null}))),null==(e=(s=this.validationMeta).validationResolve)||e.call(s,a)}catch(t){var a,n;if(i())null==(a=(n=this.validationMeta).validationReject)||a.call(n,t)}finally{delete this.validationMeta.validationPromise}})(),this.validationMeta.validationPromise},this.handleSubmit=async t=>{if(t.preventDefault(),t.stopPropagation(),this.store.setState((t=>({...t,isSubmitted:!1,submissionAttempts:t.submissionAttempts+1}))),!this.state.canSubmit)return;this.store.setState((t=>({...t,isSubmitting:!0})));const e=()=>{this.store.setState((t=>({...t,isSubmitting:!1})))};var i,s,a,n;if(await this.validateAllFields(),!this.state.isFieldsValid)return e(),void(null==(i=(s=this.options).onInvalidSubmit)||i.call(s,this.state.values,this));if(await this.validateForm(),!this.state.isValid)return e(),void(null==(a=(n=this.options).onInvalidSubmit)||a.call(n,this.state.values,this));try{var o,l;await(null==(o=(l=this.options).onSubmit)?void 0:o.call(l,this.state.values,this)),this.store.batch((()=>{this.store.setState((t=>({...t,isSubmitted:!0}))),e()}))}catch(t){throw e(),t}},this.getFieldValue=t=>s(this.state.values,t),this.getFieldMeta=t=>this.state.fieldMeta[t],this.getFieldInfo=t=>{var e;return(e=this.fieldInfo)[t]||(e[t]={instances:{}})},this.setFieldMeta=(t,e)=>{this.store.setState((s=>({...s,fieldMeta:{...s.fieldMeta,[t]:i(e,s.fieldMeta[t])}})))},this.setFieldValue=(t,e,i)=>{var s;const n=null==(s=null==i?void 0:i.touch)||s;this.store.batch((()=>{this.store.setState((i=>({...i,values:a(i.values,t,e)}))),n&&this.setFieldMeta(t,(t=>({...t,isTouched:!0})))}))},this.pushFieldValue=(t,e,i)=>this.setFieldValue(t,(t=>[...Array.isArray(t)?t:[],e]),i),this.insertFieldValue=(t,e,i,s)=>{this.setFieldValue(t,(t=>t.map(((t,s)=>s===e?i:t))),s)},this.spliceFieldValue=(t,e,i)=>{this.setFieldValue(t,(t=>t.filter(((t,i)=>i!==e))),i)},this.swapFieldValues=(t,e,i)=>{this.setFieldValue(t,(t=>{const s=t[e],n=t[i];return a(a(t,[e],n),[i],s)}))},this.store=new e(d({...null==t?void 0:t.defaultState,values:null!=(n=null==t?void 0:t.defaultValues)?n:null==t||null==(o=t.defaultState)?void 0:o.values,isFormValid:!(null!=t&&t.validate)}),{onUpdate:t=>{const e=Object.values(t.fieldMeta),i=e.some((t=>null==t?void 0:t.isValidating)),s=!e.some((t=>null==t?void 0:t.error)),a=e.some((t=>null==t?void 0:t.isTouched)),n=i||t.isFormValidating,o=!t.formError,l=s&&o,h=0===t.submissionAttempts&&!a||!n&&!t.isSubmitting&&l;t={...t,isFieldsValidating:i,isFieldsValid:s,isFormValid:o,isValid:l,canSubmit:h,isTouched:a},this.store.state=t,this.state=t}}),this.state=this.store.state,this.update(t||{})}},t.functionalUpdate=i,t.getBy=s,t.getDefaultFormState=d,t.setBy=a,Object.defineProperty(t,"__esModule",{value:!0})})); | ||
*/class e{listeners=new Set;batching=!1;queue=[];constructor(t,e){this.state=t,this.options=e}subscribe=t=>{this.listeners.add(t);const e=this.options?.onSubscribe?.(t,this);return()=>{this.listeners.delete(t),e?.()}};setState=t=>{const e=this.state;this.state=this.options?.updateFn?this.options.updateFn(e)(t):t(e),this.state!==e&&(this.options?.onUpdate?.(this.state,e),this.queue.push((()=>{this.listeners.forEach((t=>t(this.state,e)))})),this.#t())};#t=()=>{this.batching||(this.queue.forEach((t=>t())),this.queue=[])};batch=t=>{this.batching=!0,t(),this.batching=!1,this.#t()}}function i(t,e){return"function"==typeof t?t(e):t}function s(t,e){if(!e)throw new Error("A path string is required to use getBy");return u(e).reduce(((t,e)=>{if(void 0!==t)return t[e]}),t)}function a(t,e,s){const a=u(e);return function t(e){if(!a.length)return i(s,e);const n=a.shift();if("string"==typeof n)return"object"==typeof e?{...e,[n]:t(e[n])}:{[n]:t()};if("number"==typeof n){if(Array.isArray(e)){const i=e.slice(0,n);return[...i.length?i:new Array(n),t(e[n]),...e.slice(n+1)]}return[...new Array(n),t()]}throw new Error("Uh oh!")}(t)}const n=/^(\d*)$/gm,o=/\.(\d*)\./gm,l=/^(\d*)\./gm,h=/\.(\d*$)/gm,r=/\.{2,}/gm;function u(t){return t.replace("[",".").replace("]","").replace(n,"__int__$1").replace(o,".__int__$1.").replace(l,"__int__$1.").replace(h,".__int__$1").replace(r,".").split(".").map((t=>0===t.indexOf("__int__")?parseInt(t.substring("__int__".length),10):t))}function d(t){return{values:{},fieldMeta:{},canSubmit:!0,isFieldsValid:!1,isFieldsValidating:!1,isFormValid:!1,isFormValidating:!1,isSubmitted:!1,isSubmitting:!1,isTouched:!1,isValid:!1,isValidating:!1,submissionAttempts:0,formValidationCount:0,...t}}var c=0;function f(t){return"__private_"+c+++"_"+t}function v(t,e){if(!Object.prototype.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}let m=0;var p=f("updateStore"),g=f("leaseValidateAsync");class V{constructor(t){var i;this.options={},this.mount=()=>{const t=this.getInfo();t.instances[this.uid]=this;const e=this.form.store.subscribe((()=>{v(this,p)[p]()}));return()=>{e(),delete t.instances[this.uid],Object.keys(t.instances).length||delete this.form.fieldInfo[this.name]}},Object.defineProperty(this,p,{writable:!0,value:()=>{this.store.batch((()=>{const t=this.getValue(),e=this.getMeta();t!==this.state.value&&this.store.setState((e=>({...e,value:t}))),e!==this.state.meta&&this.store.setState((t=>({...t,meta:e})))}))}}),this.update=t=>{var e,i,s,a;this.options={validatePristine:null!=(e=this.form.options.defaultValidatePristine)&&e,validateOn:null!=(i=this.form.options.defaultValidateOn)?i:"change",validateAsyncOn:null!=(s=this.form.options.defaultValidateAsyncOn)?s:"blur",validateAsyncDebounceMs:null!=(a=this.form.options.defaultValidateAsyncDebounceMs)?a:0,...t},void 0===this.state.value&&void 0!==this.options.defaultValue&&this.setValue(this.options.defaultValue),void 0===this.getMeta()&&this.setMeta(this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(t,e)=>this.form.setFieldValue(this.name,t,e),this.getMeta=()=>this.form.getFieldMeta(this.name),this.setMeta=t=>this.form.setFieldMeta(this.name,t),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=t=>this.form.pushFieldValue(this.name,t),this.insertValue=(t,e)=>this.form.insertFieldValue(this.name,t,e),this.removeValue=t=>this.form.spliceFieldValue(this.name,t),this.swapValues=(t,e)=>this.form.swapFieldValues(this.name,t,e),this.getSubField=t=>new V({name:this.name+"."+t,form:this.form}),this.validateSync=async(t=this.state.value)=>{const{validate:e}=this.options;if(!e)return;const i=(this.getInfo().validationCount||0)+1;this.getInfo().validationCount=i;const s=y(e(t,this));this.state.meta.error!==s&&this.setMeta((t=>({...t,error:s}))),this.state.meta.error&&this.cancelValidateAsync()},Object.defineProperty(this,g,{writable:!0,value:()=>{const t=(this.getInfo().validationAsyncCount||0)+1;return this.getInfo().validationAsyncCount=t,t}}),this.cancelValidateAsync=()=>{v(this,g)[g](),this.setMeta((t=>({...t,isValidating:!1})))},this.validateAsync=async(t=this.state.value)=>{const{validateAsync:e,validateAsyncDebounceMs:i}=this.options;if(!e)return;!0!==this.state.meta.isValidating&&this.setMeta((t=>({...t,isValidating:!0})));const s=v(this,g)[g](),a=()=>s===this.getInfo().validationAsyncCount;if(this.getInfo().validationPromise||(this.getInfo().validationPromise=new Promise(((t,e)=>{this.getInfo().validationResolve=t,this.getInfo().validationReject=e}))),i>0&&await new Promise((t=>setTimeout(t,i))),a())try{const i=await e(t,this);if(a()){var n,o;const t=y(i);this.setMeta((e=>({...e,isValidating:!1,error:t}))),null==(n=(o=this.getInfo()).validationResolve)||n.call(o,t)}}catch(t){var l,h;if(a())throw null==(l=(h=this.getInfo()).validationReject)||l.call(h,t),t}finally{a()&&(this.setMeta((t=>({...t,isValidating:!1}))),delete this.getInfo().validationPromise)}return this.getInfo().validationPromise},this.shouldValidate=(t,e)=>{const{validateOn:i,validateAsyncOn:s}=this.options,a=function(t){return t?b[t]:3}(e);return Object.keys(b).some((e=>t?s:i===e&&a>=b[e]))},this.validate=async(t,e)=>{if(this.options.validatePristine||this.state.meta.isTouched)return this.shouldValidate(!1,t)&&this.validateSync(e),this.state.meta.error?this.state.meta.error:this.shouldValidate(!0,t)?this.validateAsync(e):void 0},this.getChangeProps=(t={})=>({...t,value:this.state.value,onChange:e=>{this.setValue(e),null==t.onChange||t.onChange(e)},onBlur:e=>{this.setMeta((t=>({...t,isTouched:!0}))),this.validate("blur"),null==t.onBlur||t.onBlur(e)}}),this.getInputProps=(t={})=>({...t,value:String(this.state.value),onChange:e=>{this.setValue(e.target.value),null==t.onChange||t.onChange(e.target.value)},onBlur:this.getChangeProps(t).onBlur}),this.form=t.form,this.uid=m++;let s="";this.form.fieldName&&(s=this.form.fieldName+"."),this.name=s+t.name,this.store=new e({value:this.getValue(),meta:null!=(i=this.getMeta())?i:{isValidating:!1,isTouched:!1,...this.options.defaultMeta}},{onUpdate:t=>{t.meta.touchedError=t.meta.isTouched?t.meta.error:void 0;const e=this.state;this.state=t,t.value!==e.value&&this.validate("change",t.value)}}),this.state=this.store.state,this.update(t)}}const b={change:0,blur:1,submit:2};function y(t){if(t)return"string"!=typeof t?"Invalid Form Values":t}t.FieldApi=V,t.FormApi=class{constructor(t){var n,o;this.options={},this.fieldInfo={},this.validationMeta={},this.update=t=>{this.store.batch((()=>{t.defaultState&&t.defaultState!==this.options.defaultState&&this.store.setState((e=>({...e,...t.defaultState}))),t.defaultValues!==this.options.defaultValues&&this.store.setState((e=>({...e,values:t.defaultValues})))})),this.options=t},this.reset=()=>this.store.setState((()=>d(this.options.defaultValues))),this.validateAllFields=async()=>{const t=[];return this.store.batch((()=>{Object.values(this.fieldInfo).forEach((e=>{Object.values(e.instances).forEach((e=>{e.state.meta.isTouched||(e.setMeta((t=>({...t,isTouched:!0}))),e.options.validate&&t.push(e.validate()))}))}))})),Promise.all(t)},this.validateForm=async()=>{const{validate:t}=this.options;if(!t)return;this.store.setState((t=>({...t,isValidating:!0,formValidationCount:t.formValidationCount+1})));const e=this.state.formValidationCount,i=()=>e===this.state.formValidationCount;this.validationMeta.validationPromise||(this.validationMeta.validationPromise=new Promise(((t,e)=>{this.validationMeta.validationResolve=t,this.validationMeta.validationReject=e})));return(async()=>{try{const a=await t(this.state.values,this);var e,s;if(i())this.store.setState((t=>({...t,isValidating:!1,error:a?"string"==typeof a?a:"Invalid Form Values":null}))),null==(e=(s=this.validationMeta).validationResolve)||e.call(s,a)}catch(t){var a,n;if(i())null==(a=(n=this.validationMeta).validationReject)||a.call(n,t)}finally{delete this.validationMeta.validationPromise}})(),this.validationMeta.validationPromise},this.handleSubmit=async t=>{if(t.preventDefault(),t.stopPropagation(),this.store.setState((t=>({...t,isSubmitted:!1,submissionAttempts:t.submissionAttempts+1}))),!this.state.canSubmit)return;this.store.setState((t=>({...t,isSubmitting:!0})));const e=()=>{this.store.setState((t=>({...t,isSubmitting:!1})))};var i,s,a,n;if(await this.validateAllFields(),!this.state.isFieldsValid)return e(),void(null==(i=(s=this.options).onInvalidSubmit)||i.call(s,this.state.values,this));if(await this.validateForm(),!this.state.isValid)return e(),void(null==(a=(n=this.options).onInvalidSubmit)||a.call(n,this.state.values,this));try{var o,l;await(null==(o=(l=this.options).onSubmit)?void 0:o.call(l,this.state.values,this)),this.store.batch((()=>{this.store.setState((t=>({...t,isSubmitted:!0}))),e()}))}catch(t){throw e(),t}},this.getFieldValue=t=>s(this.state.values,t),this.getFieldMeta=t=>this.state.fieldMeta[t],this.getFieldInfo=t=>{var e;return(e=this.fieldInfo)[t]||(e[t]={instances:{}})},this.setFieldMeta=(t,e)=>{this.store.setState((s=>({...s,fieldMeta:{...s.fieldMeta,[t]:i(e,s.fieldMeta[t])}})))},this.setFieldValue=(t,e,i)=>{var s;const n=null==(s=null==i?void 0:i.touch)||s;this.store.batch((()=>{this.store.setState((i=>({...i,values:a(i.values,t,e)}))),n&&this.setFieldMeta(t,(t=>({...t,isTouched:!0})))}))},this.pushFieldValue=(t,e,i)=>this.setFieldValue(t,(t=>[...Array.isArray(t)?t:[],e]),i),this.insertFieldValue=(t,e,i,s)=>{this.setFieldValue(t,(t=>t.map(((t,s)=>s===e?i:t))),s)},this.spliceFieldValue=(t,e,i)=>{this.setFieldValue(t,(t=>t.filter(((t,i)=>i!==e))),i)},this.swapFieldValues=(t,e,i)=>{this.setFieldValue(t,(t=>{const s=t[e],n=t[i];return a(a(t,[e],n),[i],s)}))},this.store=new e(d({...null==t?void 0:t.defaultState,values:null!=(n=null==t?void 0:t.defaultValues)?n:null==t||null==(o=t.defaultState)?void 0:o.values,isFormValid:!(null!=t&&t.validate)}),{onUpdate:t=>{const e=Object.values(t.fieldMeta),i=e.some((t=>null==t?void 0:t.isValidating)),s=!e.some((t=>null==t?void 0:t.error)),a=e.some((t=>null==t?void 0:t.isTouched)),n=i||t.isFormValidating,o=!t.formError,l=s&&o,h=0===t.submissionAttempts&&!a||!n&&!t.isSubmitting&&l;t={...t,isFieldsValidating:i,isFieldsValid:s,isFormValid:o,isValid:l,canSubmit:h,isTouched:a},this.store.state=t,this.state=t}}),this.state=this.store.state,this.update(t||{})}},t.functionalUpdate=i,t.getBy=s,t.setBy=a,Object.defineProperty(t,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=index.production.js.map |
{ | ||
"name": "@tanstack/form-core", | ||
"version": "0.0.5", | ||
"version": "0.0.6", | ||
"description": "Powerful, type-safe, framework agnostic forms.", | ||
@@ -5,0 +5,0 @@ "author": "tannerlinsley", |
@@ -8,6 +8,5 @@ // | ||
export type FieldOptions<TData, TFormData> = { | ||
export interface FieldOptions<TData, TFormData> { | ||
name: unknown extends TFormData ? string : DeepKeys<TFormData> | ||
defaultValue?: TData | ||
form?: FormApi<TFormData> | ||
validate?: ( | ||
@@ -28,2 +27,9 @@ value: TData, | ||
export type FieldApiOptions<TData, TFormData> = FieldOptions< | ||
TData, | ||
TFormData | ||
> & { | ||
form: FormApi<TFormData> | ||
} | ||
export type FieldMeta = { | ||
@@ -58,7 +64,2 @@ isTouched: boolean | ||
export type FieldApiOptions<TData, TFormData> = RequiredByKey< | ||
FieldOptions<TData, TFormData>, | ||
'form' | ||
> | ||
let uid = 0 | ||
@@ -65,0 +66,0 @@ |
@@ -1,2 +0,1 @@ | ||
import type { FormEvent } from 'react' | ||
import { Store } from '@tanstack/store' | ||
@@ -8,2 +7,12 @@ // | ||
export interface Register { | ||
// FormSubmitEvent | ||
} | ||
export type FormSubmitEvent = Register extends { | ||
FormSubmitEvent: infer E | ||
} | ||
? E | ||
: Event | ||
export type FormOptions<TData> = { | ||
@@ -15,3 +24,2 @@ defaultValues?: TData | ||
validate?: (values: TData, formApi: FormApi<TData>) => Promise<any> | ||
debugForm?: boolean | ||
defaultValidatePristine?: boolean | ||
@@ -58,3 +66,3 @@ defaultValidateOn?: ValidationCause | ||
export function getDefaultFormState<TData>( | ||
function getDefaultFormState<TData>( | ||
defaultState: Partial<FormState<TData>>, | ||
@@ -253,3 +261,3 @@ ): FormState<TData> { | ||
handleSubmit = async (e: FormEvent & { __handled?: boolean }) => { | ||
handleSubmit = async (e: FormSubmitEvent) => { | ||
e.preventDefault() | ||
@@ -256,0 +264,0 @@ e.stopPropagation() |
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
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
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
3152
430232