@rilaykit/forms 0.1.1-alpha.1 → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AND YOU CREATE
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { FormConfiguration, ValidationError, ValidationResult, FormFieldRow, ril, InputType, LayoutType, ValidationConfig, ConditionalConfig, FormFieldConfig } from '@rilaykit/core';
2
+ import { FormConfiguration, ValidationError, ValidationResult, FormFieldRow, ril, ValidationConfig, ConditionalConfig, FormFieldConfig } from '@rilaykit/core';
3
3
  export * from '@rilaykit/core';
4
4
  export { createZodValidator, ril } from '@rilaykit/core';
5
5
  import * as React$1 from 'react';
@@ -90,12 +90,12 @@ declare class form {
90
90
  /**
91
91
  * Add a single field (takes full width)
92
92
  * @param fieldId - Unique field identifier
93
- * @param componentSubType - Component subtype (e.g., 'text', 'email')
93
+ * @param componentType - Component type (e.g., 'text', 'email')
94
94
  * @param props - Props to pass to the component
95
95
  * @param options - Additional options
96
96
  * @returns form instance for chaining
97
97
  */
98
- addField(fieldId: string, componentSubType: InputType | LayoutType, props?: Record<string, any>, options?: {
98
+ addField(fieldId: string, componentType: string, props?: Record<string, any>, options?: {
99
99
  validation?: ValidationConfig;
100
100
  conditional?: ConditionalConfig;
101
101
  }): this;
@@ -107,7 +107,7 @@ declare class form {
107
107
  */
108
108
  addRowFields(fieldConfigs: Array<{
109
109
  fieldId: string;
110
- componentSubType: InputType | LayoutType;
110
+ componentType: string;
111
111
  props?: Record<string, any>;
112
112
  validation?: ValidationConfig;
113
113
  conditional?: ConditionalConfig;
@@ -122,7 +122,7 @@ declare class form {
122
122
  */
123
123
  addFields(fieldConfigs: Array<{
124
124
  fieldId: string;
125
- componentSubType: InputType | LayoutType;
125
+ componentType: string;
126
126
  props?: Record<string, any>;
127
127
  validation?: ValidationConfig;
128
128
  conditional?: ConditionalConfig;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { FormConfiguration, ValidationError, ValidationResult, FormFieldRow, ril, InputType, LayoutType, ValidationConfig, ConditionalConfig, FormFieldConfig } from '@rilaykit/core';
2
+ import { FormConfiguration, ValidationError, ValidationResult, FormFieldRow, ril, ValidationConfig, ConditionalConfig, FormFieldConfig } from '@rilaykit/core';
3
3
  export * from '@rilaykit/core';
4
4
  export { createZodValidator, ril } from '@rilaykit/core';
5
5
  import * as React$1 from 'react';
@@ -90,12 +90,12 @@ declare class form {
90
90
  /**
91
91
  * Add a single field (takes full width)
92
92
  * @param fieldId - Unique field identifier
93
- * @param componentSubType - Component subtype (e.g., 'text', 'email')
93
+ * @param componentType - Component type (e.g., 'text', 'email')
94
94
  * @param props - Props to pass to the component
95
95
  * @param options - Additional options
96
96
  * @returns form instance for chaining
97
97
  */
98
- addField(fieldId: string, componentSubType: InputType | LayoutType, props?: Record<string, any>, options?: {
98
+ addField(fieldId: string, componentType: string, props?: Record<string, any>, options?: {
99
99
  validation?: ValidationConfig;
100
100
  conditional?: ConditionalConfig;
101
101
  }): this;
@@ -107,7 +107,7 @@ declare class form {
107
107
  */
108
108
  addRowFields(fieldConfigs: Array<{
109
109
  fieldId: string;
110
- componentSubType: InputType | LayoutType;
110
+ componentType: string;
111
111
  props?: Record<string, any>;
112
112
  validation?: ValidationConfig;
113
113
  conditional?: ConditionalConfig;
@@ -122,7 +122,7 @@ declare class form {
122
122
  */
123
123
  addFields(fieldConfigs: Array<{
124
124
  fieldId: string;
125
- componentSubType: InputType | LayoutType;
125
+ componentType: string;
126
126
  props?: Record<string, any>;
127
127
  validation?: ValidationConfig;
128
128
  conditional?: ConditionalConfig;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var ir=require('react'),jsxRuntime=require('react/jsx-runtime'),er=require('clsx'),core=require('@rilaykit/core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ir__default=/*#__PURE__*/_interopDefault(ir);var er__default=/*#__PURE__*/_interopDefault(er);function j(i,r){switch(r.type){case "SET_VALUE":{let o={...i.values,[r.fieldId]:r.value};return {...i,values:o,isDirty:true}}case "SET_ERROR":return {...i,errors:{...i.errors,[r.fieldId]:r.errors},isValid:false};case "SET_WARNING":return {...i,warnings:{...i.warnings,[r.fieldId]:r.warnings}};case "CLEAR_ERROR":{let o={...i.errors};return delete o[r.fieldId],{...i,errors:o}}case "CLEAR_WARNING":{let o={...i.warnings};return delete o[r.fieldId],{...i,warnings:o}}case "MARK_TOUCHED":return {...i,touched:new Set([...i.touched,r.fieldId])};case "SET_VALIDATING":{let o=new Set(i.isValidating);return r.isValidating?o.add(r.fieldId):o.delete(r.fieldId),{...i,isValidating:o}}case "SET_SUBMITTING":return {...i,isSubmitting:r.isSubmitting};case "RESET":return {values:r.values||{},errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false};case "UPDATE_VALIDATION_STATE":{let o=Object.keys(i.errors).some(s=>i.errors[s].length>0);return {...i,isValid:!o}}default:return i}}var U=ir.createContext(null);function _({children:i,formConfig:r,defaultValues:o={},onSubmit:s,onFieldChange:e,className:a}){let m={values:o,errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false},[d,l]=ir.useReducer(j,m),t=ir.useRef(new Map),h=ir.useRef(s),u=ir.useRef(e);h.current=s,u.current=e;let y=ir.useCallback((n,f)=>{l({type:"SET_ERROR",fieldId:n,errors:f}),l({type:"UPDATE_VALIDATION_STATE"});},[]),E=ir.useCallback((n,f)=>{l({type:"SET_WARNING",fieldId:n,warnings:f});},[]),R=ir.useCallback(n=>{l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"});},[]),w=ir.useCallback(n=>{l({type:"CLEAR_WARNING",fieldId:n});},[]),b=ir.useCallback(n=>{l({type:"MARK_TOUCHED",fieldId:n});},[]),S=ir.useCallback((n,f)=>{l({type:"SET_VALIDATING",fieldId:n,isValidating:f});},[]),F=ir.useCallback((n,f)=>{if(l({type:"SET_VALUE",fieldId:n,value:f}),d.errors[n]&&d.errors[n].length>0&&(l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"})),u.current){let c={...d.values,[n]:f};u.current(n,f,c);}},[d.errors,d.values]),v=ir.useMemo(()=>r,[r]),V=ir.useCallback(async(n,f)=>{let c=v.allFields.find(P=>P.id===n);if(!c?.validation?.validator)return {isValid:true,errors:[]};let z=f!==void 0?f:d.values[n],B=t.current.get(n);B&&clearTimeout(B);let Z={fieldId:n,formData:d.values,fieldProps:c.props,touched:d.touched.has(n),dirty:d.isDirty},L=c.validation.debounceMs||0;return new Promise(P=>{let O=async()=>{S(n,true);try{let p=await c.validation.validator(z,Z,c.props);p.errors.length>0?y(n,p.errors):R(n),p.warnings&&p.warnings.length>0?E(n,p.warnings):w(n),P(p);}catch(p){let M={isValid:false,errors:[{code:"validation_error",message:p instanceof Error?p.message:"Validation error"}]};y(n,M.errors),P(M);}finally{S(n,false);}};if(L>0){let p=setTimeout(O,L);t.current.set(n,p);}else O();})},[v,d.values,d.touched,d.isDirty,y,E,R,w,S]),I=ir.useCallback(async()=>{let n=v.allFields.map(c=>V(c.id));return (await Promise.all(n)).every(c=>c.isValid)},[v,V]),D=ir.useCallback(n=>{l({type:"RESET",values:n});},[]),A=ir.useCallback(async n=>{if(n?.preventDefault(),!h.current)return true;l({type:"SET_SUBMITTING",isSubmitting:true});try{return await I()?(await h.current(d.values),!0):!1}catch(f){return console.error("Error during form submission:",f),false}finally{l({type:"SET_SUBMITTING",isSubmitting:false});}},[d.values,I]),K=ir.useMemo(()=>({formState:d,formConfig:v,setValue:F,setError:y,setWarning:E,clearError:R,clearWarning:w,markFieldTouched:b,setFieldValidating:S,validateField:V,validateAllFields:I,reset:D,submit:A}),[d,v,F,y,E,R,w,b,S,V,I,D,A]);return jsxRuntime.jsx(U.Provider,{value:K,children:jsxRuntime.jsx("form",{onSubmit:A,className:a,noValidate:true,children:i})})}function C(){let i=ir.useContext(U);if(!i)throw new Error("useFormContext must be used within a FormProvider");return i}function rr({formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,children:e}){return jsxRuntime.jsx(_,{formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,className:"streamline-form",children:e})}function W({fieldId:i,disabled:r=false,customProps:o={},className:s}){let{formState:e,formConfig:a,setValue:m,markFieldTouched:d,validateField:l}=C(),t=ir.useMemo(()=>a.allFields.find(F=>F.id===i),[a.allFields,i]);if(!t)throw new Error(`Field with ID "${i}" not found`);let h=ir.useMemo(()=>a.config.getComponent(t.componentId),[a.config,t.componentId]);if(!h)throw new Error(`Component with ID "${t.componentId}" not found`);let u=ir.useMemo(()=>({value:e.values[t.id],errors:e.errors[t.id]||[],warnings:e.warnings[t.id]||[],touched:e.touched.has(t.id),validating:e.isValidating.has(t.id)}),[e.values,e.errors,e.warnings,e.touched,e.isValidating,t.id]),y=ir.useCallback(F=>{let v=u.errors.length>0;m(t.id,F),(t.validation?.validateOnChange||v&&t.validation?.validator||u.touched&&t.validation?.validator)&&l(t.id,F);},[t.id,t.validation,m,l,u.errors.length,u.touched]),E=ir.useCallback(()=>{d(t.id),(t.validation?.validateOnBlur||t.validation?.validator)&&l(t.id);},[t.id,t.validation,d,l]),R=ir.useMemo(()=>{if(!t.conditional)return true;try{return t.conditional.condition(e.values)}catch(F){return console.warn(`Conditional evaluation failed for field "${t.id}":`,F),true}},[t.conditional,e.values,t.id]),w=ir.useMemo(()=>{if(!t.conditional||!R)return {};switch(t.conditional.action){case "disable":return {disabled:true};case "require":return {required:true};default:return {}}},[t.conditional,R]);if(!R&&t.conditional?.action==="hide")return null;let b=ir.useMemo(()=>({...h.defaultProps,...t.props,...o,...w}),[h.defaultProps,t.props,o,w]),S=ir.useMemo(()=>({id:t.id,props:b,value:u.value,onChange:y,onBlur:E,error:u.errors,warnings:u.warnings,touched:u.touched,disabled:r||w.disabled,isValidating:u.validating}),[t.id,b,u.value,y,E,u.errors,u.warnings,u.touched,r,w.disabled,u.validating]);return jsxRuntime.jsx("div",{className:er__default.default("streamline-form-field",s),"data-field-id":t.id,"data-field-type":h.subType,children:h.renderer(S)})}var q=ir__default.default.memo(W);function H({row:i,className:r}){let{formConfig:o}=C(),s=o.renderConfig?.rowRenderer;if(!s)throw new Error(`No rowRenderer configured for form "${o.id}". Please configure a rowRenderer using config.setRowRenderer() or config.setFormRenderConfig().`);let e=i.fields.map(m=>jsxRuntime.jsx(q,{fieldId:m.id},m.id)),a={row:i,children:e,className:r,spacing:i.spacing,alignment:i.alignment};return s(a)}var J=H;function ar({className:i}){let{formConfig:r}=C(),o=r.renderConfig?.bodyRenderer;if(!o)throw new Error(`No bodyRenderer configured for form "${r.id}". Please configure a bodyRenderer using config.setBodyRenderer() or config.setFormRenderConfig().`);let s=ir.useMemo(()=>r.rows.map(a=>jsxRuntime.jsx(J,{row:a},a.id)),[r.rows]);return o({formConfig:r,children:s,className:i})}function lr({className:i,children:r}){let{formState:o,submit:s,formConfig:e}=C(),a=e.renderConfig?.submitButtonRenderer;if(!a)throw new Error(`No submitButtonRenderer configured for form "${e.id}". Please configure a submitButtonRenderer using config.setSubmitButtonRenderer() or config.setFormRenderConfig().`);let m={isSubmitting:o.isSubmitting,isValid:o.isValid,isDirty:o.isDirty,onSubmit:s,className:i,children:r};return a(m)}var x=class i{constructor(r,o){this.rows=[];this.rowCounter=0;this.config=r,this.formId=o||`form-${Date.now()}`;}static create(r,o){return new i(r,o)}addField(r,o,s={},e){return this.addRowFields([{fieldId:r,componentSubType:o,props:s,validation:e?.validation,conditional:e?.conditional}])}addRowFields(r,o){if(r.length===0)throw new Error("At least one field is required");if(r.length>3)throw new Error("Maximum 3 fields per row");let s=`row-${++this.rowCounter}`,e=[];for(let m of r){let d=this.config.getComponentsBySubType(m.componentSubType);if(d.length===0)throw new Error(`No component found with subType "${m.componentSubType}"`);let l=d[0],t={id:m.fieldId,componentId:l.id,props:{...l.defaultProps,...m.props},validation:m.validation,conditional:m.conditional};e.push(t);}let a={id:s,fields:e,maxColumns:r.length,spacing:o?.spacing||"normal",alignment:o?.alignment||"stretch"};return this.rows.push(a),this}addFields(r){for(let o of r)this.addField(o.fieldId,o.componentSubType,o.props,{validation:o.validation,conditional:o.conditional});return this}setId(r){return this.formId=r,this}updateField(r,o){let s=false;for(let e of this.rows){let a=e.fields.findIndex(m=>m.id===r);a!==-1&&(e.fields[a]={...e.fields[a],...o,props:{...e.fields[a].props,...o.props}},s=true);}if(!s)throw new Error(`Field with ID "${r}" not found`);return this}removeField(r){for(let o of this.rows){let s=o.fields.filter(e=>e.id!==r);Object.assign(o,{fields:s});}return this.rows=this.rows.filter(o=>o.fields.length>0),this}getField(r){for(let o of this.rows){let s=o.fields.find(e=>e.id===r);if(s)return s}}getFields(){return this.rows.flatMap(r=>r.fields)}getRows(){return [...this.rows]}clear(){return this.rows=[],this.rowCounter=0,this}clone(r){let o=new i(this.config,r);return o.rows=this.rows.map(s=>({...s,fields:s.fields.map(e=>({...e}))})),o.rowCounter=this.rowCounter,o}validate(){let r=[],o=this.getFields(),s=o.map(a=>a.id),e=s.filter((a,m)=>s.indexOf(a)!==m);e.length>0&&r.push(`Duplicate field IDs: ${e.join(", ")}`);for(let a of o)this.config.hasComponent(a.componentId)||r.push(`Component "${a.componentId}" not found for field "${a.id}"`);for(let a of this.rows)a.fields.length>3&&r.push(`Row "${a.id}" has ${a.fields.length} fields, maximum is 3`),a.fields.length===0&&r.push(`Row "${a.id}" is empty`);return r}build(){let r=this.validate();if(r.length>0)throw new Error(`Form validation failed: ${r.join(", ")}`);return {id:this.formId,rows:[...this.rows],allFields:this.getFields(),config:this.config,renderConfig:this.config.getFormRenderConfig()}}toJSON(){return {id:this.formId,rows:this.rows}}fromJSON(r){return r.id&&(this.formId=r.id),r.rows&&(this.rows=r.rows,this.rowCounter=this.rows.length),this}getStats(){let r=this.getFields(),o=this.rows.map(s=>s.fields.length);return {totalFields:r.length,totalRows:this.rows.length,averageFieldsPerRow:this.rows.length>0?r.length/this.rows.length:0,maxFieldsInRow:o.length>0?Math.max(...o):0,minFieldsInRow:o.length>0?Math.min(...o):0}}};Object.defineProperty(exports,"createZodValidator",{enumerable:true,get:function(){return core.createZodValidator}});Object.defineProperty(exports,"ril",{enumerable:true,get:function(){return core.ril}});exports.Form=rr;exports.FormBody=ar;exports.FormBuilder=x;exports.FormField=W;exports.FormProvider=_;exports.FormRow=H;exports.FormSubmitButton=lr;exports.form=x;exports.useFormContext=C;
1
+ 'use strict';var er=require('react'),jsxRuntime=require('react/jsx-runtime'),core=require('@rilaykit/core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var er__default=/*#__PURE__*/_interopDefault(er);function j(i,r){switch(r.type){case "SET_VALUE":{let o={...i.values,[r.fieldId]:r.value};return {...i,values:o,isDirty:true}}case "SET_ERROR":return {...i,errors:{...i.errors,[r.fieldId]:r.errors},isValid:false};case "SET_WARNING":return {...i,warnings:{...i.warnings,[r.fieldId]:r.warnings}};case "CLEAR_ERROR":{let o={...i.errors};return delete o[r.fieldId],{...i,errors:o}}case "CLEAR_WARNING":{let o={...i.warnings};return delete o[r.fieldId],{...i,warnings:o}}case "MARK_TOUCHED":return {...i,touched:new Set([...i.touched,r.fieldId])};case "SET_VALIDATING":{let o=new Set(i.isValidating);return r.isValidating?o.add(r.fieldId):o.delete(r.fieldId),{...i,isValidating:o}}case "SET_SUBMITTING":return {...i,isSubmitting:r.isSubmitting};case "RESET":return {values:r.values||{},errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false};case "UPDATE_VALIDATION_STATE":{let o=Object.keys(i.errors).some(s=>i.errors[s].length>0);return {...i,isValid:!o}}default:return i}}var U=er.createContext(null);function _({children:i,formConfig:r,defaultValues:o={},onSubmit:s,onFieldChange:e,className:a}){let m={values:o,errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false},[d,l]=er.useReducer(j,m),t=er.useRef(new Map),h=er.useRef(s),f=er.useRef(e);h.current=s,f.current=e;let R=er.useCallback((n,c)=>{l({type:"SET_ERROR",fieldId:n,errors:c}),l({type:"UPDATE_VALIDATION_STATE"});},[]),E=er.useCallback((n,c)=>{l({type:"SET_WARNING",fieldId:n,warnings:c});},[]),y=er.useCallback(n=>{l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"});},[]),w=er.useCallback(n=>{l({type:"CLEAR_WARNING",fieldId:n});},[]),P=er.useCallback(n=>{l({type:"MARK_TOUCHED",fieldId:n});},[]),S=er.useCallback((n,c)=>{l({type:"SET_VALIDATING",fieldId:n,isValidating:c});},[]),F=er.useCallback((n,c)=>{if(l({type:"SET_VALUE",fieldId:n,value:c}),d.errors[n]&&d.errors[n].length>0&&(l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"})),f.current){let u={...d.values,[n]:c};f.current(n,c,u);}},[d.errors,d.values]),v=er.useMemo(()=>r,[r]),b=er.useCallback(async(n,c)=>{let u=v.allFields.find(T=>T.id===n);if(!u?.validation?.validator)return {isValid:true,errors:[]};let z=c!==void 0?c:d.values[n],B=t.current.get(n);B&&clearTimeout(B);let Z={fieldId:n,formData:d.values,fieldProps:u.props,touched:d.touched.has(n),dirty:d.isDirty},O=u.validation.debounceMs||0;return new Promise(T=>{let L=async()=>{S(n,true);try{let g=await u.validation.validator(z,Z,u.props);g.errors.length>0?R(n,g.errors):y(n),g.warnings&&g.warnings.length>0?E(n,g.warnings):w(n),T(g);}catch(g){let M={isValid:false,errors:[{code:"validation_error",message:g instanceof Error?g.message:"Validation error"}]};R(n,M.errors),T(M);}finally{S(n,false);}};if(O>0){let g=setTimeout(L,O);t.current.set(n,g);}else L();})},[v,d.values,d.touched,d.isDirty,R,E,y,w,S]),I=er.useCallback(async()=>{let n=v.allFields.map(u=>b(u.id));return (await Promise.all(n)).every(u=>u.isValid)},[v,b]),D=er.useCallback(n=>{l({type:"RESET",values:n});},[]),A=er.useCallback(async n=>{if(n?.preventDefault(),!h.current)return true;l({type:"SET_SUBMITTING",isSubmitting:true});try{return await I()?(await h.current(d.values),!0):!1}catch(c){return console.error("Error during form submission:",c),false}finally{l({type:"SET_SUBMITTING",isSubmitting:false});}},[d.values,I]),K=er.useMemo(()=>({formState:d,formConfig:v,setValue:F,setError:R,setWarning:E,clearError:y,clearWarning:w,markFieldTouched:P,setFieldValidating:S,validateField:b,validateAllFields:I,reset:D,submit:A}),[d,v,F,R,E,y,w,P,S,b,I,D,A]);return jsxRuntime.jsx(U.Provider,{value:K,children:jsxRuntime.jsx("form",{onSubmit:A,className:a,noValidate:true,children:i})})}function C(){let i=er.useContext(U);if(!i)throw new Error("useFormContext must be used within a FormProvider");return i}function rr({formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,children:e}){return jsxRuntime.jsx(_,{formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,className:"streamline-form",children:e})}function W({fieldId:i,disabled:r=false,customProps:o={},className:s}){let{formState:e,formConfig:a,setValue:m,markFieldTouched:d,validateField:l}=C(),t=er.useMemo(()=>a.allFields.find(F=>F.id===i),[a.allFields,i]);if(!t)throw new Error(`Field with ID "${i}" not found`);let h=er.useMemo(()=>a.config.getComponent(t.componentId),[a.config,t.componentId]);if(!h)throw new Error(`Component with ID "${t.componentId}" not found`);let f=er.useMemo(()=>({value:e.values[t.id],errors:e.errors[t.id]||[],warnings:e.warnings[t.id]||[],touched:e.touched.has(t.id),validating:e.isValidating.has(t.id)}),[e.values,e.errors,e.warnings,e.touched,e.isValidating,t.id]),R=er.useCallback(F=>{let v=f.errors.length>0;m(t.id,F),(t.validation?.validateOnChange||v&&t.validation?.validator||f.touched&&t.validation?.validator)&&l(t.id,F);},[t.id,t.validation,m,l,f.errors.length,f.touched]),E=er.useCallback(()=>{d(t.id),(t.validation?.validateOnBlur||t.validation?.validator)&&l(t.id);},[t.id,t.validation,d,l]),y=er.useMemo(()=>{if(!t.conditional)return true;try{return t.conditional.condition(e.values)}catch(F){return console.warn(`Conditional evaluation failed for field "${t.id}":`,F),true}},[t.conditional,e.values,t.id]),w=er.useMemo(()=>{if(!t.conditional||!y)return {};switch(t.conditional.action){case "disable":return {disabled:true};case "require":return {required:true};default:return {}}},[t.conditional,y]);if(!y&&t.conditional?.action==="hide")return null;let P=er.useMemo(()=>({...h.defaultProps,...t.props,...o,...w}),[h.defaultProps,t.props,o,w]),S=er.useMemo(()=>({id:t.id,props:P,value:f.value,onChange:R,onBlur:E,error:f.errors,warnings:f.warnings,touched:f.touched,disabled:r||w.disabled,isValidating:f.validating}),[t.id,P,f.value,R,E,f.errors,f.warnings,f.touched,r,w.disabled,f.validating]);return jsxRuntime.jsx("div",{className:s,"data-field-id":t.id,"data-field-type":h.type,children:h.renderer(S)})}var q=er__default.default.memo(W);function H({row:i,className:r}){let{formConfig:o}=C(),s=o.renderConfig?.rowRenderer;if(!s)throw new Error(`No rowRenderer configured for form "${o.id}". Please configure a rowRenderer using config.setRowRenderer() or config.setFormRenderConfig().`);let e=i.fields.map(m=>jsxRuntime.jsx(q,{fieldId:m.id},m.id)),a={row:i,children:e,className:r,spacing:i.spacing,alignment:i.alignment};return s(a)}var J=H;function sr({className:i}){let{formConfig:r}=C(),o=r.renderConfig?.bodyRenderer;if(!o)throw new Error(`No bodyRenderer configured for form "${r.id}". Please configure a bodyRenderer using config.setBodyRenderer() or config.setFormRenderConfig().`);let s=er.useMemo(()=>r.rows.map(a=>jsxRuntime.jsx(J,{row:a},a.id)),[r.rows]);return o({formConfig:r,children:s,className:i})}function dr({className:i,children:r}){let{formState:o,submit:s,formConfig:e}=C(),a=e.renderConfig?.submitButtonRenderer;if(!a)throw new Error(`No submitButtonRenderer configured for form "${e.id}". Please configure a submitButtonRenderer using config.setSubmitButtonRenderer() or config.setFormRenderConfig().`);let m={isSubmitting:o.isSubmitting,isValid:o.isValid,isDirty:o.isDirty,onSubmit:s,className:i,children:r};return a(m)}var x=class i{constructor(r,o){this.rows=[];this.rowCounter=0;this.config=r,this.formId=o||`form-${Date.now()}`;}static create(r,o){return new i(r,o)}addField(r,o,s={},e){return this.addRowFields([{fieldId:r,componentType:o,props:s,validation:e?.validation,conditional:e?.conditional}])}addRowFields(r,o){if(r.length===0)throw new Error("At least one field is required");if(r.length>3)throw new Error("Maximum 3 fields per row");let s=`row-${++this.rowCounter}`,e=[];for(let m of r){let d=this.config.getComponent(m.componentType);if(!d)throw new Error(`No component found with type "${m.componentType}"`);let l={id:m.fieldId,componentId:d.id,props:{...d.defaultProps,...m.props},validation:m.validation,conditional:m.conditional};e.push(l);}let a={id:s,fields:e,maxColumns:r.length,spacing:o?.spacing||"normal",alignment:o?.alignment||"stretch"};return this.rows.push(a),this}addFields(r){for(let o of r)this.addField(o.fieldId,o.componentType,o.props,{validation:o.validation,conditional:o.conditional});return this}setId(r){return this.formId=r,this}updateField(r,o){let s=false;for(let e of this.rows){let a=e.fields.findIndex(m=>m.id===r);a!==-1&&(e.fields[a]={...e.fields[a],...o,props:{...e.fields[a].props,...o.props}},s=true);}if(!s)throw new Error(`Field with ID "${r}" not found`);return this}removeField(r){for(let o of this.rows){let s=o.fields.filter(e=>e.id!==r);Object.assign(o,{fields:s});}return this.rows=this.rows.filter(o=>o.fields.length>0),this}getField(r){for(let o of this.rows){let s=o.fields.find(e=>e.id===r);if(s)return s}}getFields(){return this.rows.flatMap(r=>r.fields)}getRows(){return [...this.rows]}clear(){return this.rows=[],this.rowCounter=0,this}clone(r){let o=new i(this.config,r);return o.rows=this.rows.map(s=>({...s,fields:s.fields.map(e=>({...e}))})),o.rowCounter=this.rowCounter,o}validate(){let r=[],o=this.getFields(),s=o.map(a=>a.id),e=s.filter((a,m)=>s.indexOf(a)!==m);e.length>0&&r.push(`Duplicate field IDs: ${e.join(", ")}`);for(let a of o)this.config.hasComponent(a.componentId)||r.push(`Component "${a.componentId}" not found for field "${a.id}"`);for(let a of this.rows)a.fields.length>3&&r.push(`Row "${a.id}" has ${a.fields.length} fields, maximum is 3`),a.fields.length===0&&r.push(`Row "${a.id}" is empty`);return r}build(){let r=this.validate();if(r.length>0)throw new Error(`Form validation failed: ${r.join(", ")}`);return {id:this.formId,rows:[...this.rows],allFields:this.getFields(),config:this.config,renderConfig:this.config.getFormRenderConfig()}}toJSON(){return {id:this.formId,rows:this.rows}}fromJSON(r){return r.id&&(this.formId=r.id),r.rows&&(this.rows=r.rows,this.rowCounter=this.rows.length),this}getStats(){let r=this.getFields(),o=this.rows.map(s=>s.fields.length);return {totalFields:r.length,totalRows:this.rows.length,averageFieldsPerRow:this.rows.length>0?r.length/this.rows.length:0,maxFieldsInRow:o.length>0?Math.max(...o):0,minFieldsInRow:o.length>0?Math.min(...o):0}}};Object.defineProperty(exports,"createZodValidator",{enumerable:true,get:function(){return core.createZodValidator}});Object.defineProperty(exports,"ril",{enumerable:true,get:function(){return core.ril}});exports.Form=rr;exports.FormBody=sr;exports.FormBuilder=x;exports.FormField=W;exports.FormProvider=_;exports.FormRow=H;exports.FormSubmitButton=dr;exports.form=x;exports.useFormContext=C;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import ir,{createContext,useMemo,useCallback,useContext,useReducer,useRef}from'react';import {jsx}from'react/jsx-runtime';import er from'clsx';export{createZodValidator,ril}from'@rilaykit/core';function j(i,r){switch(r.type){case "SET_VALUE":{let o={...i.values,[r.fieldId]:r.value};return {...i,values:o,isDirty:true}}case "SET_ERROR":return {...i,errors:{...i.errors,[r.fieldId]:r.errors},isValid:false};case "SET_WARNING":return {...i,warnings:{...i.warnings,[r.fieldId]:r.warnings}};case "CLEAR_ERROR":{let o={...i.errors};return delete o[r.fieldId],{...i,errors:o}}case "CLEAR_WARNING":{let o={...i.warnings};return delete o[r.fieldId],{...i,warnings:o}}case "MARK_TOUCHED":return {...i,touched:new Set([...i.touched,r.fieldId])};case "SET_VALIDATING":{let o=new Set(i.isValidating);return r.isValidating?o.add(r.fieldId):o.delete(r.fieldId),{...i,isValidating:o}}case "SET_SUBMITTING":return {...i,isSubmitting:r.isSubmitting};case "RESET":return {values:r.values||{},errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false};case "UPDATE_VALIDATION_STATE":{let o=Object.keys(i.errors).some(s=>i.errors[s].length>0);return {...i,isValid:!o}}default:return i}}var U=createContext(null);function _({children:i,formConfig:r,defaultValues:o={},onSubmit:s,onFieldChange:e,className:a}){let m={values:o,errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false},[d,l]=useReducer(j,m),t=useRef(new Map),h=useRef(s),u=useRef(e);h.current=s,u.current=e;let y=useCallback((n,f)=>{l({type:"SET_ERROR",fieldId:n,errors:f}),l({type:"UPDATE_VALIDATION_STATE"});},[]),E=useCallback((n,f)=>{l({type:"SET_WARNING",fieldId:n,warnings:f});},[]),R=useCallback(n=>{l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"});},[]),w=useCallback(n=>{l({type:"CLEAR_WARNING",fieldId:n});},[]),b=useCallback(n=>{l({type:"MARK_TOUCHED",fieldId:n});},[]),S=useCallback((n,f)=>{l({type:"SET_VALIDATING",fieldId:n,isValidating:f});},[]),F=useCallback((n,f)=>{if(l({type:"SET_VALUE",fieldId:n,value:f}),d.errors[n]&&d.errors[n].length>0&&(l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"})),u.current){let c={...d.values,[n]:f};u.current(n,f,c);}},[d.errors,d.values]),v=useMemo(()=>r,[r]),V=useCallback(async(n,f)=>{let c=v.allFields.find(P=>P.id===n);if(!c?.validation?.validator)return {isValid:true,errors:[]};let z=f!==void 0?f:d.values[n],B=t.current.get(n);B&&clearTimeout(B);let Z={fieldId:n,formData:d.values,fieldProps:c.props,touched:d.touched.has(n),dirty:d.isDirty},L=c.validation.debounceMs||0;return new Promise(P=>{let O=async()=>{S(n,true);try{let p=await c.validation.validator(z,Z,c.props);p.errors.length>0?y(n,p.errors):R(n),p.warnings&&p.warnings.length>0?E(n,p.warnings):w(n),P(p);}catch(p){let M={isValid:false,errors:[{code:"validation_error",message:p instanceof Error?p.message:"Validation error"}]};y(n,M.errors),P(M);}finally{S(n,false);}};if(L>0){let p=setTimeout(O,L);t.current.set(n,p);}else O();})},[v,d.values,d.touched,d.isDirty,y,E,R,w,S]),I=useCallback(async()=>{let n=v.allFields.map(c=>V(c.id));return (await Promise.all(n)).every(c=>c.isValid)},[v,V]),D=useCallback(n=>{l({type:"RESET",values:n});},[]),A=useCallback(async n=>{if(n?.preventDefault(),!h.current)return true;l({type:"SET_SUBMITTING",isSubmitting:true});try{return await I()?(await h.current(d.values),!0):!1}catch(f){return console.error("Error during form submission:",f),false}finally{l({type:"SET_SUBMITTING",isSubmitting:false});}},[d.values,I]),K=useMemo(()=>({formState:d,formConfig:v,setValue:F,setError:y,setWarning:E,clearError:R,clearWarning:w,markFieldTouched:b,setFieldValidating:S,validateField:V,validateAllFields:I,reset:D,submit:A}),[d,v,F,y,E,R,w,b,S,V,I,D,A]);return jsx(U.Provider,{value:K,children:jsx("form",{onSubmit:A,className:a,noValidate:true,children:i})})}function C(){let i=useContext(U);if(!i)throw new Error("useFormContext must be used within a FormProvider");return i}function rr({formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,children:e}){return jsx(_,{formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,className:"streamline-form",children:e})}function W({fieldId:i,disabled:r=false,customProps:o={},className:s}){let{formState:e,formConfig:a,setValue:m,markFieldTouched:d,validateField:l}=C(),t=useMemo(()=>a.allFields.find(F=>F.id===i),[a.allFields,i]);if(!t)throw new Error(`Field with ID "${i}" not found`);let h=useMemo(()=>a.config.getComponent(t.componentId),[a.config,t.componentId]);if(!h)throw new Error(`Component with ID "${t.componentId}" not found`);let u=useMemo(()=>({value:e.values[t.id],errors:e.errors[t.id]||[],warnings:e.warnings[t.id]||[],touched:e.touched.has(t.id),validating:e.isValidating.has(t.id)}),[e.values,e.errors,e.warnings,e.touched,e.isValidating,t.id]),y=useCallback(F=>{let v=u.errors.length>0;m(t.id,F),(t.validation?.validateOnChange||v&&t.validation?.validator||u.touched&&t.validation?.validator)&&l(t.id,F);},[t.id,t.validation,m,l,u.errors.length,u.touched]),E=useCallback(()=>{d(t.id),(t.validation?.validateOnBlur||t.validation?.validator)&&l(t.id);},[t.id,t.validation,d,l]),R=useMemo(()=>{if(!t.conditional)return true;try{return t.conditional.condition(e.values)}catch(F){return console.warn(`Conditional evaluation failed for field "${t.id}":`,F),true}},[t.conditional,e.values,t.id]),w=useMemo(()=>{if(!t.conditional||!R)return {};switch(t.conditional.action){case "disable":return {disabled:true};case "require":return {required:true};default:return {}}},[t.conditional,R]);if(!R&&t.conditional?.action==="hide")return null;let b=useMemo(()=>({...h.defaultProps,...t.props,...o,...w}),[h.defaultProps,t.props,o,w]),S=useMemo(()=>({id:t.id,props:b,value:u.value,onChange:y,onBlur:E,error:u.errors,warnings:u.warnings,touched:u.touched,disabled:r||w.disabled,isValidating:u.validating}),[t.id,b,u.value,y,E,u.errors,u.warnings,u.touched,r,w.disabled,u.validating]);return jsx("div",{className:er("streamline-form-field",s),"data-field-id":t.id,"data-field-type":h.subType,children:h.renderer(S)})}var q=ir.memo(W);function H({row:i,className:r}){let{formConfig:o}=C(),s=o.renderConfig?.rowRenderer;if(!s)throw new Error(`No rowRenderer configured for form "${o.id}". Please configure a rowRenderer using config.setRowRenderer() or config.setFormRenderConfig().`);let e=i.fields.map(m=>jsx(q,{fieldId:m.id},m.id)),a={row:i,children:e,className:r,spacing:i.spacing,alignment:i.alignment};return s(a)}var J=H;function ar({className:i}){let{formConfig:r}=C(),o=r.renderConfig?.bodyRenderer;if(!o)throw new Error(`No bodyRenderer configured for form "${r.id}". Please configure a bodyRenderer using config.setBodyRenderer() or config.setFormRenderConfig().`);let s=useMemo(()=>r.rows.map(a=>jsx(J,{row:a},a.id)),[r.rows]);return o({formConfig:r,children:s,className:i})}function lr({className:i,children:r}){let{formState:o,submit:s,formConfig:e}=C(),a=e.renderConfig?.submitButtonRenderer;if(!a)throw new Error(`No submitButtonRenderer configured for form "${e.id}". Please configure a submitButtonRenderer using config.setSubmitButtonRenderer() or config.setFormRenderConfig().`);let m={isSubmitting:o.isSubmitting,isValid:o.isValid,isDirty:o.isDirty,onSubmit:s,className:i,children:r};return a(m)}var x=class i{constructor(r,o){this.rows=[];this.rowCounter=0;this.config=r,this.formId=o||`form-${Date.now()}`;}static create(r,o){return new i(r,o)}addField(r,o,s={},e){return this.addRowFields([{fieldId:r,componentSubType:o,props:s,validation:e?.validation,conditional:e?.conditional}])}addRowFields(r,o){if(r.length===0)throw new Error("At least one field is required");if(r.length>3)throw new Error("Maximum 3 fields per row");let s=`row-${++this.rowCounter}`,e=[];for(let m of r){let d=this.config.getComponentsBySubType(m.componentSubType);if(d.length===0)throw new Error(`No component found with subType "${m.componentSubType}"`);let l=d[0],t={id:m.fieldId,componentId:l.id,props:{...l.defaultProps,...m.props},validation:m.validation,conditional:m.conditional};e.push(t);}let a={id:s,fields:e,maxColumns:r.length,spacing:o?.spacing||"normal",alignment:o?.alignment||"stretch"};return this.rows.push(a),this}addFields(r){for(let o of r)this.addField(o.fieldId,o.componentSubType,o.props,{validation:o.validation,conditional:o.conditional});return this}setId(r){return this.formId=r,this}updateField(r,o){let s=false;for(let e of this.rows){let a=e.fields.findIndex(m=>m.id===r);a!==-1&&(e.fields[a]={...e.fields[a],...o,props:{...e.fields[a].props,...o.props}},s=true);}if(!s)throw new Error(`Field with ID "${r}" not found`);return this}removeField(r){for(let o of this.rows){let s=o.fields.filter(e=>e.id!==r);Object.assign(o,{fields:s});}return this.rows=this.rows.filter(o=>o.fields.length>0),this}getField(r){for(let o of this.rows){let s=o.fields.find(e=>e.id===r);if(s)return s}}getFields(){return this.rows.flatMap(r=>r.fields)}getRows(){return [...this.rows]}clear(){return this.rows=[],this.rowCounter=0,this}clone(r){let o=new i(this.config,r);return o.rows=this.rows.map(s=>({...s,fields:s.fields.map(e=>({...e}))})),o.rowCounter=this.rowCounter,o}validate(){let r=[],o=this.getFields(),s=o.map(a=>a.id),e=s.filter((a,m)=>s.indexOf(a)!==m);e.length>0&&r.push(`Duplicate field IDs: ${e.join(", ")}`);for(let a of o)this.config.hasComponent(a.componentId)||r.push(`Component "${a.componentId}" not found for field "${a.id}"`);for(let a of this.rows)a.fields.length>3&&r.push(`Row "${a.id}" has ${a.fields.length} fields, maximum is 3`),a.fields.length===0&&r.push(`Row "${a.id}" is empty`);return r}build(){let r=this.validate();if(r.length>0)throw new Error(`Form validation failed: ${r.join(", ")}`);return {id:this.formId,rows:[...this.rows],allFields:this.getFields(),config:this.config,renderConfig:this.config.getFormRenderConfig()}}toJSON(){return {id:this.formId,rows:this.rows}}fromJSON(r){return r.id&&(this.formId=r.id),r.rows&&(this.rows=r.rows,this.rowCounter=this.rows.length),this}getStats(){let r=this.getFields(),o=this.rows.map(s=>s.fields.length);return {totalFields:r.length,totalRows:this.rows.length,averageFieldsPerRow:this.rows.length>0?r.length/this.rows.length:0,maxFieldsInRow:o.length>0?Math.max(...o):0,minFieldsInRow:o.length>0?Math.min(...o):0}}};export{rr as Form,ar as FormBody,x as FormBuilder,W as FormField,_ as FormProvider,H as FormRow,lr as FormSubmitButton,x as form,C as useFormContext};
1
+ import er,{createContext,useMemo,useCallback,useContext,useReducer,useRef}from'react';import {jsx}from'react/jsx-runtime';export{createZodValidator,ril}from'@rilaykit/core';function j(i,r){switch(r.type){case "SET_VALUE":{let o={...i.values,[r.fieldId]:r.value};return {...i,values:o,isDirty:true}}case "SET_ERROR":return {...i,errors:{...i.errors,[r.fieldId]:r.errors},isValid:false};case "SET_WARNING":return {...i,warnings:{...i.warnings,[r.fieldId]:r.warnings}};case "CLEAR_ERROR":{let o={...i.errors};return delete o[r.fieldId],{...i,errors:o}}case "CLEAR_WARNING":{let o={...i.warnings};return delete o[r.fieldId],{...i,warnings:o}}case "MARK_TOUCHED":return {...i,touched:new Set([...i.touched,r.fieldId])};case "SET_VALIDATING":{let o=new Set(i.isValidating);return r.isValidating?o.add(r.fieldId):o.delete(r.fieldId),{...i,isValidating:o}}case "SET_SUBMITTING":return {...i,isSubmitting:r.isSubmitting};case "RESET":return {values:r.values||{},errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false};case "UPDATE_VALIDATION_STATE":{let o=Object.keys(i.errors).some(s=>i.errors[s].length>0);return {...i,isValid:!o}}default:return i}}var U=createContext(null);function _({children:i,formConfig:r,defaultValues:o={},onSubmit:s,onFieldChange:e,className:a}){let m={values:o,errors:{},warnings:{},touched:new Set,isValidating:new Set,isDirty:false,isValid:true,isSubmitting:false},[d,l]=useReducer(j,m),t=useRef(new Map),h=useRef(s),f=useRef(e);h.current=s,f.current=e;let R=useCallback((n,c)=>{l({type:"SET_ERROR",fieldId:n,errors:c}),l({type:"UPDATE_VALIDATION_STATE"});},[]),E=useCallback((n,c)=>{l({type:"SET_WARNING",fieldId:n,warnings:c});},[]),y=useCallback(n=>{l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"});},[]),w=useCallback(n=>{l({type:"CLEAR_WARNING",fieldId:n});},[]),P=useCallback(n=>{l({type:"MARK_TOUCHED",fieldId:n});},[]),S=useCallback((n,c)=>{l({type:"SET_VALIDATING",fieldId:n,isValidating:c});},[]),F=useCallback((n,c)=>{if(l({type:"SET_VALUE",fieldId:n,value:c}),d.errors[n]&&d.errors[n].length>0&&(l({type:"CLEAR_ERROR",fieldId:n}),l({type:"UPDATE_VALIDATION_STATE"})),f.current){let u={...d.values,[n]:c};f.current(n,c,u);}},[d.errors,d.values]),v=useMemo(()=>r,[r]),b=useCallback(async(n,c)=>{let u=v.allFields.find(T=>T.id===n);if(!u?.validation?.validator)return {isValid:true,errors:[]};let z=c!==void 0?c:d.values[n],B=t.current.get(n);B&&clearTimeout(B);let Z={fieldId:n,formData:d.values,fieldProps:u.props,touched:d.touched.has(n),dirty:d.isDirty},O=u.validation.debounceMs||0;return new Promise(T=>{let L=async()=>{S(n,true);try{let g=await u.validation.validator(z,Z,u.props);g.errors.length>0?R(n,g.errors):y(n),g.warnings&&g.warnings.length>0?E(n,g.warnings):w(n),T(g);}catch(g){let M={isValid:false,errors:[{code:"validation_error",message:g instanceof Error?g.message:"Validation error"}]};R(n,M.errors),T(M);}finally{S(n,false);}};if(O>0){let g=setTimeout(L,O);t.current.set(n,g);}else L();})},[v,d.values,d.touched,d.isDirty,R,E,y,w,S]),I=useCallback(async()=>{let n=v.allFields.map(u=>b(u.id));return (await Promise.all(n)).every(u=>u.isValid)},[v,b]),D=useCallback(n=>{l({type:"RESET",values:n});},[]),A=useCallback(async n=>{if(n?.preventDefault(),!h.current)return true;l({type:"SET_SUBMITTING",isSubmitting:true});try{return await I()?(await h.current(d.values),!0):!1}catch(c){return console.error("Error during form submission:",c),false}finally{l({type:"SET_SUBMITTING",isSubmitting:false});}},[d.values,I]),K=useMemo(()=>({formState:d,formConfig:v,setValue:F,setError:R,setWarning:E,clearError:y,clearWarning:w,markFieldTouched:P,setFieldValidating:S,validateField:b,validateAllFields:I,reset:D,submit:A}),[d,v,F,R,E,y,w,P,S,b,I,D,A]);return jsx(U.Provider,{value:K,children:jsx("form",{onSubmit:A,className:a,noValidate:true,children:i})})}function C(){let i=useContext(U);if(!i)throw new Error("useFormContext must be used within a FormProvider");return i}function rr({formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,children:e}){return jsx(_,{formConfig:i,defaultValues:r,onSubmit:o,onFieldChange:s,className:"streamline-form",children:e})}function W({fieldId:i,disabled:r=false,customProps:o={},className:s}){let{formState:e,formConfig:a,setValue:m,markFieldTouched:d,validateField:l}=C(),t=useMemo(()=>a.allFields.find(F=>F.id===i),[a.allFields,i]);if(!t)throw new Error(`Field with ID "${i}" not found`);let h=useMemo(()=>a.config.getComponent(t.componentId),[a.config,t.componentId]);if(!h)throw new Error(`Component with ID "${t.componentId}" not found`);let f=useMemo(()=>({value:e.values[t.id],errors:e.errors[t.id]||[],warnings:e.warnings[t.id]||[],touched:e.touched.has(t.id),validating:e.isValidating.has(t.id)}),[e.values,e.errors,e.warnings,e.touched,e.isValidating,t.id]),R=useCallback(F=>{let v=f.errors.length>0;m(t.id,F),(t.validation?.validateOnChange||v&&t.validation?.validator||f.touched&&t.validation?.validator)&&l(t.id,F);},[t.id,t.validation,m,l,f.errors.length,f.touched]),E=useCallback(()=>{d(t.id),(t.validation?.validateOnBlur||t.validation?.validator)&&l(t.id);},[t.id,t.validation,d,l]),y=useMemo(()=>{if(!t.conditional)return true;try{return t.conditional.condition(e.values)}catch(F){return console.warn(`Conditional evaluation failed for field "${t.id}":`,F),true}},[t.conditional,e.values,t.id]),w=useMemo(()=>{if(!t.conditional||!y)return {};switch(t.conditional.action){case "disable":return {disabled:true};case "require":return {required:true};default:return {}}},[t.conditional,y]);if(!y&&t.conditional?.action==="hide")return null;let P=useMemo(()=>({...h.defaultProps,...t.props,...o,...w}),[h.defaultProps,t.props,o,w]),S=useMemo(()=>({id:t.id,props:P,value:f.value,onChange:R,onBlur:E,error:f.errors,warnings:f.warnings,touched:f.touched,disabled:r||w.disabled,isValidating:f.validating}),[t.id,P,f.value,R,E,f.errors,f.warnings,f.touched,r,w.disabled,f.validating]);return jsx("div",{className:s,"data-field-id":t.id,"data-field-type":h.type,children:h.renderer(S)})}var q=er.memo(W);function H({row:i,className:r}){let{formConfig:o}=C(),s=o.renderConfig?.rowRenderer;if(!s)throw new Error(`No rowRenderer configured for form "${o.id}". Please configure a rowRenderer using config.setRowRenderer() or config.setFormRenderConfig().`);let e=i.fields.map(m=>jsx(q,{fieldId:m.id},m.id)),a={row:i,children:e,className:r,spacing:i.spacing,alignment:i.alignment};return s(a)}var J=H;function sr({className:i}){let{formConfig:r}=C(),o=r.renderConfig?.bodyRenderer;if(!o)throw new Error(`No bodyRenderer configured for form "${r.id}". Please configure a bodyRenderer using config.setBodyRenderer() or config.setFormRenderConfig().`);let s=useMemo(()=>r.rows.map(a=>jsx(J,{row:a},a.id)),[r.rows]);return o({formConfig:r,children:s,className:i})}function dr({className:i,children:r}){let{formState:o,submit:s,formConfig:e}=C(),a=e.renderConfig?.submitButtonRenderer;if(!a)throw new Error(`No submitButtonRenderer configured for form "${e.id}". Please configure a submitButtonRenderer using config.setSubmitButtonRenderer() or config.setFormRenderConfig().`);let m={isSubmitting:o.isSubmitting,isValid:o.isValid,isDirty:o.isDirty,onSubmit:s,className:i,children:r};return a(m)}var x=class i{constructor(r,o){this.rows=[];this.rowCounter=0;this.config=r,this.formId=o||`form-${Date.now()}`;}static create(r,o){return new i(r,o)}addField(r,o,s={},e){return this.addRowFields([{fieldId:r,componentType:o,props:s,validation:e?.validation,conditional:e?.conditional}])}addRowFields(r,o){if(r.length===0)throw new Error("At least one field is required");if(r.length>3)throw new Error("Maximum 3 fields per row");let s=`row-${++this.rowCounter}`,e=[];for(let m of r){let d=this.config.getComponent(m.componentType);if(!d)throw new Error(`No component found with type "${m.componentType}"`);let l={id:m.fieldId,componentId:d.id,props:{...d.defaultProps,...m.props},validation:m.validation,conditional:m.conditional};e.push(l);}let a={id:s,fields:e,maxColumns:r.length,spacing:o?.spacing||"normal",alignment:o?.alignment||"stretch"};return this.rows.push(a),this}addFields(r){for(let o of r)this.addField(o.fieldId,o.componentType,o.props,{validation:o.validation,conditional:o.conditional});return this}setId(r){return this.formId=r,this}updateField(r,o){let s=false;for(let e of this.rows){let a=e.fields.findIndex(m=>m.id===r);a!==-1&&(e.fields[a]={...e.fields[a],...o,props:{...e.fields[a].props,...o.props}},s=true);}if(!s)throw new Error(`Field with ID "${r}" not found`);return this}removeField(r){for(let o of this.rows){let s=o.fields.filter(e=>e.id!==r);Object.assign(o,{fields:s});}return this.rows=this.rows.filter(o=>o.fields.length>0),this}getField(r){for(let o of this.rows){let s=o.fields.find(e=>e.id===r);if(s)return s}}getFields(){return this.rows.flatMap(r=>r.fields)}getRows(){return [...this.rows]}clear(){return this.rows=[],this.rowCounter=0,this}clone(r){let o=new i(this.config,r);return o.rows=this.rows.map(s=>({...s,fields:s.fields.map(e=>({...e}))})),o.rowCounter=this.rowCounter,o}validate(){let r=[],o=this.getFields(),s=o.map(a=>a.id),e=s.filter((a,m)=>s.indexOf(a)!==m);e.length>0&&r.push(`Duplicate field IDs: ${e.join(", ")}`);for(let a of o)this.config.hasComponent(a.componentId)||r.push(`Component "${a.componentId}" not found for field "${a.id}"`);for(let a of this.rows)a.fields.length>3&&r.push(`Row "${a.id}" has ${a.fields.length} fields, maximum is 3`),a.fields.length===0&&r.push(`Row "${a.id}" is empty`);return r}build(){let r=this.validate();if(r.length>0)throw new Error(`Form validation failed: ${r.join(", ")}`);return {id:this.formId,rows:[...this.rows],allFields:this.getFields(),config:this.config,renderConfig:this.config.getFormRenderConfig()}}toJSON(){return {id:this.formId,rows:this.rows}}fromJSON(r){return r.id&&(this.formId=r.id),r.rows&&(this.rows=r.rows,this.rowCounter=this.rows.length),this}getStats(){let r=this.getFields(),o=this.rows.map(s=>s.fields.length);return {totalFields:r.length,totalRows:this.rows.length,averageFieldsPerRow:this.rows.length>0?r.length/this.rows.length:0,maxFieldsInRow:o.length>0?Math.max(...o):0,minFieldsInRow:o.length>0?Math.min(...o):0}}};export{rr as Form,sr as FormBody,x as FormBuilder,W as FormField,_ as FormProvider,H as FormRow,dr as FormSubmitButton,x as form,C as useFormContext};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rilaykit/forms",
3
- "version": "0.1.1-alpha.1",
3
+ "version": "1.0.0",
4
4
  "description": "Form building utilities and components for RilayKit",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -13,11 +13,18 @@
13
13
  "form-builder",
14
14
  "typescript"
15
15
  ],
16
- "author": "Rilay Team",
16
+ "author": "AND YOU CREATE <contact@andyoucreate.com>",
17
17
  "license": "MIT",
18
+ "homepage": "https://rilay.io",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/andyoucreate/rilay.git"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/andyoucreate/rilay/issues"
25
+ },
18
26
  "dependencies": {
19
- "clsx": "^2.1.1",
20
- "@rilaykit/core": "0.1.1-alpha.1"
27
+ "@rilaykit/core": "1.0.0"
21
28
  },
22
29
  "peerDependencies": {
23
30
  "react": ">=18.0.0",