@bgscore/react-form 0.0.23 → 0.0.25

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.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _jsxruntime = require('react/jsx-runtime');var k=_react.createContext.call(void 0, void 0);function y(){let r=_react.useContext.call(void 0, k);return r||{}}function P({children:r,controller:e,onSubmit:t}){let i=_react.useRef.call(void 0, []),a=_react.useCallback.call(void 0, o=>{let l=i.current.findIndex(p=>p.id===o.id);if(l>-1){let p=[...i.current];p[l]=o,i.current=[...p]}else i.current.push(o)},[i]),s=_react.useCallback.call(void 0, o=>{i.current=i.current.filter(l=>l.id!==o)},[]),c=async(o,l)=>{e.setIsSubmit(!0);let p=l?await e.formControl.trigger():!0,d=e.getData();p&&t&&t({...d,...o},{...e})},m={...e,registerItem:a,unregisterItem:s,items:i.current,triggerSubmit:c};return _jsxruntime.jsx.call(void 0, k.Provider,{value:m,children:r})}function h(){let r=()=>Math.random()*16%16|0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>(e==="x"?r():r()&3|8).toString(16))}function N(r,e){return typeof r=="function"?r(e):r}var F={camelCase:(r="")=>(r=r.split(".").map(e=>(e=e.charAt(0).toUpperCase()+e.slice(1),e)).join(" "),r=r.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),r.charAt(0).toUpperCase()+r.slice(1)),snackCase:(r="")=>{let t=r.replace(/_([a-z])/g,(i,a)=>a.toUpperCase()).replace(/([A-Z])/g," $1");return t=t.charAt(0).toUpperCase()+t.slice(1),t},changeAll:(r="",e=!1)=>{let t="";try{r=_optionalChain([r, 'optionalAccess', _2 => _2.split, 'call', _3 => _3("."), 'access', _4 => _4[_optionalChain([r, 'optionalAccess', _5 => _5.split, 'call', _6 => _6("."), 'optionalAccess', _7 => _7.length])-1]]),r=_optionalChain([r, 'optionalAccess', _8 => _8.split, 'call', _9 => _9("[]"), 'access', _10 => _10[_optionalChain([r, 'optionalAccess', _11 => _11.split, 'call', _12 => _12("[]"), 'optionalAccess', _13 => _13.length])-1]]),t=F.snackCase(F.camelCase(r)),e&&(t=_optionalChain([t, 'optionalAccess', _14 => _14.split, 'call', _15 => _15(" "), 'optionalAccess', _16 => _16.map, 'call', _17 => _17(i=>_optionalChain([i, 'optionalAccess', _18 => _18.length])<=3?_optionalChain([i, 'optionalAccess', _19 => _19.toUpperCase, 'call', _20 => _20()]):i), 'optionalAccess', _21 => _21.join, 'call', _22 => _22(" ")]))}catch (e2){}return t}};function D(r,e){try{return JSON.stringify(r)!==JSON.stringify(e)}catch (e3){return!1}}var R=r=>(Object.keys(r).forEach(e=>{r[e]===void 0&&(r[e]=null)}),r),U= exports.getFieldValue =(r,e,t="")=>{if(!r)return t;if(r.hasOwnProperty(e))return r[e];let i=e.replace(/\[(\d+)\]/g,".$1").split("."),a=r;for(let s of i){if(a==null)return t;a=a[s]}return a===void 0?t:a};function L(r,e){let t=!1;return r&&typeof r=="object"&&Array.isArray(r)&&(typeof e=="number"?r.length>e&&(t=!0):t=!0),t}var _reacthookform = require('react-hook-form');var K=(r,e)=>{r||(r={});let t=_react.useRef.call(void 0, null),[i,a]=_react.useState.call(void 0, !1),[s,c]=_react.useState.call(void 0, {}),m=_reacthookform.useForm.call(void 0, {...e,reValidateMode:"onSubmit",mode:"all",defaultValues:r}),o=_react.useMemo.call(void 0, ()=>h(),[]),l=u=>u?U(R(m.getValues()),u):R(m.getValues()),d={...m,ref:t,reset:u=>{u?typeof u=="string"?m.resetField(u,{}):typeof u=="object"&&L(u,0)&&u.forEach(g=>m.resetField(g)):m.reset()},updateData:u=>{let g=l();m.reset({...g,...u})},getData:l,formControl:m,useFieldArray:u=>_reacthookform.useFieldArray.call(void 0, {control:m.control,name:u}),useWatch:u=>_reacthookform.useWatch.call(void 0, {control:m.control,name:u}),isSubmit:i,formId:o,setIsSubmit:a,useSelected:u=>U(s,u),setSelected:c,selected:s};return[d,d]};var ce=({onSubmit:r,onChange:e=()=>{},onInvalid:t=()=>{},formData:i,controller:a,children:s,...c})=>{let m=_nullishCoalesce(a, () => (K())),[o]=Array.isArray(m)?m:[m],l=_react.useRef.call(void 0, void 0),p=async d=>{d.preventDefault(),d.stopPropagation(),o.setIsSubmit(!0);let u=await o.formControl.trigger(),g=o.getData();u?r&&r({...g},{...o}):t(o.formControl.formState.errors)};return _react.useEffect.call(void 0, ()=>{i&&D(l.current||{},i)&&(o.formControl.reset(i),l.current=i)},[i,o.formControl.reset]),_react.useEffect.call(void 0, ()=>{if(!e)return;let d=o.formControl.watch(e);return()=>d.unsubscribe()},[]),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, P,{controller:{...o,disabled:_optionalChain([c, 'optionalAccess', _23 => _23.disabled]),readOnly:_optionalChain([c, 'optionalAccess', _24 => _24.readOnly])},onSubmit:r,children:_jsxruntime.jsx.call(void 0, "form",{...c,id:o.formId,ref:o.ref,onSubmit:p,children:s})})})},z=ce;var Z=_react.createContext.call(void 0, void 0);function $(){let r=_react.useContext.call(void 0, Z);return r||{}}function S({children:r,...e}){return _jsxruntime.jsx.call(void 0, Z.Provider,{value:e,children:r})}var q=r=>{let e=y(),t=_reacthookform.useFieldArray.call(void 0, {control:e.control,name:r}),a={formArrayId:_react.useMemo.call(void 0, ()=>h(),[]),...t,...e};return[a,a]};var H=({name:r,defaultData:e,controller:t,children:i})=>{let a=_nullishCoalesce(t, () => (q(r))),[s]=Array.isArray(a)?a:[a];return _react.useEffect.call(void 0, ()=>{typeof e=="boolean"&&e?s.append({}):typeof e=="number"&&e>0?s.append([...Array(e).fill(null).map(()=>({}))]):typeof e=="object"&&e&&s.append(e)},[]),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:s.fields.map((c,m)=>{let o=`${r}.${m}.`,l={...s,index:m,name:o,countFields:s.fields.length,removeItem:()=>s.remove(m),watchItem:p=>s.watch(p?`${o}${p}`:o.slice(0,-1)),setValueItem:(p,d)=>s.setValue(`${o}${p}`,d),useSelectedItem:p=>s.useSelected(`${o}${p}`)};return _jsxruntime.jsx.call(void 0, _react2.default.Fragment,{children:_jsxruntime.jsx.call(void 0, S,{...l,children:N(i,l)})},c.id||m)})})};H.displayName="BgsFormArray";var Ae=H;var j=_react.createContext.call(void 0, void 0);function Re(){let r=_react.useContext.call(void 0, j);return r||{}}function B({children:r,...e}){return _jsxruntime.jsx.call(void 0, j.Provider,{value:e,children:r})}var J=_react.createContext.call(void 0, void 0);function O(){let r=_react.useContext.call(void 0, J);return r||{}}function v({children:r,...e}){return _jsxruntime.jsx.call(void 0, J.Provider,{value:e,children:r})}var _=_react.createContext.call(void 0, void 0);function Q(){let r=_react.useContext.call(void 0, _);return r||{}}function X({children:r,...e}){return _jsxruntime.jsx.call(void 0, _.Provider,{value:e,children:r})}function W({validationRules:r,label:e}){let{formControl:t,getData:i}=y(),a=[];return r&&(typeof r=="string"?Y(r,!0,e,t,i,{}).forEach(s=>a.push(s)):typeof r=="object"&&Object.keys(r).forEach(s=>{let{validate:c}=a.find(o=>o.validate)||{};if(["minLength","maxLength","min","max","match","diff","regexp","pattern","required","email"].includes(s)){let o=r[s],l="";if(s==="email"&&!o)return;["match","diff"].includes(s)&&typeof o=="object"&&(o=r[s].dataField,l=r[s].label),o!=null&&Y(s,o,e,t,i,c,l).forEach(p=>a.push(p))}else if(typeof r[s]=="object"){let o=r[s];a.push({validate:{...c,[s]:l=>o.validation(l)||o.message&&(typeof o.message=="string"?o.message:o.message(e))}})}})),Object.assign({},...a)}var Y=(r,e,t,i,a,s,c)=>{let m=[],{validationMessage:o}=Q(),{required:l,minLength:p,maxLength:d,min:u,max:g,email:x,match:b,diff:C,pattern:f}=o||{},A={required:{value:!!e,message:l?l(t):`${t} is required`},minLength:{value:e,message:p?p(t,e):`${t} must be at least ${e} characters long`},maxLength:{value:e,message:d?d(t,e):`${t} cannot be more than ${e} characters long`},min:{value:Number(e),message:u?u(t,e):`${t} should be at least ${e}`},max:{value:Number(e),message:g?g(t,e):`${t} should be at most ${e}`},regexp:(n="")=>n?new RegExp(e.regexp).test(n)||`${t} ${e.message}`:!0,email:(n="")=>n?n.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)||(x?x(t):`${t} must be type email`):!0,match:(n="")=>n?n===(a&&a(e))||(b?b(t,c||F.changeAll(e)):`${t} must be same with ${c||F.changeAll(e)}`):!0,diff:(n="")=>n?n!==(a&&a(e))||(C?C(t,c||F.changeAll(e)):`${t} must be different with ${c||F.changeAll(e)}`):!0,pattern:{alphabet:(n="")=>!!n&&new RegExp("^[A-Za-z ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _25 => _25.alphabet])?_optionalChain([f, 'optionalAccess', _26 => _26.alphabet, 'call', _27 => _27(t)]):`${t} must be format Alphabet`),alphanumber:(n="")=>!!n&&new RegExp("^[A-Za-z0-9 ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _28 => _28.alphanumber])?_optionalChain([f, 'optionalAccess', _29 => _29.alphanumber, 'call', _30 => _30(t)]):`${t} must be format Alphabet or Number`),number:(n="")=>!!n&&new RegExp("^[0-9]*$").test(n)||(_optionalChain([f, 'optionalAccess', _31 => _31.number])?_optionalChain([f, 'optionalAccess', _32 => _32.number, 'call', _33 => _33(t)]):`${t} must be format Number`),lowercase:(n="")=>!!n&&new RegExp("^[a-z0-9 ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _34 => _34.lowercase])?_optionalChain([f, 'optionalAccess', _35 => _35.lowercase, 'call', _36 => _36(t)]):`${t} must be format Lowercase`),url:(n="")=>!!n&&/^(ftp|http|https):\/\/[^ "]+$/.test(n)||(_optionalChain([f, 'optionalAccess', _37 => _37.url])?_optionalChain([f, 'optionalAccess', _38 => _38.url, 'call', _39 => _39(t)]):`${t} must be a valid URL`),uppercase:(n="")=>!!n&&new RegExp("^[A-Z0-9 ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _40 => _40.uppercase])?_optionalChain([f, 'optionalAccess', _41 => _41.uppercase, 'call', _42 => _42(t)]):`${t} must be format Uppercase`),mixedcase:(n="")=>!!n&&/[a-z]/.test(n)&&/[A-Z]/.test(n)||(_optionalChain([f, 'optionalAccess', _43 => _43.mixedcase])?_optionalChain([f, 'optionalAccess', _44 => _44.mixedcase, 'call', _45 => _45(t)]):`${t} must be mixed case`),specialcharacters:(n="")=>!!n&&/[^a-zA-Z0-9\s]/.test(n)||(_optionalChain([f, 'optionalAccess', _46 => _46.specialcharacters])?_optionalChain([f, 'optionalAccess', _47 => _47.specialcharacters, 'call', _48 => _48(t)]):`${t} must contain special characters`)}}[r];if(A){let{validate:n}=m.find(te=>te.validate)||{};typeof A=="function"?m.push({validate:{...n,...s,[r]:A}}):r==="pattern"?m.push({validate:{...n,...s,[`${r}${e}`]:A[e]}}):m.push({[r]:A})}return m};var Ne=({children:r,...e})=>{let t=_react.useMemo.call(void 0, ()=>h(),[]),{registerItem:i,unregisterItem:a,formControl:s,disabled:c,readOnly:m,formId:o}=y(),{name:l,formId:p,...d}=O(),{formId:u,name:g}=$();_react.useEffect.call(void 0, ()=>(i({id:t,...e}),()=>{a(t)}),[t,e]),!e.label&&!e.noLabel&&(e.label=F.changeAll(e.dataField)),g&&o===u&&(e.dataField=`${g}${e.dataField}`);let x=!1;typeof e.disabled=="boolean"?x=e.disabled:typeof d.disabled=="boolean"?x=d.disabled:x=!!c;let b=!1;typeof e.readOnly=="boolean"?b=e.readOnly:typeof d.readOnly=="boolean"?b=d.readOnly:b=!!m;let C=!1;return typeof e.hidden=="boolean"&&(C=e.hidden),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:s.control&&_jsxruntime.jsx.call(void 0, _reacthookform.Controller,{name:e.dataField,control:s.control,rules:x||b||C?{required:!1}:W(e),render:f=>_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, B,{...e,controller:f,children:r})})})})},De= exports.BgsController =Ne;var re=({children:r,...e})=>{let t=y(),i=_react.useMemo.call(void 0, ()=>h(),[]);return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, v,{...t,...e,formGroupId:i,children:r})})};re.displayName="BgsFormGroup";var Ee=re;var Me=(o=>(o.alphabet="alphabet",o.alphaNumber="alphanumber",o.number="number",o.lowercase="lowercase",o.url="url",o.uppercase="uppercase",o.mixedCase="mixedcase",o.specialCharacters="specialcharacters",o))(Me||{});var it=z;exports.BgsArrayForm = Ae; exports.BgsController = De; exports.BgsGroupForm = Ee; exports.BgsReactFormProvider = X; exports.PatternTypeEnum = Me; exports.default = it; exports.getFieldValue = U; exports.useBgsArrayForm = $; exports.useBgsControllerForm = Re; exports.useBgsForm = y; exports.useBgsGroupForm = O; exports.useControllerRhf = _reacthookform.useController; exports.useFormArrayInit = q; exports.useFormContextRhf = _reacthookform.useFormContext; exports.useFormInit = K;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _jsxruntime = require('react/jsx-runtime');var W=_react.createContext.call(void 0, void 0);function y(){let e=_react.useContext.call(void 0, W);return e||{}}function T({children:e,controller:r,onSubmit:t}){let a=_react.useRef.call(void 0, []),i=_react.useCallback.call(void 0, o=>{let p=a.current.findIndex(l=>l.id===o.id);if(p>-1){let l=[...a.current];l[p]=o,a.current=[...l]}else a.current.push(o)},[a]),s=_react.useCallback.call(void 0, o=>{a.current=a.current.filter(p=>p.id!==o)},[]),c=async(o,p)=>{r.setIsSubmit(!0);let l=p?await r.formControl.trigger():!0,d=r.getData();l&&t&&t({...d,...o},{...r})},m={...r,registerItem:i,unregisterItem:s,items:a.current,triggerSubmit:c};return _jsxruntime.jsx.call(void 0, W.Provider,{value:m,children:e})}function h(){let e=()=>Math.random()*16%16|0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>(r==="x"?e():e()&3|8).toString(16))}function k(e,r){return typeof e=="function"?e(r):e}var F={camelCase:(e="")=>(e=e.split(".").map(r=>(r=r.charAt(0).toUpperCase()+r.slice(1),r)).join(" "),e=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),e.charAt(0).toUpperCase()+e.slice(1)),snackCase:(e="")=>{let t=e.replace(/_([a-z])/g,(a,i)=>i.toUpperCase()).replace(/([A-Z])/g," $1");return t=t.charAt(0).toUpperCase()+t.slice(1),t},changeAll:(e="",r=!1)=>{let t="";try{e=_optionalChain([e, 'optionalAccess', _2 => _2.split, 'call', _3 => _3("."), 'access', _4 => _4[_optionalChain([e, 'optionalAccess', _5 => _5.split, 'call', _6 => _6("."), 'optionalAccess', _7 => _7.length])-1]]),e=_optionalChain([e, 'optionalAccess', _8 => _8.split, 'call', _9 => _9("[]"), 'access', _10 => _10[_optionalChain([e, 'optionalAccess', _11 => _11.split, 'call', _12 => _12("[]"), 'optionalAccess', _13 => _13.length])-1]]),t=F.snackCase(F.camelCase(e)),r&&(t=_optionalChain([t, 'optionalAccess', _14 => _14.split, 'call', _15 => _15(" "), 'optionalAccess', _16 => _16.map, 'call', _17 => _17(a=>_optionalChain([a, 'optionalAccess', _18 => _18.length])<=3?_optionalChain([a, 'optionalAccess', _19 => _19.toUpperCase, 'call', _20 => _20()]):a), 'optionalAccess', _21 => _21.join, 'call', _22 => _22(" ")]))}catch (e2){}return t}};function v(e,r){try{return JSON.stringify(e)!==JSON.stringify(r)}catch (e3){return!1}}var R=e=>(Object.keys(e).forEach(r=>{e[r]===void 0&&(e[r]=null)}),e),C= exports.getFieldValue =(e,r,t="")=>{if(!e)return t;if(e.hasOwnProperty(r))return e[r];let a=r.replace(/\[(\d+)\]/g,".$1").split("."),i=e;for(let s of a){if(i==null)return t;i=i[s]}return i===void 0?t:i};function N(e,r){let t=!1;return e&&typeof e=="object"&&Array.isArray(e)&&(typeof r=="number"?e.length>r&&(t=!0):t=!0),t}var _reacthookform = require('react-hook-form');var L=(e,r)=>{e||(e={});let t=_react.useRef.call(void 0, null),[a,i]=_react.useState.call(void 0, !1),[s,c]=_react.useState.call(void 0, {}),m=_reacthookform.useForm.call(void 0, {...r,reValidateMode:"onSubmit",mode:"all",defaultValues:e}),o=_react.useMemo.call(void 0, ()=>h(),[]),p=u=>u?C(R(m.getValues()),u):R(m.getValues()),d={...m,ref:t,reset:u=>{u?typeof u=="string"?m.resetField(u,{}):typeof u=="object"&&N(u,0)&&u.forEach(g=>m.resetField(g)):m.reset()},updateData:u=>{let g=p();m.reset({...g,...u})},getData:p,formControl:m,useFieldArray:u=>_reacthookform.useFieldArray.call(void 0, {control:m.control,name:u}),useWatch:u=>_reacthookform.useWatch.call(void 0, {control:m.control,name:u}),isSubmit:a,formId:o,setIsSubmit:i,useSelected:u=>C(s,u),setSelected:c,selected:s};return[d,d]};var le=({onSubmit:e,onChange:r=()=>{},onInvalid:t=()=>{},formData:a,controller:i,children:s,...c})=>{let m=_nullishCoalesce(i, () => (L())),[o]=Array.isArray(m)?m:[m],p=_react.useRef.call(void 0, void 0),l=async d=>{d.preventDefault(),d.stopPropagation(),o.setIsSubmit(!0);let u=await o.formControl.trigger(),g=o.getData();u?e&&e({...g},{...o}):t(o.formControl.formState.errors)};return _react.useEffect.call(void 0, ()=>{a&&v(p.current||{},a)&&(o.formControl.reset(a),p.current=a)},[a,o.formControl.reset]),_react.useEffect.call(void 0, ()=>{if(!r)return;let d=o.formControl.watch(r);return()=>d.unsubscribe()},[]),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, T,{controller:{...o,disabled:_optionalChain([c, 'optionalAccess', _23 => _23.disabled]),readOnly:_optionalChain([c, 'optionalAccess', _24 => _24.readOnly])},onSubmit:e,children:_jsxruntime.jsx.call(void 0, "form",{...c,id:o.formId,ref:o.ref,onSubmit:l,children:s})})})},K=le;var M=_react.createContext.call(void 0, void 0);function I(){let e=_react.useContext.call(void 0, M);return e||{}}function $({children:e,...r}){return _jsxruntime.jsx.call(void 0, M.Provider,{value:r,children:e})}var z=e=>{let r=y(),t=_reacthookform.useFieldArray.call(void 0, {control:r.control,name:e}),i={formArrayId:_react.useMemo.call(void 0, ()=>h(),[]),...t,...r};return[i,i]};var Z=({name:e,defaultData:r,controller:t,children:a})=>{let i=_nullishCoalesce(t, () => (z(e))),[s]=Array.isArray(i)?i:[i];return _react.useEffect.call(void 0, ()=>{typeof r=="boolean"&&r?s.append({}):typeof r=="number"&&r>0?s.append([...Array(r).fill(null).map(()=>({}))]):typeof r=="object"&&r&&s.append(r)},[]),_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:s.fields.map((c,m)=>{let o=`${e}.${m}.`,p={...s,index:m,name:o,countFields:s.fields.length,removeItem:()=>s.remove(m),watchItem:l=>s.watch(l?`${o}${l}`:o.slice(0,-1)),setValueItem:(l,d)=>s.setValue(`${o}${l}`,d),useSelectedItem:l=>s.useSelected(`${o}${l}`)};return _jsxruntime.jsx.call(void 0, _react2.default.Fragment,{children:_jsxruntime.jsx.call(void 0, $,{...p,children:k(a,p)})},c.id||m)})})};Z.displayName="BgsFormArray";var he=Z;var q=_react.createContext.call(void 0, void 0);function w(){let e=_react.useContext.call(void 0, q);return e||{}}function B({children:e,...r}){return _jsxruntime.jsx.call(void 0, q.Provider,{value:r,children:e})}var j=({children:e,...r})=>{let t=y(),a=_react.useMemo.call(void 0, ()=>h(),[]);return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:_jsxruntime.jsx.call(void 0, B,{...t,...r,formGroupId:a,children:e})})};j.displayName="BgsFormGroup";var Te=j;var J=_react.createContext.call(void 0, void 0);function _(){let e=_react.useContext.call(void 0, J);return e||{}}function Q({children:e,...r}){return _jsxruntime.jsx.call(void 0, J.Provider,{value:r,children:e})}function O({validationRules:e,label:r}){let{formControl:t,getData:a}=y(),i=[];return e&&(typeof e=="string"?X(e,!0,r,t,a,{}).forEach(s=>i.push(s)):typeof e=="object"&&Object.keys(e).forEach(s=>{let{validate:c}=i.find(o=>o.validate)||{};if(["minLength","maxLength","min","max","match","diff","regexp","pattern","required","email"].includes(s)){let o=e[s],p="";if(s==="email"&&!o)return;["match","diff"].includes(s)&&typeof o=="object"&&(o=e[s].dataField,p=e[s].label),o!=null&&X(s,o,r,t,a,c,p).forEach(l=>i.push(l))}else if(typeof e[s]=="object"){let o=e[s];i.push({validate:{...c,[s]:p=>o.validation(p)||o.message&&(typeof o.message=="string"?o.message:o.message(r))}})}})),Object.assign({},...i)}var X=(e,r,t,a,i,s,c)=>{let m=[],{validationMessage:o}=_(),{required:p,minLength:l,maxLength:d,min:u,max:g,email:x,match:b,diff:U,pattern:f}=o||{},A={required:{value:!!r,message:p?p(t):`${t} is required`},minLength:{value:r,message:l?l(t,r):`${t} must be at least ${r} characters long`},maxLength:{value:r,message:d?d(t,r):`${t} cannot be more than ${r} characters long`},min:{value:Number(r),message:u?u(t,r):`${t} should be at least ${r}`},max:{value:Number(r),message:g?g(t,r):`${t} should be at most ${r}`},regexp:(n="")=>n?new RegExp(r.regexp).test(n)||`${t} ${r.message}`:!0,email:(n="")=>n?n.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)||(x?x(t):`${t} must be type email`):!0,match:(n="")=>n?n===(i&&i(r))||(b?b(t,c||F.changeAll(r)):`${t} must be same with ${c||F.changeAll(r)}`):!0,diff:(n="")=>n?n!==(i&&i(r))||(U?U(t,c||F.changeAll(r)):`${t} must be different with ${c||F.changeAll(r)}`):!0,pattern:{alphabet:(n="")=>!!n&&new RegExp("^[A-Za-z ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _25 => _25.alphabet])?_optionalChain([f, 'optionalAccess', _26 => _26.alphabet, 'call', _27 => _27(t)]):`${t} must be format Alphabet`),alphanumber:(n="")=>!!n&&new RegExp("^[A-Za-z0-9 ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _28 => _28.alphanumber])?_optionalChain([f, 'optionalAccess', _29 => _29.alphanumber, 'call', _30 => _30(t)]):`${t} must be format Alphabet or Number`),number:(n="")=>!!n&&new RegExp("^[0-9]*$").test(n)||(_optionalChain([f, 'optionalAccess', _31 => _31.number])?_optionalChain([f, 'optionalAccess', _32 => _32.number, 'call', _33 => _33(t)]):`${t} must be format Number`),lowercase:(n="")=>!!n&&new RegExp("^[a-z0-9 ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _34 => _34.lowercase])?_optionalChain([f, 'optionalAccess', _35 => _35.lowercase, 'call', _36 => _36(t)]):`${t} must be format Lowercase`),url:(n="")=>!!n&&/^(ftp|http|https):\/\/[^ "]+$/.test(n)||(_optionalChain([f, 'optionalAccess', _37 => _37.url])?_optionalChain([f, 'optionalAccess', _38 => _38.url, 'call', _39 => _39(t)]):`${t} must be a valid URL`),uppercase:(n="")=>!!n&&new RegExp("^[A-Z0-9 ]*$").test(n)||(_optionalChain([f, 'optionalAccess', _40 => _40.uppercase])?_optionalChain([f, 'optionalAccess', _41 => _41.uppercase, 'call', _42 => _42(t)]):`${t} must be format Uppercase`),mixedcase:(n="")=>!!n&&/[a-z]/.test(n)&&/[A-Z]/.test(n)||(_optionalChain([f, 'optionalAccess', _43 => _43.mixedcase])?_optionalChain([f, 'optionalAccess', _44 => _44.mixedcase, 'call', _45 => _45(t)]):`${t} must be mixed case`),specialcharacters:(n="")=>!!n&&/[^a-zA-Z0-9\s]/.test(n)||(_optionalChain([f, 'optionalAccess', _46 => _46.specialcharacters])?_optionalChain([f, 'optionalAccess', _47 => _47.specialcharacters, 'call', _48 => _48(t)]):`${t} must contain special characters`)}}[e];if(A){let{validate:n}=m.find(Y=>Y.validate)||{};typeof A=="function"?m.push({validate:{...n,...s,[e]:A}}):e==="pattern"?m.push({validate:{...n,...s,[`${e}${r}`]:A[r]}}):m.push({[e]:A})}return m};var Er=e=>{let r=_react.useMemo.call(void 0, ()=>h(),[]),{registerItem:t,unregisterItem:a,formControl:i,disabled:s,readOnly:c,formId:m}=y(),{name:o,formId:p,...l}=w(),{formId:d,name:u}=I();_react.useEffect.call(void 0, ()=>(t({id:r,...e}),()=>{a(r)}),[r,e]),!e.label&&!e.noLabel&&(e.label=F.changeAll(e.dataField)),u&&m===d&&(e.dataField=`${u}${e.dataField}`);let g=!1;typeof e.disabled=="boolean"?g=e.disabled:typeof l.disabled=="boolean"?g=l.disabled:g=!!s;let x=!1;typeof e.readOnly=="boolean"?x=e.readOnly:typeof l.readOnly=="boolean"?x=l.readOnly:x=!!c;let b=!1;typeof e.hidden=="boolean"&&(b=e.hidden);let U=_reacthookform.useController.call(void 0, {name:e.dataField,control:i.control,disabled:g,defaultValue:e.defaultValue,rules:g||x||b?{required:!1}:O(e)});return{...e,controller:U}};var Oe=(o=>(o.alphabet="alphabet",o.alphaNumber="alphanumber",o.number="number",o.lowercase="lowercase",o.url="url",o.uppercase="uppercase",o.mixedCase="mixedcase",o.specialCharacters="specialcharacters",o))(Oe||{});var Zr=K;exports.BgsArrayForm = he; exports.BgsGroupForm = Te; exports.BgsReactFormProvider = Q; exports.PatternTypeEnum = Oe; exports.default = Zr; exports.getFieldValue = C; exports.useBgsArrayForm = I; exports.useBgsForm = y; exports.useBgsGroupForm = w; exports.useController = Er; exports.useFormArrayInit = z; exports.useFormInit = L;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode, PropsWithChildren } from 'react';
3
3
  import { DeepPartialSkipArrayKey, ControllerRenderProps, FieldValues, ControllerFieldState, UseFormStateReturn, UseFormReturn, UseFieldArrayReturn, EventType, FieldErrors, UseFieldArraySwap, UseFieldArrayMove, UseFieldArrayPrepend, UseFieldArrayAppend, UseFieldArrayRemove, UseFieldArrayInsert, UseFieldArrayUpdate, UseFieldArrayReplace, FieldArrayWithId, UseFormProps } from 'react-hook-form';
4
- export { useController as useControllerRhf, useFormContext as useFormContextRhf } from 'react-hook-form';
5
4
 
6
5
  type ControllerWithKey = ControllerProps & {
7
6
  id: string;
@@ -13,7 +12,7 @@ interface FormDefaultProps {
13
12
  }
14
13
  type Children<T = unknown> = ChildFunction<T> | React.ReactNode;
15
14
  type ChildFunction<T = unknown> = (props: T) => Children<T>;
16
- interface Controller$1 {
15
+ interface Controller {
17
16
  field: ControllerRenderProps<FieldValues, string>;
18
17
  fieldState: ControllerFieldState;
19
18
  formState: UseFormStateReturn<FieldValues>;
@@ -77,6 +76,7 @@ interface ControllerProps {
77
76
  disabled?: boolean;
78
77
  hidden?: boolean;
79
78
  readOnly?: boolean;
79
+ defaultValue?: any;
80
80
  }
81
81
  type PatternType = "alphabet" | "alphanumber" | "number" | "lowercase" | "url" | "uppercase" | "mixedcase" | "specialcharacters";
82
82
  declare enum PatternTypeEnum {
@@ -142,7 +142,7 @@ type UseFormArray<T> = UseFormArrayInitReturn<T> & {
142
142
  useSelectedItem: UseSelected<T>;
143
143
  };
144
144
  type UseController = ControllerProps & {
145
- controller: Controller$1;
145
+ controller: Controller;
146
146
  };
147
147
 
148
148
  declare const BgsForm: <T>({ onSubmit, onChange, onInvalid, formData, controller: controllerProps, children, ...others }: PropsWithChildren<FormProps<T>>) => react_jsx_runtime.JSX.Element;
@@ -152,8 +152,6 @@ declare const FormArray: {
152
152
  displayName: string;
153
153
  };
154
154
 
155
- declare const Controller: ({ children, ...props }: PropsWithChildren<ControllerProps>) => react_jsx_runtime.JSX.Element;
156
-
157
155
  declare const FormGroup: {
158
156
  ({ children, ...formProps }: PropsWithChildren<FormGroupProps>): react_jsx_runtime.JSX.Element;
159
157
  displayName: string;
@@ -161,8 +159,6 @@ declare const FormGroup: {
161
159
 
162
160
  declare function useFormArray<T = unknown>(): UseFormArray<T>;
163
161
 
164
- declare function useController<T = unknown>(): UseController & T;
165
-
166
162
  declare function useForm<T = unknown>(): UseBgsForm<T>;
167
163
 
168
164
  type UseFormGroup = FormGroupProps & UseFormInitReturn & {
@@ -199,6 +195,8 @@ declare const useFormInit: <T = unknown>(defaultValues?: Partial<T> | undefined,
199
195
 
200
196
  declare const useFormArrayInit: <T = unknown>(name: string) => UseFormArrayInitReturn<T>[];
201
197
 
198
+ declare const useController: (props: ControllerProps) => UseController;
199
+
202
200
  declare const getFieldValue: <T, P extends NestedKeyOf<T>, D = undefined>(obj: T, path: P, defaultValue?: D) => PathValue<T, P> | D;
203
201
 
204
- export { FormArray as BgsArrayForm, Controller as BgsController, FormGroup as BgsGroupForm, BgsReactFormProvider, type ControllerProps, type FormArrayProps, type FormGroupProps, type FormProps, type OnSubmit, type PatternType, PatternTypeEnum, type SelectedNested, type TriggerSubmit, type UseBgsForm, type UseController, type UseFormArray, type UseFormArrayInitReturn, type UseFormInitReturn, type UseSelected, type ValidationCallback, type ValidationOptions, type ValidationRules, BgsForm as default, getFieldValue, useFormArray as useBgsArrayForm, useController as useBgsControllerForm, useForm as useBgsForm, useFormGroup as useBgsGroupForm, useFormArrayInit, useFormInit };
202
+ export { FormArray as BgsArrayForm, FormGroup as BgsGroupForm, BgsReactFormProvider, type ControllerProps, type FormArrayProps, type FormGroupProps, type FormProps, type OnSubmit, type PatternType, PatternTypeEnum, type SelectedNested, type TriggerSubmit, type UseBgsForm, type UseController, type UseFormArray, type UseFormArrayInitReturn, type UseFormInitReturn, type UseSelected, type ValidationCallback, type ValidationOptions, type ValidationRules, BgsForm as default, getFieldValue, useFormArray as useBgsArrayForm, useForm as useBgsForm, useFormGroup as useBgsGroupForm, useController, useFormArrayInit, useFormInit };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode, PropsWithChildren } from 'react';
3
3
  import { DeepPartialSkipArrayKey, ControllerRenderProps, FieldValues, ControllerFieldState, UseFormStateReturn, UseFormReturn, UseFieldArrayReturn, EventType, FieldErrors, UseFieldArraySwap, UseFieldArrayMove, UseFieldArrayPrepend, UseFieldArrayAppend, UseFieldArrayRemove, UseFieldArrayInsert, UseFieldArrayUpdate, UseFieldArrayReplace, FieldArrayWithId, UseFormProps } from 'react-hook-form';
4
- export { useController as useControllerRhf, useFormContext as useFormContextRhf } from 'react-hook-form';
5
4
 
6
5
  type ControllerWithKey = ControllerProps & {
7
6
  id: string;
@@ -13,7 +12,7 @@ interface FormDefaultProps {
13
12
  }
14
13
  type Children<T = unknown> = ChildFunction<T> | React.ReactNode;
15
14
  type ChildFunction<T = unknown> = (props: T) => Children<T>;
16
- interface Controller$1 {
15
+ interface Controller {
17
16
  field: ControllerRenderProps<FieldValues, string>;
18
17
  fieldState: ControllerFieldState;
19
18
  formState: UseFormStateReturn<FieldValues>;
@@ -77,6 +76,7 @@ interface ControllerProps {
77
76
  disabled?: boolean;
78
77
  hidden?: boolean;
79
78
  readOnly?: boolean;
79
+ defaultValue?: any;
80
80
  }
81
81
  type PatternType = "alphabet" | "alphanumber" | "number" | "lowercase" | "url" | "uppercase" | "mixedcase" | "specialcharacters";
82
82
  declare enum PatternTypeEnum {
@@ -142,7 +142,7 @@ type UseFormArray<T> = UseFormArrayInitReturn<T> & {
142
142
  useSelectedItem: UseSelected<T>;
143
143
  };
144
144
  type UseController = ControllerProps & {
145
- controller: Controller$1;
145
+ controller: Controller;
146
146
  };
147
147
 
148
148
  declare const BgsForm: <T>({ onSubmit, onChange, onInvalid, formData, controller: controllerProps, children, ...others }: PropsWithChildren<FormProps<T>>) => react_jsx_runtime.JSX.Element;
@@ -152,8 +152,6 @@ declare const FormArray: {
152
152
  displayName: string;
153
153
  };
154
154
 
155
- declare const Controller: ({ children, ...props }: PropsWithChildren<ControllerProps>) => react_jsx_runtime.JSX.Element;
156
-
157
155
  declare const FormGroup: {
158
156
  ({ children, ...formProps }: PropsWithChildren<FormGroupProps>): react_jsx_runtime.JSX.Element;
159
157
  displayName: string;
@@ -161,8 +159,6 @@ declare const FormGroup: {
161
159
 
162
160
  declare function useFormArray<T = unknown>(): UseFormArray<T>;
163
161
 
164
- declare function useController<T = unknown>(): UseController & T;
165
-
166
162
  declare function useForm<T = unknown>(): UseBgsForm<T>;
167
163
 
168
164
  type UseFormGroup = FormGroupProps & UseFormInitReturn & {
@@ -199,6 +195,8 @@ declare const useFormInit: <T = unknown>(defaultValues?: Partial<T> | undefined,
199
195
 
200
196
  declare const useFormArrayInit: <T = unknown>(name: string) => UseFormArrayInitReturn<T>[];
201
197
 
198
+ declare const useController: (props: ControllerProps) => UseController;
199
+
202
200
  declare const getFieldValue: <T, P extends NestedKeyOf<T>, D = undefined>(obj: T, path: P, defaultValue?: D) => PathValue<T, P> | D;
203
201
 
204
- export { FormArray as BgsArrayForm, Controller as BgsController, FormGroup as BgsGroupForm, BgsReactFormProvider, type ControllerProps, type FormArrayProps, type FormGroupProps, type FormProps, type OnSubmit, type PatternType, PatternTypeEnum, type SelectedNested, type TriggerSubmit, type UseBgsForm, type UseController, type UseFormArray, type UseFormArrayInitReturn, type UseFormInitReturn, type UseSelected, type ValidationCallback, type ValidationOptions, type ValidationRules, BgsForm as default, getFieldValue, useFormArray as useBgsArrayForm, useController as useBgsControllerForm, useForm as useBgsForm, useFormGroup as useBgsGroupForm, useFormArrayInit, useFormInit };
202
+ export { FormArray as BgsArrayForm, FormGroup as BgsGroupForm, BgsReactFormProvider, type ControllerProps, type FormArrayProps, type FormGroupProps, type FormProps, type OnSubmit, type PatternType, PatternTypeEnum, type SelectedNested, type TriggerSubmit, type UseBgsForm, type UseController, type UseFormArray, type UseFormArrayInitReturn, type UseFormInitReturn, type UseSelected, type ValidationCallback, type ValidationOptions, type ValidationRules, BgsForm as default, getFieldValue, useFormArray as useBgsArrayForm, useForm as useBgsForm, useFormGroup as useBgsGroupForm, useController, useFormArrayInit, useFormInit };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{useEffect as M,useRef as de}from"react";import{createContext as oe,useCallback as G,useContext as ne,useRef as se}from"react";import{jsx as ie}from"react/jsx-runtime";var k=oe(void 0);function y(){let r=ne(k);return r||{}}function P({children:r,controller:e,onSubmit:t}){let i=se([]),a=G(o=>{let l=i.current.findIndex(p=>p.id===o.id);if(l>-1){let p=[...i.current];p[l]=o,i.current=[...p]}else i.current.push(o)},[i]),s=G(o=>{i.current=i.current.filter(l=>l.id!==o)},[]),c=async(o,l)=>{e.setIsSubmit(!0);let p=l?await e.formControl.trigger():!0,d=e.getData();p&&t&&t({...d,...o},{...e})},m={...e,registerItem:a,unregisterItem:s,items:i.current,triggerSubmit:c};return ie(k.Provider,{value:m,children:r})}function h(){let r=()=>Math.random()*16%16|0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>(e==="x"?r():r()&3|8).toString(16))}function N(r,e){return typeof r=="function"?r(e):r}var F={camelCase:(r="")=>(r=r.split(".").map(e=>(e=e.charAt(0).toUpperCase()+e.slice(1),e)).join(" "),r=r.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),r.charAt(0).toUpperCase()+r.slice(1)),snackCase:(r="")=>{let t=r.replace(/_([a-z])/g,(i,a)=>a.toUpperCase()).replace(/([A-Z])/g," $1");return t=t.charAt(0).toUpperCase()+t.slice(1),t},changeAll:(r="",e=!1)=>{let t="";try{r=r?.split(".")[r?.split(".")?.length-1],r=r?.split("[]")[r?.split("[]")?.length-1],t=F.snackCase(F.camelCase(r)),e&&(t=t?.split(" ")?.map(i=>i?.length<=3?i?.toUpperCase():i)?.join(" "))}catch{}return t}};function D(r,e){try{return JSON.stringify(r)!==JSON.stringify(e)}catch{return!1}}var R=r=>(Object.keys(r).forEach(e=>{r[e]===void 0&&(r[e]=null)}),r),U=(r,e,t="")=>{if(!r)return t;if(r.hasOwnProperty(e))return r[e];let i=e.replace(/\[(\d+)\]/g,".$1").split("."),a=r;for(let s of i){if(a==null)return t;a=a[s]}return a===void 0?t:a};function L(r,e){let t=!1;return r&&typeof r=="object"&&Array.isArray(r)&&(typeof e=="number"?r.length>e&&(t=!0):t=!0),t}import{useFieldArray as ae,useForm as me,useWatch as le}from"react-hook-form";import{useMemo as ue,useRef as pe,useState as E}from"react";var K=(r,e)=>{r||(r={});let t=pe(null),[i,a]=E(!1),[s,c]=E({}),m=me({...e,reValidateMode:"onSubmit",mode:"all",defaultValues:r}),o=ue(()=>h(),[]),l=u=>u?U(R(m.getValues()),u):R(m.getValues()),d={...m,ref:t,reset:u=>{u?typeof u=="string"?m.resetField(u,{}):typeof u=="object"&&L(u,0)&&u.forEach(g=>m.resetField(g)):m.reset()},updateData:u=>{let g=l();m.reset({...g,...u})},getData:l,formControl:m,useFieldArray:u=>ae({control:m.control,name:u}),useWatch:u=>le({control:m.control,name:u}),isSubmit:i,formId:o,setIsSubmit:a,useSelected:u=>U(s,u),setSelected:c,selected:s};return[d,d]};import{Fragment as fe,jsx as I}from"react/jsx-runtime";var ce=({onSubmit:r,onChange:e=()=>{},onInvalid:t=()=>{},formData:i,controller:a,children:s,...c})=>{let m=a??K(),[o]=Array.isArray(m)?m:[m],l=de(void 0),p=async d=>{d.preventDefault(),d.stopPropagation(),o.setIsSubmit(!0);let u=await o.formControl.trigger(),g=o.getData();u?r&&r({...g},{...o}):t(o.formControl.formState.errors)};return M(()=>{i&&D(l.current||{},i)&&(o.formControl.reset(i),l.current=i)},[i,o.formControl.reset]),M(()=>{if(!e)return;let d=o.formControl.watch(e);return()=>d.unsubscribe()},[]),I(fe,{children:I(P,{controller:{...o,disabled:c?.disabled,readOnly:c?.readOnly},onSubmit:r,children:I("form",{...c,id:o.formId,ref:o.ref,onSubmit:p,children:s})})})},z=ce;import be,{useEffect as Ce}from"react";import{createContext as ge,useContext as ye}from"react";import{jsx as Fe}from"react/jsx-runtime";var Z=ge(void 0);function $(){let r=ye(Z);return r||{}}function S({children:r,...e}){return Fe(Z.Provider,{value:e,children:r})}import{useFieldArray as he}from"react-hook-form";import{useMemo as xe}from"react";var q=r=>{let e=y(),t=he({control:e.control,name:r}),a={formArrayId:xe(()=>h(),[]),...t,...e};return[a,a]};import{Fragment as Ue,jsx as w}from"react/jsx-runtime";var H=({name:r,defaultData:e,controller:t,children:i})=>{let a=t??q(r),[s]=Array.isArray(a)?a:[a];return Ce(()=>{typeof e=="boolean"&&e?s.append({}):typeof e=="number"&&e>0?s.append([...Array(e).fill(null).map(()=>({}))]):typeof e=="object"&&e&&s.append(e)},[]),w(Ue,{children:s.fields.map((c,m)=>{let o=`${r}.${m}.`,l={...s,index:m,name:o,countFields:s.fields.length,removeItem:()=>s.remove(m),watchItem:p=>s.watch(p?`${o}${p}`:o.slice(0,-1)),setValueItem:(p,d)=>s.setValue(`${o}${p}`,d),useSelectedItem:p=>s.useSelected(`${o}${p}`)};return w(be.Fragment,{children:w(S,{...l,children:N(i,l)})},c.id||m)})})};H.displayName="BgsFormArray";var Ae=H;import{useEffect as We,useMemo as Ge}from"react";import{createContext as Te,useContext as Pe}from"react";import{jsx as Ie}from"react/jsx-runtime";var j=Te(void 0);function Re(){let r=Pe(j);return r||{}}function B({children:r,...e}){return Ie(j.Provider,{value:e,children:r})}import{Controller as ke}from"react-hook-form";import{createContext as $e,useContext as Se}from"react";import{jsx as we}from"react/jsx-runtime";var J=$e(void 0);function O(){let r=Se(J);return r||{}}function v({children:r,...e}){return we(J.Provider,{value:e,children:r})}import{createContext as Be,useContext as Oe}from"react";import{jsx as ve}from"react/jsx-runtime";var _=Be(void 0);function Q(){let r=Oe(_);return r||{}}function X({children:r,...e}){return ve(_.Provider,{value:e,children:r})}function W({validationRules:r,label:e}){let{formControl:t,getData:i}=y(),a=[];return r&&(typeof r=="string"?Y(r,!0,e,t,i,{}).forEach(s=>a.push(s)):typeof r=="object"&&Object.keys(r).forEach(s=>{let{validate:c}=a.find(o=>o.validate)||{};if(["minLength","maxLength","min","max","match","diff","regexp","pattern","required","email"].includes(s)){let o=r[s],l="";if(s==="email"&&!o)return;["match","diff"].includes(s)&&typeof o=="object"&&(o=r[s].dataField,l=r[s].label),o!=null&&Y(s,o,e,t,i,c,l).forEach(p=>a.push(p))}else if(typeof r[s]=="object"){let o=r[s];a.push({validate:{...c,[s]:l=>o.validation(l)||o.message&&(typeof o.message=="string"?o.message:o.message(e))}})}})),Object.assign({},...a)}var Y=(r,e,t,i,a,s,c)=>{let m=[],{validationMessage:o}=Q(),{required:l,minLength:p,maxLength:d,min:u,max:g,email:x,match:b,diff:C,pattern:f}=o||{},A={required:{value:!!e,message:l?l(t):`${t} is required`},minLength:{value:e,message:p?p(t,e):`${t} must be at least ${e} characters long`},maxLength:{value:e,message:d?d(t,e):`${t} cannot be more than ${e} characters long`},min:{value:Number(e),message:u?u(t,e):`${t} should be at least ${e}`},max:{value:Number(e),message:g?g(t,e):`${t} should be at most ${e}`},regexp:(n="")=>n?new RegExp(e.regexp).test(n)||`${t} ${e.message}`:!0,email:(n="")=>n?n.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)||(x?x(t):`${t} must be type email`):!0,match:(n="")=>n?n===(a&&a(e))||(b?b(t,c||F.changeAll(e)):`${t} must be same with ${c||F.changeAll(e)}`):!0,diff:(n="")=>n?n!==(a&&a(e))||(C?C(t,c||F.changeAll(e)):`${t} must be different with ${c||F.changeAll(e)}`):!0,pattern:{alphabet:(n="")=>!!n&&new RegExp("^[A-Za-z ]*$").test(n)||(f?.alphabet?f?.alphabet(t):`${t} must be format Alphabet`),alphanumber:(n="")=>!!n&&new RegExp("^[A-Za-z0-9 ]*$").test(n)||(f?.alphanumber?f?.alphanumber(t):`${t} must be format Alphabet or Number`),number:(n="")=>!!n&&new RegExp("^[0-9]*$").test(n)||(f?.number?f?.number(t):`${t} must be format Number`),lowercase:(n="")=>!!n&&new RegExp("^[a-z0-9 ]*$").test(n)||(f?.lowercase?f?.lowercase(t):`${t} must be format Lowercase`),url:(n="")=>!!n&&/^(ftp|http|https):\/\/[^ "]+$/.test(n)||(f?.url?f?.url(t):`${t} must be a valid URL`),uppercase:(n="")=>!!n&&new RegExp("^[A-Z0-9 ]*$").test(n)||(f?.uppercase?f?.uppercase(t):`${t} must be format Uppercase`),mixedcase:(n="")=>!!n&&/[a-z]/.test(n)&&/[A-Z]/.test(n)||(f?.mixedcase?f?.mixedcase(t):`${t} must be mixed case`),specialcharacters:(n="")=>!!n&&/[^a-zA-Z0-9\s]/.test(n)||(f?.specialcharacters?f?.specialcharacters(t):`${t} must contain special characters`)}}[r];if(A){let{validate:n}=m.find(te=>te.validate)||{};typeof A=="function"?m.push({validate:{...n,...s,[r]:A}}):r==="pattern"?m.push({validate:{...n,...s,[`${r}${e}`]:A[e]}}):m.push({[r]:A})}return m};import{Fragment as V,jsx as T}from"react/jsx-runtime";var Ne=({children:r,...e})=>{let t=Ge(()=>h(),[]),{registerItem:i,unregisterItem:a,formControl:s,disabled:c,readOnly:m,formId:o}=y(),{name:l,formId:p,...d}=O(),{formId:u,name:g}=$();We(()=>(i({id:t,...e}),()=>{a(t)}),[t,e]),!e.label&&!e.noLabel&&(e.label=F.changeAll(e.dataField)),g&&o===u&&(e.dataField=`${g}${e.dataField}`);let x=!1;typeof e.disabled=="boolean"?x=e.disabled:typeof d.disabled=="boolean"?x=d.disabled:x=!!c;let b=!1;typeof e.readOnly=="boolean"?b=e.readOnly:typeof d.readOnly=="boolean"?b=d.readOnly:b=!!m;let C=!1;return typeof e.hidden=="boolean"&&(C=e.hidden),T(V,{children:s.control&&T(ke,{name:e.dataField,control:s.control,rules:x||b||C?{required:!1}:W(e),render:f=>T(V,{children:T(B,{...e,controller:f,children:r})})})})},De=Ne;import{useMemo as Le}from"react";import{Fragment as Ke,jsx as ee}from"react/jsx-runtime";var re=({children:r,...e})=>{let t=y(),i=Le(()=>h(),[]);return ee(Ke,{children:ee(v,{...t,...e,formGroupId:i,children:r})})};re.displayName="BgsFormGroup";var Ee=re;var Me=(o=>(o.alphabet="alphabet",o.alphaNumber="alphanumber",o.number="number",o.lowercase="lowercase",o.url="url",o.uppercase="uppercase",o.mixedCase="mixedcase",o.specialCharacters="specialcharacters",o))(Me||{});import{useController as Ct,useFormContext as At}from"react-hook-form";var it=z;export{Ae as BgsArrayForm,De as BgsController,Ee as BgsGroupForm,X as BgsReactFormProvider,Me as PatternTypeEnum,it as default,U as getFieldValue,$ as useBgsArrayForm,Re as useBgsControllerForm,y as useBgsForm,O as useBgsGroupForm,Ct as useControllerRhf,q as useFormArrayInit,At as useFormContextRhf,K as useFormInit};
1
+ import{useEffect as E,useRef as me}from"react";import{createContext as V,useCallback as G,useContext as ee,useRef as re}from"react";import{jsx as te}from"react/jsx-runtime";var W=V(void 0);function y(){let e=ee(W);return e||{}}function T({children:e,controller:r,onSubmit:t}){let a=re([]),i=G(o=>{let p=a.current.findIndex(l=>l.id===o.id);if(p>-1){let l=[...a.current];l[p]=o,a.current=[...l]}else a.current.push(o)},[a]),s=G(o=>{a.current=a.current.filter(p=>p.id!==o)},[]),c=async(o,p)=>{r.setIsSubmit(!0);let l=p?await r.formControl.trigger():!0,d=r.getData();l&&t&&t({...d,...o},{...r})},m={...r,registerItem:i,unregisterItem:s,items:a.current,triggerSubmit:c};return te(W.Provider,{value:m,children:e})}function h(){let e=()=>Math.random()*16%16|0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>(r==="x"?e():e()&3|8).toString(16))}function k(e,r){return typeof e=="function"?e(r):e}var F={camelCase:(e="")=>(e=e.split(".").map(r=>(r=r.charAt(0).toUpperCase()+r.slice(1),r)).join(" "),e=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"),e.charAt(0).toUpperCase()+e.slice(1)),snackCase:(e="")=>{let t=e.replace(/_([a-z])/g,(a,i)=>i.toUpperCase()).replace(/([A-Z])/g," $1");return t=t.charAt(0).toUpperCase()+t.slice(1),t},changeAll:(e="",r=!1)=>{let t="";try{e=e?.split(".")[e?.split(".")?.length-1],e=e?.split("[]")[e?.split("[]")?.length-1],t=F.snackCase(F.camelCase(e)),r&&(t=t?.split(" ")?.map(a=>a?.length<=3?a?.toUpperCase():a)?.join(" "))}catch{}return t}};function v(e,r){try{return JSON.stringify(e)!==JSON.stringify(r)}catch{return!1}}var R=e=>(Object.keys(e).forEach(r=>{e[r]===void 0&&(e[r]=null)}),e),C=(e,r,t="")=>{if(!e)return t;if(e.hasOwnProperty(r))return e[r];let a=r.replace(/\[(\d+)\]/g,".$1").split("."),i=e;for(let s of a){if(i==null)return t;i=i[s]}return i===void 0?t:i};function N(e,r){let t=!1;return e&&typeof e=="object"&&Array.isArray(e)&&(typeof r=="number"?e.length>r&&(t=!0):t=!0),t}import{useFieldArray as oe,useForm as ne,useWatch as se}from"react-hook-form";import{useMemo as ae,useRef as ie,useState as D}from"react";var L=(e,r)=>{e||(e={});let t=ie(null),[a,i]=D(!1),[s,c]=D({}),m=ne({...r,reValidateMode:"onSubmit",mode:"all",defaultValues:e}),o=ae(()=>h(),[]),p=u=>u?C(R(m.getValues()),u):R(m.getValues()),d={...m,ref:t,reset:u=>{u?typeof u=="string"?m.resetField(u,{}):typeof u=="object"&&N(u,0)&&u.forEach(g=>m.resetField(g)):m.reset()},updateData:u=>{let g=p();m.reset({...g,...u})},getData:p,formControl:m,useFieldArray:u=>oe({control:m.control,name:u}),useWatch:u=>se({control:m.control,name:u}),isSubmit:a,formId:o,setIsSubmit:i,useSelected:u=>C(s,u),setSelected:c,selected:s};return[d,d]};import{Fragment as ue,jsx as P}from"react/jsx-runtime";var le=({onSubmit:e,onChange:r=()=>{},onInvalid:t=()=>{},formData:a,controller:i,children:s,...c})=>{let m=i??L(),[o]=Array.isArray(m)?m:[m],p=me(void 0),l=async d=>{d.preventDefault(),d.stopPropagation(),o.setIsSubmit(!0);let u=await o.formControl.trigger(),g=o.getData();u?e&&e({...g},{...o}):t(o.formControl.formState.errors)};return E(()=>{a&&v(p.current||{},a)&&(o.formControl.reset(a),p.current=a)},[a,o.formControl.reset]),E(()=>{if(!r)return;let d=o.formControl.watch(r);return()=>d.unsubscribe()},[]),P(ue,{children:P(T,{controller:{...o,disabled:c?.disabled,readOnly:c?.readOnly},onSubmit:e,children:P("form",{...c,id:o.formId,ref:o.ref,onSubmit:l,children:s})})})},K=le;import ye,{useEffect as Fe}from"react";import{createContext as pe,useContext as ce}from"react";import{jsx as de}from"react/jsx-runtime";var M=pe(void 0);function I(){let e=ce(M);return e||{}}function $({children:e,...r}){return de(M.Provider,{value:r,children:e})}import{useFieldArray as fe}from"react-hook-form";import{useMemo as ge}from"react";var z=e=>{let r=y(),t=fe({control:r.control,name:e}),i={formArrayId:ge(()=>h(),[]),...t,...r};return[i,i]};import{Fragment as xe,jsx as S}from"react/jsx-runtime";var Z=({name:e,defaultData:r,controller:t,children:a})=>{let i=t??z(e),[s]=Array.isArray(i)?i:[i];return Fe(()=>{typeof r=="boolean"&&r?s.append({}):typeof r=="number"&&r>0?s.append([...Array(r).fill(null).map(()=>({}))]):typeof r=="object"&&r&&s.append(r)},[]),S(xe,{children:s.fields.map((c,m)=>{let o=`${e}.${m}.`,p={...s,index:m,name:o,countFields:s.fields.length,removeItem:()=>s.remove(m),watchItem:l=>s.watch(l?`${o}${l}`:o.slice(0,-1)),setValueItem:(l,d)=>s.setValue(`${o}${l}`,d),useSelectedItem:l=>s.useSelected(`${o}${l}`)};return S(ye.Fragment,{children:S($,{...p,children:k(a,p)})},c.id||m)})})};Z.displayName="BgsFormArray";var he=Z;import{useMemo as Ce}from"react";import{createContext as be,useContext as Ae}from"react";import{jsx as Ue}from"react/jsx-runtime";var q=be(void 0);function w(){let e=Ae(q);return e||{}}function B({children:e,...r}){return Ue(q.Provider,{value:r,children:e})}import{Fragment as Re,jsx as H}from"react/jsx-runtime";var j=({children:e,...r})=>{let t=y(),a=Ce(()=>h(),[]);return H(Re,{children:H(B,{...t,...r,formGroupId:a,children:e})})};j.displayName="BgsFormGroup";var Te=j;import{createContext as Pe,useContext as Ie}from"react";import{jsx as $e}from"react/jsx-runtime";var J=Pe(void 0);function _(){let e=Ie(J);return e||{}}function Q({children:e,...r}){return $e(J.Provider,{value:r,children:e})}import{useEffect as Se,useMemo as we}from"react";import{useController as Be}from"react-hook-form";function O({validationRules:e,label:r}){let{formControl:t,getData:a}=y(),i=[];return e&&(typeof e=="string"?X(e,!0,r,t,a,{}).forEach(s=>i.push(s)):typeof e=="object"&&Object.keys(e).forEach(s=>{let{validate:c}=i.find(o=>o.validate)||{};if(["minLength","maxLength","min","max","match","diff","regexp","pattern","required","email"].includes(s)){let o=e[s],p="";if(s==="email"&&!o)return;["match","diff"].includes(s)&&typeof o=="object"&&(o=e[s].dataField,p=e[s].label),o!=null&&X(s,o,r,t,a,c,p).forEach(l=>i.push(l))}else if(typeof e[s]=="object"){let o=e[s];i.push({validate:{...c,[s]:p=>o.validation(p)||o.message&&(typeof o.message=="string"?o.message:o.message(r))}})}})),Object.assign({},...i)}var X=(e,r,t,a,i,s,c)=>{let m=[],{validationMessage:o}=_(),{required:p,minLength:l,maxLength:d,min:u,max:g,email:x,match:b,diff:U,pattern:f}=o||{},A={required:{value:!!r,message:p?p(t):`${t} is required`},minLength:{value:r,message:l?l(t,r):`${t} must be at least ${r} characters long`},maxLength:{value:r,message:d?d(t,r):`${t} cannot be more than ${r} characters long`},min:{value:Number(r),message:u?u(t,r):`${t} should be at least ${r}`},max:{value:Number(r),message:g?g(t,r):`${t} should be at most ${r}`},regexp:(n="")=>n?new RegExp(r.regexp).test(n)||`${t} ${r.message}`:!0,email:(n="")=>n?n.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)||(x?x(t):`${t} must be type email`):!0,match:(n="")=>n?n===(i&&i(r))||(b?b(t,c||F.changeAll(r)):`${t} must be same with ${c||F.changeAll(r)}`):!0,diff:(n="")=>n?n!==(i&&i(r))||(U?U(t,c||F.changeAll(r)):`${t} must be different with ${c||F.changeAll(r)}`):!0,pattern:{alphabet:(n="")=>!!n&&new RegExp("^[A-Za-z ]*$").test(n)||(f?.alphabet?f?.alphabet(t):`${t} must be format Alphabet`),alphanumber:(n="")=>!!n&&new RegExp("^[A-Za-z0-9 ]*$").test(n)||(f?.alphanumber?f?.alphanumber(t):`${t} must be format Alphabet or Number`),number:(n="")=>!!n&&new RegExp("^[0-9]*$").test(n)||(f?.number?f?.number(t):`${t} must be format Number`),lowercase:(n="")=>!!n&&new RegExp("^[a-z0-9 ]*$").test(n)||(f?.lowercase?f?.lowercase(t):`${t} must be format Lowercase`),url:(n="")=>!!n&&/^(ftp|http|https):\/\/[^ "]+$/.test(n)||(f?.url?f?.url(t):`${t} must be a valid URL`),uppercase:(n="")=>!!n&&new RegExp("^[A-Z0-9 ]*$").test(n)||(f?.uppercase?f?.uppercase(t):`${t} must be format Uppercase`),mixedcase:(n="")=>!!n&&/[a-z]/.test(n)&&/[A-Z]/.test(n)||(f?.mixedcase?f?.mixedcase(t):`${t} must be mixed case`),specialcharacters:(n="")=>!!n&&/[^a-zA-Z0-9\s]/.test(n)||(f?.specialcharacters?f?.specialcharacters(t):`${t} must contain special characters`)}}[e];if(A){let{validate:n}=m.find(Y=>Y.validate)||{};typeof A=="function"?m.push({validate:{...n,...s,[e]:A}}):e==="pattern"?m.push({validate:{...n,...s,[`${e}${r}`]:A[r]}}):m.push({[e]:A})}return m};var Er=e=>{let r=we(()=>h(),[]),{registerItem:t,unregisterItem:a,formControl:i,disabled:s,readOnly:c,formId:m}=y(),{name:o,formId:p,...l}=w(),{formId:d,name:u}=I();Se(()=>(t({id:r,...e}),()=>{a(r)}),[r,e]),!e.label&&!e.noLabel&&(e.label=F.changeAll(e.dataField)),u&&m===d&&(e.dataField=`${u}${e.dataField}`);let g=!1;typeof e.disabled=="boolean"?g=e.disabled:typeof l.disabled=="boolean"?g=l.disabled:g=!!s;let x=!1;typeof e.readOnly=="boolean"?x=e.readOnly:typeof l.readOnly=="boolean"?x=l.readOnly:x=!!c;let b=!1;typeof e.hidden=="boolean"&&(b=e.hidden);let U=Be({name:e.dataField,control:i.control,disabled:g,defaultValue:e.defaultValue,rules:g||x||b?{required:!1}:O(e)});return{...e,controller:U}};var Oe=(o=>(o.alphabet="alphabet",o.alphaNumber="alphanumber",o.number="number",o.lowercase="lowercase",o.url="url",o.uppercase="uppercase",o.mixedCase="mixedcase",o.specialCharacters="specialcharacters",o))(Oe||{});var Zr=K;export{he as BgsArrayForm,Te as BgsGroupForm,Q as BgsReactFormProvider,Oe as PatternTypeEnum,Zr as default,C as getFieldValue,I as useBgsArrayForm,y as useBgsForm,w as useBgsGroupForm,Er as useController,z as useFormArrayInit,L as useFormInit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bgscore/react-form",
3
- "version": "0.0.23",
3
+ "version": "0.0.25",
4
4
  "description": "React form component library using context and react-hook-form with dynamic arrays, groups, and validations.",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",