@fluig-kit/ecm 1.0.23 → 1.0.25

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