@fluig-kit/ecm 1.0.23 → 1.0.24

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