@fluig-kit/ecm 1.0.18 → 1.0.20

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,Symbol.toStringTag,{value:"Module"});const g=require("react/jsx-runtime"),l=require("react"),F=require("react-hook-form"),j=require("@hookform/resolvers"),W=require("zod"),w=require("@fluig-kit/core");var Y=function(e,o){for(var r={};e.length;){var n=e[0],a=n.code,c=n.message,s=n.path.join(".");if(!r[s])if("unionErrors"in n){var i=n.unionErrors[0].errors[0];r[s]={message:i.message,type:i.code}}else r[s]={message:c,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(v){return v.errors.forEach(function(d){return e.push(d)})}),o){var u=r[s].types,t=u&&u[n.code];r[s]=F.appendErrors(s,o,r,a,t?[].concat(t,n.message):n.message)}e.shift()}return r},U=function(e,o,r){return r===void 0&&(r={}),function(n,a,c){try{return Promise.resolve(function(s,i){try{var u=Promise.resolve(e[r.mode==="sync"?"parse":"parseAsync"](n,o)).then(function(t){return c.shouldUseNativeValidation&&j.validateFieldsNatively({},c),{errors:{},values:r.raw?n:t}})}catch(t){return i(t)}return u&&u.then?u.then(void 0,i):u}(0,function(s){if(function(i){return Array.isArray(i==null?void 0:i.errors)}(s))return{values:{},errors:j.toNestErrors(Y(s.errors,!c.shouldUseNativeValidation&&c.criteriaMode==="all"),c)};throw s}))}catch(s){return Promise.reject(s)}}};const O=l.createContext(null);function B({children:e,baseSchema:o}){const[r,n]=l.useState([]),a=l.useMemo(()=>o??W.z.object({}),[o]),c=l.useCallback((t,v)=>{n(d=>d.some(A=>A.id===t)?d:[...d,{id:t,schema:v}])},[]),s=l.useCallback(t=>{n(v=>v.some(d=>d.id===t)?v.filter(d=>d.id!==t):v)},[]),i=l.useMemo(()=>r.length?r.map(t=>t.schema).reduce((t,v)=>t.and(v),a):a,[r,a]),u=l.useMemo(()=>({registerSchema:c,unregisterSchema:s,mergedSchema:i}),[c,s,i]);return g.jsx(O.Provider,{value:u,children:e})}function T(){const e=l.useContext(O);if(!e)throw new Error("useSchemaRegistry deve ser usado dentro de <SchemaRegistryProvider>");return e}function N(e){return typeof e=="number"?e:isNaN(Number(e))?null:Number(e)}function L(e,o,r){if(!e)return!0;const n=Array.isArray(o)?o[0]:o,a=e.field??n,c=r==null?void 0:r[a];return e.hasValue!==void 0?e.hasValue?c!=null&&c!=="":c==null||c==="":e.equals!==void 0?c===e.equals:e.notEquals!==void 0?c!==e.notEquals:!0}function G(e,o,r,n,a){const c=new Set(e),s=new Set(o);return r==null||r.forEach(i=>{if(i.from!==void 0){const t=Array.isArray(i.from)?i.from:[i.from];if(n===null||!t.includes(n))return}if(!L(i.when,i.target,a))return;const u=Array.isArray(i.target)?i.target:[i.target];switch(i.type){case"readonly":u.forEach(t=>{s.add(t),c.delete(t)});break;case"active":u.forEach(t=>{c.add(t),s.delete(t)});break;case"hidden":u.forEach(t=>{c.delete(t),s.delete(t)});break}}),{active:Array.from(c),readonly:Array.from(s)}}function z(e,o,r,n){const a=new Set(e.active),c=new Set(e.readonly),s=new Set(e.hidden??[]);return o==null||o.forEach(i=>{if(i.from!==void 0){const t=Array.isArray(i.from)?i.from:[i.from];if(r===null||!t.includes(r))return}if(!L(i.when,i.target,n))return;const u=Array.isArray(i.target)?i.target:[i.target];switch(i.type){case"hidden":u.forEach(t=>{s.add(t),a.delete(t),c.delete(t)});break;case"active":u.forEach(t=>{a.add(t),c.delete(t),s.delete(t)});break;case"readonly":u.forEach(t=>{c.add(t),a.delete(t),s.delete(t)});break}}),{active:Array.from(a),readonly:Array.from(c),hidden:Array.from(s)}}function H(e,o){if(!(e!=null&&e.length))return o;const r=new Map(o.map(a=>[a.name,a])),n=[];return e.forEach(a=>{r.has(a)&&(n.push(r.get(a)),r.delete(a))}),r.forEach(a=>n.push(a)),n}function $(e){var n,a;const o=new Set,r=(c=[])=>{c.forEach(s=>{var i;s.target&&(Array.isArray(s.target)?s.target:[s.target]).forEach(t=>o.add(t)),(i=s.when)!=null&&i.field&&o.add(s.when.field)})};return r((n=e==null?void 0:e.fields)==null?void 0:n.rules),r((a=e==null?void 0:e.sections)==null?void 0:a.rules),Array.from(o)}function K({activityId:e,previousActivityId:o,control:r,workflowStructure:n,sectionsRegistry:a}){const{registerSchema:c,unregisterSchema:s}=T(),i=N(e),u=N(o),t=i!==null?n[i]:null,v=l.useMemo(()=>$(t),[i,t]),d=F.useWatch({control:r,name:v,defaultValue:{}}),A=l.useMemo(()=>{const m={};return v.forEach((f,h)=>{m[f]=Array.isArray(d)?d[h]:d}),m},[d,v]),y=l.useMemo(()=>{if(!t)return{sections:[],fields:{active:[],readonly:[],hidden:[]}};const m=G(t.sections.active,t.sections.readonly,t.sections.rules,u,A);let f=[...m.readonly.map(b=>({name:b,mode:"readonly"})),...m.active.map(b=>({name:b,mode:"active"}))];f=H(t.sections.order,f);const h=z({active:t.fields.active,readonly:t.fields.readonly,hidden:t.fields.hidden},t.fields.rules,u,A);return{sections:f,fields:h}},[t,u,A,a]);return l.useEffect(()=>{const m=y.sections.filter(f=>f.mode==="active").map(f=>f.name);m.forEach(f=>{var b;const h=(b=a==null?void 0:a[f])==null?void 0:b.schema;h&&c(f,h)}),Object.keys(a??{}).filter(f=>!m.includes(f)).forEach(s)},[y.sections,a,c,s]),y}const J=l.createContext(null);function I(){const e=l.useContext(J);if(!e)throw new Error("useFluigRuntime deve ser usado dentro de <FluigRuntimeProvider>");return e}function Q(e){const{activityId:o,previousActivityId:r}=I();l.useEffect(()=>{o!=null&&e.setValue("CURRENTACTIVITYID",o),r!=null&&e.setValue("LASTACTIVITYID",r)},[o,r,e]),l.useEffect(()=>{if(typeof window>"u"||!window.top)return;const n=window.top.document,a=c=>{const s=c.target;(s.closest("[data-take-decision]")||s.closest("[data-take-task]")||s.closest(".movement-button"))&&(console.log("[FluigLifecycle] Ação de movimentação detectada. Ativando modo Edição."),e.setValue("FORM_MODE","MOD"))};return n.addEventListener("click",a),()=>{n.removeEventListener("click",a)}},[e]),l.useEffect(()=>{var a,c;if(typeof window>"u")return;const n=((a=window.top)==null?void 0:a.document.getElementById("send-process-button"))||((c=window.parent)==null?void 0:c.document.getElementById("workflow-actions-send"))||document.getElementById("send-process-button");if(!n){console.warn("[FluigWorkflowReact] Botão de envio do Fluig não encontrado. A validação automática pode falhar.");return}return window.beforeSendValidate=()=>(e.handleSubmit(()=>{window.top.__FLUIG_REACT_FORM_DATA__=e.getValues(),e.setValue("FORM_MODE","VIEW"),window.beforeSendValidate=()=>!0;try{n.dispatchEvent(new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0}))}catch{n.click()}},s=>{var i,u,t;console.error("[Validation Errors]",s),(u=(i=window.top)==null?void 0:i.FLUIGC)!=null&&u.toast?(t=window.top)==null||t.FLUIGC.toast({title:"Atenção",message:"Verifique os campos obrigatórios destacados em vermelho.",type:"danger"}):alert("Verifique os campos obrigatórios.")})(),!1),()=>{}},[e])}const X=({workflowStructure:e,sectionsRegistry:o,className:r})=>{const{control:n,handleSubmit:a,register:c,setValue:s,watch:i}=F.useFormContext(),u=I(),t=i("FORM_MODE"),v=l.useRef(!1);l.useEffect(()=>{v.current||(u.activityId!=null&&s("CURRENTACTIVITYID",u.activityId),u.previousActivityId!=null&&s("LASTACTIVITYID",u.previousActivityId),v.current=!0)},[u,s]);const{sections:d,fields:A}=K({control:n,activityId:u.activityId,previousActivityId:u.previousActivityId,workflowStructure:e,sectionsRegistry:o}),y=m=>{console.log("✅ [FluigWorkflowForm] Dados válidos:",m)};return g.jsxs("form",{id:"fluig-react-form",className:r,onSubmit:a(y),noValidate:!0,children:[g.jsxs("div",{className:"hidden",style:{display:"none"},children:[g.jsx("input",{type:"hidden",...c("CURRENTACTIVITYID")}),g.jsx("input",{type:"hidden",...c("LASTACTIVITYID")}),g.jsx("input",{type:"hidden",...c("FORM_MODE")})]}),d.length===0&&u.activityId!==null&&g.jsxs("p",{children:["Não foi possível encontrar a atividade: ",String(u.activityId)]}),d.map(({name:m,mode:f})=>{if(f==="hidden")return null;const h=o[m];if(!h)return null;const b=h.Component,k=t==="VIEW";return g.jsx(b,{id:m,fields:A,readOnly:f==="readonly"||k},m)}),u.isDev&&u.showDebugSubmit&&g.jsx("div",{style:{width:"100%",padding:"16px",paddingTop:"0"},children:g.jsx("button",{type:"submit",className:"btn btn-primary btn-lg btn-block",children:"Submit (Debug)"})})]})},Z=e=>{const{mergedSchema:o}=T(),r=I(),n=F.useForm({resolver:o?U(o):void 0,defaultValues:r.prefilledValues,mode:"onBlur"});return Q(n),l.useEffect(()=>{r.showDebugLogs&&(w.DebugLogger.header("Form Initialized"),w.DebugLogger.table("Prefilled Values (DOM Capture)",r.prefilledValues),w.DebugLogger.info("RHF Current Values",n.getValues()),w.DebugLogger.end())},[r.showDebugLogs,r.prefilledValues,n]),g.jsx(F.FormProvider,{...n,children:g.jsx(X,{...e})})};async function ee(e){if(!e)return console.warn("[setFluigNextActivity] Nenhuma atividade informada."),!1;const{wfView:o,wkfView:r}=await te();if(!o||!r)return!1;re(o);const n=Number(e),a=ne(o,n);return a?(oe(o,r,a,n),console.log(`[setFluigNextActivity] Próxima atividade definida: ${n}`),!0):(console.warn(`[setFluigNextActivity] Estado ${n} não encontrado nas próximas atividades disponíveis.`),console.log("Estados disponíveis:",o.availableStatesCOPY||o.availableStates),!1)}async function te(){const e=await w.parentProxy.top.ECM.workflowView,o=await w.parentProxy.top.ECM_WKFView;return!e||!o?(console.warn("[setFluigNextActivity] Contexto Fluig inválido ou não carregado."),{}):{wfView:e,wkfView:o}}function re(e){e.availableStatesCOPY||(e.availableStatesCOPY=e.availableStates)}function ne(e,o){const r=e.availableStatesCOPY||e.availableStates;return r==null?void 0:r.find(n=>n.sequence===o)}function oe(e,o,r,n){e.availableUsers.users=[],e.availableStates=[r],o.selectActivity=()=>n}const _=l.createContext(null);function ie(){const e=l.useContext(_);if(!e)throw new Error("useSection deve ser usado dentro de um componente <Section>");return e}function se({id:e,className:o,schema:r,children:n,form:a,prefilledValues:c,readOnly:s,fields:i={},hidden:u=!1}){const{isView:t,activityId:v}=I(),d=v,A=F.useFormContext(),y=a||A;if(!y)return console.error(`[FluigWorkflowReact] Section "${e}" não encontrou o 'form'.`),null;if(u)return null;const m=l.useCallback(p=>{var S,C,V;return(S=i.hidden)!=null&&S.includes(p)?"hidden":(C=i.readonly)!=null&&C.includes(p)?"readonly":(V=i.active)!=null&&V.includes(p)?"active":s?"readonly":"active"},[i,s]),f=l.useCallback(p=>m(p)==="hidden",[m]),h=l.useCallback(p=>m(p)==="readonly",[m]),b=l.useCallback(p=>{if(!p)return;const S=y.getValues("CURRENTACTIVITYID");y.setValue("LASTACTIVITYID",S),y.setValue("CURRENTACTIVITYID",d),ee(Number(p))},[y,d]);l.useEffect(()=>{if(!t||!c||!r||!y)return;const p=y.getValues(),S=r.shape;S&&Object.entries(S).forEach(([C,V])=>{var M,P;let E=V;for(;(M=E==null?void 0:E._def)!=null&&M.schema;)E=E._def.schema;const x=(P=E==null?void 0:E._def)==null?void 0:P.fluig;if((x==null?void 0:x.type)!=="options"||!Array.isArray(x.values)||p[C]!==void 0)return;const D={};x.values.forEach(R=>{D[R]=c[R]==="on"}),y.setValue(C,D,{shouldDirty:!1,shouldValidate:!1})})},[t,c,r,y]);const k=l.useMemo(()=>({id:e,form:y,isHidden:f,isReadOnly:h,isView:t,next:b,wf_activity_id:d}),[e,y,f,h,t,b,d]);return g.jsx(_.Provider,{value:k,children:g.jsx("section",{id:e,className:[e,o].filter(Boolean).join(" "),children:n})})}const q=l.createContext(null);function ae({children:e,config:o}){const r=l.useMemo(()=>w.createFluigClient(o),[o]);return g.jsx(q.Provider,{value:r,children:e})}function ce(){const e=l.useContext(q);if(!e)throw new Error("useFluigApi deve ser usado dentro de um <FluigApiProvider>");return e}Object.defineProperty(exports,"DebugLogger",{enumerable:!0,get:()=>w.DebugLogger});Object.defineProperty(exports,"createFluigClient",{enumerable:!0,get:()=>w.createFluigClient});Object.defineProperty(exports,"parentProxy",{enumerable:!0,get:()=>w.parentProxy});exports.FluigApiProvider=ae;exports.FluigWorkflowForm=Z;exports.SchemaRegistryProvider=B;exports.Section=se;exports.useFluigApi=ce;exports.useFluigRuntime=I;exports.useSchemaRegistry=T;exports.useSection=ie;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),l=require("react"),F=require("react-hook-form"),N=require("@hookform/resolvers"),W=require("zod"),A=require("@fluig-kit/core");var U=function(e,o){for(var t={};e.length;){var r=e[0],i=r.code,s=r.message,a=r.path.join(".");if(!t[a])if("unionErrors"in r){var c=r.unionErrors[0].errors[0];t[a]={message:c.message,type:c.code}}else t[a]={message:s,type:i};if("unionErrors"in r&&r.unionErrors.forEach(function(g){return g.errors.forEach(function(d){return e.push(d)})}),o){var u=t[a].types,n=u&&u[r.code];t[a]=F.appendErrors(a,o,t,i,n?[].concat(n,r.message):r.message)}e.shift()}return t},B=function(e,o,t){return t===void 0&&(t={}),function(r,i,s){try{return Promise.resolve(function(a,c){try{var u=Promise.resolve(e[t.mode==="sync"?"parse":"parseAsync"](r,o)).then(function(n){return s.shouldUseNativeValidation&&N.validateFieldsNatively({},s),{errors:{},values:t.raw?r:n}})}catch(n){return c(n)}return u&&u.then?u.then(void 0,c):u}(0,function(a){if(function(c){return Array.isArray(c==null?void 0:c.errors)}(a))return{values:{},errors:N.toNestErrors(U(a.errors,!s.shouldUseNativeValidation&&s.criteriaMode==="all"),s)};throw a}))}catch(a){return Promise.reject(a)}}};const O=l.createContext(null);function z({children:e,baseSchema:o}){const[t,r]=l.useState([]),i=l.useMemo(()=>o??W.z.object({}),[o]),s=l.useCallback((n,g)=>{r(d=>d.some(w=>w.id===n)?d:[...d,{id:n,schema:g}])},[]),a=l.useCallback(n=>{r(g=>g.some(d=>d.id===n)?g.filter(d=>d.id!==n):g)},[]),c=l.useMemo(()=>t.length?t.map(n=>n.schema).reduce((n,g)=>n.and(g),i):i,[t,i]),u=l.useMemo(()=>({registerSchema:s,unregisterSchema:a,mergedSchema:c}),[s,a,c]);return p.jsx(O.Provider,{value:u,children:e})}function T(){const e=l.useContext(O);if(!e)throw new Error("useSchemaRegistry deve ser usado dentro de <SchemaRegistryProvider>");return e}function j(e){return typeof e=="number"?e:isNaN(Number(e))?null:Number(e)}function L(e,o,t){if(!e)return!0;const r=Array.isArray(o)?o[0]:o,i=e.field??r,s=t==null?void 0:t[i];return e.hasValue!==void 0?e.hasValue?s!=null&&s!=="":s==null||s==="":e.equals!==void 0?s===e.equals:e.notEquals!==void 0?s!==e.notEquals:!0}function G(e,o,t,r,i){const s=new Set(e),a=new Set(o);return t==null||t.forEach(c=>{if(c.from!==void 0){const n=Array.isArray(c.from)?c.from:[c.from];if(r===null||!n.includes(r))return}if(!L(c.when,c.target,i))return;const u=Array.isArray(c.target)?c.target:[c.target];switch(c.type){case"readonly":u.forEach(n=>{a.add(n),s.delete(n)});break;case"active":u.forEach(n=>{s.add(n),a.delete(n)});break;case"hidden":u.forEach(n=>{s.delete(n),a.delete(n)});break}}),{active:Array.from(s),readonly:Array.from(a)}}function H(e,o,t,r){const i=new Set(e.active),s=new Set(e.readonly),a=new Set(e.hidden??[]);return o==null||o.forEach(c=>{if(c.from!==void 0){const n=Array.isArray(c.from)?c.from:[c.from];if(t===null||!n.includes(t))return}if(!L(c.when,c.target,r))return;const u=Array.isArray(c.target)?c.target:[c.target];switch(c.type){case"hidden":u.forEach(n=>{a.add(n),i.delete(n),s.delete(n)});break;case"active":u.forEach(n=>{i.add(n),s.delete(n),a.delete(n)});break;case"readonly":u.forEach(n=>{s.add(n),i.delete(n),a.delete(n)});break}}),{active:Array.from(i),readonly:Array.from(s),hidden:Array.from(a)}}function $(e,o){if(!(e!=null&&e.length))return o;const t=new Map(o.map(i=>[i.name,i])),r=[];return e.forEach(i=>{t.has(i)&&(r.push(t.get(i)),t.delete(i))}),t.forEach(i=>r.push(i)),r}function K(e){var r,i;const o=new Set,t=(s=[])=>{s.forEach(a=>{var c;a.target&&(Array.isArray(a.target)?a.target:[a.target]).forEach(n=>o.add(n)),(c=a.when)!=null&&c.field&&o.add(a.when.field)})};return t((r=e==null?void 0:e.fields)==null?void 0:r.rules),t((i=e==null?void 0:e.sections)==null?void 0:i.rules),Array.from(o)}function J({activityId:e,previousActivityId:o,control:t,workflowStructure:r,sectionsRegistry:i}){const{registerSchema:s,unregisterSchema:a}=T(),c=j(e),u=j(o),n=c!==null?r[c]:null,g=l.useMemo(()=>K(n),[c,n]),d=F.useWatch({control:t,name:g,defaultValue:{}}),w=l.useMemo(()=>{const m={};return g.forEach((f,v)=>{m[f]=Array.isArray(d)?d[v]:d}),m},[d,g]),y=l.useMemo(()=>{if(!n)return{sections:[],fields:{active:[],readonly:[],hidden:[]}};const m=G(n.sections.active,n.sections.readonly,n.sections.rules,u,w);let f=[...m.readonly.map(h=>({name:h,mode:"readonly"})),...m.active.map(h=>({name:h,mode:"active"}))];f=$(n.sections.order,f);const v=H({active:n.fields.active,readonly:n.fields.readonly,hidden:n.fields.hidden},n.fields.rules,u,w);return{sections:f,fields:v}},[n,u,w,i]);return l.useEffect(()=>{const m=y.sections.filter(f=>f.mode==="active").map(f=>f.name);m.forEach(f=>{var h;const v=(h=i==null?void 0:i[f])==null?void 0:h.schema;v&&s(f,v)}),Object.keys(i??{}).filter(f=>!m.includes(f)).forEach(a)},[y.sections,i,s,a]),y}function Q(){if(typeof document>"u")return{};const e={};return document.querySelectorAll("input[type='radio'][name]").forEach(o=>{const t=o,r=t.getAttribute("name");r&&t.checked&&(e[r]=t.value)}),document.querySelectorAll("input[name], textarea[name], select[name]").forEach(o=>{const t=o,r=t.getAttribute("name");if(!r||e[r]!==void 0)return;const i=t.getAttribute("value")??t.value??t.textContent??"";e[r]=String(i).trim()}),document.querySelectorAll("span[name]").forEach(o=>{var i;const t=o,r=t.getAttribute("name");if(r){const s=((i=t.textContent)==null?void 0:i.trim())??"";s!==""&&(e[r]=s)}}),e}const q=l.createContext(null);function X({children:e,devConfig:o}){const[t,r]=l.useState(null),i=l.useRef(o);l.useEffect(()=>{i.current=o},[o]);const s=l.useMemo(()=>Q()??{},[]);return l.useEffect(()=>{let a=!0;return(async()=>{var m,f;const u=typeof window<"u"&&window.location.hostname==="localhost";let n=null;try{const v=await((m=A.parentProxy.top.ECM)==null?void 0:m.workflowView);if(v){const h=await v.sequence;n=h!==void 0?Number(h):null}}catch(v){u||console.warn("[FluigRuntime] Erro Proxy:",v)}const d=(s.FORM_MODE||"").toLowerCase()==="view",w={isView:d,isReadOnly:d,activityId:n,previousActivityId:s.LASTACTIVITYID?Number(s.LASTACTIVITYID):null,prefilledValues:s,showDebugSubmit:!1,showDebugLogs:!1,isDev:!1};let y={...w};if((f=i.current)!=null&&f.enabled){const v=i.current,h=v.isView??w.isView;y={...w,...v,isView:h,isReadOnly:h,isDev:!0,activityId:v.activityId!==void 0?v.activityId:n}}a&&r(y)})(),()=>{a=!1}},[s]),t?p.jsx(q.Provider,{value:t,children:e}):null}function x(){const e=l.useContext(q);if(!e)throw new Error("useFluigRuntime deve ser usado dentro de <FluigRuntimeProvider>");return e}function Z(e){const{activityId:o,previousActivityId:t}=x();l.useEffect(()=>{o!=null&&e.setValue("CURRENTACTIVITYID",o),t!=null&&e.setValue("LASTACTIVITYID",t)},[o,t,e]),l.useEffect(()=>{if(typeof window>"u"||!window.top)return;const r=window.top.document,i=s=>{const a=s.target;(a.closest("[data-take-decision]")||a.closest("[data-take-task]")||a.closest(".movement-button"))&&(console.log("[FluigLifecycle] Ação detectada: setando modo 'edit'"),e.setValue("FORM_MODE","edit"))};return r.addEventListener("click",i),()=>r.removeEventListener("click",i)},[e]),l.useEffect(()=>{var i,s;if(typeof window>"u")return;const r=((i=window.top)==null?void 0:i.document.getElementById("send-process-button"))||((s=window.parent)==null?void 0:s.document.getElementById("workflow-actions-send"));r&&(window.beforeSendValidate=()=>{let a=!1;return e.handleSubmit(()=>{window.top.__FLUIG_REACT_FORM_DATA__=e.getValues(),e.setValue("FORM_MODE","view"),window.beforeSendValidate=()=>!0,a=!0,r.click()},c=>{var u,n;console.error("[Validation Errors]",c),(n=(u=window.top)==null?void 0:u.FLUIGC)!=null&&n.toast&&window.top.FLUIGC.toast({title:"Atenção",message:"Verifique os campos obrigatórios.",type:"danger"})})(),a})},[e])}const ee=({workflowStructure:e,sectionsRegistry:o,className:t})=>{const{control:r,handleSubmit:i,register:s,setValue:a,watch:c}=F.useFormContext(),u=x(),n=c("FORM_MODE"),g=l.useRef(!1);l.useEffect(()=>{g.current||(u.activityId!=null&&a("CURRENTACTIVITYID",u.activityId),u.previousActivityId!=null&&a("LASTACTIVITYID",u.previousActivityId),g.current=!0)},[u,a]);const{sections:d,fields:w}=J({control:r,activityId:u.activityId,previousActivityId:u.previousActivityId,workflowStructure:e,sectionsRegistry:o}),y=m=>{console.log("✅ [FluigWorkflowForm] Dados válidos:",m)};return p.jsxs("form",{id:"fluig-react-form",className:t,onSubmit:i(y),noValidate:!0,children:[p.jsxs("div",{className:"hidden",style:{display:"none"},children:[p.jsx("input",{type:"hidden",...s("CURRENTACTIVITYID")}),p.jsx("input",{type:"hidden",...s("LASTACTIVITYID")}),p.jsx("input",{type:"hidden",...s("FORM_MODE")})]}),d.length===0&&u.activityId!==null&&p.jsxs("p",{children:["Não foi possível encontrar a atividade: ",String(u.activityId)]}),d.map(({name:m,mode:f})=>{if(f==="hidden")return null;const v=o[m];if(!v)return null;const h=v.Component,R=n==="VIEW";return p.jsx(h,{id:m,fields:w,readOnly:f==="readonly"||R},m)}),u.isDev&&u.showDebugSubmit&&p.jsx("div",{style:{width:"100%",padding:"16px",paddingTop:"0"},children:p.jsx("button",{type:"submit",className:"btn btn-primary btn-lg btn-block",children:"Submit (Debug)"})})]})},te=e=>{const{mergedSchema:o}=T(),t=x(),r=F.useForm({resolver:o?B(o):void 0,defaultValues:t.prefilledValues,mode:"onBlur"});return Z(r),l.useEffect(()=>{t.showDebugLogs&&(A.DebugLogger.header("Form Initialized"),A.DebugLogger.table("Prefilled Values (DOM Capture)",t.prefilledValues),A.DebugLogger.info("RHF Current Values",r.getValues()),A.DebugLogger.end())},[t.showDebugLogs,t.prefilledValues,r]),p.jsx(F.FormProvider,{...r,children:p.jsx(ee,{...e})})};async function ne(e){if(!e)return console.warn("[setFluigNextActivity] Nenhuma atividade informada."),!1;const{wfView:o,wkfView:t}=await re();if(!o||!t)return!1;oe(o);const r=Number(e),i=ie(o,r);return i?(se(o,t,i,r),console.log(`[setFluigNextActivity] Próxima atividade definida: ${r}`),!0):(console.warn(`[setFluigNextActivity] Estado ${r} não encontrado nas próximas atividades disponíveis.`),console.log("Estados disponíveis:",o.availableStatesCOPY||o.availableStates),!1)}async function re(){const e=await A.parentProxy.top.ECM.workflowView,o=await A.parentProxy.top.ECM_WKFView;return!e||!o?(console.warn("[setFluigNextActivity] Contexto Fluig inválido ou não carregado."),{}):{wfView:e,wkfView:o}}function oe(e){e.availableStatesCOPY||(e.availableStatesCOPY=e.availableStates)}function ie(e,o){const t=e.availableStatesCOPY||e.availableStates;return t==null?void 0:t.find(r=>r.sequence===o)}function se(e,o,t,r){e.availableUsers.users=[],e.availableStates=[t],o.selectActivity=()=>r}const _=l.createContext(null);function ae(){const e=l.useContext(_);if(!e)throw new Error("useSection deve ser usado dentro de um componente <Section>");return e}function ce({id:e,className:o,schema:t,children:r,form:i,prefilledValues:s,readOnly:a,fields:c={},hidden:u=!1}){const{isView:n,activityId:g}=x(),d=g,w=F.useFormContext(),y=i||w;if(!y)return console.error(`[FluigWorkflowReact] Section "${e}" não encontrou o 'form'.`),null;if(u)return null;const m=l.useCallback(b=>{var E,V,C;return(E=c.hidden)!=null&&E.includes(b)?"hidden":(V=c.readonly)!=null&&V.includes(b)?"readonly":(C=c.active)!=null&&C.includes(b)?"active":a?"readonly":"active"},[c,a]),f=l.useCallback(b=>m(b)==="hidden",[m]),v=l.useCallback(b=>m(b)==="readonly",[m]),h=l.useCallback(b=>{if(!b)return;const E=y.getValues("CURRENTACTIVITYID");y.setValue("LASTACTIVITYID",E),y.setValue("CURRENTACTIVITYID",d),ne(Number(b))},[y,d]);l.useEffect(()=>{if(!n||!s||!t||!y)return;const b=y.getValues(),E=t.shape;E&&Object.entries(E).forEach(([V,C])=>{var k,P;let S=C;for(;(k=S==null?void 0:S._def)!=null&&k.schema;)S=S._def.schema;const I=(P=S==null?void 0:S._def)==null?void 0:P.fluig;if((I==null?void 0:I.type)!=="options"||!Array.isArray(I.values)||b[V]!==void 0)return;const D={};I.values.forEach(M=>{D[M]=s[M]==="on"}),y.setValue(V,D,{shouldDirty:!1,shouldValidate:!1})})},[n,s,t,y]);const R=l.useMemo(()=>({id:e,form:y,isHidden:f,isReadOnly:v,isView:n,next:h,wf_activity_id:d}),[e,y,f,v,n,h,d]);return p.jsx(_.Provider,{value:R,children:p.jsx("section",{id:e,className:[e,o].filter(Boolean).join(" "),children:r})})}const Y=l.createContext(null);function ue({children:e,config:o}){const t=l.useMemo(()=>A.createFluigClient(o),[o]);return p.jsx(Y.Provider,{value:t,children:e})}function le(){const e=l.useContext(Y);if(!e)throw new Error("useFluigApi deve ser usado dentro de um <FluigApiProvider>");return e}Object.defineProperty(exports,"DebugLogger",{enumerable:!0,get:()=>A.DebugLogger});Object.defineProperty(exports,"createFluigClient",{enumerable:!0,get:()=>A.createFluigClient});Object.defineProperty(exports,"parentProxy",{enumerable:!0,get:()=>A.parentProxy});exports.FluigApiProvider=ue;exports.FluigRuntimeProvider=X;exports.FluigWorkflowForm=te;exports.SchemaRegistryProvider=z;exports.Section=ce;exports.useFluigApi=le;exports.useFluigRuntime=x;exports.useSchemaRegistry=T;exports.useSection=ae;
package/dist/index.d.ts CHANGED
@@ -49,6 +49,13 @@ export declare type FluigRuntimeDevConfig = Partial<Omit<FluigRuntimeState, "pre
49
49
  enabled?: boolean;
