@objectstack/studio 5.0.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/index-81ZhtCq-.js +159 -0
- package/dist/assets/index-CSlaSCb_.css +2 -0
- package/dist/assets/rolldown-runtime-aKtaBQYM.js +1 -0
- package/dist/assets/vendor-charts-CMWbKNvz.js +34 -0
- package/dist/assets/vendor-icons-C-VDCqO9.js +1 -0
- package/dist/assets/vendor-kzrx2K5g.css +1 -0
- package/dist/assets/vendor-object-ui-core-C_SRaIe4.js +59 -0
- package/dist/assets/vendor-object-ui-form-DRRdiS9F.js +1 -0
- package/dist/assets/vendor-object-ui-grid-BvNa3IUR.js +6 -0
- package/dist/assets/vendor-object-ui-views-CyaLQwFl.js +0 -0
- package/dist/assets/vendor-rQmwIIxi.js +152 -0
- package/dist/assets/vendor-radix-DlDjksHy.js +1 -0
- package/dist/assets/vendor-react-CfxtBSJn.js +9 -0
- package/dist/assets/vendor-tanstack-D6oxbowc.js +1 -0
- package/dist/index.html +30 -2
- package/package.json +30 -24
- package/dist/assets/dist-BLpBniak.js +0 -1
- package/dist/assets/index-4mX9YJ8G.css +0 -2
- package/dist/assets/index-BaTw7zW8.js +0 -230
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{bn as t,vn as n}from"./vendor-rQmwIIxi.js";import{Bn as r,Hn as i,Mt as a,Pn as o,Un as s,Vn as c,jt as l,z as u}from"./vendor-icons-C-VDCqO9.js";import{At as d,Cn as f,D as p,Dt as m,E as h,G as g,K as _,M as v,Ot as y,P as b,Q as x,R as S,St as C,T as w,Tt as T,U as E,W as D,at as O,ct as k,d as A,dn as j,g as M,gt as N,j as P,k as F,mt as I,o as L,p as R,q as z,rn as B,v as V,w as ee,xt as H,yt as U}from"./vendor-object-ui-core-C_SRaIe4.js";var W=e(t(),1),G=n(),K=({label:e,description:t,collapsible:n=!1,collapsed:a=!1,columns:o=1,children:s,className:c,gridClassName:l,showBorder:u})=>{let[f,p]=(0,W.useState)(a),g={1:`grid-cols-1`,2:`grid-cols-1 md:grid-cols-2`,3:`grid-cols-1 md:grid-cols-2 lg:grid-cols-3`,4:`grid-cols-1 md:grid-cols-2 lg:grid-cols-4`},y=()=>{n&&p(!f)},b=u??!!e,x=e||t?(0,G.jsxs)(`div`,{className:v(`flex items-start gap-2`,!b&&`mb-4`,n&&`cursor-pointer select-none`),onClick:y,role:n?`button`:void 0,"aria-expanded":n?!f:void 0,children:[n&&(0,G.jsx)(`span`,{className:`mt-0.5 text-muted-foreground`,children:(0,G.jsx)(f?r:i,{className:`h-4 w-4`})}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[e&&(0,G.jsx)(`h3`,{className:`text-base font-semibold text-foreground`,children:e}),t&&(0,G.jsx)(`p`,{className:`text-sm text-muted-foreground mt-0.5`,children:t})]})]}):null,S=f?null:(0,G.jsx)(`div`,{className:v(`grid gap-4`,l||g[o]),children:s});return b?(0,G.jsxs)(d,{className:v(`form-section`,c),children:[x&&(0,G.jsxs)(D,{className:`pb-3`,children:[e&&(0,G.jsx)(h,{className:`text-base`,children:e}),t&&(0,G.jsx)(m,{children:t}),n&&(0,G.jsx)(`button`,{type:`button`,className:`absolute right-4 top-4 text-muted-foreground`,onClick:y,"aria-expanded":!f,"aria-label":f?`Expand section`:`Collapse section`,children:(0,G.jsx)(f?r:i,{className:`h-4 w-4`})})]}),S&&(0,G.jsx)(_,{children:S})]}):(0,G.jsxs)(`div`,{className:v(`form-section`,c),children:[x,S]})},q=({schema:e,dataSource:t,className:n})=>{let{fieldLabel:r}=B(),[i,a]=(0,W.useState)(null),[o,s]=(0,W.useState)({}),[c,l]=(0,W.useState)(!0),[u,d]=(0,W.useState)(null),[f,m]=(0,W.useState)(e.defaultTab||e.sections[0]?.name||e.sections[0]?.label||`tab-0`);W.useEffect(()=>{(async()=>{if(!t){l(!1);return}try{a(await t.getObjectSchema(e.objectName))}catch(e){d(e)}})()},[e.objectName,t]),W.useEffect(()=>{(i||!t)&&(async()=>{if(e.mode===`create`||!e.recordId||!t){s(e.initialData||e.initialValues||{}),l(!1);return}try{s(await t.findOne(e.objectName,e.recordId)||{})}catch(e){d(e)}finally{l(!1)}})()},[i,e.mode,e.recordId,e.initialData,e.initialValues,t,e.objectName]);let h=(0,W.useCallback)(t=>{let n=[];for(let a of t.fields){let t=typeof a==`string`?a:a.name;if(typeof a==`object`)n.push(a);else if(i?.fields?.[t]){let a=i.fields[t];n.push({name:t,label:r(e.objectName,t,a.label||t),type:M(a.type),required:a.required||!1,disabled:e.readOnly||e.mode===`view`||a.readonly,placeholder:a.placeholder,description:a.help||a.description,validation:A(a),field:a,options:a.options,multiple:a.multiple})}else n.push({name:t,label:t,type:`input`})}return n},[i,e.readOnly,e.mode]),g=(0,W.useCallback)(async n=>{if(!t)return e.onSuccess&&await e.onSuccess(n),n;try{let r;return e.mode===`create`?r=await t.create(e.objectName,n):e.mode===`edit`&&e.recordId&&(r=await t.update(e.objectName,e.recordId,n)),e.onSuccess&&await e.onSuccess(r),r}catch(t){throw e.onError&&e.onError(t),t}},[e,t]),_=(0,W.useCallback)(()=>{e.onCancel&&e.onCancel()},[e]),b=(e,t)=>e.name||e.label||`tab-${t}`;if(u)return(0,G.jsxs)(`div`,{className:`p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,G.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:`Error loading form`}),(0,G.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:u.message})]});if(c)return(0,G.jsxs)(`div`,{className:`p-8 text-center`,children:[(0,G.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900`}),(0,G.jsx)(`p`,{className:`mt-2 text-sm text-gray-600`,children:`Loading form...`})]});let x={type:`form`,fields:e.sections.flatMap(e=>h(e)),layout:`vertical`,defaultValues:o,submitLabel:e.submitText||(e.mode===`create`?`Create`:`Update`),cancelLabel:e.cancelText,showSubmit:e.showSubmit!==!1&&e.mode!==`view`,showCancel:e.showCancel!==!1,onSubmit:g,onCancel:_},S=e.tabPosition===`left`||e.tabPosition===`right`;return(0,G.jsx)(`div`,{className:v(`w-full`,n,e.className),children:(0,G.jsxs)(p,{value:f,onValueChange:m,orientation:S?`vertical`:`horizontal`,className:v(S&&`flex gap-4`),children:[(0,G.jsx)(y,{className:v(S?`flex-col h-auto`:``,e.tabPosition===`bottom`&&`order-last`,e.tabPosition===`right`&&`order-last`),children:e.sections.map((e,t)=>(0,G.jsx)(z,{value:b(e,t),className:S?`w-full justify-start`:``,children:e.label||`Tab ${t+1}`},b(e,t)))}),(0,G.jsx)(`div`,{className:`flex-1`,children:e.sections.map((t,n)=>(0,G.jsx)(P,{value:b(t,n),className:`mt-0`,children:(0,G.jsx)(K,{description:t.description,columns:t.columns||1,children:(0,G.jsx)(j,{schema:{...x,fields:h(t),showSubmit:e.showSubmit!==!1&&e.mode!==`view`,showCancel:e.showCancel!==!1}})})},b(t,n)))})]})})},J=({schema:e,dataSource:t,className:n})=>{let{fieldLabel:i}=B(),[o,l]=(0,W.useState)(null),[u,d]=(0,W.useState)({}),[f,p]=(0,W.useState)(!0),[m,h]=(0,W.useState)(null),[g,_]=(0,W.useState)(0),[y,b]=(0,W.useState)(new Set),[x,S]=(0,W.useState)(!1),C=e.sections.length,w=g===0,T=g===C-1;W.useEffect(()=>{(async()=>{if(!t){p(!1);return}try{l(await t.getObjectSchema(e.objectName))}catch(e){h(e)}})()},[e.objectName,t]),W.useEffect(()=>{(o||!t)&&(async()=>{if(e.mode===`create`||!e.recordId||!t){d(e.initialData||e.initialValues||{}),p(!1);return}try{d(await t.findOne(e.objectName,e.recordId)||{})}catch(e){h(e)}finally{p(!1)}})()},[o,e.mode,e.recordId,e.initialData,e.initialValues,t,e.objectName]);let E=(0,W.useCallback)(t=>{let n=[],r=(e,t)=>typeof t==`string`&&t.trim()?{...e,visible:e=>V(t,e)}:e;for(let a of t.fields){let t=typeof a==`string`?a:a.name;if(typeof a==`object`)n.push(r(a,a.visibleOn));else if(o?.fields?.[t]){let a=o.fields[t];n.push(r({name:t,label:i(e.objectName,t,a.label||t),type:M(a.type),required:a.required||!1,disabled:e.readOnly||e.mode===`view`||a.readonly,placeholder:a.placeholder,description:a.help||a.description,validation:A(a),field:a,options:a.options,multiple:a.multiple},a.visible_on??a.visibleOn))}else n.push({name:t,label:t,type:`input`})}return n},[o,e.readOnly,e.mode,e.objectName]),D=(0,W.useMemo)(()=>g>=0&&g<C?E(e.sections[g]):[],[g,C,e.sections,E]),O=(0,W.useCallback)(async n=>{let r={...u,...n};if(d(r),b(e=>new Set(e).add(g)),T){S(!0);try{if(!t)return e.onSuccess&&await e.onSuccess(r),r;let n;return e.mode===`create`?n=await t.create(e.objectName,r):e.mode===`edit`&&e.recordId&&(n=await t.update(e.objectName,e.recordId,r)),e.onSuccess&&await e.onSuccess(n),n}catch(t){throw e.onError&&e.onError(t),t}finally{S(!1)}}else k(g+1)},[u,g,T,e,t]),k=(0,W.useCallback)(t=>{t>=0&&t<C&&(_(t),e.onStepChange&&e.onStepChange(t))},[C,e]),N=(0,W.useCallback)(()=>{k(g-1)},[g,k]),P=(0,W.useCallback)(()=>{e.onCancel&&e.onCancel()},[e]),F=(0,W.useCallback)(t=>{(e.allowSkip||y.has(t)||t<=g)&&k(t)},[e.allowSkip,y,g,k]);if(m)return(0,G.jsxs)(`div`,{className:`p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,G.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:`Error loading form`}),(0,G.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:m.message})]});if(f)return(0,G.jsxs)(`div`,{className:`p-8 text-center`,children:[(0,G.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900`}),(0,G.jsx)(`p`,{className:`mt-2 text-sm text-gray-600`,children:`Loading form...`})]});let I=e.sections[g];return(0,G.jsxs)(`div`,{className:v(`w-full`,n,e.className),children:[e.showStepIndicator!==!1&&(0,G.jsx)(`nav`,{"aria-label":`Progress`,className:`mb-8`,children:(0,G.jsx)(`ol`,{className:`flex items-center`,children:e.sections.map((t,n)=>{let r=n===g,i=y.has(n),a=e.allowSkip||i||n<=g;return(0,G.jsxs)(`li`,{className:v(`relative flex-1`,n!==C-1&&`pr-8 sm:pr-12`),children:[n!==C-1&&(0,G.jsx)(`div`,{className:`absolute top-3 sm:top-4 left-6 -right-4 sm:left-10 sm:-right-2 h-0.5`,"aria-hidden":`true`,children:(0,G.jsx)(`div`,{className:v(`h-full`,i?`bg-primary`:`bg-muted`)})}),(0,G.jsxs)(`button`,{type:`button`,className:v(`group relative flex items-center`,a?`cursor-pointer`:`cursor-not-allowed`),onClick:()=>F(n),disabled:!a,children:[(0,G.jsx)(`span`,{className:v(`flex h-6 w-6 sm:h-8 sm:w-8 items-center justify-center rounded-full text-xs sm:text-sm font-medium transition-colors`,i&&`bg-primary text-primary-foreground`,r&&!i&&`border-2 border-primary bg-background text-primary`,!r&&!i&&`border-2 border-muted bg-background text-muted-foreground`),children:i?(0,G.jsx)(s,{className:`h-3 w-3 sm:h-4 sm:w-4`}):n+1}),(0,G.jsx)(`span`,{className:`ml-2 sm:ml-3 text-xs sm:text-sm font-medium hidden sm:block`,children:(0,G.jsx)(`span`,{className:v(r?`text-foreground`:`text-muted-foreground`),children:t.label||`Step ${n+1}`})})]})]},n)})})}),(0,G.jsx)(`div`,{className:`min-h-[200px]`,children:I&&(0,G.jsx)(K,{label:I.label,description:I.description,columns:I.columns||1,children:D.length>0?(0,G.jsx)(j,{schema:{type:`form`,fields:D,layout:`vertical`,defaultValues:u,showSubmit:!1,showCancel:!1,onSubmit:O}}):(0,G.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`No fields configured for this step`})})}),(0,G.jsxs)(`div`,{className:`flex items-center justify-between mt-6 pt-4 border-t`,children:[(0,G.jsx)(`div`,{children:e.showCancel!==!1&&(0,G.jsx)(U,{variant:`ghost`,onClick:P,children:e.cancelText||`Cancel`})}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsxs)(`span`,{className:`text-sm text-muted-foreground mr-2`,children:[`Step `,g+1,` of `,C]}),!w&&(0,G.jsxs)(U,{variant:`outline`,onClick:N,children:[(0,G.jsx)(c,{className:`h-4 w-4 mr-1`}),e.prevText||`Back`]}),T?(0,G.jsxs)(U,{onClick:()=>O(u),disabled:x||e.mode===`view`,children:[x&&(0,G.jsx)(a,{className:`mr-2 h-4 w-4 animate-spin`,"aria-hidden":!0}),x?`Submitting...`:e.submitText||(e.mode===`create`?`Create`:`Update`)]}):(0,G.jsxs)(U,{onClick:()=>O(u),children:[e.nextText||`Next`,(0,G.jsx)(r,{className:`h-4 w-4 ml-1`})]})]})]})]})},Y=({schema:e,dataSource:t,className:n})=>{let{fieldLabel:r}=B(),[i,a]=(0,W.useState)(null),[o,s]=(0,W.useState)({}),[c,l]=(0,W.useState)(!0),[u,d]=(0,W.useState)(null);(0,W.useEffect)(()=>{(async()=>{if(!t){l(!1);return}try{a(await t.getObjectSchema(e.objectName))}catch(e){d(e),l(!1)}})()},[e.objectName,t]),(0,W.useEffect)(()=>{(i||!t)&&(async()=>{if(e.mode===`create`||!e.recordId){s(e.initialData||e.initialValues||{}),l(!1);return}if(!t){s(e.initialData||e.initialValues||{}),l(!1);return}try{s(await t.findOne(e.objectName,e.recordId)||{})}catch(e){d(e)}finally{l(!1)}})()},[i,e.mode,e.recordId,e.initialData,e.initialValues,t,e.objectName]);let f=(0,W.useCallback)(t=>{let n=[],a=(e,t)=>typeof t==`string`&&t.trim()?{...e,visible:e=>V(t,e)}:e;for(let o of t.fields){let t=typeof o==`string`?o:o.name;if(typeof o==`object`)n.push(a(o,o.visibleOn));else if(i?.fields?.[t]){let o=i.fields[t];n.push(a({name:t,label:r(e.objectName,t,o.label||t),type:M(o.type),required:o.required||!1,disabled:e.readOnly||e.mode===`view`||o.readonly,placeholder:o.placeholder,description:o.help||o.description,validation:A(o),field:o,options:o.options,multiple:o.multiple},o.visible_on??o.visibleOn))}else n.push({name:t,label:t,type:`input`})}return n},[i,e.readOnly,e.mode,e.objectName]),p=(0,W.useCallback)(async n=>{if(!t)return e.onSuccess&&await e.onSuccess(n),n;try{let r;return e.mode===`create`?r=await t.create(e.objectName,n):e.mode===`edit`&&e.recordId&&(r=await t.update(e.objectName,e.recordId,n)),e.onSuccess&&await e.onSuccess(r),r}catch(t){throw e.onError&&e.onError(t),t}},[e,t]),m=(0,W.useCallback)(()=>{e.onCancel&&e.onCancel()},[e]),h=(0,W.useMemo)(()=>e.sections.slice(0,1),[e.sections]),g=(0,W.useMemo)(()=>e.sections.slice(1),[e.sections]);(0,W.useMemo)(()=>e.sections.flatMap(e=>f(e)),[e.sections,f]);let _=e.splitDirection||`horizontal`,y=e.splitSize||50;if(u)return(0,G.jsxs)(`div`,{className:`p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,G.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:`Error loading form`}),(0,G.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:u.message})]});if(c)return(0,G.jsxs)(`div`,{className:`p-8 text-center`,children:[(0,G.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900`}),(0,G.jsx)(`p`,{className:`mt-2 text-sm text-gray-600`,children:`Loading form...`})]});let b={type:`form`,layout:`vertical`,defaultValues:o,onSubmit:p,onCancel:m},x=(t,n)=>(0,G.jsx)(`div`,{className:`space-y-4 p-4`,children:t.map((t,r)=>(0,G.jsx)(K,{label:t.label,description:t.description,columns:t.columns||1,children:(0,G.jsx)(j,{schema:{...b,fields:f(t),showSubmit:n&&e.showSubmit!==!1&&e.mode!==`view`,showCancel:n&&e.showCancel!==!1,submitLabel:e.submitText||(e.mode===`create`?`Create`:`Update`),cancelLabel:e.cancelText}})},t.name||t.label||r))});return(0,G.jsx)(`div`,{className:v(`w-full`,n,e.className),children:(0,G.jsxs)(T,{orientation:_,className:`min-h-[300px] rounded-lg border`,children:[(0,G.jsx)(I,{defaultSize:y,minSize:20,children:x(h,g.length===0)}),g.length>0&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(H,{withHandle:e.splitResizable!==!1}),(0,G.jsx)(I,{defaultSize:100-y,minSize:20,children:x(g,!0)})]})]})})},te=new Set([`field:formula`,`field:summary`,`field:auto_number`,`field:autonumber`]),ne=new Set([`field:textarea`,`field:markdown`,`field:html`,`field:grid`,`field:rich-text`,`textarea`,`markdown`,`html`,`grid`,`rich-text`]),re=new Set([`formula`,`summary`,`auto_number`,`autonumber`]);function ie(e){return ne.has(e)}function ae(e){return re.has(e)}function oe(e){return e<=3?1:2}function X(e,t){return t<=1?e:e.map(e=>e.colSpan===void 0&&e.type&&ie(e.type)?{...e,colSpan:t}:e)}var se=new Set([`id`,`created_at`,`createdAt`,`updated_at`,`updatedAt`,`last_modified_at`,`lastModifiedAt`,`deleted_at`,`deletedAt`,`created_by`,`createdBy`,`updated_by`,`updatedBy`,`last_modified_by`,`lastModifiedBy`,`organization_id`,`organizationId`,`org_id`,`orgId`,`tenant_id`,`tenantId`,`owner`,`owner_id`,`_version`,`_rev`]);function ce(e,t){return e.filter(e=>!(se.has(e.name)||t?.fields?.[e.name]?.readonly===!0))}function le(e,t){return e.filter(e=>{if(e.type&&te.has(e.type))return!1;let n=t?.fields?.[e.name];return n?!ae(n.type):!0})}function Z(e){return e<=1?`default`:e===2?`xl`:`full`}function Q(e,t,n,r){let i=[...e];if(i=ce(i,t),r===`create`&&(i=le(i,t)),n!==void 0)return i=X(i,n),{fields:i,columns:n};let a=oe(i.length);return i=X(i,a),{fields:i,columns:a}}var ue=new Set([`id`,`_id`,`created_at`,`updated_at`,`createdAt`,`updatedAt`,`organization_id`,`organizationId`]),de=new Set([`formula`,`rollup`,`lookup_value`,`auto_number`,`autonumber`,`computed`]);function fe(e,t){if(!e||typeof e!=`object`)return e;let n={},r=t?.fields;for(let[t,i]of Object.entries(e))if(!ue.has(t)){if(r){let e=r[t];if(!e)continue;let n=String(e.type||``).toLowerCase();if(de.has(n)||e.computed===!0||e.formula||e.readOnly===!0||e.readonly===!0)continue}n[t]=i}return n}var pe={1:void 0,2:`grid gap-4 grid-cols-1 @md:grid-cols-2`,3:`grid gap-4 grid-cols-1 @md:grid-cols-2 @2xl:grid-cols-3`,4:`grid gap-4 grid-cols-1 @md:grid-cols-2 @2xl:grid-cols-3 @4xl:grid-cols-4`},me=({schema:e,dataSource:t,className:n})=>{let{fieldLabel:r}=B(),[i,a]=(0,W.useState)(null),[o,s]=(0,W.useState)([]),[c,l]=(0,W.useState)({}),[u,d]=(0,W.useState)(!0),[f,p]=(0,W.useState)(null),m=e.open!==!1,h=e.drawerSide||`right`,[_,y]=(0,W.useState)(()=>{let t={};return e.sections?.forEach((e,n)=>{let r=e.name||String(n);e.collapsed&&(t[r]=!0)}),t});(0,W.useEffect)(()=>{(async()=>{if(!t){d(!1);return}try{a(await t.getObjectSchema(e.objectName))}catch(e){p(e),d(!1)}})()},[e.objectName,t]),(0,W.useEffect)(()=>{(i||!t)&&(async()=>{if(e.mode===`create`||!e.recordId){l(e.initialData||e.initialValues||{}),d(!1);return}if(!t){l(e.initialData||e.initialValues||{}),d(!1);return}try{l(await t.findOne(e.objectName,e.recordId)||{})}catch(e){p(e)}finally{d(!1)}})()},[i,e.mode,e.recordId,e.initialData,e.initialValues,t,e.objectName]);let b=(0,W.useCallback)(t=>{let n=[];for(let a of t.fields){let t=typeof a==`string`?a:a.name;if(typeof a==`object`)n.push(a);else if(i?.fields?.[t]){let a=i.fields[t];n.push({name:t,label:r(e.objectName,t,a.label||t),type:M(a.type),required:a.required||!1,disabled:e.readOnly||e.mode===`view`||a.readonly,placeholder:a.placeholder,description:a.help||a.description,validation:A(a),field:a,options:a.options,multiple:a.multiple})}else n.push({name:t,label:t,type:`input`})}return n},[i,e.readOnly,e.mode]);(0,W.useEffect)(()=>{if(!i&&t)return;if(e.customFields?.length){s(e.customFields),d(!1);return}if(e.sections?.length){d(!1);return}if(!i)return;let n=e.fields||Object.keys(i.fields||{}),a=[];for(let t of n){let n=typeof t==`string`?t:t.name;if(!n)continue;let o=i.fields?.[n];o&&a.push({name:n,label:r(e.objectName,n,o.label||n),type:M(o.type),required:o.required||!1,disabled:e.readOnly||e.mode===`view`||o.readonly,placeholder:o.placeholder,description:o.help||o.description,validation:A(o),field:o,options:o.options,multiple:o.multiple})}s(a),d(!1)},[i,e.fields,e.customFields,e.sections,e.readOnly,e.mode,t]);let x=(0,W.useCallback)(async n=>{if(!t)return e.onSuccess&&await e.onSuccess(n),e.onOpenChange?.(!1),n;try{let r,a=fe(n,i);return e.mode===`create`?r=await t.create(e.objectName,a):e.mode===`edit`&&e.recordId&&(r=await t.update(e.objectName,e.recordId,a)),e.onSuccess&&await e.onSuccess(r),e.onOpenChange?.(!1),r}catch(t){throw e.onError&&e.onError(t),t}},[e,t,i]),S=(0,W.useCallback)(()=>{e.onCancel&&e.onCancel(),e.onOpenChange?.(!1)},[e]),C=(0,W.useMemo)(()=>{if(e.drawerWidth)return h===`left`||h===`right`?{width:e.drawerWidth,maxWidth:e.drawerWidth}:{height:e.drawerWidth,maxHeight:e.drawerWidth}},[e.drawerWidth,h]),T={type:`form`,layout:e.layout===`vertical`||e.layout===`horizontal`?e.layout:`vertical`,defaultValues:c,submitLabel:e.submitText||(e.mode===`create`?`Create`:`Update`),cancelLabel:e.cancelText,showSubmit:e.showSubmit!==!1&&e.mode!==`view`,showCancel:e.showCancel!==!1,onSubmit:x,onCancel:S};return(0,G.jsx)(k,{open:m,onOpenChange:e.onOpenChange,children:(0,G.jsxs)(E,{side:h,className:v(`overflow-y-auto`,n,e.className),style:C,children:[(e.title||e.description)&&(0,G.jsxs)(w,{children:[e.title&&(0,G.jsx)(g,{children:e.title}),e.description&&(0,G.jsx)(F,{children:e.description})]}),(0,G.jsx)(`div`,{className:`@container py-4`,children:(()=>{if(f)return(0,G.jsxs)(`div`,{className:`p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,G.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:`Error loading form`}),(0,G.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:f.message})]});if(u)return(0,G.jsxs)(`div`,{className:`p-8 text-center`,children:[(0,G.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900`}),(0,G.jsx)(`p`,{className:`mt-2 text-sm text-gray-600`,children:`Loading form...`})]});if(e.sections?.length){let t=[];return e.sections.forEach((e,n)=>{let r=e.name||String(n),i=_[r]??e.collapsed??!1;t.push({name:`__section_${r}`,label:e.label||``,type:`section-divider`,colSpan:4,collapsible:e.collapsible,collapsed:i,onToggle:e.collapsible?()=>y(e=>({...e,[r]:!i})):void 0});let a=b(e);i?t.push(...a.map(e=>({...e,hidden:!0}))):t.push(...a)}),(0,G.jsx)(j,{schema:{...T,fields:t}})}let t=Q(o,i,e.columns,e.mode),n=pe[t.columns||1];return(0,G.jsx)(j,{schema:{...T,fields:t.fields,columns:t.columns,...n?{fieldContainerClass:n}:{}}})})()})]})})},he={sm:`sm:max-w-sm`,default:`sm:max-w-lg`,lg:`sm:max-w-2xl`,xl:`sm:max-w-5xl`,full:`sm:max-w-[95vw] sm:w-full`},ge={1:void 0,2:`grid gap-4 grid-cols-1 @md:grid-cols-2`,3:`grid gap-4 grid-cols-1 @md:grid-cols-2 @2xl:grid-cols-3`,4:`grid gap-4 grid-cols-1 @md:grid-cols-2 @2xl:grid-cols-3 @4xl:grid-cols-4`},_e=({schema:e,dataSource:t,className:n})=>{let{fieldLabel:r}=B(),i=L(),o=(0,W.useCallback)(t=>{if(!i?.isLoaded)return t;let n=[];for(let r of t){if(!r?.name){n.push(r);continue}i.checkField(e.objectName,r.name,`read`)&&(!i.checkField(e.objectName,r.name,`write`)&&e.mode!==`view`?n.push({...r,readOnly:!0,disabled:!0}):n.push(r))}return n},[i,e.objectName,e.mode]),[s,c]=(0,W.useState)(null),[l,u]=(0,W.useState)([]),[d,f]=(0,W.useState)({}),[p,m]=(0,W.useState)(!0),[h,g]=(0,W.useState)(null),[_,y]=(0,W.useState)(!1),S=e.open!==!1,w=(0,W.useId)(),T=(0,W.useMemo)(()=>e.sections?.length||e.customFields?.length?null:Q(l,s,e.columns,e.mode),[l,s,e.columns,e.mode,e.sections,e.customFields]),E=he[(0,W.useMemo)(()=>{if(e.modalSize)return e.modalSize;if(T?.columns&&T.columns>1)return Z(T.columns);if(e.sections?.length){let t=Math.max(...e.sections.map(e=>Number(e.columns)||1));if(t>1)return Z(t)}return`default`},[e.modalSize,T,e.sections])]||he.default;(0,W.useEffect)(()=>{(async()=>{if(!t){m(!1);return}try{c(await t.getObjectSchema(e.objectName))}catch(e){g(e),m(!1)}})()},[e.objectName,t]),(0,W.useEffect)(()=>{(s||!t)&&(async()=>{if(e.mode===`create`||!e.recordId){f(e.initialData||e.initialValues||{}),m(!1);return}if(!t){f(e.initialData||e.initialValues||{}),m(!1);return}try{f(await t.findOne(e.objectName,e.recordId)||{})}catch(e){g(e)}finally{m(!1)}})()},[s,e.mode,e.recordId,e.initialData,e.initialValues,t,e.objectName]);let D=(0,W.useCallback)(t=>{let n=[],i=(e,t)=>typeof t==`string`&&t.trim()?{...e,visible:e=>V(t,e)}:e;for(let a of t.fields){let t=typeof a==`string`?a:a.name;if(typeof a==`object`)n.push(i(a,a.visibleOn));else if(s?.fields?.[t]){let a=s.fields[t];n.push(i({name:t,label:r(e.objectName,t,a.label||t),type:M(a.type),required:a.required||!1,disabled:e.readOnly||e.mode===`view`||a.readonly,placeholder:a.placeholder,description:a.help||a.description,validation:A(a),field:a,options:a.options,multiple:a.multiple},a.visible_on??a.visibleOn))}else n.push({name:t,label:t,type:`input`})}return n},[s,e.readOnly,e.mode,e.objectName]);(0,W.useEffect)(()=>{if(!s&&t)return;if(e.customFields?.length){u(e.customFields),m(!1);return}if(e.sections?.length){m(!1);return}if(!s)return;let n=e.fields||Object.keys(s.fields||{}),i=[];for(let t of n){let n=typeof t==`string`?t:t.name;if(!n)continue;let a=s.fields?.[n];a&&i.push({name:n,label:r(e.objectName,n,a.label||n),type:M(a.type),required:a.required||!1,disabled:e.readOnly||e.mode===`view`||a.readonly,placeholder:a.placeholder,description:a.help||a.description,validation:A(a),field:a,options:a.options,multiple:a.multiple})}u(i),m(!1)},[s,e.fields,e.customFields,e.sections,e.readOnly,e.mode,t]);let k=(0,W.useCallback)(async n=>{y(!0);try{if(!t)return e.onSuccess&&await e.onSuccess(n),e.onOpenChange?.(!1),n;let r,a=fe(n,s);if(i?.isLoaded){let t={};for(let n of Object.keys(a))i.checkField(e.objectName,n,`write`)&&(t[n]=a[n]);a=t}return e.mode===`create`?r=await t.create(e.objectName,a):e.mode===`edit`&&e.recordId&&(r=await t.update(e.objectName,e.recordId,a)),e.onSuccess&&await e.onSuccess(r),e.onOpenChange?.(!1),r}catch(t){throw e.onError&&e.onError(t),t}finally{y(!1)}},[e,t,s,i]),P=(0,W.useCallback)(()=>{e.onCancel&&e.onCancel(),e.onOpenChange?.(!1)},[e]),F=e.layout===`vertical`||e.layout===`horizontal`?e.layout:`vertical`,I=e.showSubmit!==!1&&e.mode!==`view`,R=e.showCancel!==!1,z=e.submitText||(e.mode===`create`?`Create`:`Update`),H=e.cancelText||`Cancel`,q={type:`form`,layout:F,defaultValues:d,submitLabel:z,cancelLabel:H,showSubmit:I,showCancel:R,onSubmit:k,onCancel:P,showActions:!1,id:w},J=()=>{if(h)return(0,G.jsxs)(`div`,{className:`p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,G.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:`Error loading form`}),(0,G.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:h.message})]});if(p)return(0,G.jsx)(`div`,{className:`space-y-4`,"data-testid":`modal-form-skeleton`,children:[1,2,3].map(e=>(0,G.jsxs)(`div`,{className:`space-y-2`,children:[(0,G.jsx)(x,{className:`h-4 w-24`}),(0,G.jsx)(x,{className:`h-10 w-full`})]},e))});if(e.sections?.length)return(0,G.jsx)(`div`,{className:`space-y-6`,children:e.sections.map((e,t)=>{let n=e.columns||1;return(0,G.jsx)(K,{label:e.label,description:e.description,columns:n,gridClassName:ge[n],children:(0,G.jsx)(j,{schema:{...q,fields:o(D(e))}})},e.name||e.label||t)})});let t=T??Q(l,s,e.columns,e.mode),n=ge[t.columns||1];return(0,G.jsx)(j,{schema:{...q,fields:o(t.fields),columns:t.columns,...n?{fieldContainerClass:n}:{}}})},Y=!p&&!h&&(I||R);return(0,G.jsx)(b,{open:S,onOpenChange:e.onOpenChange,children:(0,G.jsxs)(ee,{className:v(E,`flex flex-col h-[100dvh] sm:h-auto sm:max-h-[90vh] overflow-hidden p-0`,n,e.className),children:[(e.title||e.description)&&(0,G.jsxs)(O,{className:`shrink-0 px-4 pt-4 sm:px-6 sm:pt-6 pb-2 border-b`,children:[e.title&&(0,G.jsx)(N,{children:e.title}),e.description&&(0,G.jsx)(C,{children:e.description})]}),(0,G.jsx)(`div`,{className:`@container flex-1 overflow-y-auto px-4 sm:px-6 py-4`,children:J()}),Y&&(0,G.jsx)(`div`,{className:`shrink-0 border-t px-4 sm:px-6 py-3 bg-background`,"data-testid":`modal-form-footer`,children:(0,G.jsxs)(`div`,{className:`flex flex-col sm:flex-row gap-2 sm:justify-end`,children:[R&&(0,G.jsx)(U,{type:`button`,variant:`outline`,onClick:P,disabled:_,className:`w-full sm:w-auto`,children:H}),I&&(0,G.jsxs)(U,{type:`submit`,form:w,disabled:_,className:`w-full sm:w-auto`,children:[_&&(0,G.jsx)(a,{className:`mr-2 h-4 w-4 animate-spin`}),z]})]})})]})})},$=({schema:e,dataSource:t})=>{let n=L(),r=(0,W.useMemo)(()=>{if(!n?.isLoaded)return e;let t=t=>t?.name?n.checkField(e.objectName,t.name,`read`)?!n.checkField(e.objectName,t.name,`write`)&&e.mode!==`view`?{...t,readOnly:!0,disabled:!0}:t:null:t,r=e=>Array.isArray(e)?e.map(t).filter(Boolean):e;return{...e,fields:r(e.fields),sections:e.sections?.map(e=>({...e,fields:r(e.fields)}))}},[e,n]),{sectionLabel:i}=B(),a=e=>e?.name?i(r.objectName,e.name,e.label||e.name):e?.label;if(r.formType===`tabbed`&&r.sections?.length)return(0,G.jsx)(q,{schema:{...r,formType:`tabbed`,sections:r.sections.map(e=>({name:e.name,label:a(e),description:e.description,columns:e.columns,fields:e.fields})),defaultTab:r.defaultTab,tabPosition:r.tabPosition},dataSource:t,className:r.className});if(r.formType===`wizard`&&r.sections?.length)return(0,G.jsx)(J,{schema:{...r,formType:`wizard`,sections:r.sections.map(e=>({name:e.name,label:a(e),description:e.description,columns:e.columns,fields:e.fields})),allowSkip:r.allowSkip,showStepIndicator:r.showStepIndicator,nextText:r.nextText,prevText:r.prevText,onStepChange:r.onStepChange},dataSource:t,className:r.className});if(r.formType===`split`&&r.sections?.length)return(0,G.jsx)(Y,{schema:{...r,formType:`split`,sections:r.sections.map(e=>({name:e.name,label:a(e),description:e.description,columns:e.columns,fields:e.fields})),splitDirection:r.splitDirection,splitSize:r.splitSize,splitResizable:r.splitResizable},dataSource:t,className:r.className});if(r.formType===`drawer`){let{layout:e,...n}=r,i=r.layout===`vertical`||r.layout===`horizontal`?r.layout:void 0;return(0,G.jsx)(me,{schema:{...n,layout:i,formType:`drawer`,sections:r.sections?.map(e=>({name:e.name,label:a(e),description:e.description,columns:e.columns,fields:e.fields,collapsible:e.collapsible,collapsed:e.collapsed})),open:r.open,onOpenChange:r.onOpenChange,drawerSide:r.drawerSide,drawerWidth:r.drawerWidth},dataSource:t,className:r.className})}if(r.formType===`modal`){let{layout:e,...n}=r,i=r.layout===`vertical`||r.layout===`horizontal`?r.layout:void 0;return(0,G.jsx)(_e,{schema:{...n,layout:i,formType:`modal`,sections:r.sections?.map(e=>({name:e.name,label:a(e),description:e.description,columns:e.columns,fields:e.fields})),open:r.open,onOpenChange:r.onOpenChange,modalSize:r.modalSize,modalCloseButton:r.modalCloseButton},dataSource:t,className:r.className})}return(0,G.jsx)(ve,{schema:r,dataSource:t})},ve=({schema:e,dataSource:t})=>{let{fieldLabel:n,sectionLabel:r}=B(),i=S(),a=L(),o=(0,W.useCallback)(t=>{if(!a?.isLoaded)return t;let n=[];for(let r of t)a.checkField(e.objectName,r.name,`read`)&&(!a.checkField(e.objectName,r.name,`write`)&&e.mode!==`view`?n.push({...r,readOnly:!0,disabled:!0,description:r.description??`You do not have edit access to this field.`}):n.push(r));return n},[a,e.objectName,e.mode]),[s,c]=(0,W.useState)(null),[l,u]=(0,W.useState)([]),[d,f]=(0,W.useState)(null),[p,m]=(0,W.useState)(!0),[h,g]=(0,W.useState)(null),_=e.customFields&&e.customFields.length>0;(0,W.useEffect)(()=>{_&&(f(e.initialData||e.initialValues||{}),m(!1))},[_,e.initialData,e.initialValues]),(0,W.useEffect)(()=>{_?c({name:e.objectName,fields:{}}):e.objectName&&t?(async()=>{try{if(!t)throw Error(`DataSource is required when using ObjectQL schema fetching (inline fields not provided)`);let n=await t.getObjectSchema(e.objectName);if(!n)throw Error(`No schema found for object "${e.objectName}"`);c(n)}catch(e){g(e),m(!1)}})():_||m(!1)},[e.objectName,t,_]),(0,W.useEffect)(()=>{s&&!_&&(async()=>{if(!e.recordId||e.mode===`create`){f(e.initialData||e.initialValues||{}),m(!1);return}if(!_){if(!t){g(Error(`DataSource is required for fetching record data (inline data not provided)`)),m(!1);return}m(!0);try{f(await t.findOne(e.objectName,e.recordId))}catch(e){console.error(`Failed to fetch record:`,e),g(e)}finally{m(!1)}}})()},[e.objectName,e.recordId,e.mode,e.initialValues,e.initialData,t,s,_]);let v=(0,W.useCallback)(e=>{if(!e||typeof e.visible==`function`)return e;let t=e.visibleOn;return typeof t==`string`&&t.trim()?{...e,visible:e=>V(t,e)}:e},[]);(0,W.useEffect)(()=>{if(_&&e.customFields){u(e.customFields.map(v)),m(!1);return}if(!s)return;let r=[],i=e.fields||Object.keys(s.fields||{});(Array.isArray(i)?i:Object.keys(i)).forEach(t=>{let i=typeof t==`string`?t:t.name;if(!i)return;let a=s.fields?.[i];if(!a&&!_)return;let o=!a?.permissions||a?.permissions.write!==!1;if(e.mode!==`view`&&!o)return;let c=e.customFields?.find(e=>e.name===i);if(c)r.push(v(c));else if(a){let o={name:i,label:n(e.objectName,i,a.label||t),type:M(a.type),required:a.required||!1,disabled:e.readOnly||e.mode===`view`||a.readonly||s?.managedBy&&s.managedBy!==`platform`,placeholder:a.placeholder,description:a.help||a.description,validation:A(a),field:a};if((a.type===`select`||a.type===`lookup`||a.type===`master_detail`)&&(o.options=a.options||[],o.multiple=a.multiple),(a.type===`number`||a.type===`currency`||a.type===`percent`)&&(o.inputType=`number`,o.min=a.min,o.max=a.max,o.step=a.precision?10**-a.precision:void 0),a.type===`date`&&(o.inputType=`date`),a.type===`datetime`&&(o.inputType=`datetime-local`),(a.type===`text`||a.type===`textarea`||a.type===`markdown`||a.type===`html`)&&(o.maxLength=a.max_length,o.minLength=a.min_length),(a.type===`file`||a.type===`image`)&&(o.inputType=`file`,o.multiple=a.multiple,o.accept=a.accept?a.accept.join(`,`):void 0,a.max_size)){let e=`Max size: ${R(a.max_size)}`;o.description=o.description?`${o.description} (${e})`:e}a.type===`email`&&(o.inputType=`email`),a.type===`phone`&&(o.inputType=`tel`),a.type===`url`&&(o.inputType=`url`),a.type===`password`&&(o.inputType=`password`),a.type===`time`&&(o.inputType=`time`),(a.type===`formula`||a.type===`summary`||a.type===`auto_number`)&&(o.disabled=!0),a.visible_on&&(o.visible=e=>V(a.visible_on,e)),r.push(o)}}),u(r),!_&&e.recordId&&e.mode!==`create`&&t||m(!1)},[s,e.fields,e.customFields,e.readOnly,e.mode,_,e.recordId,t]);let y=(0,W.useCallback)(async(n,r)=>{if(n&&(n.nativeEvent||n._reactName===`onSubmit`)&&(console.warn(`ObjectForm: Received Event instead of data in handleSubmit! This suggests a Form renderer issue.`),r===void 0&&(r=n,n={})),_&&!t)return e.onSuccess&&await e.onSuccess(n),n;if(!t)throw Error(`DataSource is required for form submission (inline mode not configured)`);let i=n;if(a?.isLoaded&&n&&typeof n==`object`){i={};for(let t of Object.keys(n))a.checkField(e.objectName,t,`write`)&&(i[t]=n[t])}try{let n;if(e.mode===`create`)n=await t.create(e.objectName,i);else if(e.mode===`edit`&&e.recordId)n=await t.update(e.objectName,e.recordId,i);else throw Error(`Invalid form mode or missing record ID`);return e.onSuccess&&await e.onSuccess(n),n}catch(t){throw console.error(`Failed to submit form:`,t),e.onError&&e.onError(t),t}},[e,t,_,a]),b=(0,W.useCallback)(()=>{e.onCancel&&e.onCancel()},[e]),x={...W.useMemo(()=>{if(!s?.fields)return{};let e={};return Object.keys(s.fields).forEach(t=>{let n=s.fields[t];n.defaultValue!==void 0&&(e[t]=n.defaultValue)}),e},[s]),...d};if(h)return(0,G.jsxs)(`div`,{className:`p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,G.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:`Error loading form`}),(0,G.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:h.message})]});if(p)return(0,G.jsxs)(`div`,{className:`p-4 sm:p-8 text-center`,children:[(0,G.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900`}),(0,G.jsx)(`p`,{className:`mt-2 text-sm text-gray-600`,children:`Loading form...`})]});let C=e.layout===`vertical`||e.layout===`horizontal`?e.layout:`vertical`;if(e.sections?.length&&(!e.formType||e.formType===`simple`))return(0,G.jsx)(`div`,{className:`w-full space-y-6`,children:e.sections.map((t,n)=>{let i=t.fields.map(e=>typeof e==`string`?e:e.name),a=o(l.filter(e=>i.includes(e.name)));return(0,G.jsx)(K,{label:t.name?r(e.objectName,t.name,t.label||t.name):t.label,description:t.description,collapsible:t.collapsible,collapsed:t.collapsed,columns:t.columns,showBorder:t.showBorder,children:(0,G.jsx)(j,{schema:{type:`form`,fields:a,layout:C,defaultValues:x,showSubmit:n===e.sections.length-1&&e.showSubmit!==!1&&e.mode!==`view`,showCancel:n===e.sections.length-1&&e.showCancel!==!1,submitLabel:e.submitText||(e.mode===`create`?`Create`:`Update`),cancelLabel:e.cancelText,onSubmit:y,onCancel:b}})},t.name||t.label||n)})});let w=e.sections?.length,T=o(l),E=w?{fields:T,columns:e.columns}:Q(T,s,e.columns,e.mode),D=e.mobile,O=D?.fullscreenLongText?E.fields.map(e=>{let t=e.type;return t===`textarea`||t===`field:textarea`||t===`string-multiline`||t===`field:markdown`||t===`field:html`?{...e,mobile_fullscreen:!0}:e}):E.fields,k=D?.stepper,N=D?.stepperMinFields??8,P=Math.max(1,D?.stepperFieldsPerStep??1);if(!e.formType&&!w&&O.length>=2&&(k===!0||k===`auto`&&i&&O.length>=N)){let n=O,r=[];for(let e=0;e<n.length;e+=P){let t=n.slice(e,e+P);r.push({name:`step-${Math.floor(e/P)+1}`,label:t[0]?.label||t[0]?.name||`Step ${Math.floor(e/P)+1}`,fields:t})}return(0,G.jsx)(J,{schema:{...e,formType:`wizard`,sections:r,showStepIndicator:!0},dataSource:t,className:e.className})}let F={type:`form`,fields:O,layout:C,columns:E.columns,submitLabel:e.submitText||(e.mode===`create`?`Create`:`Update`),cancelLabel:e.cancelText,showSubmit:e.showSubmit!==!1&&e.mode!==`view`,showCancel:e.showCancel!==!1,resetOnSubmit:e.showReset,defaultValues:x,onSubmit:y,onCancel:b,className:e.className,mobileStickyActions:!!D?.stickyActions};return(0,G.jsx)(`div`,{className:D?.stickyActions?`w-full pb-20 md:pb-0`:`w-full`,"data-mobile-form":D?`true`:void 0,children:(0,G.jsx)(j,{schema:F})})},ye={text:200,email:254,url:2048,phone:32,textarea:5e3,markdown:5e3,html:5e3},be=`_company_website_2`,xe=1500;function Se(e,t=[]){try{let n=new URL(e,typeof window<`u`?window.location.href:`http://localhost`);return typeof window<`u`&&n.origin===window.location.origin?!0:n.protocol!==`https:`&&n.protocol!==`http:`?!1:t.some(e=>{if(e===n.host)return!0;if(e.startsWith(`*.`)){let t=e.slice(1);return n.host.endsWith(t)&&n.host.length>t.length}return!1})}catch{return!1}}function Ce(e){return e&&e.map(e=>{let t=ye[String(e.type||``).toLowerCase()];return!t||(e.maxLength??e.max_length)?e:{...e,maxLength:t}})}var we=({config:e,dataSource:t,prefillParams:n,className:r})=>{let[i,s]=(0,W.useState)(!1),[c,d]=(0,W.useState)(!1),[f,p]=(0,W.useState)(null),[m,h]=(0,W.useState)(!(e.consent?.required??!!e.consent)),[g,_]=(0,W.useState)(null),v=(0,W.useRef)(null),y=(0,W.useRef)(Date.now());(0,W.useEffect)(()=>{i||(y.current=Date.now())},[i]);let b=e.honeypot===!1?null:e.honeypot||be,x=e.minFillTime??xe,S=(0,W.useMemo)(()=>Ce(e.customFields),[e.customFields]),C=(0,W.useMemo)(()=>{if(!t||S&&S.length>0||!e.fields||e.fields.length===0)return;let n=async(e,t)=>t;return{...t,create:n,update:(e,t,n)=>Promise.resolve(n),delete:()=>Promise.reject(Error(`Not permitted on public form`))}},[t,S,e.fields]),w=(0,W.useMemo)(()=>{let t={};if(n)for(let[e,r]of Object.entries(n))t[e]=r;if(typeof window<`u`&&e.allowedPrefillFields?.length){let n=new Set(e.allowedPrefillFields);new URLSearchParams(window.location.search).forEach((e,r)=>{n.has(r)&&!(r in t)&&(t[r]=e)})}return Object.keys(t).length>0?t:void 0},[n,e.allowedPrefillFields]),T=(0,W.useCallback)(async n=>{if(e.consent?.required&&!m){_(e.texts?.consentRequired??`Please accept the privacy policy to continue.`);return}if(_(null),b&&v.current?.value){s(!0);return}if(x>0&&Date.now()-y.current<x){p(e.texts?.rateLimited??`Please take a moment to review your answers before submitting.`);return}let r={...n};b&&delete r[b],e.captchaToken&&(r._captcha=e.captchaToken),d(!0),p(null);try{t&&await t.create(e.objectName,r),s(!0);let n=e.thankYouPage?.redirectUrl;if(n)if(Se(n,e.allowedRedirectHosts)){let t=e.thankYouPage?.redirectDelay??3e3;setTimeout(()=>{window.location.href=n},t)}else console.warn(`[EmbeddableForm] Blocked unsafe redirect target:`,n),p(e.texts?.redirectBlocked??null)}catch(e){p(e instanceof Error?e.message:`Failed to submit form. Please try again.`)}finally{d(!1)}},[t,e,m,b,x]),E=(0,W.useCallback)(()=>{s(!1),p(null)},[]),D=(0,W.useMemo)(()=>{let t={};return e.branding?.backgroundColor&&(t.backgroundColor=e.branding.backgroundColor),t},[e.branding]);if(i){let t=e.thankYouPage,n=e.texts??{},i=Math.ceil((t?.redirectDelay??3e3)/1e3),a=(n.redirecting??`Redirecting in {{seconds}} seconds…`).replace(`{{seconds}}`,String(i));return(0,G.jsx)(`div`,{className:`min-h-screen flex items-center justify-center p-4 bg-gradient-to-b from-muted/40 via-background to-background ${r||``}`,style:D,children:(0,G.jsxs)(`div`,{className:`max-w-md w-full bg-card border rounded-xl shadow-sm p-8 text-center space-y-4`,children:[(0,G.jsx)(`div`,{className:`mx-auto inline-flex h-14 w-14 items-center justify-center rounded-full bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400`,children:(0,G.jsx)(o,{className:`h-8 w-8`,"aria-hidden":`true`})}),(0,G.jsx)(`h2`,{className:`text-xl font-semibold text-foreground`,children:t?.title||n.thankYouTitle||`Thank You!`}),(0,G.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t?.message||n.thankYouMessage||`Your submission has been received successfully.`}),e.allowMultiple&&(0,G.jsx)(U,{variant:`outline`,size:`sm`,onClick:E,className:`mt-2`,children:n.submitAnother??`Submit Another Response`}),t?.redirectUrl&&(0,G.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a})]})})}let O=e.texts??{},k=!!e.consent?.required,A=`${e.formId}-consent`;return(0,G.jsx)(`div`,{className:`min-h-screen flex items-center justify-center p-4 sm:p-6 bg-gradient-to-b from-muted/40 via-background to-background ${r||``}`,style:D,children:(0,G.jsxs)(`div`,{className:`max-w-2xl w-full bg-card border rounded-xl shadow-sm overflow-hidden`,children:[e.branding?.coverImage&&(0,G.jsx)(`div`,{className:`h-28 sm:h-32 w-full bg-cover bg-center`,style:{backgroundImage:`url(${JSON.stringify(e.branding.coverImage)})`},role:`presentation`}),(0,G.jsxs)(`div`,{className:`px-6 sm:px-8 pt-7 pb-5 border-b bg-muted/20`,style:e.branding?.primaryColor?{borderBottomColor:e.branding.primaryColor}:void 0,children:[e.branding?.logo&&(0,G.jsx)(`img`,{src:e.branding.logo,alt:``,className:`h-8 mb-4`}),e.title&&(0,G.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight text-foreground`,children:e.title}),e.description&&(0,G.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2 leading-relaxed`,children:e.description}),(0,G.jsx)(`p`,{className:`text-[11px] text-muted-foreground/70 mt-3`,"aria-hidden":`true`,children:O.requiredHint??`* Required field`})]}),(0,G.jsxs)(`div`,{className:`relative px-6 sm:px-8 py-6`,children:[f&&(0,G.jsx)(`div`,{role:`alert`,"aria-live":`assertive`,className:`mb-4 p-3 bg-destructive/10 border border-destructive/30 rounded-md text-sm text-destructive`,children:f}),(0,G.jsx)($,{schema:{type:`object-form`,objectName:e.objectName,mode:`create`,fields:e.fields,customFields:S,initialData:w,onSuccess:T,submitText:c?O.submitting??`Submitting...`:O.submit??`Submit`},dataSource:C}),b&&(0,G.jsxs)(`div`,{"aria-hidden":`true`,className:`absolute left-[-10000px] top-auto h-px w-px overflow-hidden`,children:[(0,G.jsx)(`label`,{htmlFor:`${e.formId}-${b}`,children:`Do not fill this field`}),(0,G.jsx)(`input`,{ref:v,id:`${e.formId}-${b}`,type:`text`,name:b,tabIndex:-1,autoComplete:`off`,defaultValue:``})]}),e.consent&&(0,G.jsxs)(`div`,{className:`mt-4`,children:[(0,G.jsxs)(`label`,{className:`flex items-start gap-2 text-sm text-foreground cursor-pointer select-none`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:A,checked:m,onChange:e=>{h(e.target.checked),e.target.checked&&_(null)},"aria-required":k||void 0,"aria-invalid":g?`true`:void 0,"aria-describedby":g?`${A}-error`:void 0,className:`mt-0.5 h-4 w-4 rounded border-input accent-primary`}),(0,G.jsxs)(`span`,{className:`leading-relaxed`,children:[e.consent.label??O.consentLabelDefault??`I agree to the privacy policy.`,k&&(0,G.jsx)(`span`,{"aria-hidden":`true`,className:`text-destructive ml-0.5`,children:`*`}),e.consent.privacyUrl&&(0,G.jsxs)(G.Fragment,{children:[` `,(0,G.jsx)(`a`,{href:e.consent.privacyUrl,target:`_blank`,rel:`noopener noreferrer`,className:`underline text-primary hover:opacity-80`,children:O.consentLink??`Privacy policy`})]})]})]}),g&&(0,G.jsx)(`p`,{id:`${A}-error`,role:`alert`,className:`mt-1.5 text-xs text-destructive`,children:g})]}),c&&(0,G.jsxs)(`div`,{className:`mt-3 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,G.jsx)(a,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":`true`}),(0,G.jsx)(`span`,{children:O.submitting??`Submitting…`})]})]}),(0,G.jsxs)(`div`,{className:`px-6 sm:px-8 py-4 border-t bg-muted/20 flex flex-col sm:flex-row items-center justify-between gap-2`,children:[(0,G.jsxs)(`p`,{className:`inline-flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,G.jsx)(l,{className:`h-3 w-3`,"aria-hidden":`true`}),(0,G.jsx)(`span`,{children:O.secureNotice??`Your information is transmitted securely and only used to respond to your request.`})]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground/80`,children:[e.privacyPolicyUrl&&(0,G.jsxs)(`a`,{href:e.privacyPolicyUrl,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 underline hover:text-foreground`,children:[(0,G.jsx)(u,{className:`h-3 w-3`,"aria-hidden":`true`}),O.consentLink??`Privacy policy`]}),(0,G.jsx)(`span`,{children:O.poweredBy??`Powered by ObjectStack`})]})]})]})})};function Te(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.floor(e/60)}m ${Math.round(e%60)}s`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}var Ee=({formId:e,formTitle:t,metrics:n,className:r})=>{let i=(0,W.useMemo)(()=>{if(!n.abandonedSubmissions)return 100;let e=n.totalSubmissions+n.abandonedSubmissions;return e===0?0:Math.round(n.totalSubmissions/e*100)},[n.totalSubmissions,n.abandonedSubmissions]),a=(0,W.useMemo)(()=>n.dailySubmissions?.length?Math.max(...n.dailySubmissions.map(e=>e.count),1):1,[n.dailySubmissions]);return(0,G.jsxs)(`div`,{className:`space-y-4 ${r||``}`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-foreground`,children:t||`Form Analytics`}),(0,G.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Form ID: `,e]})]}),(0,G.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-4`,children:[(0,G.jsx)(d,{children:(0,G.jsxs)(D,{className:`pb-2`,children:[(0,G.jsx)(m,{children:`Total Submissions`}),(0,G.jsx)(h,{className:`text-2xl`,children:n.totalSubmissions.toLocaleString()})]})}),(0,G.jsxs)(d,{children:[(0,G.jsxs)(D,{className:`pb-2`,children:[(0,G.jsx)(m,{children:`Fill Rate`}),(0,G.jsxs)(h,{className:`text-2xl`,children:[i,`%`]})]}),(0,G.jsx)(_,{children:(0,G.jsx)(`div`,{className:`w-full bg-muted rounded-full h-2`,children:(0,G.jsx)(`div`,{className:`bg-primary rounded-full h-2 transition-all`,style:{width:`${i}%`}})})})]}),(0,G.jsx)(d,{children:(0,G.jsxs)(D,{className:`pb-2`,children:[(0,G.jsx)(m,{children:`Avg. Completion Time`}),(0,G.jsx)(h,{className:`text-2xl`,children:n.avgCompletionTime?Te(n.avgCompletionTime):`—`})]})})]}),n.dailySubmissions&&n.dailySubmissions.length>0&&(0,G.jsxs)(d,{children:[(0,G.jsx)(D,{children:(0,G.jsx)(h,{className:`text-sm font-medium`,children:`Daily Submissions`})}),(0,G.jsx)(_,{children:(0,G.jsx)(`div`,{className:`flex items-end gap-1 h-32`,children:n.dailySubmissions.map((e,t)=>(0,G.jsxs)(`div`,{className:`flex-1 flex flex-col items-center gap-1`,children:[(0,G.jsx)(`div`,{className:`w-full bg-primary/80 rounded-t transition-all hover:bg-primary`,style:{height:`${e.count/a*100}%`,minHeight:e.count>0?`4px`:`0`},title:`${e.date}: ${e.count} submissions`}),(0,G.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate w-full text-center`,children:e.date.slice(-5)})]},t))})})]}),n.fieldDropOff&&n.fieldDropOff.length>0&&(0,G.jsxs)(d,{children:[(0,G.jsxs)(D,{children:[(0,G.jsx)(h,{className:`text-sm font-medium`,children:`Field Completion Rates`}),(0,G.jsx)(m,{children:`Percentage of users who completed each field`})]}),(0,G.jsx)(_,{children:(0,G.jsx)(`div`,{className:`space-y-3`,children:n.fieldDropOff.map((e,t)=>(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsxs)(`div`,{className:`flex justify-between text-sm`,children:[(0,G.jsx)(`span`,{className:`text-foreground`,children:e.label}),(0,G.jsxs)(`span`,{className:`text-muted-foreground`,children:[e.completionRate,`%`]})]}),(0,G.jsx)(`div`,{className:`w-full bg-muted rounded-full h-1.5`,children:(0,G.jsx)(`div`,{className:`rounded-full h-1.5 transition-all ${e.completionRate>=80?`bg-green-500`:e.completionRate>=50?`bg-yellow-500`:`bg-destructive`}`,style:{width:`${e.completionRate}%`}})})]},t))})})]})]})},De=({schema:e})=>(0,G.jsx)($,{schema:e});f.register(`object-form`,De,{namespace:`plugin-form`,label:`Object Form`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`fields`,type:`array`,label:`Fields`},{name:`mode`,type:`enum`,label:`Mode`,enum:[`create`,`edit`,`view`]},{name:`formType`,type:`enum`,label:`Form Type`,enum:[`simple`,`tabbed`,`wizard`,`split`,`drawer`,`modal`]},{name:`sections`,type:`array`,label:`Sections`},{name:`title`,type:`string`,label:`Title`},{name:`description`,type:`string`,label:`Description`},{name:`layout`,type:`enum`,label:`Layout`,enum:[`vertical`,`horizontal`,`inline`,`grid`]},{name:`columns`,type:`number`,label:`Columns`},{name:`defaultTab`,type:`string`,label:`Default Tab`},{name:`tabPosition`,type:`enum`,label:`Tab Position`,enum:[`top`,`bottom`,`left`,`right`]},{name:`allowSkip`,type:`boolean`,label:`Allow Skip Steps`},{name:`showStepIndicator`,type:`boolean`,label:`Show Step Indicator`},{name:`splitDirection`,type:`enum`,label:`Split Direction`,enum:[`horizontal`,`vertical`]},{name:`splitSize`,type:`number`,label:`Split Panel Size (%)`},{name:`splitResizable`,type:`boolean`,label:`Split Resizable`},{name:`drawerSide`,type:`enum`,label:`Drawer Side`,enum:[`top`,`bottom`,`left`,`right`]},{name:`drawerWidth`,type:`string`,label:`Drawer Width`},{name:`modalSize`,type:`enum`,label:`Modal Size`,enum:[`sm`,`default`,`lg`,`xl`,`full`]}]}),f.register(`form`,De,{namespace:`view`,skipFallback:!0,label:`Data Form View`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`fields`,type:`array`,label:`Fields`},{name:`mode`,type:`enum`,label:`Mode`,enum:[`create`,`edit`,`view`]}]}),f.register(`embeddable-form`,({schema:e})=>(0,G.jsx)(we,{config:e}),{namespace:`plugin-form`,label:`Embeddable Form`,category:`plugin`,inputs:[{name:`formId`,type:`string`,label:`Form ID`,required:!0},{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`title`,type:`string`,label:`Form Title`},{name:`description`,type:`string`,label:`Description`},{name:`fields`,type:`array`,label:`Fields`},{name:`allowMultiple`,type:`boolean`,label:`Allow Multiple Submissions`}]}),f.register(`form-analytics`,({schema:e})=>(0,G.jsx)(Ee,{formId:e.formId,formTitle:e.formTitle,metrics:e.metrics||{totalSubmissions:0}}),{namespace:`plugin-form`,label:`Form Analytics`,category:`plugin`,inputs:[{name:`formId`,type:`string`,label:`Form ID`,required:!0},{name:`formTitle`,type:`string`,label:`Form Title`},{name:`metrics`,type:`object`,label:`Submission Metrics`}]});export{$ as t};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{bn as t,vn as n,yn as r}from"./vendor-rQmwIIxi.js";import{A as i,An as a,Bn as o,C as s,Dn as c,Fn as l,Hn as u,J as d,Jt as f,Mt as p,N as m,Pn as h,X as g,Y as _,Z as v,a as y,cr as ee,f as b,g as x,gn as S,h as te,hn as C,in as ne,m as w,or as T,qn as re,x as ie,y as E}from"./vendor-icons-C-VDCqO9.js";import{$ as ae,A as D,B as O,C as k,Cn as A,Ct as j,Et as oe,H as se,I as ce,J as M,L as le,M as N,N as ue,Nt as P,O as de,P as fe,Pt as pe,S as me,St as F,V as he,X as I,Y as ge,Z as L,_ as _e,_t as R,an as ve,at as z,b as ye,bn as be,bt as xe,cn as Se,dn as Ce,dt as we,et as Te,f as Ee,ft as De,gt as Oe,h as ke,ht as Ae,it as je,jt as Me,kt as Ne,lt as B,m as Pe,mn as Fe,nt as Ie,pn as Le,pt as Re,rn as ze,rt as Be,st as Ve,tt as He,u as Ue,un as We,ut as Ge,wt as Ke,x as qe,xn as Je,y as Ye,yn as Xe,yt as V}from"./vendor-object-ui-core-C_SRaIe4.js";var H=e(t(),1),Ze=e(r(),1),U=n();function W(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function G(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return o.length!==r.length||o.some((e,t)=>r[t]!==e)?(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i):i}return o.updateDeps=e=>{r=e},o}function K(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var q=(e,t)=>Math.abs(e-t)<1.01,J=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Y,X=()=>{if(Y!==void 0)return Y;if(typeof navigator>`u`)return Y=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Y=!0;let e=navigator.maxTouchPoints;return Y=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Qe=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},$e=e=>e,Z=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},et=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(Qe(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(Qe(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},tt={passive:!0},nt=typeof window>`u`?!0:`onscrollend`in window,rt=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&nt,o=0,s=a?null:J(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,tt),a&&r.addEventListener(`scrollend`,u,tt),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},it=(e,t)=>rt(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),at=(e,t,n)=>{if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},ot=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},st=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:$e,rangeExtractor:Z,onChange:()=>{},measureElement:at,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}this.options=t},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=G(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.scrollElement&&`ownerDocument`in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0,this.scrollDirection=t?this.getScrollOffset()<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!X()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,tt),e.addEventListener(`touchend`,n,tt),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(e,t)=>{let n=new Map,r=new Map;for(let i=t-1;i>=0;i--){let t=e[i];if(n.has(t.lane))continue;let a=r.get(t.lane);if(a==null||t.end>a.end?r.set(t.lane,t):t.end<a.end&&n.set(t.lane,!0),n.size===this.options.lanes)break}return r.size===this.options.lanes?Array.from(r.values()).sort((e,t)=>e.end===t.end?e.index-t.index:e.end-t.end)[0]:void 0},this.getMeasurementOptions=G(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(e,t,n,r,i,a,o)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=G(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{let c=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let l=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=this.options.gap,a=e*2,o=this._flatMeasurements;if(!o||o.length<a){let e=new Float64Array(a);o&&l>0&&e.set(o.subarray(0,l*2)),o=e,this._flatMeasurements=o}let s;if(l===0)s=t+n;else{let e=l-1;s=o[e*2]+o[e*2+1]+i}for(let t=l;t<e;t++){let e=r(t),n=c.get(e),a=typeof n==`number`?n:this.options.estimateSize(t);o[t*2]=s,o[t*2+1]=a,s+=a+i}let u=W(e,o,r);return this.measurementsCache=u,u}let u=this.measurementsCache.slice(0,l),d=Array(a).fill(void 0);for(let e=0;e<l;e++){let t=u[e];t&&(d[t.lane]=e)}for(let i=l;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),s,l,f=o===`estimate`||c.has(e);if(a!==void 0&&this.options.lanes>1){s=a;let e=d[s],r=e===void 0?void 0:u[e];l=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?u[i-1]:this.getFurthestMeasurement(u,i);l=e?e.end+this.options.gap:t+n,s=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,s)}let p=c.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=l+m;u[i]={index:i,start:l,size:m,end:h,key:e,lane:s},d[s]=i}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=G(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?lt({measurements:e,outerSize:t,scrollOffset:n,lanes:r,flat:r===1&&this._flatMeasurements!=null?this._flatMeasurements:null}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=G(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=t-(this.itemSizeCache.get(i)??n);o!==0&&(this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?r<this.getScrollOffset()+this.scrollAdjustments&&this.scrollDirection!==`backward`:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},o,this))&&(X()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=o:this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0})),(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++,this.notify(!1))},this.getVirtualItems=G(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return K(t[ct(0,t.length-1,r?e=>n[e*2]:e=>K(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`)if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t];if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&q(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},ct=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function lt({measurements:e,outerSize:t,scrollOffset:n,lanes:r,flat:i}){let a=e.length-1,o=i?e=>i[e*2]:t=>e[t].start,s=i?e=>i[e*2]+i[e*2+1]:t=>e[t].end;if(e.length<=r)return{startIndex:0,endIndex:a};let c=ct(0,a,o,n),l=c;if(r===1)for(;l<a&&s(l)<n+t;)l++;else if(r>1){let i=Array(r).fill(0);for(;l<a&&i.some(e=>e<n+t);){let t=e[l];i[t.lane]=t.end,l++}let o=Array(r).fill(n+t);for(;c>=0&&o.some(e=>e>=n);){let t=e[c];o[t.lane]=t.start,c--}c=Math.max(0,c-c%r),l=Math.min(a,l+(r-1-l%r))}return{startIndex:c,endIndex:l}}var ut=typeof document<`u`?H.useLayoutEffect:H.useEffect;function dt({useFlushSync:e=!0,...t}){let n=H.useReducer(e=>e+1,0)[1],r={...t,onChange:(r,i)=>{var a;e&&i?(0,Ze.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,r,i)}},[i]=H.useState(()=>new st(r));return i.setOptions(r),ut(()=>i._didMount(),[]),ut(()=>i._willUpdate()),i}function Q(e){return dt({observeElementRect:et,observeElementOffset:it,scrollToFn:ot,...e})}var ft={red:`bg-red-100`,green:`bg-green-100`,blue:`bg-blue-100`,yellow:`bg-yellow-100`,orange:`bg-orange-100`,purple:`bg-purple-100`,pink:`bg-pink-100`,gray:`bg-gray-100`,grey:`bg-gray-100`,indigo:`bg-indigo-100`,teal:`bg-teal-100`,cyan:`bg-cyan-100`,amber:`bg-amber-100`,lime:`bg-lime-100`,emerald:`bg-emerald-100`,rose:`bg-rose-100`,sky:`bg-sky-100`,violet:`bg-violet-100`,fuchsia:`bg-fuchsia-100`,slate:`bg-slate-100`,zinc:`bg-zinc-100`,stone:`bg-stone-100`,neutral:`bg-neutral-100`};function pt(e){return e.startsWith(`bg-`)?e:ft[e.toLowerCase().trim()]}function mt(e){return(0,H.useCallback)(t=>{if(!e?.field||!e.colors)return;let n=String(t[e.field]??``),r=e.colors[n];if(r)return pt(r)},[e?.field,e?.colors])}function ht(e){if(e==null||e===``)return``;if(Array.isArray(e))return e.map(e=>ht(e)).join(`|`);if(typeof e==`object`){let t=e.id??e._id??e.pk??e.value;if(t!=null&&t!==``)return String(t);let n=e.name??e.label??e.title;if(n!=null&&n!==``)return String(n);try{return JSON.stringify(e)}catch{return``}}return String(e)}function gt(e,t){return ht(e[t])}function _t(e,t,n){if(e==null||e===``)return`(empty)`;if(n){let r=n(t,e);if(r!==void 0&&r!==``)return r}if(Array.isArray(e))return e.map(e=>{if(n){let r=n(t,e);if(r!==void 0&&r!==``)return r}return _t(e,t)}).join(`, `)||`(empty)`;if(typeof e==`object`){let t=e.name??e.label??e.title??e.display_name??e.displayName??e.fullName??e.full_name;if(t!=null&&t!==``)return String(t);let n=e.id??e._id??e.pk;return n!=null&&n!==``?String(n):`(empty)`}return String(e)}function vt(e,t){return t.map(({field:t,type:n})=>{if(n===`count_distinct`){let r=new Set;for(let n of e){let e=n[t];e!=null&&e!==``&&r.add(e)}return{field:t,type:n,value:r.size}}if(n===`count`)return{field:t,type:n,value:e.length};let r=e.map(e=>Number(e[t])).filter(e=>Number.isFinite(e)),i;switch(n){case`sum`:i=r.reduce((e,t)=>e+t,0);break;case`avg`:i=r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0;break;case`min`:i=r.length>0?Math.min(...r):0;break;case`max`:i=r.length>0?Math.max(...r):0;break;default:i=0}return{field:t,type:n,value:i}})}function yt(e,t,n){let r=e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`});return n===`desc`?-r:r}function bt(e,t,n,r){let i=e?.fields,a=!!(i&&i.length>0),[o,s]=(0,H.useState)({});return{groups:(0,H.useMemo)(()=>{if(!a||!i)return[];let e=(t,a,s)=>{if(a>=i.length)return[];let c=i[a],l=new Map,u=[];for(let e of t){let t=gt(e,c.field);l.has(t)||(l.set(t,{label:_t(e[c.field],c.field,r),rows:[]}),u.push(t)),l.get(t).rows.push(e)}let d=c.order??`asc`;return u.sort((e,t)=>yt(l.get(e)?.label??e,l.get(t)?.label??t,d)),u.map(t=>{let r=l.get(t),u=s?`${s}__${a}:${t}`:`${a}:${t}`,d=!!c.collapsed,f=u in o?o[u]:d,p=n&&n.length>0?vt(r.rows,n):[],m=a+1<i.length?e(r.rows,a+1,u):[];return{key:u,label:r.label,field:c.field,depth:a,rows:r.rows,collapsed:f,aggregations:p,subgroups:m}})};return e(t,0,``)},[t,i,a,o,n,r]),isGrouped:a,toggleGroup:(0,H.useCallback)(e=>{s(t=>{let n=e.split(`__`).pop()||``,r=/^(\d+):/.exec(n),a=r?Number(r[1]):0,o=!!i?.[a]?.collapsed;return{...t,[e]:t[e]===void 0?!o:!t[e]}})},[i])}}var xt=({groupKey:e,label:t,count:n,collapsed:r,aggregations:i,fieldLabel:a,labelColorClass:s,onToggle:c,children:l})=>{let d=s?N(`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium`,s):`inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs font-medium text-foreground`;return(0,U.jsxs)(`div`,{"data-testid":`group-row-${e}`,className:`group/grouprow`,children:[a&&(0,U.jsx)(`div`,{className:`px-1 pb-1 text-[11px] font-medium text-muted-foreground tracking-wide group-label-caption`,children:a}),(0,U.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 px-1 py-1 text-sm text-left rounded-md hover:bg-muted/40 transition-colors`,onClick:()=>c(e),"aria-expanded":!r,children:[(0,U.jsx)(r?o:u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,U.jsx)(`span`,{className:N(d,`group-label`),children:t}),(0,U.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums group-count`,children:n}),i&&i.length>0&&(0,U.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground group-aggregations`,children:i.map(e=>(0,U.jsxs)(`span`,{className:`mr-2`,children:[e.type,`: `,Number.isInteger(e.value)?e.value:e.value.toFixed(2)]},`${e.field}-${e.type}`))})]}),!r&&(0,U.jsx)(`div`,{className:`mt-1 ml-1.5 pl-3 border-l border-border/60`,children:l})]})};function St(e){return typeof e==`string`?{type:e}:e}function Ct(e,t){if(t.length===0)return null;switch(e){case`count`:return t.length;case`sum`:return t.reduce((e,t)=>e+t,0);case`avg`:return t.reduce((e,t)=>e+t,0)/t.length;case`min`:return Math.min(...t);case`max`:return Math.max(...t);default:return null}}function wt(e,t,n){if(t===null)return``;let r={count:`Count`,sum:`Sum`,avg:`Avg`,min:`Min`,max:`Max`}[e]||e,i=n?.type,a;if(e!==`count`&&i===`currency`){let e=n?.currency||n?.defaultCurrency,r=n?.precision??n?.scale??0;try{a=e?new Intl.NumberFormat(void 0,{style:`currency`,currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(t):new Intl.NumberFormat(void 0,{minimumFractionDigits:r,maximumFractionDigits:r}).format(t)}catch{a=t.toLocaleString()}}else if(e!==`count`&&i===`percent`){let e=n?.precision??0;a=`${(t>-1&&t<1?t*100:t).toFixed(e)}%`}else a=e===`avg`?t.toLocaleString(void 0,{maximumFractionDigits:2}):t.toLocaleString();return`${r}: ${a}`}function Tt(e,t,n){return(0,H.useMemo)(()=>{let r=new Map;if(!e||e.length===0||t.length===0)return{summaries:r,hasSummary:!1};for(let i of e){if(!i.summary)continue;let e=St(i.summary),a=e.field||i.field,o=[];for(let e of t){let t=e[a];if(t!=null&&typeof t==`number`&&!isNaN(t))o.push(t);else if(t!=null&&typeof t==`string`){let e=parseFloat(t);isNaN(e)||o.push(e)}}let s;if(e.type===`count`){let e=t.filter(e=>e[a]!=null&&e[a]!==``).length;s=e>0?e:null}else s=Ct(e.type,o);let c=n?.[a],l={type:i.type??c?.type,currency:i.currency??c?.currency,defaultCurrency:i.defaultCurrency??c?.defaultCurrency,precision:i.precision??c?.precision,scale:i.scale??c?.scale};r.set(i.field,{field:i.field,value:s,label:wt(e.type,s,l)})}return{summaries:r,hasSummary:r.size>0}},[e,t,n])}var Et={"grid.openMenu":`Open menu`,"grid.edit":`Edit`,"grid.delete":`Delete`};function Dt(){try{let{t:e}=ve();return t=>{let n=e(t);return n===t?Et[t]??t:n}}catch{return e=>Et[e]??e}}function Ot(e){return e.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var kt=({row:e,rowActions:t,rowActionDefs:n,canEdit:r,canDelete:a,onEdit:o,onDelete:s,onAction:c,onActionDef:l})=>{let u=Dt();return(0,U.jsxs)(he,{children:[(0,U.jsx)(pe,{asChild:!0,children:(0,U.jsxs)(V,{variant:`ghost`,size:`icon`,className:`h-8 w-8 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0`,"data-testid":`row-action-trigger`,children:[(0,U.jsx)(C,{className:`h-4 w-4`}),(0,U.jsx)(`span`,{className:`sr-only`,children:u(`grid.openMenu`)})]})}),(0,U.jsxs)(ce,{align:`end`,onClick:e=>e.stopPropagation(),children:[r&&o&&(0,U.jsxs)(xe,{onClick:()=>o(e),children:[(0,U.jsx)(i,{className:`mr-2 h-4 w-4`}),u(`grid.edit`)]}),a&&s&&(0,U.jsxs)(xe,{onClick:()=>s(e),children:[(0,U.jsx)(E,{className:`mr-2 h-4 w-4`}),u(`grid.delete`)]}),n?.map(t=>(0,U.jsx)(xe,{onClick:()=>l?.(t,e),"data-testid":`row-action-${t.name}`,className:t.variant===`danger`?`text-destructive focus:text-destructive`:void 0,children:t.label??Ot(t.name)},t.name)),t?.map(t=>(0,U.jsx)(xe,{onClick:()=>c?.(t,e),"data-testid":`row-action-${t}`,children:Ot(t)},t))]})]})},At=({selectedRows:e,actions:t,actionDefs:n,onAction:r,onActionDef:i,onClearSelection:a,pageSize:o,totalMatching:s,allMatchingSelected:c,onSelectAllMatching:l})=>{let u=Array.isArray(n)&&n.length>0,d=Array.isArray(t)&&t.length>0;return!u&&!d||e.length===0?null:(0,U.jsxs)(`div`,{className:`border-t border-primary/30 px-4 py-2 flex flex-col gap-1.5 text-xs bg-primary/10 text-foreground shrink-0 shadow-sm motion-safe:animate-in motion-safe:slide-in-from-bottom-2 motion-safe:fade-in-0 motion-safe:duration-200`,role:`region`,"aria-label":`Bulk actions`,"data-testid":`bulk-actions-bar`,children:[(!c&&typeof s==`number`&&typeof o==`number`&&o>0&&e.length>=o&&s>o||c)&&(0,U.jsx)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground`,"data-testid":`bulk-cross-page-banner`,children:c?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(m,{className:`h-3 w-3 text-primary shrink-0`}),(0,U.jsxs)(`span`,{children:[`All `,s,` matching records are selected.`]})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`span`,{children:[`All `,o,` on this page are selected.`]}),(0,U.jsxs)(`button`,{type:`button`,className:`font-medium text-primary underline-offset-2 hover:underline`,onClick:l,"data-testid":`bulk-select-all-matching`,children:[`Select all `,s,` matching`]})]})}),(0,U.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,U.jsx)(m,{className:`h-3.5 w-3.5 text-primary shrink-0`}),(0,U.jsx)(`span`,{className:`font-medium tabular-nums`,children:(0,U.jsx)(`span`,{className:`inline-block motion-safe:animate-in motion-safe:zoom-in-90 motion-safe:duration-150`,children:c?`${s} items selected (all matches)`:`${e.length} ${e.length===1?`item`:`items`} selected`},c?`all-${s}`:e.length)}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 ml-3`,children:[u&&n.map(t=>{let n=t.variant===`danger`||t.operation===`delete`,r=t.icon?Ae(t.icon):null;return(0,U.jsxs)(V,{variant:n?`destructive`:`outline`,size:`sm`,className:`h-7 px-2.5 text-xs gap-1.5`,onClick:()=>i?.(t,e),"data-testid":`bulk-action-${t.name}`,children:[r?(0,U.jsx)(Ke,{name:r,className:`h-3 w-3`}):n?(0,U.jsx)(E,{className:`h-3 w-3`}):null,t.label??Ot(t.name)]},t.name)}),!u&&d&&t.map(t=>{let n=String(t).toLowerCase(),i=n.includes(`delete`)||n.includes(`remove`)||n.includes(`destroy`),a=i?E:null;return(0,U.jsxs)(V,{variant:i?`destructive`:`outline`,size:`sm`,className:`h-7 px-2.5 text-xs gap-1.5`,onClick:()=>r?.(t,e),"data-testid":`bulk-action-${t}`,children:[a&&(0,U.jsx)(a,{className:`h-3 w-3`}),Ot(t)]},t)})]}),(0,U.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs ml-auto gap-1`,onClick:a,children:[(0,U.jsx)(y,{className:`h-3 w-3`}),`Clear`]})]})]})};function jt({resource:e,dataSource:t}){let[n,r]=(0,H.useState)({total:0,done:0,failed:0,inFlight:!1}),[i,a]=(0,H.useState)(null),o=(0,H.useRef)([]),s=(0,H.useRef)(null),c=(0,H.useCallback)(()=>{r({total:0,done:0,failed:0,inFlight:!1}),a(null),o.current=[],s.current=null},[]);return{run:(0,H.useCallback)(async(n,i,c)=>{let l=i.length,u=Math.max(1,n.batchSize??200),d=[],f=0,p=0;a(null),r({total:l,done:0,failed:0,inFlight:!0});let m=()=>({...n.patch??{},...c}),h=[];if(n.operation===`update`){let e=Object.keys(m());for(let t of i){let n=String(t.id??``);if(!n)continue;let r={};for(let n of e)r[n]=t[n];h.push({id:n,prev:r})}}for(let a=0;a<i.length;a+=u){let o=i.slice(a,a+u),s=[];for(let e=0;e<o.length;e+=1){let t=o[e].id==null?``:String(o[e].id);t?s.push(t):(p+=1,d.push({id:`index_${a+e}`,error:`Missing record id`}))}if(s.length===0){r({total:l,done:f,failed:p,inFlight:!0});continue}let c=s.length>=2,h,g=`bulk`;n.operation===`update`&&typeof t.bulkUpdate==`function`?(h=n=>t.bulkUpdate(e,n,m()),g=`bulk update`):n.operation===`delete`&&typeof t.bulkDelete==`function`&&(h=n=>t.bulkDelete(e,n),g=`bulk delete`);let _=await Xe({ids:s,originalSize:o.length,offset:a,allowBulk:c,label:g},{bulkCall:h,perRow:r=>{switch(n.operation){case`delete`:return t.delete(e,r);case`update`:return t.update(e,r,m());case`custom`:return Promise.resolve();default:return Promise.reject(Error(`Unknown operation: ${n.operation}`))}}});f+=_.succeeded,p+=_.failed,d.push(..._.errors),r({total:l,done:f,failed:p,inFlight:!0})}let g={total:l,succeeded:f,failed:p,errors:d},_=new Set(d.map(e=>e.id));return o.current=h.filter(e=>!_.has(e.id)),s.current={def:n,rows:i,params:c},r({total:l,done:f,failed:p,inFlight:!1}),a(g),f>0&&Ne.invalidate(e),g},[e,t]),undo:(0,H.useCallback)(async()=>{let n=o.current;if(!n.length)return null;let i=n.length,s=[],c=0,l=0;a(null),r({total:i,done:0,failed:0,inFlight:!0}),(await Promise.allSettled(n.map(n=>t.update(e,n.id,n.prev)))).forEach((e,t)=>{e.status===`fulfilled`?c+=1:(l+=1,s.push({id:n[t].id,error:e.reason instanceof Error?e.reason.message:String(e.reason)}))});let u={total:i,succeeded:c,failed:l,errors:s};return o.current=[],r({total:i,done:c,failed:l,inFlight:!1}),a(u),u},[e,t]),retry:(0,H.useCallback)(async n=>{let r=s.current;if(!r||!r.rows.find(e=>String(e.id??``)===n))return!1;let i={...r.def.patch??{},...r.params};try{switch(r.def.operation){case`delete`:await t.delete(e,n);break;case`update`:await t.update(e,n,i);break;case`custom`:return!0;default:return!1}return a(e=>{if(!e)return e;let t=e.errors.filter(e=>e.id!==n);return{...e,errors:t,succeeded:e.succeeded+1,failed:Math.max(0,e.failed-1)}}),!0}catch{return!1}},[e,t]),progress:n,result:i,reset:c}}var Mt=({def:e,rows:t,resource:n,dataSource:r,open:i,onClose:o,labelKey:s=`name`})=>{let c=e?.params??[],l=(0,H.useMemo)(()=>{let e={};for(let t of c)t.default!==void 0&&(e[t.name]=t.default);return e},[e?.name]),[u,d]=(0,H.useState)(`params`),[f,m]=(0,H.useState)(l),[g,_]=(0,H.useState)({}),{run:v,undo:y,retry:ee,progress:b,result:S,reset:te}=jt({resource:n,dataSource:r}),[C,ne]=(0,H.useState)(null),[w,T]=(0,H.useState)(!1),[re,ie]=(0,H.useState)(null);(0,H.useEffect)(()=>{i&&(te(),m(l),ie(null),T(!1),ne(null),d(c.length===0?`confirm`:`params`))},[i,e?.name,l,c.length,te]),(0,H.useEffect)(()=>{if(!i||typeof r.find!=`function`)return;let e=c.filter(e=>e.type===`lookup`&&e.object&&!g[e.name]);if(e.length===0)return;let t=!1;return(async()=>{let n={};for(let t of e)try{let e=await r.find(t.object,{$top:200}),i=Array.isArray(e)?e:e?.data??[];n[t.name]=i.map(e=>({value:String(e.id??e._id??``),label:String(e.name??e.full_name??e.email??e.id??`(unnamed)`)})).filter(e=>e.value)}catch{n[t.name]=[]}t||_(e=>({...e,...n}))})(),()=>{t=!0}},[i,e?.name]);let E=(0,H.useMemo)(()=>{for(let e of c)if(e.required){let t=f[e.name];if(t==null||t===``)return!1}return!0},[c,f]),ae=e?.maxRecords??1/0,D=t.length>ae,A=(0,H.useCallback)(async()=>{e&&(d(`running`),await v(e,t,f),d(`result`))},[e,t,f,v]),j=(0,H.useCallback)(()=>{if(!S?.errors?.length)return;let t=[`record_id,error_message`,...S.errors.map(e=>`${e.id},"${e.error.replace(/"/g,`""`)}"`)].join(`
|
|
2
|
+
`),n=new Blob([t],{type:`text/csv;charset=utf-8`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`bulk_errors_${e?.name??`action`}_${Date.now()}.csv`,i.click(),URL.revokeObjectURL(r)},[S,e?.name]),se=!!e&&e.operation===`update`&&!!S&&S.succeeded>0&&re===null,ce=(0,H.useCallback)(async()=>{T(!0);try{await y()&&ie(Date.now())}finally{T(!1)}},[y]),M=(0,H.useCallback)(async e=>{ne(e);try{await ee(e)}finally{ne(null)}},[ee]);if(!e)return null;let le=e.label??e.name,N=t.slice(0,5),ue=Math.max(0,t.length-N.length);return(0,U.jsx)(fe,{open:i,onOpenChange:e=>{e||o(S)},children:(0,U.jsxs)(k,{className:`max-w-md`,children:[(0,U.jsxs)(z,{children:[(0,U.jsxs)(Oe,{className:`flex items-center gap-2`,children:[u===`running`&&(0,U.jsx)(p,{className:`h-4 w-4 animate-spin`}),le]}),u===`confirm`&&(0,U.jsx)(F,{children:e.confirmText??`This will apply to ${t.length} record${t.length===1?``:`s`}.`})]}),u===`params`&&(0,U.jsx)(`div`,{className:`space-y-3`,children:c.map(e=>(0,U.jsx)(Pt,{param:e,value:f[e.name],lookupOptions:g[e.name],onChange:t=>m(n=>({...n,[e.name]:t}))},e.name))}),u===`confirm`&&(0,U.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[D&&(0,U.jsxs)(`div`,{className:`rounded-md bg-destructive/10 text-destructive px-3 py-2 flex items-start gap-2`,children:[(0,U.jsx)(x,{className:`h-4 w-4 mt-0.5 shrink-0`}),(0,U.jsxs)(`div`,{children:[`Selection (`,t.length,`) exceeds the action limit (`,ae,`). Reduce the selection to proceed.`]})]}),(0,U.jsxs)(`div`,{className:`text-muted-foreground`,children:[`Affected records (`,t.length,`):`]}),(0,U.jsx)(we,{className:`max-h-32 rounded border bg-muted/30 p-2`,children:(0,U.jsxs)(`ul`,{className:`text-xs space-y-1`,children:[N.map((e,t)=>(0,U.jsxs)(`li`,{className:`truncate`,children:[`• `,String(e[s]??e.id??`Row ${t+1}`)]},String(e.id??t))),ue>0&&(0,U.jsxs)(`li`,{className:`text-muted-foreground`,children:[`… and `,ue,` more`]})]})}),Object.keys(f).length>0&&(0,U.jsx)(`div`,{className:`rounded border bg-muted/30 p-2 text-xs space-y-0.5`,children:Object.entries(f).map(([e,t])=>(0,U.jsxs)(`div`,{children:[(0,U.jsxs)(`span`,{className:`text-muted-foreground`,children:[e,`:`]}),` `,Nt(t)]},e))})]}),u===`running`&&(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsx)(O,{value:b.total?(b.done+b.failed)/b.total*100:0}),(0,U.jsxs)(`div`,{className:`text-xs text-muted-foreground text-center`,children:[b.done+b.failed,` / `,b.total,` processed`,b.failed>0&&` · ${b.failed} failed`]})]}),u===`result`&&S&&(0,U.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-2`,children:[S.failed===0?(0,U.jsx)(h,{className:`h-5 w-5 text-emerald-500`}):(0,U.jsx)(x,{className:`h-5 w-5 text-amber-500`}),(0,U.jsxs)(`span`,{children:[re===null?``:`Undone — `,`Succeeded `,S.succeeded,` / `,S.total,S.failed>0&&` · Failed ${S.failed}`]})]}),S.errors.length>0&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(we,{className:`max-h-48 rounded border bg-destructive/5 p-2`,"data-testid":`bulk-error-inspector`,children:(0,U.jsx)(`ul`,{className:`text-xs space-y-1.5`,children:S.errors.map(t=>(0,U.jsxs)(`li`,{className:`flex items-start gap-2`,"data-testid":`bulk-error-row-${t.id}`,children:[(0,U.jsx)(a,{className:`h-3 w-3 mt-0.5 shrink-0 text-destructive`}),(0,U.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,U.jsxs)(`div`,{className:`truncate`,children:[(0,U.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.id,`:`]}),` `,t.error]})}),e.operation!==`custom`&&(0,U.jsx)(V,{variant:`ghost`,size:`sm`,className:`h-5 px-1.5 text-[10px]`,onClick:()=>M(t.id),disabled:C===t.id,"data-testid":`bulk-error-retry-${t.id}`,children:C===t.id?`…`:`Retry`})]},t.id))})}),(0,U.jsx)(V,{variant:`outline`,size:`sm`,onClick:j,children:`Download error CSV`})]})]}),(0,U.jsxs)(oe,{children:[u===`params`&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(V,{variant:`ghost`,onClick:()=>o(),children:`Cancel`}),(0,U.jsx)(V,{onClick:()=>d(`confirm`),disabled:!E,children:`Next`})]}),u===`confirm`&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(V,{variant:`ghost`,onClick:()=>c.length?d(`params`):o(),children:c.length?`Back`:`Cancel`}),(0,U.jsx)(V,{variant:e.variant===`danger`?`destructive`:`default`,onClick:A,disabled:D,children:e.confirmLabel??`Run`})]}),u===`running`&&(0,U.jsx)(V,{variant:`ghost`,disabled:!0,children:`Running…`}),u===`result`&&(0,U.jsxs)(U.Fragment,{children:[se&&(0,U.jsx)(V,{variant:`outline`,onClick:ce,disabled:w,"data-testid":`bulk-undo-button`,children:w?`Undoing…`:`Undo`}),(0,U.jsx)(V,{onClick:()=>o(S),children:`Done`})]})]})]})})};function Nt(e){return e==null||e===``?`—`:typeof e==`boolean`?e?`Yes`:`No`:String(e)}var Pt=({param:e,value:t,onChange:n,lookupOptions:r})=>{let i=`bulk-param-${e.name}`,a=(0,U.jsxs)(ue,{htmlFor:i,className:`text-xs`,children:[e.label??e.name,e.required&&(0,U.jsx)(`span`,{className:`text-destructive ml-0.5`,children:`*`})]}),o=null;switch(e.type){case`boolean`:o=(0,U.jsx)(Re,{id:i,checked:!!t,onCheckedChange:n});break;case`textarea`:o=(0,U.jsx)(de,{id:i,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder});break;case`select`:{let r=e.options??[];o=(0,U.jsxs)(R,{value:t==null?``:String(t),onValueChange:n,children:[(0,U.jsx)(De,{id:i,children:(0,U.jsx)(Ie,{placeholder:e.placeholder??`Select…`})}),(0,U.jsx)(Ve,{children:r.map(e=>(0,U.jsx)(M,{value:String(e.value),children:e.label},String(e.value)))})]});break}case`lookup`:{let a=r??[];o=(0,U.jsxs)(R,{value:t??``,onValueChange:n,children:[(0,U.jsx)(De,{id:i,children:(0,U.jsx)(Ie,{placeholder:a.length===0?`Loading…`:e.placeholder??`Select…`})}),(0,U.jsx)(Ve,{children:a.map(e=>(0,U.jsx)(M,{value:e.value,children:e.label},e.value))})]});break}case`number`:o=(0,U.jsx)(I,{id:i,type:`number`,value:t??``,onChange:e=>n(e.target.value===``?void 0:Number(e.target.value)),placeholder:e.placeholder});break;default:o=(0,U.jsx)(I,{id:i,type:`text`,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder})}return(0,U.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,U.jsx)(`div`,{className:`flex items-center justify-between`,children:a}),o,e.help&&(0,U.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.help})]})},Ft=({testId:e,onActivate:t,children:n})=>(0,U.jsx)(`span`,{role:`link`,tabIndex:0,"data-testid":e,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer inline-flex items-center gap-1`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),t())},children:n}),It={"grid.actions":`Actions`,"grid.edit":`Edit`,"grid.delete":`Delete`,"grid.export":`Export`,"grid.exportAs":`Export as {{format}}`,"grid.loading":`Loading grid...`,"grid.errorLoading":`Error loading grid`,"grid.pullToRefresh":`Pull to refresh`,"grid.refreshing":`Refreshing…`,"grid.openRecord":`Open record`,"grid.empty":`Empty`,"grid.yes":`Yes`,"grid.no":`No`,"grid.systemFields":`System`};function Lt(){try{let e=ve();return e.t(`grid.actions`)===`grid.actions`?{t:(e,t)=>{let n=It[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}:{t:e.t}}catch{return{t:(e,t)=>{let n=It[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}}}function Rt(e){if(e!=null)return typeof e==`string`?e:void 0}function zt(e){return e.data?Array.isArray(e.data)?{provider:`value`,items:e.data}:e.data:e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function Bt(e){if(!(!e||e.length===0))return typeof e[0]==`object`&&e[0],e}var Vt=({schema:e,dataSource:t,onEdit:n,onDelete:r,onBulkDelete:i,onRowSelect:a,onRowClick:o,onCellChange:l,onRowSave:u,onBatchSave:d,onAddRecord:p,...h})=>{let[y,ee]=(0,H.useState)([]),[x,C]=(0,H.useState)(!0),[ne,w]=(0,H.useState)(null),{t:T}=Lt(),{fieldLabel:E,translateOptions:O}=ze(),[k,A]=(0,H.useState)(null),[oe,ce]=(0,H.useState)(!1),[M,N]=(0,H.useState)(0),[ue,P]=(0,H.useState)(!1),[de,fe]=(0,H.useState)(!1),pe=j({dataSource:t}),[F,he]=(0,H.useState)(e.rowHeight??`compact`),[I,R]=(0,H.useState)([]),[ve,z]=(0,H.useState)(!1),[xe,we]=(0,H.useState)(void 0),[Te,De]=(0,H.useState)(null),[Oe,Ae]=(0,H.useState)([]),Me=H.useRef(null);H.useEffect(()=>{e.rowHeight&&e.rowHeight!==F&&he(e.rowHeight)},[e.rowHeight]);let Ne=H.useMemo(()=>e.id?`grid-columns-${e.objectName}-${e.id}`:`grid-columns-${e.objectName}`,[e.objectName,e.id]),[B,Fe]=(0,H.useState)(()=>{let t=e.columnState;if(t&&typeof t==`object`)return t;try{let e=localStorage.getItem(Ne);return e?JSON.parse(e):{}}catch{return{}}}),Ie=H.useMemo(()=>JSON.stringify(e.columnState??null),[e.columnState]);H.useEffect(()=>{let t=e.columnState;t&&typeof t==`object`&&Fe(t)},[Ie]);let Re=(0,H.useCallback)(e=>{Fe(e);try{localStorage.setItem(Ne,JSON.stringify(e))}catch(e){console.warn(`Failed to persist column state:`,e)}let t=h.onColumnStateChange;if(typeof t==`function`)try{t(e)}catch(e){console.warn(`onColumnStateChange threw:`,e)}},[Ne,h]),{ref:Ve,isRefreshing:He,pullDistance:Ge}=Ue({onRefresh:(0,H.useCallback)(async()=>{N(e=>e+1)},[]),enabled:!!t&&!!e.objectName});(0,H.useEffect)(()=>{let e=()=>ce(window.innerWidth<480);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let Ke=h.data,Xe=Le(e.bind),Ze=zt(e),W=H.useMemo(()=>Ke&&Array.isArray(Ke)?{provider:`value`,items:Ke}:Xe&&Array.isArray(Xe)?{provider:`value`,items:Xe}:Ze,[JSON.stringify(Ze),Xe,Ke]),G=W?.provider===`value`,K=W?.provider===`object`&&W&&`object`in W?W.object:e.objectName,q=e.fields,J=e.columns,Y=e.filter,X=e.sort,Qe=e.pagination,$e=e.pageSize;(0,H.useEffect)(()=>{G&&W?.provider===`value`&&(ee(e=>{let t=W.items;return JSON.stringify(e)===JSON.stringify(t)?e:t}),C(!1))},[G,W]),(0,H.useEffect)(()=>{if(!G||!K||!t)return;let e=!1;return(async()=>{try{if(typeof t.getObjectSchema!=`function`)return;let n=await t.getObjectSchema(K);e||A(n)}catch(e){console.warn(`[ObjectGrid] Failed to fetch objectSchema for inline data (objectName: ${K}):`,e)}})(),()=>{e=!0}},[G,K,t]),(0,H.useEffect)(()=>{if(G)return;let n=!1;return(async()=>{C(!0),w(null);try{let r=null,i=Bt(J)||q;if(K&&t)if(typeof t.getObjectSchema==`function`){let e=await t.getObjectSchema(K);if(n)return;r=e}else r={name:K,fields:{}};else if(i&&K)r={name:K,fields:{}};else if(K)throw Error(`DataSource required`);else throw Error(`Object name required for data fetching`);if(n||A(r),t&&K){let i={$select:(()=>{let e=e=>e.map(e=>typeof e==`string`?e:e?.name||e?.field).includes(`id`)?e:[`id`,...e];if(q)return e(q);if(J&&Array.isArray(J))return e(J.map(e=>typeof e==`string`?e:e.field))})(),$top:Qe?.pageSize||$e||50};Y&&Array.isArray(Y)?i.$filter=Y:e.defaultFilters&&(i.$filter=e.defaultFilters),X?typeof X==`string`?i.$orderby=X:Array.isArray(X)&&(i.$orderby=X.map(e=>`${e.field} ${e.order}`).join(`, `)):e.defaultSort&&(i.$orderby=`${e.defaultSort.field} ${e.defaultSort.order}`);let a=Je(r?.fields,J??q);a.length>0&&(i.$expand=a);let o=await t.find(K,i);if(n)return;ee(o.data||[]);let s=o.total;we(typeof s==`number`?s:void 0),Me.current={...i},z(!1)}}catch(e){n||w(e)}finally{n||C(!1)}})(),()=>{n=!0}},[K,q,J,Y,X,Qe,$e,t,G,W,M]);let Z=We({navigation:e.navigation,objectName:e.objectName,onNavigate:e.onNavigate,onRowClick:o}),{execute:et}=Se(),tt=mt(e.rowColor),nt=(0,H.useCallback)(t=>{let n=e.conditionalFormatting;if(!(!n||n.length===0))for(let e of n){let n=!1,r=(`condition`in e?e.condition:void 0)||(`expression`in e?e.expression:void 0)||void 0;if(r)n=be(r,t);else if(`field`in e&&`operator`in e&&e.field&&e.operator){let r=e,i=t[r.field];switch(r.operator){case`equals`:n=i===r.value;break;case`not_equals`:n=i!==r.value;break;case`contains`:n=typeof i==`string`&&typeof r.value==`string`&&i.includes(r.value);break;case`greater_than`:n=typeof i==`number`&&typeof r.value==`number`&&i>r.value;break;case`less_than`:n=typeof i==`number`&&typeof r.value==`number`&&i<r.value;break;case`in`:n=Array.isArray(r.value)&&r.value.includes(i);break}}if(n){let t={};return`style`in e&&e.style&&Object.assign(t,e.style),`backgroundColor`in e&&e.backgroundColor&&(t.backgroundColor=e.backgroundColor),`textColor`in e&&e.textColor&&(t.color=e.textColor),`borderColor`in e&&e.borderColor&&(t.borderColor=e.borderColor),t}}},[e.conditionalFormatting]),rt=H.useMemo(()=>{let t=e.grouping;if(!t?.fields?.length)return;let n=new Map;for(let r of t.fields){let t=r.field,i=k?.fields?.[t],a=Bt(e.columns)?.find?.(e=>typeof e==`object`&&e?.field===t),o=a?.type||i?.type,s=a?.options||i?.options,c=new Map;if(Array.isArray(s)&&s.length>0){let n=e.objectName?O(e.objectName,t,s):s;for(let e of n)if(e&&e.value!==void 0&&e.value!==null){let t=e.label;c.set(String(e.value),String(t??e.value))}}n.set(t,{type:o||void 0,options:c.size>0?c:void 0})}return(e,t)=>{let r=n.get(e);if(r){if(r.options){let e=r.options.get(String(t));if(e!==void 0)return e}if(r.type===`boolean`||typeof t==`boolean`){if(t===!0||t===`true`)return T(`grid.booleanTrue`,`Yes`);if(t===!1||t===`false`)return T(`grid.booleanFalse`,`No`)}}}},[e.grouping,e.columns,e.objectName,k,O,T]),{groups:it,isGrouped:at,toggleGroup:ot}=bt(e.grouping,y,e.aggregations,rt),{summaries:st,hasSummary:ct}=Tt(H.useMemo(()=>{let t=Bt(e.columns);if(t&&t.length>0&&typeof t[0]==`object`)return t},[e.columns]),y,k?.fields),lt=(0,H.useCallback)(()=>{let t=e=>e&&{text:(0,U.jsx)(te,{className:`h-3.5 w-3.5`}),number:(0,U.jsx)(f,{className:`h-3.5 w-3.5`}),currency:(0,U.jsx)(f,{className:`h-3.5 w-3.5`}),percent:(0,U.jsx)(f,{className:`h-3.5 w-3.5`}),date:(0,U.jsx)(re,{className:`h-3.5 w-3.5`}),datetime:(0,U.jsx)(c,{className:`h-3.5 w-3.5`}),boolean:(0,U.jsx)(m,{className:`h-3.5 w-3.5`}),user:(0,U.jsx)(b,{className:`h-3.5 w-3.5`}),select:(0,U.jsx)(s,{className:`h-3.5 w-3.5`})}[e]||(0,U.jsx)(te,{className:`h-3.5 w-3.5`}),n=e=>{if(e.type)return e.type;let t=e.field.toLowerCase();if([`completed`,`is_completed`,`done`,`active`,`enabled`,`archived`].some(e=>t===e||t===`is_${e}`))return`boolean`;if([`created_time`,`modified_time`,`updated_time`,`created_at`,`updated_at`,`modified_at`,`last_login`,`logged_at`].some(e=>t===e||t.endsWith(`_${e}`)))return`datetime`;if([`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`].some(e=>t.includes(e))){if(y.length>0){let t=y.find(t=>t[e.field]!=null)?.[e.field];if(typeof t==`string`&&!isNaN(Date.parse(t)))return`date`}return`date`}if([`probability`,`percent`,`percentage`,`completion`,`progress`,`rate`].some(e=>t.includes(e))&&y.length>0&&typeof y.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`percent`;if([`status`,`priority`,`category`,`stage`,`type`,`severity`,`level`].some(e=>t.includes(e))&&y.length>0){let t=new Set(y.map(t=>t[e.field]).filter(Boolean));if(t.size>0&&t.size<=10)return`select`}if([`assignee`,`owner`,`author`,`reporter`,`creator`,`user`].some(e=>t.includes(e)))return`user`;if([`amount`,`price`,`total`,`revenue`,`cost`,`budget`,`salary`].some(e=>t.includes(e))&&y.length>0&&typeof y.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`currency`;if(y.length>0){let t=y.find(t=>t[e.field]!=null)?.[e.field];if(typeof t==`string`&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(t))return`datetime`}return null},r=Bt(J);if(r){if(r.length>0&&typeof r[0]==`object`&&r[0]!==null){let i=r[0];if(`accessorKey`in i)return r.map(r=>{if(r.cell)return r;let i=n({field:r.accessorKey,label:r.header,type:r.type});if(!i)return r;let a=Pe(i),o={name:r.accessorKey,type:i};return i===`select`&&(o.options=Array.from(new Set(y.map(e=>e[r.accessorKey]).filter(Boolean))).map(e=>({value:e,label:ye(String(e))}))),r.appearance!=null&&(o.appearance=r.appearance),{...r,...e.showColumnTypeIcons&&{headerIcon:t(i)},cell:e=>(0,U.jsx)(a,{value:e,field:o})}});if(`field`in i)return r.filter(e=>e?.field&&typeof e.field==`string`&&!e.hidden).map((r,i)=>{let a=Rt(r.label)||r.field.charAt(0).toUpperCase()+r.field.slice(1).replace(/_/g,` `),o=e.objectName?E(e.objectName,r.field,a):a,s,c=k?.fields?.[r.field],l=r.type||c?.type||n({field:r.field})||null,u=r.format??c?.format,d=l?ke({type:l,format:u}):null,f=d?Pe(d):null,p={name:r.field,type:d||`text`};c&&(c.label&&(p.label=c.label),c.currency&&(p.currency=c.currency),c.precision!==void 0&&(p.precision=c.precision),c.format&&(p.format=c.format),c.options&&(p.options=O(e.objectName,r.field,c.options))),d===`select`&&!p.options&&(p.options=Array.from(new Set(y.map(e=>e[r.field]).filter(Boolean))).map(e=>({value:e,label:ye(String(e))}))),r.options&&(p.options=O(e.objectName,r.field,r.options));let m=r.appearance??c?.appearance;m!=null&&(p.appearance=m);let h=i===0&&!r.link&&!r.action,g=r.link||h;s=r.link&&r.action||h&&r.action||g?(e,t)=>(0,U.jsx)(Ft,{testId:h?`primary-field-link`:`link-cell`,onActivate:()=>Z.handleClick(t),children:f?(0,U.jsx)(f,{value:e,field:p}):e!=null&&e!==``?String(e):(0,U.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):r.action?(e,t)=>(0,U.jsx)(V,{variant:`outline`,size:`sm`,className:`h-7 text-xs`,"data-testid":`action-cell`,onClick:n=>{n.stopPropagation(),et({type:r.action,params:{record:t,field:r.field,value:e}})},children:Ot(r.action)}):f?e=>(0,U.jsx)(f,{value:e,field:p}):e=>e!=null&&e!==``?(0,U.jsx)(`span`,{children:String(e)}):(0,U.jsx)(se,{});let _=r.prefix;if(_?.field){let e=s,t=_.type===`badge`?Pe(`select`):null;s=(n,r)=>{let i=r[_.field];return(0,U.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[i!=null&&i!==``?t?(0,U.jsx)(t,{value:i,field:{name:_.field,type:`select`}}):(0,U.jsx)(`span`,{className:`text-muted-foreground text-xs mr-1.5`,children:String(i)}):null,e(n,r)]})}}let v=[`number`,`currency`,`percent`],ee=d||r.type,b=r.align||(ee&&v.includes(ee)?`right`:void 0),x=i===0||r.essential===!0;return{header:o,accessorKey:r.field,...e.showColumnTypeIcons&&{headerIcon:t(d)},...!x&&{className:`hidden sm:table-cell`},...r.width&&{width:r.width},...b&&{align:b},sortable:r.sortable!==!1,...r.resizable!==void 0&&{resizable:r.resizable},...r.wrap!==void 0&&{wrap:r.wrap},...s&&{cell:s},...r.pinned&&{pinned:r.pinned}}})}return r.filter(e=>typeof e==`string`&&e.trim().length>0).map((r,i)=>{let a=k?.fields?.[r],o=a?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),s=e.objectName?E(e.objectName,r,o):o,c=a?.type||n({field:r})||null,l=c?Pe(c):null,u={name:r,type:c||`text`};a&&(a.label&&(u.label=a.label),a.currency&&(u.currency=a.currency),a.precision!==void 0&&(u.precision=a.precision),a.format&&(u.format=a.format),a.options&&(u.options=O(e.objectName,r,a.options))),c===`select`&&!u.options&&(u.options=Array.from(new Set(y.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:ye(String(e))}))),(c===`select`||c===`status`)&&a?.appearance!=null&&(u.appearance=a.appearance);let d=c&&[`number`,`currency`,`percent`].includes(c)?`right`:void 0,f=i===0,p;return f&&l?p=(e,t)=>(0,U.jsx)(Ft,{testId:`primary-field-link`,onActivate:()=>Z.handleClick(t),children:(0,U.jsx)(l,{value:e,field:u})}):f?p=(e,t)=>(0,U.jsx)(Ft,{testId:`primary-field-link`,onActivate:()=>Z.handleClick(t),children:e!=null&&e!==``?String(e):(0,U.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):l&&(p=e=>(0,U.jsx)(l,{value:e,field:u})),{header:s,accessorKey:r,...e.showColumnTypeIcons&&c&&{headerIcon:t(c)},...d&&{align:d},...p&&{cell:p},sortable:a?.sortable!==!1}})}if(G){let r=W?.provider===`value`?W.items:[];if(r.length>0)return(q||Object.keys(r[0])).map(r=>{let i=k?.fields?.[r],a=i?.type||n({field:r})||null,o=a?Pe(a):null,s=i?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),c={name:r,type:a||`text`};i&&(i.label&&(c.label=i.label),i.currency&&(c.currency=i.currency),i.precision!==void 0&&(c.precision=i.precision),i.format&&(c.format=i.format),i.options&&(c.options=O(e.objectName,r,i.options))),a===`select`&&!c.options&&(c.options=Array.from(new Set(y.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:ye(String(e))}))),(a===`select`||a===`status`)&&i?.appearance!=null&&(c.appearance=i.appearance);let l=a&&[`number`,`currency`,`percent`].includes(a)?`right`:void 0;return{header:s,accessorKey:r,...e.showColumnTypeIcons&&a&&{headerIcon:t(a)},...l&&{align:l},...o&&{cell:e=>(0,U.jsx)(o,{value:e,field:c})},sortable:i?.sortable!==!1}})}if(!k)return[];let i=[],a=new Set([`id`,`created_at`,`createdAt`,`updated_at`,`updatedAt`,`deleted_at`,`deletedAt`,`created_by`,`createdBy`,`updated_by`,`updatedBy`,`_version`,`_rev`]),o=k?.compactLayout,l=Object.keys(k.fields||{}),u;if(q)u=q;else if(o?.length)u=o.filter(e=>k.fields?.[e]);else{let e=l.filter(e=>{let t=k.fields?.[e];return!(!t||t.hidden||t.readonly&&a.has(e))});u=[...e.filter(e=>!a.has(e)),...e.filter(e=>a.has(e))]}return u.forEach(t=>{let n=k.fields?.[t];if(!n||n.permissions&&n.permissions.read===!1)return;let r=Pe(n.type),a=[`number`,`currency`,`percent`],o=n.options?{...n,options:O(e.objectName,t,n.options)}:n;i.push({header:e.objectName?E(e.objectName,t,n.label||t):n.label||t,accessorKey:t,...a.includes(n.type)&&{align:`right`},cell:e=>(0,U.jsx)(r,{value:e,field:o}),sortable:n.sortable!==!1})}),i},[k,q,J,W,G,Z.handleClick,et,y,E,O,e.objectName]),ut=(0,H.useCallback)(t=>{let n=e.exportOptions,r=n?.maxRecords||0,i=n?.includeHeaders!==!1,a=n?.fileNamePrefix||e.objectName||`export`;if((t===`csv`||t===`xlsx`||t===`json`)&&pe.isSupported&&e.objectName&&!G&&n?.streaming!==!1){let n=lt().filter(e=>e.accessorKey!==`_actions`).map(e=>e.accessorKey).filter(Boolean);P(!1),fe(!0),pe.start(e.objectName,{format:t===`json`?`json`:t,fields:n.length?n:void 0,includeHeaders:i,limit:r>0?r:void 0});return}let o=r>0?y.slice(0,r):y,s=(e,t)=>{let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n)},c=e=>{let t=e==null?``:String(e);return t.includes(`,`)||t.includes(`"`)||t.includes(`
|
|
3
|
+
`)||t.includes(`\r`)?`"${t.replace(/"/g,`""`)}"`:t};if(t===`csv`){let e=lt().filter(e=>e.accessorKey!==`_actions`),t=e.map(e=>e.accessorKey),n=e.map(e=>e.header),r=[];i&&r.push(n.join(`,`)),o.forEach(e=>{r.push(t.map(t=>c(e[t])).join(`,`))}),s(new Blob([r.join(`
|
|
4
|
+
`)],{type:`text/csv;charset=utf-8;`}),`${a}.csv`)}else t===`json`&&s(new Blob([JSON.stringify(o,null,2)],{type:`application/json`}),`${a}.json`);P(!1)},[y,e.exportOptions,e.objectName,lt,pe,G]);if(ne)return(0,U.jsxs)(`div`,{className:`p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,U.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:T(`grid.errorLoading`)}),(0,U.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:ne.message})]});if(x&&y.length===0)return oe?(0,U.jsx)(`div`,{className:`space-y-2 p-2`,children:[1,2,3].map(e=>(0,U.jsxs)(`div`,{className:`border rounded-lg p-3 bg-card animate-pulse`,children:[(0,U.jsx)(`div`,{className:`h-5 bg-muted rounded w-3/4 mb-3`}),(0,U.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,U.jsx)(`div`,{className:`h-4 bg-muted rounded w-1/4`}),(0,U.jsx)(`div`,{className:`h-5 bg-muted rounded-full w-20`})]}),(0,U.jsx)(`div`,{className:`h-3 bg-muted rounded w-1/3`})]},e))}):(0,U.jsxs)(`div`,{className:`p-4 sm:p-8 text-center`,children:[(0,U.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-foreground`}),(0,U.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:T(`grid.loading`)})]});let dt=[...lt()];if(B.widths&&(dt=dt.map(e=>{let t=B.widths?.[e.accessorKey];return t?{...e,size:t}:e})),B.order&&B.order.length>0){let e=new Map(B.order.map((e,t)=>[e,t]));dt.sort((t,n)=>(e.get(t.accessorKey)??1/0)-(e.get(n.accessorKey)??1/0))}let Q=(`operations`in e?e.operations:void 0)??{update:!!n,delete:!!r},ft=Array.isArray(e.rowActions)?e.rowActions:[],pt=Array.isArray(e.rowActionDefs)?e.rowActionDefs:[],ht=ft.includes(`edit`),gt=ft.includes(`delete`),_t=ft.filter(e=>e!==`edit`&&e!==`delete`),vt=!!((Q?.update||ht)&&n),yt=!!((Q?.delete||gt)&&r),St=!!(Q&&(Q.update||Q.delete)),Ct=_t.length>0||pt.length>0||ht||gt,wt=St||Ct?[...dt,{header:T(`grid.actions`),accessorKey:`_actions`,cell:(e,t)=>(0,U.jsx)(kt,{row:t,rowActions:_t,rowActionDefs:pt,canEdit:vt,canDelete:yt,onEdit:n,onDelete:r,onAction:(e,t)=>et({type:e,params:{record:t}}),onActionDef:(e,t)=>{let{params:n,...r}=e,i={...r};Array.isArray(n)&&n.length>0&&(i.actionParams=n),i.params={_rowRecord:t},et(i)}}),sortable:!1}]:dt,Et=wt.filter(e=>e.pinned===`left`),Dt=wt.filter(e=>e.pinned===`right`),jt=wt.filter(e=>!e.pinned),Nt=Et.length>0||Dt.length>0,Pt=`sticky right-0 z-10 bg-background border-l border-border`,It=F===`compact`?`px-3 py-1 h-9 text-[13px] leading-tight`:F===`short`?`px-3 py-1 h-9 text-[13px] leading-normal`:F===`tall`?`px-3 py-2.5 h-14 text-sm`:F===`extra_tall`?`px-3 py-3.5 h-16 text-sm leading-relaxed`:`px-3 py-1.5 h-11 text-[13px] leading-normal`,Vt=e=>({...e,cellClassName:[It,e.cellClassName].filter(Boolean).join(` `)}),Ht=Nt?[...Et.map(Vt),...jt.map(Vt),...Dt.map(e=>({...Vt(e),className:[e.className,Pt].filter(Boolean).join(` `),cellClassName:[It,e.cellClassName,Pt].filter(Boolean).join(` `)}))]:wt.map(Vt),Ut=Nt?Et.length:e.frozenColumns??1,$=e.batchActions??e.bulkActions,Wt=Array.isArray(e.bulkActionDefs)?e.bulkActionDefs:[],Gt=$&&$.length>0?$:yt&&i&&Wt.length===0?[`delete`]:[],Kt=Gt.length>0||Wt.length>0,qt=!1;e.selection?.type?qt=e.selection.type===`none`?!1:e.selection.type:e.selectable===void 0?Kt&&(qt=`multiple`):qt=e.selectable;let Jt=async n=>{if(!ve)return n;let r=e.objectName;if(!t||!r)return n;let i={...Me.current??{}};delete i.$top,delete i.$skip;let a=5e3,o=[],s=0;for(;o.length<a;){let e=(await t.find(r,{...i,$top:500,$skip:s})).data??[];if(e.length===0||(o.push(...e),e.length<500))break;s+=500}return o.slice(0,a)},Yt=(e,t)=>{(async()=>{let n=await Jt(t);if(e===`delete`&&i){i(n),R([]),z(!1);return}et({type:e,params:{records:n}})})()},Xt=(e,t)=>{(async()=>{let n=await Jt(t);De(e),Ae(n)})()},Zt=e=>{De(null),Ae([]),e&&(R([]),z(!1),N(e=>e+1))},Qt=e.pagination===void 0?e.showPagination===void 0?!0:e.showPagination:!0,$t=e.pagination?.pageSize||e.pageSize||10,en=e.searchableFields===void 0?e.showSearch===void 0?!0:e.showSearch:e.searchableFields.length>0,tn={type:`data-table`,caption:e.label||e.title,columns:Ht,data:y,pagination:Qt,pageSize:$t,searchable:en,selectable:qt,sortable:!0,exportable:Q?.export,borderless:!0,rowActions:!!(e.editable&&St),resizableColumns:e.resizable??e.resizableColumns??!0,reorderableColumns:e.reorderableColumns??!1,editable:e.editable??!1,singleClickEdit:e.singleClickEdit??!0,className:e.className,cellClassName:F===`compact`?`px-3 py-1 text-[13px] leading-tight`:F===`short`?`px-3 py-1 text-[13px] leading-normal`:F===`tall`?`px-3 py-2.5 text-sm`:F===`extra_tall`?`px-3 py-3.5 text-sm leading-relaxed`:`px-3 py-1.5 text-[13px] leading-normal`,showRowNumbers:!0,showAddRow:!!Q?.create,onAddRecord:p,rowClassName:e.rowColor?(e,t)=>tt(e):void 0,rowStyle:e.conditionalFormatting?.length?(e,t)=>nt(e):void 0,frozenColumns:Ut,onSelectionChange:e=>{R(e),a?.(e)},onRowClick:Z.handleClick,onCellChange:l,onRowSave:u,onBatchSave:d,onColumnResize:(e,t)=>{Re({...B,widths:{...B.widths,[e]:t}})},onColumnReorder:e=>{Re({...B,order:e})}},nn=e=>({...tn,caption:void 0,data:e,pagination:!1,searchable:!1,borderless:!0}),rn=e.label?`${e.label} Detail`:e.objectName?`${e.objectName.charAt(0).toUpperCase()+e.objectName.slice(1)} Detail`:`Record Detail`;if(oe&&y.length>0&&!at){let e=lt().filter(e=>e.accessorKey!==`_actions`),t=new Map;e.forEach(e=>t.set(e.accessorKey,e));let n=e[0],r=[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`],i=[`stage`,`status`,`priority`,`category`,`severity`,`level`],a=[`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`],o=[`probability`,`percent`,`rate`,`ratio`,`confidence`,`score`],s=e=>{let t=(e||``).toLowerCase();return t.includes(`won`)||t.includes(`completed`)||t.includes(`done`)||t.includes(`active`)||t===`activated`||t===`success`||t===`approved`||t===`paid`?`bg-green-50 text-green-700 border-green-200 dark:bg-green-950/40 dark:text-green-300 dark:border-green-900/60`:t.includes(`lost`)||t.includes(`cancelled`)||t.includes(`rejected`)||t.includes(`closed lost`)||t===`expired`||t===`terminated`||t===`failed`||t===`overdue`?`bg-red-50 text-red-700 border-red-200 dark:bg-red-950/40 dark:text-red-300 dark:border-red-900/60`:t.includes(`negotiation`)||t.includes(`review`)||t.includes(`in progress`)||t.includes(`approval`)||t===`in_approval`||t===`pending_approval`?`bg-yellow-50 text-yellow-800 border-yellow-200 dark:bg-yellow-950/40 dark:text-yellow-300 dark:border-yellow-900/60`:t.includes(`proposal`)||t.includes(`pending`)?`bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900/60`:t.includes(`qualification`)||t.includes(`qualified`)?`bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-950/40 dark:text-indigo-300 dark:border-indigo-900/60`:t.includes(`prospecting`)||t.includes(`new`)||t.includes(`open`)?`bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-900/60`:t===`draft`||t.includes(`draft`)?`bg-slate-50 text-slate-700 border-slate-200 dark:bg-slate-950/40 dark:text-slate-300 dark:border-slate-900/60`:`bg-muted text-muted-foreground border-border`},c=e=>{let t=(e||``).toLowerCase();return t.includes(`won`)||t.includes(`completed`)||t.includes(`done`)||t.includes(`active`)||t===`activated`?`border-l-green-500`:t.includes(`lost`)||t.includes(`cancelled`)||t.includes(`rejected`)||t===`expired`||t===`terminated`?`border-l-red-500`:t.includes(`negotiation`)||t.includes(`review`)||t.includes(`in progress`)||t.includes(`approval`)?`border-l-yellow-500`:t.includes(`proposal`)||t.includes(`pending`)?`border-l-blue-500`:t.includes(`qualification`)||t.includes(`qualified`)?`border-l-indigo-500`:t.includes(`prospecting`)||t.includes(`new`)||t.includes(`open`)?`border-l-purple-500`:t===`draft`||t.includes(`draft`)?`border-l-slate-400`:`border-l-gray-300`},l=e=>{let t=e.toLowerCase();return r.some(e=>t.includes(e))?`amount`:i.some(e=>t.includes(e))?`stage`:a.some(e=>t.includes(e))?`date`:o.some(e=>t.includes(e))?`percent`:`other`};return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`space-y-2 p-2`,children:y.map((t,r)=>{let i=e.slice(1,5),a=i.find(e=>l(e.accessorKey)===`amount`),o=i.find(e=>l(e.accessorKey)===`stage`),u=i.filter(e=>l(e.accessorKey)===`date`),d=i.filter(e=>l(e.accessorKey)===`percent`),f=i.filter(e=>e!==a&&e!==o&&!u.includes(e)&&!d.includes(e)),p=o?String(t[o.accessorKey]??``):``,m=p?c(p):``;return(0,U.jsxs)(`div`,{className:[`border rounded-lg p-2.5 bg-card hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,m?`border-l-[3px] ${m}`:``].filter(Boolean).join(` `),onClick:()=>Z.handleClick(t),children:[n&&(0,U.jsx)(`div`,{className:`font-semibold text-sm truncate mb-1`,children:t[n.accessorKey]!=null&&typeof t[n.accessorKey]==`object`?String(t[n.accessorKey]):t[n.accessorKey]??`—`}),(a||o)&&(0,U.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[a&&(0,U.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:typeof t[a.accessorKey]==`number`?_e(t[a.accessorKey]):t[a.accessorKey]!=null&&typeof t[a.accessorKey]==`object`?String(t[a.accessorKey]):t[a.accessorKey]??`—`}),o&&t[o.accessorKey]&&(0,U.jsx)(je,{variant:`outline`,className:`text-xs shrink-0 max-w-[140px] truncate ${s(String(t[o.accessorKey]))}`,children:String(t[o.accessorKey])})]}),(u.length>0||d.length>0)&&(0,U.jsxs)(`div`,{className:`flex items-center justify-between py-0.5 text-xs text-muted-foreground`,children:[u[0]&&(0,U.jsx)(`span`,{className:`tabular-nums`,children:t[u[0].accessorKey]?Ye(t[u[0].accessorKey],`short`):`—`}),d[0]&&t[d[0].accessorKey]!=null&&(0,U.jsx)(`span`,{className:`tabular-nums`,children:qe(Number(t[d[0].accessorKey]))})]}),u.slice(1).map(e=>(0,U.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,U.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,U.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums`,children:t[e.accessorKey]?Ye(t[e.accessorKey],`short`):`—`})]},e.accessorKey)),f.map(e=>{let n=t[e.accessorKey];return n==null||n===``?null:(0,U.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,U.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,U.jsx)(`span`,{className:`text-xs font-medium truncate ml-2 text-right`,children:e.cell?e.cell(n,t):String(n)})]},e.accessorKey)})]},t.id||t._id||r)})}),Z.isOverlay&&(0,U.jsx)(Be,{...Z,title:rn,children:e=>(0,U.jsx)(`div`,{className:`space-y-3`,children:Object.entries(e).map(([e,t])=>(0,U.jsxs)(`div`,{className:`flex flex-col`,children:[(0,U.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:e.replace(/_/g,` `)}),(0,U.jsx)(`span`,{className:`text-sm`,children:String(t??`—`)})]},e))})})]})}let an=()=>{he(e=>e===`compact`?`short`:e===`short`?`medium`:e===`medium`?`tall`:e===`tall`?`extra_tall`:`compact`)},on={compact:_,short:g,medium:v,tall:ie,extra_tall:ie}[F],sn=e.rowHeight!==void 0&&!e.hideRowHeightToggle,cn=e.exportOptions||sn?(0,U.jsxs)(`div`,{className:`flex items-center justify-end gap-1 px-2 py-1`,children:[sn&&(0,U.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,onClick:an,title:`Row height: ${F}`,children:[(0,U.jsx)(on,{className:`h-3.5 w-3.5 mr-1.5`}),(0,U.jsx)(`span`,{className:`hidden sm:inline capitalize`,children:F})]}),e.exportOptions&&(0,U.jsxs)(L,{open:ue,onOpenChange:P,children:[(0,U.jsx)(ge,{asChild:!0,children:(0,U.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,children:[(0,U.jsx)(S,{className:`h-3.5 w-3.5 mr-1.5`}),(0,U.jsx)(`span`,{className:`hidden sm:inline`,children:T(`grid.export`)})]})}),(0,U.jsx)(ae,{align:`end`,className:`w-48 p-2`,children:(0,U.jsx)(`div`,{className:`space-y-1`,children:(e.exportOptions.formats||[`csv`,`json`]).map(e=>(0,U.jsxs)(V,{variant:`ghost`,size:`sm`,className:`w-full justify-start h-8 text-xs`,onClick:()=>ut(e),children:[(0,U.jsx)(S,{className:`h-3.5 w-3.5 mr-2`}),T(`grid.exportAs`,{format:e.toUpperCase()})]},e))})})]})]}):null,ln=e=>{let t=[`_id`,`id`,`created_at`,`updated_at`,`created_by`,`updated_by`],n=Object.entries(e),r=e=>k?.fields?.[e]?.hidden===!0,i=n.filter(([e])=>!t.includes(e)&&!r(e)),a=n.filter(([e])=>t.includes(e)&&e!==`_id`&&e!==`id`),o=e=>e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `),s=(e,t)=>{if(t==null||t===``)return(0,U.jsx)(`span`,{className:`text-muted-foreground/50 text-sm italic`,children:T(`grid.empty`)});let n=k?.fields?.[e];if(n?.type){let e=Pe(n.type);if(e)return(0,U.jsx)(e,{value:t,field:n})}return typeof t==`boolean`?(0,U.jsx)(je,{variant:t?`default`:`outline`,children:T(t?`grid.yes`:`grid.no`)}):typeof t==`string`&&!isNaN(Date.parse(t))&&(e.includes(`date`)||e.includes(`_at`)||e.includes(`time`))?(0,U.jsx)(`span`,{className:`text-sm tabular-nums`,children:Ye(t)}):typeof t==`number`&&[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`].some(t=>e.toLowerCase().includes(t))?(0,U.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:me(t)}):(0,U.jsx)(`span`,{className:`text-sm break-words`,children:String(t)})};return(0,U.jsxs)(`div`,{className:`space-y-4`,"data-testid":`record-detail-panel`,children:[(0,U.jsx)(`div`,{className:`rounded-lg border bg-card`,children:(0,U.jsx)(`div`,{className:`divide-y`,children:i.map(([e,t])=>(0,U.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 px-4 py-3`,children:[(0,U.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground sm:w-1/3 sm:text-right sm:pt-0.5 uppercase tracking-wide shrink-0`,children:o(e)}),(0,U.jsx)(`div`,{className:`flex-1 min-w-0`,children:s(e,t)})]},e))})}),a.length>0&&(0,U.jsxs)(`div`,{className:`rounded-lg border bg-muted/30`,children:[(0,U.jsx)(`div`,{className:`px-4 py-2 border-b`,children:(0,U.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:T(`grid.systemFields`)})}),(0,U.jsx)(`div`,{className:`divide-y divide-border/50`,children:a.map(([e,t])=>(0,U.jsxs)(`div`,{className:`flex items-center gap-4 px-4 py-2`,children:[(0,U.jsx)(`span`,{className:`text-xs text-muted-foreground w-1/3 text-right shrink-0`,children:o(e)}),(0,U.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1 min-w-0 break-words`,children:String(t??``)})]},e))})]})]})},un=ct?(0,U.jsx)(`div`,{className:`border-t bg-muted/30 px-2 py-1.5`,"data-testid":`column-summary-footer`,children:(0,U.jsx)(`div`,{className:`flex gap-4 text-xs text-muted-foreground font-medium`,children:Ht.filter(e=>st.has(e.accessorKey)).map(e=>{let t=st.get(e.accessorKey);return(0,U.jsxs)(`span`,{"data-testid":`summary-${e.accessorKey}`,children:[e.header,`: `,t.label]},e.accessorKey)})})}):null,dn=(t,n)=>{let r=k?.fields?.[t],i=e.objectName?E(e.objectName,t,r?.label||t):r?.label||t,a,o=r?.type;if(o===`select`||o===`status`){let i=r?.options?O(e.objectName,t,r.options):void 0,o=Array.isArray(i)?i.find(e=>String(e.label)===n||String(e.value)===n):void 0;a=Ee(o?.color,o?.value??n)}return{fieldLabel:i,labelColorClass:a}},fn=e=>{let{fieldLabel:t,labelColorClass:n}=dn(e.field,e.label);return(0,U.jsx)(`div`,{children:(0,U.jsx)(xt,{groupKey:e.key,label:e.label,count:e.rows.length,collapsed:e.collapsed,aggregations:e.aggregations,fieldLabel:e.depth===0?t:void 0,labelColorClass:n,onToggle:ot,children:e.subgroups.length>0?(0,U.jsx)(`div`,{className:`space-y-4 mt-2`,children:e.subgroups.map(fn)}):(0,U.jsx)(Ce,{schema:nn(e.rows)})})},e.key)},pn=at?(0,U.jsx)(`div`,{className:`space-y-4 px-3 sm:px-4 pt-2 pb-4`,children:it.map(fn)}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Ce,{schema:tn}),un]}),mn=(0,U.jsx)(le,{open:de,onOpenChange:fe,job:pe,filename:`${e.exportOptions?.fileNamePrefix||e.objectName||`export`}.${pe.progress?.format||`csv`}`,closeAfterDownloadMs:400}),hn=(0,U.jsx)(Mt,{def:Te,rows:Oe,open:!!Te,onClose:Zt,dataSource:t,resource:e.objectName??``});return Z.isOverlay&&Z.mode===`split`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Be,{...Z,title:rn,mainContent:(0,U.jsxs)(U.Fragment,{children:[cn,pn,(0,U.jsx)(At,{selectedRows:I,actions:Gt??[],actionDefs:Wt,onAction:Yt,onActionDef:Xt,onClearSelection:()=>{R([]),z(!1)},pageSize:y.length,totalMatching:xe,allMatchingSelected:ve,onSelectAllMatching:()=>z(!0)})]}),children:e=>ln(e)}),mn,hn]}):(0,U.jsxs)(`div`,{ref:Ve,className:`relative h-full`,children:[(0,U.jsx)(D,{active:x&&y.length>0}),Ge>0&&(0,U.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:Ge},children:T(He?`grid.refreshing`:`grid.pullToRefresh`)}),cn,pn,(0,U.jsx)(At,{selectedRows:I,actions:Gt??[],actionDefs:Wt,onAction:Yt,onActionDef:Xt,onClearSelection:()=>{R([]),z(!1)},pageSize:y.length,totalMatching:xe,allMatchingSelected:ve,onSelectAllMatching:()=>z(!0)}),Z.isOverlay&&(0,U.jsx)(Be,{...Z,title:rn,children:e=>ln(e)}),mn,hn]})},Ht={"grid.import.title":`Import {{object}}`,"grid.import.stepUpload":`Upload`,"grid.import.stepMapping":`Mapping`,"grid.import.stepPreview":`Preview`,"grid.import.uploadDescription":`Upload a CSV file to get started.`,"grid.import.mappingDescription":`Map CSV columns to object fields.`,"grid.import.previewDescription":`Review data before importing.`,"grid.import.dragDrop":`Drag & drop a CSV file here, or click to browse`,"grid.import.browseFiles":`Browse Files`,"grid.import.onlyCsv":`Only CSV files are supported.`,"grid.import.fileNeedsHeader":`File must contain a header row and at least one data row.`,"grid.import.mappingTemplate":`Mapping template:`,"grid.import.chooseTemplate":`Choose template…`,"grid.import.noSavedTemplates":`No saved templates`,"grid.import.noneOption":`— None —`,"grid.import.saveCurrent":`Save current`,"grid.import.templateName":`Template name`,"grid.import.save":`Save`,"grid.import.deleteTemplate":`Delete template`,"grid.import.csvColumn":`CSV Column`,"grid.import.mapsTo":`Maps To`,"grid.import.status":`Status`,"grid.import.skipColumn":`Skip column`,"grid.import.skip":`— Skip —`,"grid.import.mapped":`Mapped`,"grid.import.skipped":`Skipped`,"grid.import.rowsWithErrors":`{{count}} row(s) with errors`,"grid.import.rowsCorrected":`{{count}} row(s) corrected`,"grid.import.clickToFix":`— click a highlighted cell to fix it inline.`,"grid.import.showingRows":`Showing {{shown}} of {{total}} rows`,"grid.import.importing":`Importing… {{progress}}%`,"grid.import.importComplete":`Import Complete`,"grid.import.imported":`{{count}} imported`,"grid.import.skippedCount":`{{count}} skipped`,"grid.import.moreErrors":`…and {{count}} more errors`,"grid.import.cancel":`Cancel`,"grid.import.back":`Back`,"grid.import.next":`Next`,"grid.import.close":`Close`,"grid.import.importNRows":`Import {{count}} Rows`,"grid.import.importingProgress":`Importing…`,"grid.import.required":`Required`,"grid.import.invalidType":`Invalid {{type}}`};function Ut(e,t){if(!t)return e;let n=e;for(let[e,r]of Object.entries(t))n=n.replace(RegExp(`{{${e}}}`,`g`),String(r));return n}function $(){let e=(e,t)=>Ut(Ht[e]??e,t);try{let t=ve();return t.t(`grid.import.title`)===`grid.import.title`?{t:e}:{t:(n,r)=>{let i=t.t(n,r);return i===n?e(n,r):i}}}catch{return{t:e}}}var Wt=10;function Gt(e){let t=[],n=[],r=``,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=e[a+1];i?o===`"`&&s===`"`?(r+=`"`,a++):o===`"`?i=!1:r+=o:o===`"`?i=!0:o===`,`?(n.push(r.trim()),r=``):o===`
|
|
5
|
+
`||o===`\r`&&s===`
|
|
6
|
+
`?(n.push(r.trim()),n.some(e=>e!==``)&&t.push(n),n=[],r=``,o===`\r`&&a++):r+=o}return n.push(r.trim()),n.some(e=>e!==``)&&t.push(n),t}function Kt(e,t){if(!e)return!0;switch(t){case`number`:case`currency`:case`percent`:return!isNaN(Number(e));case`boolean`:return[`true`,`false`,`1`,`0`,`yes`,`no`].includes(e.toLowerCase());case`date`:case`datetime`:return!isNaN(Date.parse(e));default:return!0}}function qt(e,t){let n={};return e.forEach((e,r)=>{let i=e.toLowerCase().replace(/[_\s-]/g,``),a=t.find(e=>{let t=e.name.toLowerCase().replace(/[_\s-]/g,``),n=e.label.toLowerCase().replace(/[_\s-]/g,``);return t===i||n===i});a&&(n[r]=a.name)}),n}function Jt(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function Yt(e,t){if(!e)return[];try{let n=e.getItem(t);if(!n)return[];let r=JSON.parse(n);return Array.isArray(r)?r.filter(e=>e&&e.id&&e.name&&e.mapping):[]}catch{return[]}}function Xt(e,t,n){if(e)try{e.setItem(t,JSON.stringify(n))}catch{}}function Zt(e,t){let n={};return Object.entries(t).forEach(([t,r])=>{let i=e[Number(t)];i&&(n[i.trim().toLowerCase()]=r)}),n}function Qt(e,t,n){let r=new Set(n.map(e=>e.name)),i={};return t.forEach((t,n)=>{let a=e.mapping[t.trim().toLowerCase()];a&&r.has(a)&&(i[n]=a)}),i}function $t(e,t,n){let r=[],i={};for(let a of t){let t=e[a.csvIdx]??``;if(a.field.required&&!t){r.push({row:n,field:a.field.name,message:`Required field is empty`});continue}if(t&&!Kt(t,a.field.type)){r.push({row:n,field:a.field.name,message:`Invalid ${a.field.type} value: "${t}"`});continue}i[a.field.name]=t}return{record:i,errors:r}}var en=({onFileLoaded:e})=>{let{t}=$(),[n,r]=(0,H.useState)(!1),[i,a]=(0,H.useState)(null),o=(0,H.useCallback)(n=>{if(a(null),!n.name.endsWith(`.csv`)){a(t(`grid.import.onlyCsv`));return}let r=new FileReader;r.onload=n=>{let r=Gt(n.target?.result);if(r.length<2){a(t(`grid.import.fileNeedsHeader`));return}e(r[0],r.slice(1))},r.readAsText(n)},[e,t]);return(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-4 py-6`,children:[(0,U.jsxs)(`div`,{className:N(`flex w-full flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-10 transition-colors`,n?`border-primary bg-primary/5`:`border-muted-foreground/25`),onDragOver:e=>{e.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:e=>{e.preventDefault(),r(!1);let t=e.dataTransfer.files[0];t&&o(t)},children:[(0,U.jsx)(w,{className:`h-10 w-10 text-muted-foreground`}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`grid.import.dragDrop`)}),(0,U.jsxs)(`label`,{children:[(0,U.jsx)(`input`,{type:`file`,accept:`.csv`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&o(t)}}),(0,U.jsx)(V,{variant:`outline`,size:`sm`,asChild:!0,children:(0,U.jsx)(`span`,{children:t(`grid.import.browseFiles`)})})]})]}),i&&(0,U.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-destructive`,children:[(0,U.jsx)(l,{className:`h-4 w-4`}),` `,i]})]})},tn=({templates:e,selectedId:t,onSelect:n,onSaveAs:r,onDelete:i,disabled:a})=>{let{t:o}=$(),[s,c]=(0,H.useState)(``),[l,u]=(0,H.useState)(!1);return(0,U.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2 rounded-md border bg-muted/30 p-2`,"data-testid":`import-template-bar`,children:[(0,U.jsx)(d,{className:`h-4 w-4 text-muted-foreground`}),(0,U.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:o(`grid.import.mappingTemplate`)}),(0,U.jsxs)(R,{value:t??`__none__`,onValueChange:e=>e!==`__none__`&&n(e),children:[(0,U.jsx)(De,{className:`h-7 w-48 text-xs`,"data-testid":`import-template-select`,children:(0,U.jsx)(Ie,{placeholder:e.length?o(`grid.import.chooseTemplate`):o(`grid.import.noSavedTemplates`)})}),(0,U.jsxs)(Ve,{children:[(0,U.jsx)(M,{value:`__none__`,disabled:e.length===0,children:e.length?o(`grid.import.noneOption`):o(`grid.import.noSavedTemplates`)}),e.map(e=>(0,U.jsx)(M,{value:e.id,children:e.name},e.id))]})]}),l?(0,U.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,U.jsx)(I,{value:s,onChange:e=>c(e.target.value),placeholder:o(`grid.import.templateName`),className:`h-7 w-40 text-xs`,"data-testid":`import-template-name-input`,autoFocus:!0}),(0,U.jsx)(V,{type:`button`,size:`sm`,onClick:()=>{s.trim()&&(r(s.trim()),c(``),u(!1))},disabled:!s.trim()||a,"data-testid":`import-template-confirm-save`,children:o(`grid.import.save`)}),(0,U.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{u(!1),c(``)},children:o(`grid.import.cancel`)})]}):(0,U.jsx)(V,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>u(!0),disabled:a,"data-testid":`import-template-save-btn`,children:o(`grid.import.saveCurrent`)}),t&&(0,U.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:i,"aria-label":o(`grid.import.deleteTemplate`),"data-testid":`import-template-delete-btn`,children:(0,U.jsx)(E,{className:`h-3.5 w-3.5`})})]})},nn=({headers:e,fields:t,mapping:n,onMappingChange:r,templates:i,selectedTemplateId:a,onSelectTemplate:o,onSaveTemplate:s,onDeleteTemplate:c})=>{let{t:l}=$(),u=(0,H.useMemo)(()=>new Set(Object.values(n)),[n]),d=(0,H.useCallback)((e,t)=>{let i={...n};t===`__skip__`?delete i[e]:i[e]=t,r(i)},[n,r]);return(0,U.jsxs)(`div`,{children:[(0,U.jsx)(tn,{templates:i,selectedId:a,onSelect:o,onSaveAs:s,onDelete:c,disabled:Object.keys(n).length===0}),(0,U.jsx)(`div`,{className:`max-h-[420px] overflow-auto`,children:(0,U.jsxs)(Ge,{children:[(0,U.jsx)(B,{children:(0,U.jsxs)(P,{children:[(0,U.jsx)(He,{children:l(`grid.import.csvColumn`)}),(0,U.jsx)(He,{children:l(`grid.import.mapsTo`)}),(0,U.jsx)(He,{className:`w-24 text-center`,children:l(`grid.import.status`)})]})}),(0,U.jsx)(Te,{children:e.map((e,r)=>(0,U.jsxs)(P,{children:[(0,U.jsx)(Me,{className:`font-medium`,children:e}),(0,U.jsx)(Me,{children:(0,U.jsxs)(R,{value:n[r]??`__skip__`,onValueChange:e=>d(r,e),children:[(0,U.jsx)(De,{className:`h-8 w-56`,children:(0,U.jsx)(Ie,{placeholder:l(`grid.import.skipColumn`)})}),(0,U.jsxs)(Ve,{children:[(0,U.jsx)(M,{value:`__skip__`,children:l(`grid.import.skip`)}),t.map(e=>(0,U.jsxs)(M,{value:e.name,disabled:u.has(e.name)&&n[r]!==e.name,children:[e.label,e.required?` *`:``]},e.name))]})]})}),(0,U.jsx)(Me,{className:`text-center`,children:n[r]?(0,U.jsx)(je,{variant:`default`,className:`text-xs`,children:l(`grid.import.mapped`)}):(0,U.jsx)(je,{variant:`secondary`,className:`text-xs`,children:l(`grid.import.skipped`)})})]},r))})]})})]})},rn=({headers:e,rows:t,mapping:n,fields:r,corrections:i,onCorrect:a})=>{let{t:o}=$(),s=(0,H.useMemo)(()=>Object.entries(n).map(([t,n])=>({csvIdx:Number(t),header:e[Number(t)],field:r.find(e=>e.name===n)})),[n,e,r]),c=t.slice(0,Wt),u=(0,H.useCallback)((e,t)=>{let n=i[e]?.[t];return n===void 0?c[e]?.[t]??``:n},[i,c]),d=(0,H.useMemo)(()=>c.map((e,t)=>{let n={};for(let e of s){let r=u(t,e.csvIdx);e.field.required&&!r?n[e.csvIdx]=o(`grid.import.required`):r&&!Kt(r,e.field.type)&&(n[e.csvIdx]=o(`grid.import.invalidType`,{type:e.field.type}))}return n}),[c,s,u,o]),f=d.filter(e=>Object.keys(e).length>0).length,p=Object.keys(i).length;return(0,U.jsxs)(`div`,{className:`max-h-[440px] overflow-auto`,children:[(f>0||p>0)&&(0,U.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs`,"data-testid":`import-preview-status`,children:[f>0&&(0,U.jsxs)(`span`,{className:`flex items-center gap-1 text-destructive`,children:[(0,U.jsx)(l,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsWithErrors`,{count:f})]}),p>0&&(0,U.jsxs)(`span`,{className:`flex items-center gap-1 text-emerald-600`,children:[(0,U.jsx)(h,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsCorrected`,{count:p})]}),(0,U.jsx)(`span`,{className:`text-muted-foreground`,children:o(`grid.import.clickToFix`)})]}),(0,U.jsxs)(Ge,{children:[(0,U.jsx)(B,{children:(0,U.jsxs)(P,{children:[(0,U.jsx)(He,{className:`w-12`,children:`#`}),s.map(e=>(0,U.jsx)(He,{children:e.field.label},e.csvIdx))]})}),(0,U.jsx)(Te,{children:c.map((e,t)=>{let n=d[t],r=Object.keys(n).length>0,o=i[t]!==void 0;return(0,U.jsxs)(P,{className:N(r&&`bg-destructive/5`,!r&&o&&`bg-emerald-50 dark:bg-emerald-950/20`),"data-testid":`import-preview-row-${t}`,children:[(0,U.jsx)(Me,{className:`text-xs text-muted-foreground`,children:t+1}),s.map(e=>{let r=u(t,e.csvIdx),o=n[e.csvIdx],s=i[t]?.[e.csvIdx]!==void 0;return(0,U.jsx)(Me,{className:N(o&&`text-destructive`,s&&!o&&`text-emerald-600`),title:o,children:(0,U.jsx)(I,{value:r,onChange:n=>a(t,e.csvIdx,n.target.value),className:N(`h-7 px-1 text-xs`,o&&`border-destructive`,s&&!o&&`border-emerald-500`),"data-testid":`import-preview-cell-${t}-${e.csvIdx}`,"aria-invalid":o?`true`:`false`,"aria-label":`${e.field.label} for row ${t+1}`})},e.csvIdx)})]},t)})})]}),(0,U.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:o(`grid.import.showingRows`,{shown:c.length,total:t.length})})]})},an=({objectName:e,objectLabel:t,fields:n,dataSource:r,onComplete:i,onCancel:a,open:o,onOpenChange:s,onErrorMode:c=`skip`,templateStorageKey:l,templateStorage:u})=>{let[d,f]=(0,H.useState)(`upload`),[p,m]=(0,H.useState)([]),[g,_]=(0,H.useState)([]),[v,b]=(0,H.useState)({}),[x,S]=(0,H.useState)(!1),[te,C]=(0,H.useState)(0),[w,re]=(0,H.useState)(null),[ie,E]=(0,H.useState)({}),ae=t??e,D=(0,H.useMemo)(()=>u===void 0?Jt():u,[u]),A=l??`objectui:import-templates:${e}`,[j,se]=(0,H.useState)(()=>Yt(D,A)),[ce,M]=(0,H.useState)(null);(0,H.useEffect)(()=>{se(Yt(D,A))},[D,A]);let le=(0,H.useCallback)(e=>{let t=j.find(t=>t.id===e);t&&(M(e),b(Qt(t,p,n)))},[j,p,n]),ue=(0,H.useCallback)(e=>{let t={id:`tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:e,mapping:Zt(p,v),updatedAt:Date.now()},n=[...j,t];se(n),M(t.id),Xt(D,A,n)},[j,p,v,D,A]),P=(0,H.useCallback)(()=>{if(!ce)return;let e=j.filter(e=>e.id!==ce);se(e),M(null),Xt(D,A,e)},[j,ce,D,A]),de=(0,H.useCallback)((e,t,n)=>{E(r=>{let i={...r},a={...i[e]??{}};return n===(g[e]?.[t]??``)?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,i})},[g]),pe=(0,H.useMemo)(()=>{let e=new Set(Object.values(v));return n.filter(t=>t.required&&!e.has(t.name))},[n,v]),me=(0,H.useCallback)((e,t)=>{m(e),_(t),b(qt(e,n)),E({}),f(`mapping`)},[n]),he=(0,H.useCallback)(async()=>{S(!0),C(0);let t=[],a=0,o=0,s=Object.entries(v).map(([e,t])=>({csvIdx:Number(e),field:n.find(e=>e.name===t)}));for(let n=0;n<g.length;n++){let i=g[n],l=ie[n],{record:u,errors:d}=$t(l?i.map((e,t)=>l[t]===void 0?e:l[t]):i,s,n+1);if(d.length>0){if(o++,t.push(...d),c===`stop`)break}else try{r?.create&&await r.create(e,u),a++}catch(e){o++;let r=e instanceof Error?e.message:`Failed to create record`;if(t.push({row:n+1,field:``,message:r}),c===`stop`)break}C(Math.round((n+1)/g.length*100))}let l={totalRows:g.length,importedRows:a,skippedRows:o,errors:t};re(l),S(!1),i?.(l)},[g,v,n,r,e,i,c,ie]),I=(0,H.useCallback)(()=>{f(`upload`),m([]),_([]),b({}),C(0),re(null),E({}),M(null)},[]),ge=(0,H.useCallback)(()=>{I(),s?.(!1),a?.()},[I,s,a]),{t:L}=$();return(0,U.jsx)(fe,{open:o,onOpenChange:e=>{e?s?.(e):ge()},children:(0,U.jsxs)(k,{className:`flex max-h-[85vh] flex-col gap-4 overflow-hidden sm:max-w-4xl`,children:[(0,U.jsxs)(z,{children:[(0,U.jsxs)(Oe,{className:`flex items-center gap-2`,children:[(0,U.jsx)(ne,{className:`h-5 w-5`}),` `,L(`grid.import.title`,{object:ae})]}),(0,U.jsxs)(F,{children:[d===`upload`&&L(`grid.import.uploadDescription`),d===`mapping`&&L(`grid.import.mappingDescription`),d===`preview`&&L(`grid.import.previewDescription`)]})]}),(0,U.jsx)(`div`,{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground`,children:[`upload`,`mapping`,`preview`].map((e,t)=>(0,U.jsxs)(H.Fragment,{children:[t>0&&(0,U.jsx)(T,{className:`h-3 w-3`}),(0,U.jsxs)(`span`,{className:N(`rounded-full px-3 py-1`,d===e?`bg-primary text-primary-foreground`:`bg-muted`),children:[t+1,`. `,L(e===`upload`?`grid.import.stepUpload`:e===`mapping`?`grid.import.stepMapping`:`grid.import.stepPreview`)]})]},e))}),(0,U.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:w?(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:[(0,U.jsx)(h,{className:`h-10 w-10 text-green-500`}),(0,U.jsx)(`p`,{className:`text-lg font-semibold`,children:L(`grid.import.importComplete`)}),(0,U.jsxs)(`div`,{className:`flex gap-3`,children:[(0,U.jsx)(je,{variant:`default`,children:L(`grid.import.imported`,{count:w.importedRows})}),w.skippedRows>0&&(0,U.jsx)(je,{variant:`destructive`,children:L(`grid.import.skippedCount`,{count:w.skippedRows})})]}),w.errors.length>0&&(0,U.jsxs)(`div`,{className:`max-h-32 w-full overflow-auto rounded border p-2 text-xs`,children:[w.errors.slice(0,10).map((e,t)=>(0,U.jsxs)(`p`,{className:`text-destructive`,children:[`Row `,e.row,e.field?` (${e.field})`:``,`: `,e.message]},t)),w.errors.length>10&&(0,U.jsx)(`p`,{className:`text-muted-foreground`,children:L(`grid.import.moreErrors`,{count:w.errors.length-10})})]})]}):(0,U.jsxs)(U.Fragment,{children:[d===`upload`&&(0,U.jsx)(en,{onFileLoaded:me}),d===`mapping`&&(0,U.jsx)(nn,{headers:p,fields:n,mapping:v,onMappingChange:b,templates:j,selectedTemplateId:ce,onSelectTemplate:le,onSaveTemplate:ue,onDeleteTemplate:P}),d===`preview`&&(0,U.jsx)(rn,{headers:p,rows:g,mapping:v,fields:n,corrections:ie,onCorrect:de}),x&&(0,U.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,U.jsx)(O,{value:te,className:`h-2`}),(0,U.jsx)(`p`,{className:`text-center text-xs text-muted-foreground`,children:L(`grid.import.importing`,{progress:te})})]})]})}),(0,U.jsx)(oe,{className:`gap-2 sm:gap-0`,children:w?(0,U.jsx)(V,{onClick:ge,children:L(`grid.import.close`)}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(V,{variant:`ghost`,onClick:ge,disabled:x,children:[(0,U.jsx)(y,{className:`mr-1 h-4 w-4`}),` `,L(`grid.import.cancel`)]}),(d===`mapping`||d===`preview`)&&(0,U.jsxs)(V,{variant:`outline`,onClick:()=>f(d===`mapping`?`upload`:`mapping`),disabled:x,children:[(0,U.jsx)(ee,{className:`mr-1 h-4 w-4`}),` `,L(`grid.import.back`)]}),d===`mapping`&&(0,U.jsxs)(V,{onClick:()=>f(`preview`),disabled:Object.keys(v).length===0||pe.length>0,children:[L(`grid.import.next`),` `,(0,U.jsx)(T,{className:`ml-1 h-4 w-4`})]}),d===`preview`&&(0,U.jsx)(V,{onClick:he,disabled:x,children:x?L(`grid.import.importingProgress`):L(`grid.import.importNRows`,{count:g.length})})]})})]})})},on=({schema:e,...t})=>{let{dataSource:n}=Fe()||{};return(0,U.jsx)(Vt,{schema:e,dataSource:n,...t})};A.register(`object-grid`,on,{namespace:`plugin-grid`,label:`Object Grid`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`columns`,type:`array`,label:`Columns`},{name:`filters`,type:`array`,label:`Filters`}]}),A.register(`grid`,on,{namespace:`view`,label:`Data Grid`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`columns`,type:`array`,label:`Columns`},{name:`filters`,type:`array`,label:`Filters`}]}),A.register(`import-wizard`,({schema:e,...t})=>{let{dataSource:n}=Fe()||{};return(0,U.jsx)(an,{objectName:e.objectName,objectLabel:e.objectLabel,fields:e.fields??[],dataSource:n,...t})},{namespace:`plugin-grid`,label:`Import Wizard`,category:`plugin`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`fields`,type:`array`,label:`Fields`,required:!0}]});export{Q as n,Vt as t};
|
|
Binary file
|