50
50
  };
51
51
 
52
+ export declare function FluigRuntimeProvider({ children, devConfig, }: FluigRuntimeProviderProps): JSX_2.Element | null;
53
+
54
+ declare interface FluigRuntimeProviderProps {
55
+ children: ReactNode;
56
+ devConfig?: FluigRuntimeDevConfig;
57
+ }
58
+
52
59
  export declare interface FluigRuntimeState {
53
60
  isView: boolean;
54
61
  isReadOnly: boolean;
package/dist/index.js CHANGED
@@ -1,461 +1,516 @@
1
- import { jsx as p, jsxs as D } from "react/jsx-runtime";
2
- import { createContext as T, useState as $, useMemo as b, useCallback as F, useContext as k, useEffect as S, useRef as z } from "react";
3
- import { appendErrors as H, useWatch as K, useForm as J, FormProvider as Q, useFormContext as Y } from "react-hook-form";
4
- import { validateFieldsNatively as X, toNestErrors as Z } from "@hookform/resolvers";
5
- import { z as ee } from "zod";
6
- import { DebugLogger as x, parentProxy as L, createFluigClient as te } from "@fluig-kit/core";
7
- import { DebugLogger as Ne, createFluigClient as De, parentProxy as Re } from "@fluig-kit/core";
8
- var ne = function(e, o) {
9
- for (var n = {}; e.length; ) {
10
- var r = e[0], s = r.code, c = r.message, a = r.path.join(".");
11
- if (!n[a]) if ("unionErrors" in r) {
12
- var i = r.unionErrors[0].errors[0];
13
- n[a] = { message: i.message, type: i.code };
14
- } else n[a] = { message: c, type: s };
15
- if ("unionErrors" in r && r.unionErrors.forEach(function(m) {
16
- return m.errors.forEach(function(u) {
17
- return e.push(u);
1
+ import { jsx as g, jsxs as N } from "react/jsx-runtime";
2
+ import { createContext as x, useState as q, useMemo as A, useCallback as I, useContext as D, useEffect as b, useRef as U } from "react";
3
+ import { appendErrors as K, useWatch as J, useForm as Q, FormProvider as X, useFormContext as W } from "react-hook-form";
4
+ import { validateFieldsNatively as Z, toNestErrors as ee } from "@hookform/resolvers";
5
+ import { z as te } from "zod";
6
+ import { parentProxy as k, DebugLogger as T, createFluigClient as ne } from "@fluig-kit/core";
7
+ import { DebugLogger as ke, createFluigClient as Pe, parentProxy as Me } from "@fluig-kit/core";
8
+ var re = function(e, o) {
9
+ for (var t = {}; e.length; ) {
10
+ var r = e[0], i = r.code, a = r.message, s = r.path.join(".");
11
+ if (!t[s]) if ("unionErrors" in r) {
12
+ var c = r.unionErrors[0].errors[0];
13
+ t[s] = { message: c.message, type: c.code };
14
+ } else t[s] = { message: a, type: i };
15
+ if ("unionErrors" in r && r.unionErrors.forEach(function(v) {
16
+ return v.errors.forEach(function(l) {
17
+ return e.push(l);
18
18
  });
19
19
  }), o) {
20
- var l = n[a].types, t = l && l[r.code];
21
- n[a] = H(a, o, n, s, t ? [].concat(t, r.message) : r.message);
20
+ var u = t[s].types, n = u && u[r.code];
21
+ t[s] = K(s, o, t, i, n ? [].concat(n, r.message) : r.message);
22
22
  }
23
23
  e.shift();
24
24
  }
25
- return n;
26
- }, re = function(e, o, n) {
27
- return n === void 0 && (n = {}), function(r, s, c) {
25
+ return t;
26
+ }, oe = function(e, o, t) {
27
+ return t === void 0 && (t = {}), function(r, i, a) {
28
28
  try {
29
- return Promise.resolve(function(a, i) {
29
+ return Promise.resolve(function(s, c) {
30
30
  try {
31
- var l = Promise.resolve(e[n.mode === "sync" ? "parse" : "parseAsync"](r, o)).then(function(t) {
32
- return c.shouldUseNativeValidation && X({}, c), { errors: {}, values: n.raw ? r : t };
31
+ var u = Promise.resolve(e[t.mode === "sync" ? "parse" : "parseAsync"](r, o)).then(function(n) {
32
+ return a.shouldUseNativeValidation && Z({}, a), { errors: {}, values: t.raw ? r : n };
33
33
  });
34
- } catch (t) {
35
- return i(t);
34
+ } catch (n) {
35
+ return c(n);
36
36
  }
37
- return l && l.then ? l.then(void 0, i) : l;
38
- }(0, function(a) {
39
- if (function(i) {
40
- return Array.isArray(i == null ? void 0 : i.errors);
41
- }(a)) return { values: {}, errors: Z(ne(a.errors, !c.shouldUseNativeValidation && c.criteriaMode === "all"), c) };
42
- throw a;
37
+ return u && u.then ? u.then(void 0, c) : u;
38
+ }(0, function(s) {
39
+ if (function(c) {
40
+ return Array.isArray(c == null ? void 0 : c.errors);
41
+ }(s)) return { values: {}, errors: ee(re(s.errors, !a.shouldUseNativeValidation && a.criteriaMode === "all"), a) };
42
+ throw s;
43
43
  }));
44
- } catch (a) {
45
- return Promise.reject(a);
44
+ } catch (s) {
45
+ return Promise.reject(s);
46
46
  }
47
47
  };
48
48
  };
49
- const U = T(
49
+ const j = x(
50
50
  null
51
51
  );
52
- function Se({
52
+ function Ie({
53
53
  children: e,
54
54
  baseSchema: o
55
55
  }) {
56
- const [n, r] = $([]), s = b(() => o ?? ee.object({}), [o]), c = F((t, m) => {
57
- r((u) => u.some((w) => w.id === t) ? u : [...u, { id: t, schema: m }]);
58
- }, []), a = F((t) => {
59
- r((m) => m.some((u) => u.id === t) ? m.filter((u) => u.id !== t) : m);
60
- }, []), i = b(() => n.length ? n.map((t) => t.schema).reduce((t, m) => t.and(m), s) : s, [n, s]), l = b(
56
+ const [t, r] = q([]), i = A(() => o ?? te.object({}), [o]), a = I((n, v) => {
57
+ r((l) => l.some((p) => p.id === n) ? l : [...l, { id: n, schema: v }]);
58
+ }, []), s = I((n) => {
59
+ r((v) => v.some((l) => l.id === n) ? v.filter((l) => l.id !== n) : v);
60
+ }, []), c = A(() => t.length ? t.map((n) => n.schema).reduce((n, v) => n.and(v), i) : i, [t, i]), u = A(
61
61
  () => ({
62
- registerSchema: c,
63
- unregisterSchema: a,
64
- mergedSchema: i
62
+ registerSchema: a,
63
+ unregisterSchema: s,
64
+ mergedSchema: c
65
65
  }),
66
- [c, a, i]
66
+ [a, s, c]
67
67
  );
68
- return /* @__PURE__ */ p(U.Provider, { value: l, children: e });
68
+ return /* @__PURE__ */ g(j.Provider, { value: u, children: e });
69
69
  }
70
- function j() {
71
- const e = k(U);
70
+ function B() {
71
+ const e = D(j);
72
72
  if (!e)
73
73
  throw new Error(
74
74
  "useSchemaRegistry deve ser usado dentro de <SchemaRegistryProvider>"
75
75
  );
76
76
  return e;
77
77
  }
78
- function W(e) {
78
+ function Y(e) {
79
79
  return typeof e == "number" ? e : isNaN(Number(e)) ? null : Number(e);
80
80
  }
81
- function q(e, o, n) {
81
+ function z(e, o, t) {
82
82
  if (!e) return !0;
83
- const r = Array.isArray(o) ? o[0] : o, s = e.field ?? r, c = n == null ? void 0 : n[s];
84
- return e.hasValue !== void 0 ? e.hasValue ? c != null && c !== "" : c == null || c === "" : e.equals !== void 0 ? c === e.equals : e.notEquals !== void 0 ? c !== e.notEquals : !0;
83
+ const r = Array.isArray(o) ? o[0] : o, i = e.field ?? r, a = t == null ? void 0 : t[i];
84
+ return e.hasValue !== void 0 ? e.hasValue ? a != null && a !== "" : a == null || a === "" : e.equals !== void 0 ? a === e.equals : e.notEquals !== void 0 ? a !== e.notEquals : !0;
85
85
  }
86
- function oe(e, o, n, r, s) {
87
- const c = new Set(e), a = new Set(o);
88
- return n == null || n.forEach((i) => {
89
- if (i.from !== void 0) {
90
- const t = Array.isArray(i.from) ? i.from : [i.from];
91
- if (r === null || !t.includes(r)) return;
86
+ function ie(e, o, t, r, i) {
87
+ const a = new Set(e), s = new Set(o);
88
+ return t == null || t.forEach((c) => {
89
+ if (c.from !== void 0) {
90
+ const n = Array.isArray(c.from) ? c.from : [c.from];
91
+ if (r === null || !n.includes(r)) return;
92
92
  }
93
- if (!q(i.when, i.target, s)) return;
94
- const l = Array.isArray(i.target) ? i.target : [i.target];
95
- switch (i.type) {
93
+ if (!z(c.when, c.target, i)) return;
94
+ const u = Array.isArray(c.target) ? c.target : [c.target];
95
+ switch (c.type) {
96
96
  case "readonly":
97
- l.forEach((t) => {
98
- a.add(t), c.delete(t);
97
+ u.forEach((n) => {
98
+ s.add(n), a.delete(n);
99
99
  });
100
100
  break;
101
101
  case "active":
102
- l.forEach((t) => {
103
- c.add(t), a.delete(t);
102
+ u.forEach((n) => {
103
+ a.add(n), s.delete(n);
104
104
  });
105
105
  break;
106
106
  case "hidden":
107
- l.forEach((t) => {
108
- c.delete(t), a.delete(t);
107
+ u.forEach((n) => {
108
+ a.delete(n), s.delete(n);
109
109
  });
110
110
  break;
111
111
  }
112
- }), { active: Array.from(c), readonly: Array.from(a) };
112
+ }), { active: Array.from(a), readonly: Array.from(s) };
113
113
  }
114
- function ie(e, o, n, r) {
115
- const s = new Set(e.active), c = new Set(e.readonly), a = new Set(e.hidden ?? []);
116
- return o == null || o.forEach((i) => {
117
- if (i.from !== void 0) {
118
- const t = Array.isArray(i.from) ? i.from : [i.from];
119
- if (n === null || !t.includes(n)) return;
114
+ function ae(e, o, t, r) {
115
+ const i = new Set(e.active), a = new Set(e.readonly), s = new Set(e.hidden ?? []);
116
+ return o == null || o.forEach((c) => {
117
+ if (c.from !== void 0) {
118
+ const n = Array.isArray(c.from) ? c.from : [c.from];
119
+ if (t === null || !n.includes(t)) return;
120
120
  }
121
- if (!q(i.when, i.target, r)) return;
122
- const l = Array.isArray(i.target) ? i.target : [i.target];
123
- switch (i.type) {
121
+ if (!z(c.when, c.target, r)) return;
122
+ const u = Array.isArray(c.target) ? c.target : [c.target];
123
+ switch (c.type) {
124
124
  case "hidden":
125
- l.forEach((t) => {
126
- a.add(t), s.delete(t), c.delete(t);
125
+ u.forEach((n) => {
126
+ s.add(n), i.delete(n), a.delete(n);
127
127
  });
128
128
  break;
129
129
  case "active":
130
- l.forEach((t) => {
131
- s.add(t), c.delete(t), a.delete(t);
130
+ u.forEach((n) => {
131
+ i.add(n), a.delete(n), s.delete(n);
132
132
  });
133
133
  break;
134
134
  case "readonly":
135
- l.forEach((t) => {
136
- c.add(t), s.delete(t), a.delete(t);
135
+ u.forEach((n) => {
136
+ a.add(n), i.delete(n), s.delete(n);
137
137
  });
138
138
  break;
139
139
  }
140
140
  }), {
141
- active: Array.from(s),
142
- readonly: Array.from(c),
143
- hidden: Array.from(a)
141
+ active: Array.from(i),
142
+ readonly: Array.from(a),
143
+ hidden: Array.from(s)
144
144
  };
145
145
  }
146
- function ae(e, o) {
146
+ function se(e, o) {
147
147
  if (!(e != null && e.length)) return o;
148
- const n = new Map(o.map((s) => [s.name, s])), r = [];
149
- return e.forEach((s) => {
150
- n.has(s) && (r.push(n.get(s)), n.delete(s));
151
- }), n.forEach((s) => r.push(s)), r;
148
+ const t = new Map(o.map((i) => [i.name, i])), r = [];
149
+ return e.forEach((i) => {
150
+ t.has(i) && (r.push(t.get(i)), t.delete(i));
151
+ }), t.forEach((i) => r.push(i)), r;
152
152
  }
153
- function se(e) {
154
- var r, s;
155
- const o = /* @__PURE__ */ new Set(), n = (c = []) => {
156
- c.forEach((a) => {
157
- var i;
158
- a.target && (Array.isArray(a.target) ? a.target : [a.target]).forEach((t) => o.add(t)), (i = a.when) != null && i.field && o.add(a.when.field);
153
+ function ce(e) {
154
+ var r, i;
155
+ const o = /* @__PURE__ */ new Set(), t = (a = []) => {
156
+ a.forEach((s) => {
157
+ var c;
158
+ s.target && (Array.isArray(s.target) ? s.target : [s.target]).forEach((n) => o.add(n)), (c = s.when) != null && c.field && o.add(s.when.field);
159
159
  });
160
160
  };
161
- return n((r = e == null ? void 0 : e.fields) == null ? void 0 : r.rules), n((s = e == null ? void 0 : e.sections) == null ? void 0 : s.rules), Array.from(o);
161
+ return t((r = e == null ? void 0 : e.fields) == null ? void 0 : r.rules), t((i = e == null ? void 0 : e.sections) == null ? void 0 : i.rules), Array.from(o);
162
162
  }
163
- function ce({
163
+ function ue({
164
164
  activityId: e,
165
165
  previousActivityId: o,
166
- control: n,
166
+ control: t,
167
167
  workflowStructure: r,
168
- sectionsRegistry: s
168
+ sectionsRegistry: i
169
169
  }) {
170
- const { registerSchema: c, unregisterSchema: a } = j(), i = W(e), l = W(o), t = i !== null ? r[i] : null, m = b(() => se(t), [i, t]), u = K({
171
- control: n,
172
- name: m,
170
+ const { registerSchema: a, unregisterSchema: s } = B(), c = Y(e), u = Y(o), n = c !== null ? r[c] : null, v = A(() => ce(n), [c, n]), l = J({
171
+ control: t,
172
+ name: v,
173
173
  defaultValue: {}
174
- }), w = b(() => {
174
+ }), p = A(() => {
175
175
  const f = {};
176
- return m.forEach((d, h) => {
177
- f[d] = Array.isArray(u) ? u[h] : u;
176
+ return v.forEach((d, m) => {
177
+ f[d] = Array.isArray(l) ? l[m] : l;
178
178
  }), f;
179
- }, [u, m]), v = b(() => {
180
- if (!t)
179
+ }, [l, v]), y = A(() => {
180
+ if (!n)
181
181
  return {
182
182
  sections: [],
183
183
  fields: { active: [], readonly: [], hidden: [] }
184
184
  };
185
- const f = oe(
186
- t.sections.active,
187
- t.sections.readonly,
188
- t.sections.rules,
189
- l,
190
- w
185
+ const f = ie(
186
+ n.sections.active,
187
+ n.sections.readonly,
188
+ n.sections.rules,
189
+ u,
190
+ p
191
191
  );
192
192
  let d = [
193
- ...f.readonly.map((g) => ({
194
- name: g,
193
+ ...f.readonly.map((h) => ({
194
+ name: h,
195
195
  mode: "readonly"
196
196
  })),
197
- ...f.active.map((g) => ({
198
- name: g,
197
+ ...f.active.map((h) => ({
198
+ name: h,
199
199
  mode: "active"
200
200
  }))
201
201
  ];
202
- d = ae(t.sections.order, d);
203
- const h = ie(
202
+ d = se(n.sections.order, d);
203
+ const m = ae(
204
204
  {
205
- active: t.fields.active,
206
- readonly: t.fields.readonly,
207
- hidden: t.fields.hidden
205
+ active: n.fields.active,
206
+ readonly: n.fields.readonly,
207
+ hidden: n.fields.hidden
208
208
  },
209
- t.fields.rules,
210
- l,
211
- w
209
+ n.fields.rules,
210
+ u,
211
+ p
212
212
  );
213
- return { sections: d, fields: h };
214
- }, [t, l, w, s]);
215
- return S(() => {
216
- const f = v.sections.filter((d) => d.mode === "active").map((d) => d.name);
213
+ return { sections: d, fields: m };
214
+ }, [n, u, p, i]);
215
+ return b(() => {
216
+ const f = y.sections.filter((d) => d.mode === "active").map((d) => d.name);
217
217
  f.forEach((d) => {
218
- var g;
219
- const h = (g = s == null ? void 0 : s[d]) == null ? void 0 : g.schema;
220
- h && c(d, h);
221
- }), Object.keys(s ?? {}).filter((d) => !f.includes(d)).forEach(a);
222
- }, [v.sections, s, c, a]), v;
218
+ var h;
219
+ const m = (h = i == null ? void 0 : i[d]) == null ? void 0 : h.schema;
220
+ m && a(d, m);
221
+ }), Object.keys(i ?? {}).filter((d) => !f.includes(d)).forEach(s);
222
+ }, [y.sections, i, a, s]), y;
223
+ }
224
+ function le() {
225
+ if (typeof document > "u") return {};
226
+ const e = {};
227
+ return document.querySelectorAll("input[type='radio'][name]").forEach((o) => {
228
+ const t = o, r = t.getAttribute("name");
229
+ r && t.checked && (e[r] = t.value);
230
+ }), document.querySelectorAll("input[name], textarea[name], select[name]").forEach((o) => {
231
+ const t = o, r = t.getAttribute("name");
232
+ if (!r || e[r] !== void 0) return;
233
+ const i = t.getAttribute("value") ?? t.value ?? t.textContent ?? "";
234
+ e[r] = String(i).trim();
235
+ }), document.querySelectorAll("span[name]").forEach((o) => {
236
+ var i;
237
+ const t = o, r = t.getAttribute("name");
238
+ if (r) {
239
+ const a = ((i = t.textContent) == null ? void 0 : i.trim()) ?? "";
240
+ a !== "" && (e[r] = a);
241
+ }
242
+ }), e;
243
+ }
244
+ const G = x(null);
245
+ function Ee({
246
+ children: e,
247
+ devConfig: o
248
+ }) {
249
+ const [t, r] = q(null), i = U(o);
250
+ b(() => {
251
+ i.current = o;
252
+ }, [o]);
253
+ const a = A(() => le() ?? {}, []);
254
+ return b(() => {
255
+ let s = !0;
256
+ return (async () => {
257
+ var f, d;
258
+ const u = typeof window < "u" && window.location.hostname === "localhost";
259
+ let n = null;
260
+ try {
261
+ const m = await ((f = k.top.ECM) == null ? void 0 : f.workflowView);
262
+ if (m) {
263
+ const h = await m.sequence;
264
+ n = h !== void 0 ? Number(h) : null;
265
+ }
266
+ } catch (m) {
267
+ u || console.warn("[FluigRuntime] Erro Proxy:", m);
268
+ }
269
+ const l = (a.FORM_MODE || "").toLowerCase() === "view", p = {
270
+ isView: l,
271
+ isReadOnly: l,
272
+ activityId: n,
273
+ previousActivityId: a.LASTACTIVITYID ? Number(a.LASTACTIVITYID) : null,
274
+ prefilledValues: a,
275
+ showDebugSubmit: !1,
276
+ showDebugLogs: !1,
277
+ isDev: !1
278
+ };
279
+ let y = { ...p };
280
+ if ((d = i.current) != null && d.enabled) {
281
+ const m = i.current, h = m.isView ?? p.isView;
282
+ y = {
283
+ ...p,
284
+ ...m,
285
+ isView: h,
286
+ isReadOnly: h,
287
+ isDev: !0,
288
+ activityId: m.activityId !== void 0 ? m.activityId : n
289
+ };
290
+ }
291
+ s && r(y);
292
+ })(), () => {
293
+ s = !1;
294
+ };
295
+ }, [a]), t ? /* @__PURE__ */ g(G.Provider, { value: t, children: e }) : null;
223
296
  }
224
- const le = T(null);
225
- function N() {
226
- const e = k(le);
297
+ function R() {
298
+ const e = D(G);
227
299
  if (!e)
228
300
  throw new Error(
229
301
  "useFluigRuntime deve ser usado dentro de <FluigRuntimeProvider>"
230
302
  );
231
303
  return e;
232
304
  }
233
- function ue(e) {
234
- const { activityId: o, previousActivityId: n } = N();
235
- S(() => {
236
- o != null && e.setValue("CURRENTACTIVITYID", o), n != null && e.setValue("LASTACTIVITYID", n);
237
- }, [o, n, e]), S(() => {
305
+ function de(e) {
306
+ const { activityId: o, previousActivityId: t } = R();
307
+ b(() => {
308
+ o != null && e.setValue("CURRENTACTIVITYID", o), t != null && e.setValue("LASTACTIVITYID", t);
309
+ }, [o, t, e]), b(() => {
238
310
  if (typeof window > "u" || !window.top) return;
239
- const r = window.top.document, s = (c) => {
240
- const a = c.target;
241
- (a.closest("[data-take-decision]") || a.closest("[data-take-task]") || a.closest(".movement-button")) && (console.log("[FluigLifecycle] Ação de movimentação detectada. Ativando modo Edição."), e.setValue("FORM_MODE", "MOD"));
311
+ const r = window.top.document, i = (a) => {
312
+ const s = a.target;
313
+ (s.closest("[data-take-decision]") || s.closest("[data-take-task]") || s.closest(".movement-button")) && (console.log("[FluigLifecycle] Ação detectada: setando modo 'edit'"), e.setValue("FORM_MODE", "edit"));
242
314
  };
243
- return r.addEventListener("click", s), () => {
244
- r.removeEventListener("click", s);
245
- };
246
- }, [e]), S(() => {
247
- var s, c;
315
+ return r.addEventListener("click", i), () => r.removeEventListener("click", i);
316
+ }, [e]), b(() => {
317
+ var i, a;
248
318
  if (typeof window > "u") return;
249
- const r = ((s = window.top) == null ? void 0 : s.document.getElementById("send-process-button")) || ((c = window.parent) == null ? void 0 : c.document.getElementById("workflow-actions-send")) || document.getElementById("send-process-button");
250
- if (!r) {
251
- console.warn(
252
- "[FluigWorkflowReact] Botão de envio do Fluig não encontrado. A validação automática pode falhar."
253
- );
254
- return;
255
- }
256
- return window.beforeSendValidate = () => (e.handleSubmit(
257
- () => {
258
- window.top.__FLUIG_REACT_FORM_DATA__ = e.getValues(), e.setValue("FORM_MODE", "VIEW"), window.beforeSendValidate = () => !0;
259
- try {
260
- r.dispatchEvent(
261
- new MouseEvent("click", {
262
- view: window,
263
- bubbles: !0,
264
- cancelable: !0
265
- })
266
- );
267
- } catch {
268
- r.click();
319
+ const r = ((i = window.top) == null ? void 0 : i.document.getElementById("send-process-button")) || ((a = window.parent) == null ? void 0 : a.document.getElementById("workflow-actions-send"));
320
+ r && (window.beforeSendValidate = () => {
321
+ let s = !1;
322
+ return e.handleSubmit(
323
+ () => {
324
+ window.top.__FLUIG_REACT_FORM_DATA__ = e.getValues(), e.setValue("FORM_MODE", "view"), window.beforeSendValidate = () => !0, s = !0, r.click();
325
+ },
326
+ (c) => {
327
+ var u, n;
328
+ console.error("[Validation Errors]", c), (n = (u = window.top) == null ? void 0 : u.FLUIGC) != null && n.toast && window.top.FLUIGC.toast({
329
+ title: "Atenção",
330
+ message: "Verifique os campos obrigatórios.",
331
+ type: "danger"
332
+ });
269
333
  }
270
- },
271
- (a) => {
272
- var i, l, t;
273
- console.error("[Validation Errors]", a), (l = (i = window.top) == null ? void 0 : i.FLUIGC) != null && l.toast ? (t = window.top) == null || t.FLUIGC.toast({
274
- title: "Atenção",
275
- message: "Verifique os campos obrigatórios destacados em vermelho.",
276
- type: "danger"
277
- }) : alert("Verifique os campos obrigatórios.");
278
- }
279
- )(), !1), () => {
280
- };
334
+ )(), s;
335
+ });
281
336
  }, [e]);
282
337
  }
283
- const de = ({
338
+ const fe = ({
284
339
  workflowStructure: e,
285
340
  sectionsRegistry: o,
286
- className: n
341
+ className: t
287
342
  }) => {
288
- const { control: r, handleSubmit: s, register: c, setValue: a, watch: i } = Y(), l = N(), t = i("FORM_MODE"), m = z(!1);
289
- S(() => {
290
- m.current || (l.activityId != null && a("CURRENTACTIVITYID", l.activityId), l.previousActivityId != null && a("LASTACTIVITYID", l.previousActivityId), m.current = !0);
291
- }, [l, a]);
292
- const { sections: u, fields: w } = ce({
343
+ const { control: r, handleSubmit: i, register: a, setValue: s, watch: c } = W(), u = R(), n = c("FORM_MODE"), v = U(!1);
344
+ b(() => {
345
+ v.current || (u.activityId != null && s("CURRENTACTIVITYID", u.activityId), u.previousActivityId != null && s("LASTACTIVITYID", u.previousActivityId), v.current = !0);
346
+ }, [u, s]);
347
+ const { sections: l, fields: p } = ue({
293
348
  control: r,
294
- activityId: l.activityId,
295
- previousActivityId: l.previousActivityId,
349
+ activityId: u.activityId,
350
+ previousActivityId: u.previousActivityId,
296
351
  workflowStructure: e,
297
352
  sectionsRegistry: o
298
353
  });
299
- return /* @__PURE__ */ D(
354
+ return /* @__PURE__ */ N(
300
355
  "form",
301
356
  {
302
357
  id: "fluig-react-form",
303
- className: n,
304
- onSubmit: s((f) => {
358
+ className: t,
359
+ onSubmit: i((f) => {
305
360
  console.log("✅ [FluigWorkflowForm] Dados válidos:", f);
306
361
  }),
307
362
  noValidate: !0,
308
363
  children: [
309
- /* @__PURE__ */ D("div", { className: "hidden", style: { display: "none" }, children: [
310
- /* @__PURE__ */ p("input", { type: "hidden", ...c("CURRENTACTIVITYID") }),
311
- /* @__PURE__ */ p("input", { type: "hidden", ...c("LASTACTIVITYID") }),
312
- /* @__PURE__ */ p("input", { type: "hidden", ...c("FORM_MODE") })
364
+ /* @__PURE__ */ N("div", { className: "hidden", style: { display: "none" }, children: [
365
+ /* @__PURE__ */ g("input", { type: "hidden", ...a("CURRENTACTIVITYID") }),
366
+ /* @__PURE__ */ g("input", { type: "hidden", ...a("LASTACTIVITYID") }),
367
+ /* @__PURE__ */ g("input", { type: "hidden", ...a("FORM_MODE") })
313
368
  ] }),
314
- u.length === 0 && l.activityId !== null && /* @__PURE__ */ D("p", { children: [
369
+ l.length === 0 && u.activityId !== null && /* @__PURE__ */ N("p", { children: [
315
370
  "Não foi possível encontrar a atividade: ",
316
- String(l.activityId)
371
+ String(u.activityId)
317
372
  ] }),
318
- u.map(({ name: f, mode: d }) => {
373
+ l.map(({ name: f, mode: d }) => {
319
374
  if (d === "hidden") return null;
320
- const h = o[f];
321
- if (!h) return null;
322
- const g = h.Component;
323
- return /* @__PURE__ */ p(
324
- g,
375
+ const m = o[f];
376
+ if (!m) return null;
377
+ const h = m.Component;
378
+ return /* @__PURE__ */ g(
379
+ h,
325
380
  {
326
381
  id: f,
327
- fields: w,
328
- readOnly: d === "readonly" || t === "VIEW"
382
+ fields: p,
383
+ readOnly: d === "readonly" || n === "VIEW"
329
384
  },
330
385
  f
331
386
  );
332
387
  }),
333
- l.isDev && l.showDebugSubmit && /* @__PURE__ */ p("div", { style: { width: "100%", padding: "16px", paddingTop: "0" }, children: /* @__PURE__ */ p("button", { type: "submit", className: "btn btn-primary btn-lg btn-block", children: "Submit (Debug)" }) })
388
+ u.isDev && u.showDebugSubmit && /* @__PURE__ */ g("div", { style: { width: "100%", padding: "16px", paddingTop: "0" }, children: /* @__PURE__ */ g("button", { type: "submit", className: "btn btn-primary btn-lg btn-block", children: "Submit (Debug)" }) })
334
389
  ]
335
390
  }
336
391
  );
337
392
  }, Fe = (e) => {
338
- const { mergedSchema: o } = j(), n = N(), r = J({
339
- resolver: o ? re(o) : void 0,
340
- defaultValues: n.prefilledValues,
393
+ const { mergedSchema: o } = B(), t = R(), r = Q({
394
+ resolver: o ? oe(o) : void 0,
395
+ defaultValues: t.prefilledValues,
341
396
  mode: "onBlur"
342
397
  });
343
- return ue(r), S(() => {
344
- n.showDebugLogs && (x.header("Form Initialized"), x.table(
398
+ return de(r), b(() => {
399
+ t.showDebugLogs && (T.header("Form Initialized"), T.table(
345
400
  "Prefilled Values (DOM Capture)",
346
- n.prefilledValues
347
- ), x.info("RHF Current Values", r.getValues()), x.end());
348
- }, [n.showDebugLogs, n.prefilledValues, r]), /* @__PURE__ */ p(Q, { ...r, children: /* @__PURE__ */ p(de, { ...e }) });
401
+ t.prefilledValues
402
+ ), T.info("RHF Current Values", r.getValues()), T.end());
403
+ }, [t.showDebugLogs, t.prefilledValues, r]), /* @__PURE__ */ g(X, { ...r, children: /* @__PURE__ */ g(fe, { ...e }) });
349
404
  };
350
- async function fe(e) {
405
+ async function me(e) {
351
406
  if (!e)
352
407
  return console.warn("[setFluigNextActivity] Nenhuma atividade informada."), !1;
353
- const { wfView: o, wkfView: n } = await me();
354
- if (!o || !n) return !1;
355
- ve(o);
356
- const r = Number(e), s = he(o, r);
357
- return s ? (ye(o, n, s, r), console.log(`[setFluigNextActivity] Próxima atividade definida: ${r}`), !0) : (console.warn(`[setFluigNextActivity] Estado ${r} não encontrado nas próximas atividades disponíveis.`), console.log("Estados disponíveis:", o.availableStatesCOPY || o.availableStates), !1);
408
+ const { wfView: o, wkfView: t } = await ve();
409
+ if (!o || !t) return !1;
410
+ ye(o);
411
+ const r = Number(e), i = he(o, r);
412
+ return i ? (pe(o, t, i, r), console.log(`[setFluigNextActivity] Próxima atividade definida: ${r}`), !0) : (console.warn(`[setFluigNextActivity] Estado ${r} não encontrado nas próximas atividades disponíveis.`), console.log("Estados disponíveis:", o.availableStatesCOPY || o.availableStates), !1);
358
413
  }
359
- async function me() {
360
- const e = await L.top.ECM.workflowView, o = await L.top.ECM_WKFView;
414
+ async function ve() {
415
+ const e = await k.top.ECM.workflowView, o = await k.top.ECM_WKFView;
361
416
  return !e || !o ? (console.warn("[setFluigNextActivity] Contexto Fluig inválido ou não carregado."), {}) : { wfView: e, wkfView: o };
362
417
  }
363
- function ve(e) {
418
+ function ye(e) {
364
419
  e.availableStatesCOPY || (e.availableStatesCOPY = e.availableStates);
365
420
  }
366
421
  function he(e, o) {
367
- const n = e.availableStatesCOPY || e.availableStates;
368
- return n == null ? void 0 : n.find((r) => r.sequence === o);
422
+ const t = e.availableStatesCOPY || e.availableStates;
423
+ return t == null ? void 0 : t.find((r) => r.sequence === o);
369
424
  }
370
- function ye(e, o, n, r) {
371
- e.availableUsers.users = [], e.availableStates = [n], o.selectActivity = () => r;
425
+ function pe(e, o, t, r) {
426
+ e.availableUsers.users = [], e.availableStates = [t], o.selectActivity = () => r;
372
427
  }
373
- const B = T(null);
374
- function Ve() {
375
- const e = k(B);
428
+ const $ = x(null);
429
+ function Ce() {
430
+ const e = D($);
376
431
  if (!e)
377
432
  throw new Error(
378
433
  "useSection deve ser usado dentro de um componente <Section>"
379
434
  );
380
435
  return e;
381
436
  }
382
- function Ie({
437
+ function Te({
383
438
  id: e,
384
439
  className: o,
385
- schema: n,
440
+ schema: t,
386
441
  children: r,
387
- form: s,
388
- prefilledValues: c,
389
- readOnly: a,
390
- fields: i = {},
391
- hidden: l = !1
442
+ form: i,
443
+ prefilledValues: a,
444
+ readOnly: s,
445
+ fields: c = {},
446
+ hidden: u = !1
392
447
  }) {
393
- const { isView: t, activityId: m } = N(), u = m, w = Y(), v = s || w;
394
- if (!v)
448
+ const { isView: n, activityId: v } = R(), l = v, p = W(), y = i || p;
449
+ if (!y)
395
450
  return console.error(
396
451
  `[FluigWorkflowReact] Section "${e}" não encontrou o 'form'.`
397
452
  ), null;
398
- if (l) return null;
399
- const f = F(
400
- (y) => {
401
- var E, V, C;
402
- return (E = i.hidden) != null && E.includes(y) ? "hidden" : (V = i.readonly) != null && V.includes(y) ? "readonly" : (C = i.active) != null && C.includes(y) ? "active" : a ? "readonly" : "active";
453
+ if (u) return null;
454
+ const f = I(
455
+ (w) => {
456
+ var V, E, C;
457
+ return (V = c.hidden) != null && V.includes(w) ? "hidden" : (E = c.readonly) != null && E.includes(w) ? "readonly" : (C = c.active) != null && C.includes(w) ? "active" : s ? "readonly" : "active";
403
458
  },
404
- [i, a]
405
- ), d = F(
406
- (y) => f(y) === "hidden",
459
+ [c, s]
460
+ ), d = I(
461
+ (w) => f(w) === "hidden",
407
462
  [f]
408
- ), h = F(
409
- (y) => f(y) === "readonly",
463
+ ), m = I(
464
+ (w) => f(w) === "readonly",
410
465
  [f]
411
- ), g = F(
412
- (y) => {
413
- if (!y) return;
414
- const E = v.getValues("CURRENTACTIVITYID");
415
- v.setValue("LASTACTIVITYID", E), v.setValue("CURRENTACTIVITYID", u), fe(Number(y));
466
+ ), h = I(
467
+ (w) => {
468
+ if (!w) return;
469
+ const V = y.getValues("CURRENTACTIVITYID");
470
+ y.setValue("LASTACTIVITYID", V), y.setValue("CURRENTACTIVITYID", l), me(Number(w));
416
471
  },
417
- [v, u]
472
+ [y, l]
418
473
  );
419
- S(() => {
420
- if (!t || !c || !n || !v) return;
421
- const y = v.getValues(), E = n.shape;
422
- E && Object.entries(E).forEach(([V, C]) => {
423
- var O, P;
424
- let A = C;
425
- for (; (O = A == null ? void 0 : A._def) != null && O.schema; )
426
- A = A._def.schema;
427
- const I = (P = A == null ? void 0 : A._def) == null ? void 0 : P.fluig;
428
- if ((I == null ? void 0 : I.type) !== "options" || !Array.isArray(I.values) || y[V] !== void 0) return;
474
+ b(() => {
475
+ if (!n || !a || !t || !y) return;
476
+ const w = y.getValues(), V = t.shape;
477
+ V && Object.entries(V).forEach(([E, C]) => {
478
+ var O, L;
479
+ let S = C;
480
+ for (; (O = S == null ? void 0 : S._def) != null && O.schema; )
481
+ S = S._def.schema;
482
+ const F = (L = S == null ? void 0 : S._def) == null ? void 0 : L.fluig;
483
+ if ((F == null ? void 0 : F.type) !== "options" || !Array.isArray(F.values) || w[E] !== void 0) return;
429
484
  const M = {};
430
- I.values.forEach((_) => {
431
- M[_] = c[_] === "on";
432
- }), v.setValue(V, M, {
485
+ F.values.forEach((_) => {
486
+ M[_] = a[_] === "on";
487
+ }), y.setValue(E, M, {
433
488
  shouldDirty: !1,
434
489
  shouldValidate: !1
435
490
  });
436
491
  });
437
- }, [t, c, n, v]);
438
- const R = b(
492
+ }, [n, a, t, y]);
493
+ const P = A(
439
494
  () => ({
440
495
  id: e,
441
- form: v,
496
+ form: y,
442
497
  isHidden: d,
443
- isReadOnly: h,
444
- isView: t,
445
- next: g,
446
- wf_activity_id: u
498
+ isReadOnly: m,
499
+ isView: n,
500
+ next: h,
501
+ wf_activity_id: l
447
502
  }),
448
- [e, v, d, h, t, g, u]
503
+ [e, y, d, m, n, h, l]
449
504
  );
450
- return /* @__PURE__ */ p(B.Provider, { value: R, children: /* @__PURE__ */ p("section", { id: e, className: [e, o].filter(Boolean).join(" "), children: r }) });
505
+ return /* @__PURE__ */ g($.Provider, { value: P, children: /* @__PURE__ */ g("section", { id: e, className: [e, o].filter(Boolean).join(" "), children: r }) });
451
506
  }
452
- const G = T(null);
453
- function Ce({ children: e, config: o }) {
454
- const n = b(() => te(o), [o]);
455
- return /* @__PURE__ */ p(G.Provider, { value: n, children: e });
507
+ const H = x(null);
508
+ function xe({ children: e, config: o }) {
509
+ const t = A(() => ne(o), [o]);
510
+ return /* @__PURE__ */ g(H.Provider, { value: t, children: e });
456
511
  }
457
- function xe() {
458
- const e = k(G);
512
+ function De() {
513
+ const e = D(H);
459
514
  if (!e)
460
515
  throw new Error(
461
516
  "useFluigApi deve ser usado dentro de um <FluigApiProvider>"
@@ -463,15 +518,16 @@ function xe() {
463
518
  return e;
464
519
  }
465
520
  export {
466
- Ne as DebugLogger,
467
- Ce as FluigApiProvider,
521
+ ke as DebugLogger,
522
+ xe as FluigApiProvider,
523
+ Ee as FluigRuntimeProvider,
468
524
  Fe as FluigWorkflowForm,
469
- Se as SchemaRegistryProvider,
470
- Ie as Section,
471
- De as createFluigClient,
472
- Re as parentProxy,
473
- xe as useFluigApi,
474
- N as useFluigRuntime,
475
- j as useSchemaRegistry,
476
- Ve as useSection
525
+ Ie as SchemaRegistryProvider,
526
+ Te as Section,
527
+ Pe as createFluigClient,
528
+ Me as parentProxy,
529
+ De as useFluigApi,
530
+ R as useFluigRuntime,
531
+ B as useSchemaRegistry,
532
+ Ce as useSection
477
533
  };
package/dist/node.cjs CHANGED
@@ -17,11 +17,13 @@
17
17
  <form id="form" name="form">
18
18
  <div id="root">
19
19
  <!-- IMPUTS DE CONTROLE -->
20
+
20
21
  <input type="hidden" name="LASTACTIVITYID" />
21
22
  <input type="hidden" name="CURRENTACTIVITYID" />
22
23
  <input type="hidden" name="FORM_MODE" />
24
+
23
25
  <!-- ////////////////// -->
24
-
26
+
25
27
  ${i}
26
28
  </div>
27
29
  </form>
package/dist/node.js CHANGED
@@ -56,11 +56,13 @@ function y(t) {
56
56
  <form id="form" name="form">
57
57
  <div id="root">
58
58
  <!-- IMPUTS DE CONTROLE -->
59
+
59
60
  <input type="hidden" name="LASTACTIVITYID" />
60
61
  <input type="hidden" name="CURRENTACTIVITYID" />
61
62
  <input type="hidden" name="FORM_MODE" />
63
+
62
64
  <!-- ////////////////// -->
63
-
65
+
64
66
  ${i}
65
67
  </div>
66
68
  </form>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluig-kit/ecm",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",