@objectstack/console 7.7.0 → 7.8.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.
Files changed (21) hide show
  1. package/dist/assets/{ApiConsolePage-C8YrK4Z2.js → ApiConsolePage-CWTG8Xo7.js} +1 -1
  2. package/dist/assets/{AppManagementPage-B_5Fa-DJ.js → AppManagementPage-GNlxvYjB.js} +1 -1
  3. package/dist/assets/{ComponentNavView-BzBKVw0V.js → ComponentNavView-BSO_oEuH.js} +1 -1
  4. package/dist/assets/{ConsoleFloatingChatbot-iFC0LZXD.js → ConsoleFloatingChatbot-CqIHTEt8.js} +1 -1
  5. package/dist/assets/{FlowRunsPage-vNJ-LHl4.js → FlowRunsPage--fqUTSur.js} +1 -1
  6. package/dist/assets/{PublicFormsPage-BV_uZLQO.js → PublicFormsPage-BYCoo2T3.js} +1 -1
  7. package/dist/assets/{SystemHubPage-DnzWHWwD.js → SystemHubPage-CrPlzy52.js} +1 -1
  8. package/dist/assets/data-adapter-ByiC1zK-.js +1 -0
  9. package/dist/assets/{index-DFCyFV4X.js → index-DKok_mql.js} +6 -6
  10. package/dist/assets/{plugin-calendar-BFas9fSm.js → plugin-calendar-C-9OPJzZ.js} +1 -1
  11. package/dist/assets/{plugin-gantt-B6c7-NaD.js → plugin-gantt-QTyZ46KN.js} +1 -1
  12. package/dist/assets/plugin-grid-CIlCwKyp.js +6 -0
  13. package/dist/assets/{plugin-kanban-CYoyum5o.js → plugin-kanban-B-o9RSK7.js} +1 -1
  14. package/dist/assets/{plugin-report-I3m5_ooy.js → plugin-report-AhX1YoV8.js} +1 -1
  15. package/dist/assets/{plugin-timeline-CQbcDFeM.js → plugin-timeline-Dju0mfv_.js} +1 -1
  16. package/dist/assets/{plugin-view-CpsHblZK.js → plugin-view-DF7-Dd3a.js} +1 -1
  17. package/dist/assets/{plugins-views-BUSRnnI0.js → plugins-views-rCdZtRbk.js} +1 -1
  18. package/dist/index.html +1 -1
  19. package/package.json +1 -1
  20. package/dist/assets/data-adapter-DnBY1kLN.js +0 -1
  21. package/dist/assets/plugin-grid-Dnbdtwqg.js +0 -6
@@ -1 +1 @@
1
- import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{r as n,y as r}from"./vendor-react-BMpe6Iqg.js";import{N as i,U as a,dt as o,ot as s,r as c,st as l}from"./framework-Bg_8y02a.js";import{$t as u,Bn as d,Bt as f,Fn as p,Ht as m,In as h,Ln as g,Qt as _,Rn as v,Rt as y,Vt as b,Ys as x,Zn as S,Zt as C,bs as w,cs as T,en as E,in as D,jt as O,ls as k,mr as A,zi as j,zn as ee,zt as te}from"./ui-components-C7AytqY9.js";import{i as M,r as N}from"./plugins-views-BUSRnnI0.js";import{a as ne}from"./plugin-grid-Dnbdtwqg.js";var P=e(r(),1),F=n(),I=`bg-blue-100 text-blue-900 border border-blue-200`,re=new Date,L=[`bg-blue-100 text-blue-900 border border-blue-200`,`bg-emerald-100 text-emerald-900 border border-emerald-200`,`bg-amber-100 text-amber-900 border border-amber-200`,`bg-rose-100 text-rose-900 border border-rose-200`,`bg-violet-100 text-violet-900 border border-violet-200`,`bg-cyan-100 text-cyan-900 border border-cyan-200`,`bg-orange-100 text-orange-900 border border-orange-200`,`bg-fuchsia-100 text-fuchsia-900 border border-fuchsia-200`],R=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i,z=/(^|\s)(bg|text|from|to|via)-/;function B(e){if(!e)return{className:I};if(R.test(e))return{className:`text-white`,inlineColor:e};if(z.test(e))return{className:e};let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return{className:L[Math.abs(t)%L.length]}}var ie={"calendar.today":`Today`,"calendar.month":`Month`,"calendar.week":`Week`,"calendar.day":`Day`,"calendar.newEvent":`New event`,"calendar.moreEvents":`+{{count}} more`,"calendar.allDay":`all-day`};function V(){try{let e=c();return e.t(`calendar.today`)===`calendar.today`?{t:(e,t)=>{let n=ie[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n},language:`en`}:{t:e.t,language:e.language}}catch{return{t:(e,t)=>{let n=ie[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n},language:`en`}}}function H({events:e=[],view:t=`month`,currentDate:n=re,locale:r=`default`,onEventClick:i,onDateClick:a,onViewChange:o,onNavigate:s,onAddClick:c,onEventDrop:l,onTimeRangeSelect:d,slotMinutes:p=30,className:h}){let[g,v]=P.useState(t),[E,D]=P.useState(n),{t:O,language:ee}=V(),M=r==="default"?ee:r;P.useEffect(()=>{D(n)},[n]),P.useEffect(()=>{v(t)},[t]);let N=P.useRef(o);N.current=o,P.useEffect(()=>{let e=window.matchMedia(`(max-width: 639px)`),t=e=>{e.matches&&(v(`day`),N.current?.(`day`))};return t(e),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let ne=()=>{let e=new Date(E);g===`month`?e.setMonth(e.getMonth()-1):g===`week`?e.setDate(e.getDate()-7):e.setDate(e.getDate()-1),D(e),s?.(e)},I=()=>{let e=new Date(E);g===`month`?e.setMonth(e.getMonth()+1):g===`week`?e.setDate(e.getDate()+7):e.setDate(e.getDate()+1),D(e),s?.(e)},L=()=>{let e=new Date;D(e),s?.(e)},R=e=>{v(e),o?.(e)},z=()=>{if(g===`month`)return E.toLocaleDateString(M,{month:`long`,year:`numeric`});if(g===`week`){let e=ae(E),t=new Date(e);return t.setDate(t.getDate()+6),`${e.toLocaleDateString(M,{month:`short`,day:`numeric`})} - ${t.toLocaleDateString(M,{month:`short`,day:`numeric`,year:`numeric`})}`}else return E.toLocaleDateString(M,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})},B=P.useRef(0);return(0,F.jsxs)(`div`,{role:`region`,"aria-label":`Calendar`,className:x(`flex flex-col h-full bg-background min-w-0 overflow-hidden`,h),children:[(0,F.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 p-2 sm:p-4 border-b min-w-0`,children:[(0,F.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,F.jsxs)(`div`,{className:`flex items-center bg-muted/50 rounded-lg p-1 gap-1`,children:[(0,F.jsx)(A,{variant:`ghost`,size:`sm`,onClick:L,className:`h-8`,"aria-label":`Go to today`,children:O(`calendar.today`)}),(0,F.jsx)(`div`,{className:`h-4 w-px bg-border mx-1`}),(0,F.jsx)(A,{variant:`ghost`,size:`icon`,"aria-label":`Previous period`,onClick:ne,className:`h-8 w-8`,children:(0,F.jsx)(k,{className:`h-4 w-4`})}),(0,F.jsx)(A,{variant:`ghost`,size:`icon`,"aria-label":`Next period`,onClick:I,className:`h-8 w-8`,children:(0,F.jsx)(T,{className:`h-4 w-4`})})]}),(0,F.jsxs)(C,{children:[(0,F.jsx)(u,{asChild:!0,children:(0,F.jsxs)(A,{variant:`ghost`,"aria-label":`Current date: ${z()}`,className:x(`text-base sm:text-xl font-semibold h-auto px-2 sm:px-3 py-1 hover:bg-muted/50 transition-colors`,`flex items-center gap-2`),children:[(0,F.jsx)(w,{className:`h-5 w-5 text-muted-foreground`}),(0,F.jsx)(`span`,{children:z()})]})}),(0,F.jsx)(_,{className:`w-auto p-0`,align:`start`,children:(0,F.jsx)(S,{mode:`single`,selected:E,onSelect:e=>{e&&(D(e),s?.(e))},autoFocus:!0,startMonth:new Date(2e3,0),endMonth:new Date(2050,11)})})]})]}),(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsxs)(y,{value:g,onValueChange:R,children:[(0,F.jsx)(b,{className:`w-32 bg-background`,children:(0,F.jsx)(m,{})}),(0,F.jsxs)(te,{children:[(0,F.jsx)(f,{value:`day`,children:O(`calendar.day`)}),(0,F.jsx)(f,{value:`week`,children:O(`calendar.week`)}),(0,F.jsx)(f,{value:`month`,children:O(`calendar.month`)})]})]}),c&&(0,F.jsxs)(A,{onClick:c,size:`sm`,className:`gap-1`,children:[(0,F.jsx)(j,{className:`h-4 w-4`}),O(`calendar.newEvent`)]})]})]}),(0,F.jsxs)(`div`,{className:`flex-1 overflow-auto`,onTouchStart:e=>{B.current=e.touches[0].clientX},onTouchEnd:e=>{let t=B.current-e.changedTouches[0].clientX;if(Math.abs(t)>50){let e=new Date(E);g===`day`?e.setDate(e.getDate()+(t>0?1:-1)):g===`week`?e.setDate(e.getDate()+(t>0?7:-7)):e.setMonth(e.getMonth()+(t>0?1:-1)),D(e),s?.(e)}},children:[g===`month`&&(0,F.jsx)(W,{date:E,events:e,locale:M,onEventClick:i,onDateClick:a,onEventDrop:l}),g===`week`&&(0,F.jsx)(Y,{mode:`week`,date:E,events:e,locale:M,slotMinutes:p,onEventClick:i,onEventDrop:l,onTimeRangeSelect:d}),g===`day`&&(0,F.jsx)(Y,{mode:`day`,date:E,events:e,locale:M,slotMinutes:p,onEventClick:i,onEventDrop:l,onTimeRangeSelect:d})]})]})}function ae(e){let t=new Date(e),n=t.getDay(),r=t.getDate()-n;return t.setDate(r),t}function oe(e){let t=e.getFullYear(),n=e.getMonth(),r=new Date(t,n,1),i=new Date(t,n+1,0),a=r.getDay(),o=[];for(let e=a-1;e>=0;e--){let t=new Date(r.getTime());t.setDate(t.getDate()-(e+1)),o.push(t)}for(let e=1;e<=i.getDate();e++)o.push(new Date(t,n,e));let s=42-o.length;for(let e=1;e<=s;e++){let t=new Date(i.getTime());t.setDate(t.getDate()+e),o.push(t)}return o}function U(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function W({date:e,events:t,locale:n=`default`,onEventClick:r,onDateClick:i,onEventDrop:a}){let o=P.useMemo(()=>oe(e),[e.getFullYear(),e.getMonth()]),s=P.useMemo(()=>new Date,[]),{t:c}=V(),l=P.useMemo(()=>{let e=new Date(2024,0,7);return Array.from({length:7},(t,r)=>{let i=new Date(e);return i.setDate(i.getDate()+r),i.toLocaleDateString(n,{weekday:`short`})})},[n]),[u,d]=P.useState(null),[f,p]=P.useState(null),m=P.useMemo(()=>{let e=new Map;for(let n of t){let t=new Date(n.start),r=n.end?new Date(n.end):new Date(t);t.setHours(0,0,0,0),r.setHours(0,0,0,0);let i=new Date(t);for(;i<=r;){let a=`${i.getFullYear()}-${i.getMonth()}-${i.getDate()}`,o=i.getTime()===t.getTime(),s=i.getTime()===r.getTime(),c=o||s||i.getDay()===0,l=e.get(a),u={event:n,isTitleDay:c,isSpanStart:o,isSpanEnd:s};l?l.push(u):e.set(a,[u]),i.setDate(i.getDate()+1)}}return e},[t]),h=(e,t,n=`move`,r)=>{d(t.id),e.dataTransfer.effectAllowed=`move`;let i={id:t.id,mode:n,...r?{sourceDay:`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}`}:{}};e.dataTransfer.setData(`text/plain`,JSON.stringify(i)),n===`resize-end`&&e.stopPropagation()},g=()=>{d(null),p(null)},_=(e,t)=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,p(t)},v=e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},y=(e,n)=>{if(e.preventDefault(),p(null),d(null),!a)return;let r=e.dataTransfer.getData(`text/plain`),i;try{i=JSON.parse(r)}catch{i={id:r,mode:`move`}}let o=t.find(e=>String(e.id)===String(i.id));if(!o)return;let s=new Date(n);if(s.setHours(0,0,0,0),i.mode===`resize-end`){let e=o.end?new Date(o.end):new Date(o.start),t=new Date(e);if(t.setHours(0,0,0,0),s.getTime()===t.getTime())return;let n=new Date(o.start);if(n.setHours(0,0,0,0),s.getTime()<n.getTime())return;let r=new Date(s);r.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),0),a(o,new Date(o.start),r);return}let c=new Date(o.start),l;if(i.sourceDay){let[e,t,n]=i.sourceDay.split(`-`).map(e=>parseInt(e,10));l=new Date(e,t,n)}else l=new Date(c);l.setHours(0,0,0,0);let u=s.getTime()-l.getTime();if(u===0)return;let f=new Date(c.getTime()+u),m;o.end&&(m=new Date(new Date(o.end).getTime()+u)),a(o,f,m)};return(0,F.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,F.jsx)(`div`,{role:`row`,className:`grid grid-cols-7 border-b`,children:l.map(e=>(0,F.jsx)(`div`,{role:`columnheader`,className:`p-2 text-center text-sm font-medium text-muted-foreground border-r last:border-r-0`,children:e},e))}),(0,F.jsx)(`div`,{role:`grid`,"aria-label":`Calendar grid`,className:`grid grid-cols-7 flex-1 auto-rows-fr`,children:o.map((t,n)=>{let o=`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`,l=m.get(o)||[],d=t.getMonth()===e.getMonth(),p=U(t,s);return(0,F.jsxs)(`div`,{role:`gridcell`,"aria-label":`${t.toLocaleDateString(`default`,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})}${l.length>0?`, ${l.length} event${l.length>1?`s`:``}`:``}`,className:x(`border-b border-r last:border-r-0 p-2 min-h-[100px] cursor-pointer hover:bg-accent/50`,!d&&`bg-muted/50 text-muted-foreground opacity-50`,f===n&&`ring-2 ring-primary`),onClick:()=>i?.(t),onDragOver:e=>_(e,n),onDragLeave:v,onDrop:e=>y(e,t),children:[(0,F.jsx)(`div`,{className:x(`text-sm font-medium mb-2`,p&&`inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-6 w-6`),...p?{"aria-current":`date`}:{},children:t.getDate()}),(0,F.jsxs)(`div`,{className:`space-y-0.5`,children:[l.slice(0,4).map(({event:e,isTitleDay:n,isSpanStart:i,isSpanEnd:o},s)=>{let c=!n,{className:l,inlineColor:d}=B(e.color),f=!!a&&o;return(0,F.jsxs)(`div`,{role:`button`,title:e.title,"aria-label":e.title,draggable:!!a,onDragStart:n=>h(n,e,`move`,t),onDragEnd:g,className:x(`relative text-xs hover:opacity-80 truncate`,a?`cursor-move`:`cursor-pointer`,c?`h-1.5`:`px-2 py-0.5`,i?`rounded-l`:`rounded-l-none`,o?`rounded-r`:`rounded-r-none`,!o&&`-mr-2`,l,u===e.id&&`opacity-50`),style:d?{backgroundColor:d}:void 0,onClick:t=>{t.stopPropagation(),r?.(e)},children:[c?``:e.title,f&&(0,F.jsx)(`span`,{role:`separator`,"aria-label":`Resize event end`,title:`Drag to change end date`,draggable:!0,onDragStart:n=>h(n,e,`resize-end`,t),onDragEnd:g,onClick:e=>e.stopPropagation(),className:`absolute inset-y-0 right-0 w-2 cursor-ew-resize bg-black/25 hover:bg-black/50 rounded-r`})]},`${e.id}-${s}`)}),l.length>4&&(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground px-2`,children:c(`calendar.moreEvents`,{count:l.length-4})})]})]},n)})})]})}var G=48;function K(e){let t=new Date(e);return t.setHours(0,0,0,0),t}function q(e){return e.getHours()*60+e.getMinutes()}function J(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Y({mode:e,date:t,events:n,locale:r=`default`,slotMinutes:i=30,onEventClick:a,onEventDrop:o,onTimeRangeSelect:s}){let{t:c}=V(),l=G*i/60,u=G*24,d=P.useMemo(()=>{if(e===`day`)return[K(t)];let n=ae(t);return Array.from({length:7},(e,t)=>{let r=new Date(n);return r.setDate(n.getDate()+t),K(r)})},[e,t.getFullYear(),t.getMonth(),t.getDate()]),f=P.useMemo(()=>new Date,[]),p=P.useCallback(e=>{if(e.allDay)return!0;let t=new Date(e.start),n=e.end?new Date(e.end):new Date(t),r=t.getHours()===0&&t.getMinutes()===0&&t.getSeconds()===0,i=n.getHours()===0&&n.getMinutes()===0&&n.getSeconds()===0,a=n.getTime()-t.getTime();return!!(r&&i||a>=1440*60*1e3)},[]),{allDayEvents:m,timedEvents:h}=P.useMemo(()=>{let e=[],t=[];for(let r of n)p(r)?e.push(r):t.push(r);return{allDayEvents:e,timedEvents:t}},[n,p]),g=P.useMemo(()=>{let e=new Map;for(let t of d)e.set(J(t),[]);for(let t of m){let n=K(new Date(t.start)),r=t.end?new Date(t.end):new Date(t.start),i=K(r);r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getTime()>n.getTime()&&(i=new Date(i),i.setDate(i.getDate()-1));for(let r of d){let a=K(r);a<n||a>i||e.get(J(r)).push({event:t,isStart:a.getTime()===n.getTime(),isEnd:a.getTime()===i.getTime()})}}return e},[d,m]),_=P.useMemo(()=>{let e=new Map;for(let t of d)e.set(J(t),[]);for(let t of h){let n=new Date(t.start),r=t.end?new Date(t.end):new Date(n.getTime()+3600*1e3);for(let i of d){let a=K(i),o=new Date(a);if(o.setDate(o.getDate()+1),r<=a||n>=o)continue;let s=n<a?a:n,c=r>o?o:r,l=q(s),u=c.getTime()===o.getTime()?1440:q(c);e.get(J(i)).push({event:t,startMin:l,endMin:Math.max(u,l+15),isStart:s.getTime()===n.getTime(),isEnd:c.getTime()===r.getTime()})}}return e},[d,h]),v=P.useMemo(()=>{let e=new Map;for(let[t,n]of _){let r=[...n].sort((e,t)=>e.startMin-t.startMin||e.endMin-t.endMin),i=[],a=[],o=[];for(let e of r){let t=0;for(;i[t]&&i[t].endMin>e.startMin;)t++;i[t]={endMin:e.endMin},a.push({entry:e,col:t})}for(let e=0;e<a.length;e++){let t=a[e],n=t.col;for(let r=0;r<a.length;r++){if(r===e)continue;let i=a[r];i.entry.startMin<t.entry.endMin&&i.entry.endMin>t.entry.startMin&&i.col>n&&(n=i.col)}o.push({...t.entry,col:t.col,cols:n+1})}e.set(t,o)}return e},[_]),y=P.useRef(null),b=P.useRef([]),[S,C]=P.useState(null),w=P.useRef(null);w.current=S;let T=P.useRef(!1),E=P.useCallback((e,t)=>{let n=b.current[t];if(!n)return 0;let r=(e-n.getBoundingClientRect().top+n.scrollTop)/G*60,a=Math.round(r/i)*i;return Math.max(0,Math.min(1440,a))},[i]),D=P.useCallback(e=>{for(let t=0;t<b.current.length;t++){let n=b.current[t];if(!n)continue;let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right)return t}return-1},[]);P.useEffect(()=>{if(!S)return;let e=e=>{let t=S.kind===`select`||S.kind===`move`?D(e.clientX):S.dayIndex,n=t<0?S.dayIndex??0:t,r=E(e.clientY,n);C(e=>e&&(e.kind===`select`?{...e,dayIndex:n>=0?n:e.dayIndex,headMinutes:r}:e.kind===`move`?{...e,dayIndex:n,minutes:r}:{...e,minutes:r}))},t=e=>{let t=w.current;if(!t){C(null);return}try{if(t.kind===`select`&&s){let e=Math.min(t.anchorMinutes,t.headMinutes),n=Math.max(t.anchorMinutes,t.headMinutes),r=e,a=n===e?Math.min(1440,e+i):n,o=d[t.dayIndex]??d[0],c=new Date(o);c.setHours(0,Math.round(r),0,0);let l=new Date(o);l.setHours(0,Math.round(a),0,0),T.current=!0,s(c,l)}else if(t.kind===`move`&&o){let e=n.find(e=>String(e.id)===String(t.eventId));if(e){let n=t.dayIndex<0?0:t.dayIndex,r=t.minutes-t.grabMinuteOffset,a=Math.max(0,Math.min(1440-t.durationMin,Math.round(r/i)*i)),s=d[n]??d[0],c=new Date(s);c.setHours(0,a,0,0);let l=new Date(c.getTime()+t.durationMin*60*1e3);T.current=!0,o(e,c,l)}}else if(t.kind===`resize-top`&&o){let e=n.find(e=>String(e.id)===String(t.eventId));if(e){let n=d[t.dayIndex]??d[0],r=Math.min(t.anchorEndMin-i,Math.max(0,t.minutes)),a=new Date(n);a.setHours(0,r,0,0);let s=new Date(n);s.setHours(0,t.anchorEndMin,0,0),T.current=!0,o(e,a,s)}}else if(t.kind===`resize-bottom`&&o){let e=n.find(e=>String(e.id)===String(t.eventId));if(e){let n=d[t.dayIndex]??d[0],r=Math.max(t.anchorStartMin+i,Math.min(1440,t.minutes)),a=new Date(n);a.setHours(0,t.anchorStartMin,0,0);let s=new Date(n);s.setHours(0,r,0,0),T.current=!0,o(e,a,s)}}}finally{C(null),setTimeout(()=>{T.current=!1},50)}};return window.addEventListener(`pointermove`,e),window.addEventListener(`pointerup`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t)}},[S,d,n,i,o,s,D,E]);let O=P.useMemo(()=>d.map(e=>({weekday:e.toLocaleDateString(r,{weekday:`short`}),day:e.getDate(),month:e.toLocaleDateString(r,{month:`short`}),isToday:U(e,f)})),[d,r,f]),k=P.useMemo(()=>Array.from({length:24},(e,t)=>new Date(2024,0,1,t,0).toLocaleTimeString(r,{hour:`numeric`})),[r]),A=(e,t,n,r)=>{if(!o||e.button!==0)return;e.stopPropagation(),e.preventDefault();let i=E(e.clientY,n);C(r===`body`?{kind:`move`,eventId:t.event.id,grabMinuteOffset:Math.max(0,i-t.startMin),durationMin:t.endMin-t.startMin,dayIndex:n,minutes:i}:r===`top`?{kind:`resize-top`,eventId:t.event.id,anchorEndMin:t.endMin,dayIndex:n,minutes:i}:{kind:`resize-bottom`,eventId:t.event.id,anchorStartMin:t.startMin,dayIndex:n,minutes:i})},j=(e,t)=>{if(!s||e.button!==0)return;e.preventDefault();let n=E(e.clientY,t);C({kind:`select`,dayIndex:t,anchorMinutes:n,headMinutes:n})},ee=e=>{if(!S)return null;if(S.kind===`select`&&S.dayIndex===e){let t=Math.min(S.anchorMinutes,S.headMinutes),n=Math.max(S.anchorMinutes,S.headMinutes);return(0,F.jsx)(`div`,{className:`absolute left-1 right-1 rounded bg-primary/30 border border-primary pointer-events-none z-10`,style:{top:t/60*G,height:Math.max(l,(n-t)/60*G)},"aria-hidden":!0,children:(0,F.jsx)(`div`,{className:`px-2 py-0.5 text-xs font-medium text-primary`,children:X(d[e],t,n,r)})})}if(S.kind===`move`&&S.dayIndex===e){let t=S.minutes-S.grabMinuteOffset,n=Math.max(0,Math.min(1440-S.durationMin,Math.round(t/i)*i));return(0,F.jsx)(`div`,{className:`absolute left-1 right-1 rounded border-2 border-dashed border-primary bg-primary/10 pointer-events-none z-10`,style:{top:n/60*G,height:S.durationMin/60*G},"aria-hidden":!0,children:(0,F.jsx)(`div`,{className:`px-2 py-0.5 text-xs font-medium text-primary`,children:X(d[e],n,n+S.durationMin,r)})})}if((S.kind===`resize-top`||S.kind===`resize-bottom`)&&S.dayIndex===e){let t,n;return S.kind===`resize-top`?(t=Math.min(S.anchorEndMin-i,Math.max(0,S.minutes)),n=S.anchorEndMin):(t=S.anchorStartMin,n=Math.max(S.anchorStartMin+i,Math.min(1440,S.minutes))),(0,F.jsx)(`div`,{className:`absolute left-1 right-1 rounded border-2 border-dashed border-primary bg-primary/10 pointer-events-none z-10`,style:{top:t/60*G,height:(n-t)/60*G},"aria-hidden":!0,children:(0,F.jsx)(`div`,{className:`px-2 py-0.5 text-xs font-medium text-primary`,children:X(d[e],t,n,r)})})}return null};return(0,F.jsxs)(`div`,{className:`flex flex-col h-full`,ref:y,children:[(0,F.jsxs)(`div`,{className:`flex border-b sticky top-0 bg-background z-20`,children:[(0,F.jsx)(`div`,{className:`w-14 shrink-0 border-r`,"aria-hidden":!0}),O.map((e,t)=>(0,F.jsxs)(`div`,{role:`columnheader`,className:x(`flex-1 p-2 text-center text-sm border-r last:border-r-0`,e.isToday&&`bg-primary/5`),children:[(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.weekday}),(0,F.jsx)(`div`,{className:x(`font-medium`,e.isToday&&`inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-6 w-6 mx-auto`),children:e.day})]},t))]}),m.length>0&&(0,F.jsxs)(`div`,{className:`flex border-b bg-muted/20 max-h-[140px] overflow-y-auto`,children:[(0,F.jsx)(`div`,{className:`w-14 shrink-0 border-r flex items-start justify-end pr-1 pt-1 text-[10px] text-muted-foreground sticky left-0 bg-muted/20`,children:c(`calendar.allDay`)===`calendar.allDay`?`all-day`:c(`calendar.allDay`)}),d.map(e=>{let t=J(e);return(0,F.jsx)(`div`,{className:`flex-1 border-r last:border-r-0 min-h-[28px] p-0.5 space-y-0.5`,children:(g.get(t)??[]).map(({event:e,isStart:t,isEnd:n},r)=>{let{className:i,inlineColor:o}=B(e.color);return(0,F.jsx)(`div`,{role:`button`,title:e.title,onClick:t=>{t.stopPropagation(),a?.(e)},className:x(`text-[11px] px-2 py-0.5 truncate cursor-pointer hover:opacity-80`,t?`rounded-l`:`rounded-l-none -ml-0.5`,n?`rounded-r`:`rounded-r-none -mr-0.5`,i),style:o?{backgroundColor:o}:void 0,children:t?e.title:`\xA0`},`${e.id}-${r}`)})},t)})]}),(0,F.jsx)(`div`,{className:`flex-1 overflow-auto`,children:(0,F.jsxs)(`div`,{className:`flex`,style:{height:u},children:[(0,F.jsx)(`div`,{className:`w-14 shrink-0 border-r relative`,children:k.map((e,t)=>(0,F.jsx)(`div`,{className:`absolute right-1 text-[10px] text-muted-foreground -translate-y-1/2`,style:{top:t*G},children:t===0?``:e},t))}),d.map((e,t)=>{let n=J(e),s=v.get(n)??[];return(0,F.jsxs)(`div`,{ref:e=>{b.current[t]=e},className:`flex-1 border-r last:border-r-0 relative select-none`,style:{height:u},onPointerDown:e=>j(e,t),"aria-label":e.toLocaleDateString(r,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`}),children:[Array.from({length:24},(e,t)=>(0,F.jsx)(`div`,{className:`absolute left-0 right-0 border-t border-muted/60 pointer-events-none`,style:{top:t*G}},t)),i<60&&Array.from({length:Math.floor(1440/i)},(e,t)=>{let n=t*i;return n%60==0?null:(0,F.jsx)(`div`,{className:`absolute left-0 right-0 border-t border-dashed border-muted/30 pointer-events-none`,style:{top:n/60*G}},t)}),s.map(n=>{let i=n.startMin/60*G,s=Math.max(l,(n.endMin-n.startMin)/60*G),c=100/n.cols,u=n.col*c,{className:d,inlineColor:f}=B(n.event.color),p=S&&S.eventId===n.event.id;return(0,F.jsxs)(`div`,{role:`button`,tabIndex:0,title:n.event.title,"aria-label":n.event.title,onPointerDown:e=>A(e,n,t,`body`),onClick:e=>{if(T.current){e.stopPropagation();return}e.stopPropagation(),a?.(n.event)},className:x(`absolute rounded text-xs px-2 py-1 overflow-hidden shadow-sm`,o?`cursor-move`:`cursor-pointer`,d,p&&`opacity-40`),style:{top:i,height:s,left:`calc(${u}% + 2px)`,width:`calc(${c}% - 4px)`,...f?{backgroundColor:f}:{}},children:[(0,F.jsx)(`div`,{className:`font-medium truncate`,children:n.event.title}),(0,F.jsx)(`div`,{className:`text-[10px] opacity-80 truncate`,children:X(e,n.startMin,n.endMin,r)}),o&&n.isStart&&(0,F.jsx)(`div`,{onPointerDown:e=>A(e,n,t,`top`),className:`absolute top-0 left-0 right-0 h-1.5 cursor-ns-resize`,"aria-label":`Resize start`}),o&&n.isEnd&&(0,F.jsx)(`div`,{onPointerDown:e=>A(e,n,t,`bottom`),className:`absolute bottom-0 left-0 right-0 h-1.5 cursor-ns-resize`,"aria-label":`Resize end`})]},`${n.event.id}-${n.startMin}`)}),ee(t)]},n)})]})})]})}function X(e,t,n,r){let i=new Date(e);i.setHours(0,Math.round(t),0,0);let a=new Date(e);a.setHours(0,Math.round(n),0,0);let o=e=>e.toLocaleTimeString(r,{hour:`numeric`,minute:`2-digit`});return`${o(i)} – ${o(a)}`}function se(e){return`data`in e&&e.data?e.data:`staticData`in e&&e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function ce(e){if(e){if(typeof e==`string`){let t=e.split(` `),n=t[0],r=t[1]?.toLowerCase()===`desc`?`desc`:`asc`;return{[n]:r}}if(Array.isArray(e))return e.reduce((e,t)=>(t.field&&t.order&&(e[t.field]=t.order),e),{})}}function le(e){return`filter`in e&&e.filter&&typeof e.filter==`object`&&`calendar`in e.filter?e.filter.calendar:e.calendar?e.calendar:e.startDateField||e.dateField?{startDateField:e.startDateField||e.dateField,endDateField:e.endDateField||e.endField,titleField:e.titleField,colorField:e.colorField,allDayField:e.allDayField}:null}var Z=({schema:e,dataSource:t,className:n,data:r,loading:a,onEventClick:o,onRowClick:c,onDateClick:u,onNavigate:f,onViewChange:m,onEventDrop:_,locale:y})=>{let b=Array.isArray(r),[x,S]=(0,P.useState)(b?r:[]),[C,w]=(0,P.useState)(b?a??!1:!0),[T,k]=(0,P.useState)(null),[j,te]=(0,P.useState)(null),[I,re]=(0,P.useState)(new Date),L=O(),R=e.defaultView,[z,B]=(0,P.useState)(()=>{let e=R===`day`||!R;return typeof window<`u`&&window.innerWidth<768&&e?`month`:R||`month`});(0,P.useEffect)(()=>{L&&z===`day`&&(R===`day`||!R)&&B(`month`)},[L]);let[ie,V]=(0,P.useState)(0);(0,P.useEffect)(()=>{if(!b&&!(!t?.onMutation||!e.objectName))return t.onMutation(t=>{t.resource===e.objectName&&V(e=>e+1)})},[t,e.objectName,b]);let{ref:ae,isRefreshing:oe,pullDistance:U}=ne({onRefresh:(0,P.useCallback)(async()=>{V(e=>e+1)},[]),enabled:!!t&&!!e.objectName}),W=(0,P.useMemo)(()=>se(e),[e.data,e.staticData,e.objectName]),G=(0,P.useMemo)(()=>le(e),[e.filter,e.calendar,e.dateField,e.endField,e.titleField,e.colorField]),K=W?.provider===`value`,q=(0,P.useRef)(null);q.current=j,(0,P.useEffect)(()=>{b&&S(r)},[r,b]),(0,P.useEffect)(()=>{b&&a!==void 0&&w(a)},[a,b]),(0,P.useEffect)(()=>{if(b)return;let n=!0;return(async()=>{try{if(!n)return;if(w(!0),K&&W?.provider===`value`){n&&(S(W.items),w(!1));return}if(!t||typeof t.find!=`function`)throw Error(`DataSource required for object/api providers`);if(W?.provider===`object`){let r=W.object,i=s(q.current?.fields),a=l(await t.find(r,{$filter:e.filter,$orderby:ce(e.sort),...i.length>0?{$expand:i}:{}}));n&&S(a)}else W?.provider===`api`&&(console.warn(`API provider not yet implemented for ObjectCalendar`),n&&S([]));n&&w(!1)}catch(e){console.error(`[ObjectCalendar] Error fetching data:`,e),n&&(k(e),w(!1))}})(),()=>{n=!1}},[b,W,t,K,e.filter,e.sort,ie]),(0,P.useEffect)(()=>{!K&&t&&(async()=>{try{if(!t)return;let n=W?.provider===`object`?W.object:e.objectName;if(!n)return;te(await t.getObjectSchema(n))}catch(e){console.error(`Failed to fetch object schema:`,e)}})()},[e.objectName,t,K,W]);let J=(0,P.useMemo)(()=>{if(!G||!x.length)return[];let{startDateField:e,endDateField:t,titleField:n,colorField:r}=G,i=j?.titleFormat,a=typeof i==`string`?i:i&&typeof i==`object`&&typeof i.source==`string`?i.source:void 0,o=j?.NAME_FIELD_KEY,s=[`name`,`full_name`,`fullName`,`title`,`subject`,`label`,`display_name`,`displayName`],c=(e,t)=>{let n=`[-\\u2013\\u2014|/·,:]`,r=!1,i=e.replace(/\{([^{}]+)\}/g,(e,n)=>{let i=t[n.trim()];return i!=null&&i!==``?(r=!0,String(i)):`\0`});return r?i.replace(RegExp(`\\s*${n}\\s*`,`g`),``).replace(RegExp(`\\s*${n}\\s*`,`g`),``).replace(RegExp(`\0`,`g`),``).replace(/\s+/g,` `).trim():``},l=e=>{let t;if(n&&(t=e[n],typeof t==`string`&&(t=t.trim())),!t&&a){let n=c(a,e);n&&(t=n)}if(!t&&o){let n=e[o];typeof n==`string`?t=n.trim():n&&(t=n)}if(!t)for(let n of s){let r=e[n],i=typeof r==`string`?r.trim():r;if(i){t=i;break}}return t||`Untitled`};return x.map((n,i)=>{let a=n[e],o=t?n[t]:null,s=l(n),c=r?n[r]:void 0;return{id:n.id||n._id||`event-${i}`,title:s,start:a?new Date(a):new Date,end:o?new Date(o):void 0,color:c,allDay:!o,data:n}}).filter(e=>!isNaN(e.start.getTime()))},[x,G,j]);(0,P.useCallback)(()=>{u?.(new Date)},[u]);let Y=e.navigation??{mode:`drawer`,width:`min(960px, 60vw)`},X=Y.mode===`drawer`||Y.mode===`modal`||Y.mode===`split`||Y.mode===`popover`,Z=i({navigation:Y,objectName:e.objectName,onRowClick:X?void 0:c}),ue=(0,P.useCallback)(async(n,r,i)=>{if(!G)return;let{startDateField:a,endDateField:o}=G,s=n?.id??n?._id;if(!s||!e.objectName||!t?.update)return;let c={[a]:r.toISOString()};o&&i&&(c[o]=i.toISOString());let l=x;S(e=>e.map(e=>(e?.id??e?._id)===s?{...e,...c}:e));try{await t.update(e.objectName,s,c)}catch(e){S(l),console.error(`[ObjectCalendar] Failed to persist drag-and-drop reschedule:`,e)}},[G,e.objectName,t,x]),[Q,$]=(0,P.useState)(null),de=(0,P.useCallback)(n=>{!G||!e.objectName||!t?.create||$({start:n,title:``,submitting:!1})},[G,e.objectName,t]),fe=(0,P.useCallback)((n,r)=>{!G||!e.objectName||!t?.create||$({start:n,end:r,title:``,submitting:!1})},[G,e.objectName,t]),pe=(0,P.useCallback)(async()=>{if(!Q||!G)return;let n=Q.title.trim();if(!n){$(e=>e&&{...e,error:`Title is required`});return}if(!e.objectName||!t?.create)return;$(e=>e&&{...e,submitting:!0,error:void 0});let{startDateField:r,endDateField:i,titleField:a}=G,o={[a||`name`]:n,[r]:Q.start.toISOString()};i&&(o[i]=(Q.end??Q.start).toISOString());let s=j?.fields;if(s&&typeof s==`object`){let e=Array.isArray(s)?s.map(e=>[e.name??e.apiName,e]):Object.entries(s);for(let[t,n]of e){if(!t||t in o||!n?.required)continue;if(n.defaultValue!==void 0&&n.defaultValue!==null){o[t]=n.defaultValue;continue}let e=n.type;if(e===`select`||e===`picklist`||e===`status`){let e=(n.options||n.choices||[])[0];e!==void 0&&(o[t]=typeof e==`object`?e.value??e.id:e)}else e===`boolean`||e===`checkbox`?o[t]=!1:(e===`number`||e===`integer`||e===`decimal`||e===`currency`||e===`percent`)&&(o[t]=0)}}try{let n=await t.create(e.objectName,o),r=(n&&(n.record||n.data||n))??null;r&&(r.id!==void 0||r._id!==void 0)&&S(e=>[...e,r]),$(null)}catch(e){let t=e?.message||String(e);$(e=>e&&{...e,submitting:!1,error:t}),console.error(`[ObjectCalendar] Quick-create failed:`,e)}},[Q,G,e.objectName,t,j]);return C?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading calendar...`})})}):T?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsxs)(`div`,{className:`text-destructive`,children:[`Error: `,T.message]})})}):G?(0,F.jsxs)(`div`,{ref:ae,className:n,children:[U>0&&(0,F.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:U},children:oe?`Refreshing…`:`Pull to refresh`}),(0,F.jsx)(`div`,{className:`bg-background h-[calc(100vh-120px)] sm:h-[calc(100vh-160px)] md:h-[calc(100vh-200px)] min-h-[400px] sm:min-h-[600px]`,children:(0,F.jsx)(H,{events:J,currentDate:I,view:z,locale:y,onEventClick:e=>{Z.handleClick(e.data),X||o?.(e.data)},onDateClick:e=>{u?u(e):de(e)},onNavigate:e=>{re(e),f?.(e)},onViewChange:e=>{B(e),m?.(e)},onAddClick:void 0,onEventDrop:(e,t,n)=>{_?_(e.data,t,n):ue(e.data,t,n)},onTimeRangeSelect:fe})}),(0,F.jsx)(p,{open:!!Q,onOpenChange:e=>{e||$(null)},children:(0,F.jsxs)(h,{className:`sm:max-w-md`,children:[(0,F.jsxs)(ee,{children:[(0,F.jsx)(d,{children:`New event`}),(0,F.jsx)(g,{children:Q&&(()=>{let e=Q.end&&Q.end.getTime()!==Q.start.getTime(),t=Q.start.toLocaleDateString(y,{year:`numeric`,month:`long`,day:`numeric`});if(e){let e=e=>e.toLocaleTimeString(y,{hour:`numeric`,minute:`2-digit`});return(0,F.jsxs)(F.Fragment,{children:[t,` · `,e(Q.start),` – `,e(Q.end)]})}return(0,F.jsxs)(F.Fragment,{children:[`On `,t]})})()})]}),(0,F.jsxs)(`div`,{className:`space-y-2`,children:[(0,F.jsx)(D,{htmlFor:`quick-create-title`,children:`Title`}),(0,F.jsx)(E,{id:`quick-create-title`,autoFocus:!0,value:Q?.title??``,onChange:e=>$(t=>t&&{...t,title:e.target.value,error:void 0}),onKeyDown:e=>{e.key===`Enter`&&!Q?.submitting&&(e.preventDefault(),pe())},placeholder:`What's this event about?`,disabled:Q?.submitting}),Q?.error&&(0,F.jsx)(`p`,{className:`text-sm text-destructive`,children:Q.error})]}),(0,F.jsxs)(v,{children:[(0,F.jsx)(A,{variant:`outline`,onClick:()=>$(null),disabled:Q?.submitting,children:`Cancel`}),(0,F.jsx)(A,{onClick:()=>void pe(),disabled:Q?.submitting||!Q?.title.trim(),children:Q?.submitting?`Creating…`:`Create`})]})]})}),Z.isOverlay&&Z.isOpen&&Z.selectedRecord&&(()=>{let n=W?.provider===`object`?W.object:e.objectName,r=Z.selectedRecord,i=r.id??r._id;if(!n||i==null)return null;let a=G?.titleField?String(r[G.titleField]??`Event Details`):`Event Details`;return(0,F.jsx)(N,{open:!0,onClose:Z.close,title:a,record:r,objectName:n,recordId:i,dataSource:t,objectSchema:j,width:Z.width??`min(960px, 60vw)`,fullPageHref:M(n,i)??void 0,onFieldSave:async(e,r)=>{t?.update&&(await t.update(n,String(i),{[e]:r}),S(t=>t.map(t=>String(t.id??t._id)===String(i)?{...t,[e]:r}:t)))},onDelete:async()=>{t?.delete&&(await t.delete(n,String(i)),S(e=>e.filter(e=>String(e.id??e._id)!==String(i))))}})})()]}):(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Calendar configuration required. Please specify startDateField and titleField.`})})})};o.register(`calendar-view`,({schema:e,className:t,onAction:n,...r})=>{let i=P.useMemo(()=>!e.data||!Array.isArray(e.data)?[]:e.data.map((t,n)=>{let r=e.titleField||`title`,i=e.startDateField||`start`,a=e.endDateField||`end`,o=e.colorField||`color`,s=e.allDayField||`allDay`;return{id:t.id||t._id||n,title:t[r]||`Untitled Event`,start:new Date(t[i]),end:t[a]?new Date(t[a]):void 0,allDay:t[s],color:t[o],data:t}}),[e.data,e.titleField,e.startDateField,e.endDateField,e.colorField,e.allDayField]);return(0,F.jsx)(H,{className:t,events:i,onEventClick:e=>{n?.({type:`event-click`,payload:e})},...r})},{namespace:`plugin-calendar`,label:`Calendar View`,inputs:[{name:`data`,type:`array`,label:`Data`,description:`Array of record objects to display as events`},{name:`titleField`,type:`string`,label:`Title Field`,defaultValue:`title`,description:`Field name to use for event title`},{name:`startDateField`,type:`string`,label:`Start Date Field`,defaultValue:`start`,description:`Field name for event start date`},{name:`endDateField`,type:`string`,label:`End Date Field`,defaultValue:`end`,description:`Field name for event end date (optional)`},{name:`allDayField`,type:`string`,label:`All Day Field`,defaultValue:`allDay`,description:`Field name for all-day flag`},{name:`colorField`,type:`string`,label:`Color Field`,defaultValue:`color`,description:`Field name for event color`},{name:`colorMapping`,type:`object`,label:`Color Mapping`,description:`Map field values to colors (e.g., {meeting: "blue", deadline: "red"})`},{name:`view`,type:`enum`,enum:[`month`,`week`,`day`],defaultValue:`month`,label:`View Mode`,description:`Calendar view mode (month, week, or day)`},{name:`currentDate`,type:`string`,label:`Current Date`,description:`ISO date string for initial calendar date`},{name:`allowCreate`,type:`boolean`,label:`Allow Create`,defaultValue:!1,description:`Allow creating events by clicking on dates`},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{view:`month`,titleField:`title`,startDateField:`start`,endDateField:`end`,allDayField:`allDay`,colorField:`color`,allowCreate:!1,data:[{id:1,title:`Team Meeting`,start:new Date(new Date().setHours(10,0,0,0)).toISOString(),end:new Date(new Date().setHours(11,0,0,0)).toISOString(),color:`#3b82f6`,allDay:!1},{id:2,title:`Project Deadline`,start:new Date(new Date().setDate(new Date().getDate()+3)).toISOString(),color:`#ef4444`,allDay:!0},{id:3,title:`Conference`,start:new Date(new Date().setDate(new Date().getDate()+7)).toISOString(),end:new Date(new Date().setDate(new Date().getDate()+9)).toISOString(),color:`#10b981`,allDay:!0}],className:`h-[600px] border rounded-lg`}});var ue=t({CalendarView:()=>H,ObjectCalendar:()=>Z,ObjectCalendarRenderer:()=>Q}),Q=({schema:e,...t})=>{let{dataSource:n}=a()||{};return(0,F.jsx)(Z,{schema:e,dataSource:n,...t})};o.register(`object-calendar`,Q,{namespace:`plugin-calendar`,label:`Object Calendar`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`calendar`,type:`object`,label:`Calendar Config`,description:`startDateField, endDateField, titleField, colorField`}]}),o.register(`calendar`,Q,{namespace:`view`,label:`Calendar View`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`calendar`,type:`object`,label:`Calendar Config`,description:`startDateField, endDateField, titleField, colorField`}]});export{ue as t};
1
+ import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{r as n,y as r}from"./vendor-react-BMpe6Iqg.js";import{N as i,U as a,dt as o,ot as s,r as c,st as l}from"./framework-Bg_8y02a.js";import{$t as u,Bn as d,Bt as f,Fn as p,Ht as m,In as h,Ln as g,Qt as _,Rn as v,Rt as y,Vt as b,Ys as x,Zn as S,Zt as C,bs as w,cs as T,en as E,in as D,jt as O,ls as k,mr as A,zi as j,zn as ee,zt as te}from"./ui-components-C7AytqY9.js";import{i as M,r as N}from"./plugins-views-rCdZtRbk.js";import{a as ne}from"./plugin-grid-CIlCwKyp.js";var P=e(r(),1),F=n(),I=`bg-blue-100 text-blue-900 border border-blue-200`,re=new Date,L=[`bg-blue-100 text-blue-900 border border-blue-200`,`bg-emerald-100 text-emerald-900 border border-emerald-200`,`bg-amber-100 text-amber-900 border border-amber-200`,`bg-rose-100 text-rose-900 border border-rose-200`,`bg-violet-100 text-violet-900 border border-violet-200`,`bg-cyan-100 text-cyan-900 border border-cyan-200`,`bg-orange-100 text-orange-900 border border-orange-200`,`bg-fuchsia-100 text-fuchsia-900 border border-fuchsia-200`],R=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i,z=/(^|\s)(bg|text|from|to|via)-/;function B(e){if(!e)return{className:I};if(R.test(e))return{className:`text-white`,inlineColor:e};if(z.test(e))return{className:e};let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return{className:L[Math.abs(t)%L.length]}}var ie={"calendar.today":`Today`,"calendar.month":`Month`,"calendar.week":`Week`,"calendar.day":`Day`,"calendar.newEvent":`New event`,"calendar.moreEvents":`+{{count}} more`,"calendar.allDay":`all-day`};function V(){try{let e=c();return e.t(`calendar.today`)===`calendar.today`?{t:(e,t)=>{let n=ie[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n},language:`en`}:{t:e.t,language:e.language}}catch{return{t:(e,t)=>{let n=ie[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n},language:`en`}}}function H({events:e=[],view:t=`month`,currentDate:n=re,locale:r=`default`,onEventClick:i,onDateClick:a,onViewChange:o,onNavigate:s,onAddClick:c,onEventDrop:l,onTimeRangeSelect:d,slotMinutes:p=30,className:h}){let[g,v]=P.useState(t),[E,D]=P.useState(n),{t:O,language:ee}=V(),M=r==="default"?ee:r;P.useEffect(()=>{D(n)},[n]),P.useEffect(()=>{v(t)},[t]);let N=P.useRef(o);N.current=o,P.useEffect(()=>{let e=window.matchMedia(`(max-width: 639px)`),t=e=>{e.matches&&(v(`day`),N.current?.(`day`))};return t(e),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let ne=()=>{let e=new Date(E);g===`month`?e.setMonth(e.getMonth()-1):g===`week`?e.setDate(e.getDate()-7):e.setDate(e.getDate()-1),D(e),s?.(e)},I=()=>{let e=new Date(E);g===`month`?e.setMonth(e.getMonth()+1):g===`week`?e.setDate(e.getDate()+7):e.setDate(e.getDate()+1),D(e),s?.(e)},L=()=>{let e=new Date;D(e),s?.(e)},R=e=>{v(e),o?.(e)},z=()=>{if(g===`month`)return E.toLocaleDateString(M,{month:`long`,year:`numeric`});if(g===`week`){let e=ae(E),t=new Date(e);return t.setDate(t.getDate()+6),`${e.toLocaleDateString(M,{month:`short`,day:`numeric`})} - ${t.toLocaleDateString(M,{month:`short`,day:`numeric`,year:`numeric`})}`}else return E.toLocaleDateString(M,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})},B=P.useRef(0);return(0,F.jsxs)(`div`,{role:`region`,"aria-label":`Calendar`,className:x(`flex flex-col h-full bg-background min-w-0 overflow-hidden`,h),children:[(0,F.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 p-2 sm:p-4 border-b min-w-0`,children:[(0,F.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,F.jsxs)(`div`,{className:`flex items-center bg-muted/50 rounded-lg p-1 gap-1`,children:[(0,F.jsx)(A,{variant:`ghost`,size:`sm`,onClick:L,className:`h-8`,"aria-label":`Go to today`,children:O(`calendar.today`)}),(0,F.jsx)(`div`,{className:`h-4 w-px bg-border mx-1`}),(0,F.jsx)(A,{variant:`ghost`,size:`icon`,"aria-label":`Previous period`,onClick:ne,className:`h-8 w-8`,children:(0,F.jsx)(k,{className:`h-4 w-4`})}),(0,F.jsx)(A,{variant:`ghost`,size:`icon`,"aria-label":`Next period`,onClick:I,className:`h-8 w-8`,children:(0,F.jsx)(T,{className:`h-4 w-4`})})]}),(0,F.jsxs)(C,{children:[(0,F.jsx)(u,{asChild:!0,children:(0,F.jsxs)(A,{variant:`ghost`,"aria-label":`Current date: ${z()}`,className:x(`text-base sm:text-xl font-semibold h-auto px-2 sm:px-3 py-1 hover:bg-muted/50 transition-colors`,`flex items-center gap-2`),children:[(0,F.jsx)(w,{className:`h-5 w-5 text-muted-foreground`}),(0,F.jsx)(`span`,{children:z()})]})}),(0,F.jsx)(_,{className:`w-auto p-0`,align:`start`,children:(0,F.jsx)(S,{mode:`single`,selected:E,onSelect:e=>{e&&(D(e),s?.(e))},autoFocus:!0,startMonth:new Date(2e3,0),endMonth:new Date(2050,11)})})]})]}),(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsxs)(y,{value:g,onValueChange:R,children:[(0,F.jsx)(b,{className:`w-32 bg-background`,children:(0,F.jsx)(m,{})}),(0,F.jsxs)(te,{children:[(0,F.jsx)(f,{value:`day`,children:O(`calendar.day`)}),(0,F.jsx)(f,{value:`week`,children:O(`calendar.week`)}),(0,F.jsx)(f,{value:`month`,children:O(`calendar.month`)})]})]}),c&&(0,F.jsxs)(A,{onClick:c,size:`sm`,className:`gap-1`,children:[(0,F.jsx)(j,{className:`h-4 w-4`}),O(`calendar.newEvent`)]})]})]}),(0,F.jsxs)(`div`,{className:`flex-1 overflow-auto`,onTouchStart:e=>{B.current=e.touches[0].clientX},onTouchEnd:e=>{let t=B.current-e.changedTouches[0].clientX;if(Math.abs(t)>50){let e=new Date(E);g===`day`?e.setDate(e.getDate()+(t>0?1:-1)):g===`week`?e.setDate(e.getDate()+(t>0?7:-7)):e.setMonth(e.getMonth()+(t>0?1:-1)),D(e),s?.(e)}},children:[g===`month`&&(0,F.jsx)(W,{date:E,events:e,locale:M,onEventClick:i,onDateClick:a,onEventDrop:l}),g===`week`&&(0,F.jsx)(Y,{mode:`week`,date:E,events:e,locale:M,slotMinutes:p,onEventClick:i,onEventDrop:l,onTimeRangeSelect:d}),g===`day`&&(0,F.jsx)(Y,{mode:`day`,date:E,events:e,locale:M,slotMinutes:p,onEventClick:i,onEventDrop:l,onTimeRangeSelect:d})]})]})}function ae(e){let t=new Date(e),n=t.getDay(),r=t.getDate()-n;return t.setDate(r),t}function oe(e){let t=e.getFullYear(),n=e.getMonth(),r=new Date(t,n,1),i=new Date(t,n+1,0),a=r.getDay(),o=[];for(let e=a-1;e>=0;e--){let t=new Date(r.getTime());t.setDate(t.getDate()-(e+1)),o.push(t)}for(let e=1;e<=i.getDate();e++)o.push(new Date(t,n,e));let s=42-o.length;for(let e=1;e<=s;e++){let t=new Date(i.getTime());t.setDate(t.getDate()+e),o.push(t)}return o}function U(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function W({date:e,events:t,locale:n=`default`,onEventClick:r,onDateClick:i,onEventDrop:a}){let o=P.useMemo(()=>oe(e),[e.getFullYear(),e.getMonth()]),s=P.useMemo(()=>new Date,[]),{t:c}=V(),l=P.useMemo(()=>{let e=new Date(2024,0,7);return Array.from({length:7},(t,r)=>{let i=new Date(e);return i.setDate(i.getDate()+r),i.toLocaleDateString(n,{weekday:`short`})})},[n]),[u,d]=P.useState(null),[f,p]=P.useState(null),m=P.useMemo(()=>{let e=new Map;for(let n of t){let t=new Date(n.start),r=n.end?new Date(n.end):new Date(t);t.setHours(0,0,0,0),r.setHours(0,0,0,0);let i=new Date(t);for(;i<=r;){let a=`${i.getFullYear()}-${i.getMonth()}-${i.getDate()}`,o=i.getTime()===t.getTime(),s=i.getTime()===r.getTime(),c=o||s||i.getDay()===0,l=e.get(a),u={event:n,isTitleDay:c,isSpanStart:o,isSpanEnd:s};l?l.push(u):e.set(a,[u]),i.setDate(i.getDate()+1)}}return e},[t]),h=(e,t,n=`move`,r)=>{d(t.id),e.dataTransfer.effectAllowed=`move`;let i={id:t.id,mode:n,...r?{sourceDay:`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}`}:{}};e.dataTransfer.setData(`text/plain`,JSON.stringify(i)),n===`resize-end`&&e.stopPropagation()},g=()=>{d(null),p(null)},_=(e,t)=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,p(t)},v=e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},y=(e,n)=>{if(e.preventDefault(),p(null),d(null),!a)return;let r=e.dataTransfer.getData(`text/plain`),i;try{i=JSON.parse(r)}catch{i={id:r,mode:`move`}}let o=t.find(e=>String(e.id)===String(i.id));if(!o)return;let s=new Date(n);if(s.setHours(0,0,0,0),i.mode===`resize-end`){let e=o.end?new Date(o.end):new Date(o.start),t=new Date(e);if(t.setHours(0,0,0,0),s.getTime()===t.getTime())return;let n=new Date(o.start);if(n.setHours(0,0,0,0),s.getTime()<n.getTime())return;let r=new Date(s);r.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),0),a(o,new Date(o.start),r);return}let c=new Date(o.start),l;if(i.sourceDay){let[e,t,n]=i.sourceDay.split(`-`).map(e=>parseInt(e,10));l=new Date(e,t,n)}else l=new Date(c);l.setHours(0,0,0,0);let u=s.getTime()-l.getTime();if(u===0)return;let f=new Date(c.getTime()+u),m;o.end&&(m=new Date(new Date(o.end).getTime()+u)),a(o,f,m)};return(0,F.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,F.jsx)(`div`,{role:`row`,className:`grid grid-cols-7 border-b`,children:l.map(e=>(0,F.jsx)(`div`,{role:`columnheader`,className:`p-2 text-center text-sm font-medium text-muted-foreground border-r last:border-r-0`,children:e},e))}),(0,F.jsx)(`div`,{role:`grid`,"aria-label":`Calendar grid`,className:`grid grid-cols-7 flex-1 auto-rows-fr`,children:o.map((t,n)=>{let o=`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`,l=m.get(o)||[],d=t.getMonth()===e.getMonth(),p=U(t,s);return(0,F.jsxs)(`div`,{role:`gridcell`,"aria-label":`${t.toLocaleDateString(`default`,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})}${l.length>0?`, ${l.length} event${l.length>1?`s`:``}`:``}`,className:x(`border-b border-r last:border-r-0 p-2 min-h-[100px] cursor-pointer hover:bg-accent/50`,!d&&`bg-muted/50 text-muted-foreground opacity-50`,f===n&&`ring-2 ring-primary`),onClick:()=>i?.(t),onDragOver:e=>_(e,n),onDragLeave:v,onDrop:e=>y(e,t),children:[(0,F.jsx)(`div`,{className:x(`text-sm font-medium mb-2`,p&&`inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-6 w-6`),...p?{"aria-current":`date`}:{},children:t.getDate()}),(0,F.jsxs)(`div`,{className:`space-y-0.5`,children:[l.slice(0,4).map(({event:e,isTitleDay:n,isSpanStart:i,isSpanEnd:o},s)=>{let c=!n,{className:l,inlineColor:d}=B(e.color),f=!!a&&o;return(0,F.jsxs)(`div`,{role:`button`,title:e.title,"aria-label":e.title,draggable:!!a,onDragStart:n=>h(n,e,`move`,t),onDragEnd:g,className:x(`relative text-xs hover:opacity-80 truncate`,a?`cursor-move`:`cursor-pointer`,c?`h-1.5`:`px-2 py-0.5`,i?`rounded-l`:`rounded-l-none`,o?`rounded-r`:`rounded-r-none`,!o&&`-mr-2`,l,u===e.id&&`opacity-50`),style:d?{backgroundColor:d}:void 0,onClick:t=>{t.stopPropagation(),r?.(e)},children:[c?``:e.title,f&&(0,F.jsx)(`span`,{role:`separator`,"aria-label":`Resize event end`,title:`Drag to change end date`,draggable:!0,onDragStart:n=>h(n,e,`resize-end`,t),onDragEnd:g,onClick:e=>e.stopPropagation(),className:`absolute inset-y-0 right-0 w-2 cursor-ew-resize bg-black/25 hover:bg-black/50 rounded-r`})]},`${e.id}-${s}`)}),l.length>4&&(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground px-2`,children:c(`calendar.moreEvents`,{count:l.length-4})})]})]},n)})})]})}var G=48;function K(e){let t=new Date(e);return t.setHours(0,0,0,0),t}function q(e){return e.getHours()*60+e.getMinutes()}function J(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Y({mode:e,date:t,events:n,locale:r=`default`,slotMinutes:i=30,onEventClick:a,onEventDrop:o,onTimeRangeSelect:s}){let{t:c}=V(),l=G*i/60,u=G*24,d=P.useMemo(()=>{if(e===`day`)return[K(t)];let n=ae(t);return Array.from({length:7},(e,t)=>{let r=new Date(n);return r.setDate(n.getDate()+t),K(r)})},[e,t.getFullYear(),t.getMonth(),t.getDate()]),f=P.useMemo(()=>new Date,[]),p=P.useCallback(e=>{if(e.allDay)return!0;let t=new Date(e.start),n=e.end?new Date(e.end):new Date(t),r=t.getHours()===0&&t.getMinutes()===0&&t.getSeconds()===0,i=n.getHours()===0&&n.getMinutes()===0&&n.getSeconds()===0,a=n.getTime()-t.getTime();return!!(r&&i||a>=1440*60*1e3)},[]),{allDayEvents:m,timedEvents:h}=P.useMemo(()=>{let e=[],t=[];for(let r of n)p(r)?e.push(r):t.push(r);return{allDayEvents:e,timedEvents:t}},[n,p]),g=P.useMemo(()=>{let e=new Map;for(let t of d)e.set(J(t),[]);for(let t of m){let n=K(new Date(t.start)),r=t.end?new Date(t.end):new Date(t.start),i=K(r);r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getTime()>n.getTime()&&(i=new Date(i),i.setDate(i.getDate()-1));for(let r of d){let a=K(r);a<n||a>i||e.get(J(r)).push({event:t,isStart:a.getTime()===n.getTime(),isEnd:a.getTime()===i.getTime()})}}return e},[d,m]),_=P.useMemo(()=>{let e=new Map;for(let t of d)e.set(J(t),[]);for(let t of h){let n=new Date(t.start),r=t.end?new Date(t.end):new Date(n.getTime()+3600*1e3);for(let i of d){let a=K(i),o=new Date(a);if(o.setDate(o.getDate()+1),r<=a||n>=o)continue;let s=n<a?a:n,c=r>o?o:r,l=q(s),u=c.getTime()===o.getTime()?1440:q(c);e.get(J(i)).push({event:t,startMin:l,endMin:Math.max(u,l+15),isStart:s.getTime()===n.getTime(),isEnd:c.getTime()===r.getTime()})}}return e},[d,h]),v=P.useMemo(()=>{let e=new Map;for(let[t,n]of _){let r=[...n].sort((e,t)=>e.startMin-t.startMin||e.endMin-t.endMin),i=[],a=[],o=[];for(let e of r){let t=0;for(;i[t]&&i[t].endMin>e.startMin;)t++;i[t]={endMin:e.endMin},a.push({entry:e,col:t})}for(let e=0;e<a.length;e++){let t=a[e],n=t.col;for(let r=0;r<a.length;r++){if(r===e)continue;let i=a[r];i.entry.startMin<t.entry.endMin&&i.entry.endMin>t.entry.startMin&&i.col>n&&(n=i.col)}o.push({...t.entry,col:t.col,cols:n+1})}e.set(t,o)}return e},[_]),y=P.useRef(null),b=P.useRef([]),[S,C]=P.useState(null),w=P.useRef(null);w.current=S;let T=P.useRef(!1),E=P.useCallback((e,t)=>{let n=b.current[t];if(!n)return 0;let r=(e-n.getBoundingClientRect().top+n.scrollTop)/G*60,a=Math.round(r/i)*i;return Math.max(0,Math.min(1440,a))},[i]),D=P.useCallback(e=>{for(let t=0;t<b.current.length;t++){let n=b.current[t];if(!n)continue;let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right)return t}return-1},[]);P.useEffect(()=>{if(!S)return;let e=e=>{let t=S.kind===`select`||S.kind===`move`?D(e.clientX):S.dayIndex,n=t<0?S.dayIndex??0:t,r=E(e.clientY,n);C(e=>e&&(e.kind===`select`?{...e,dayIndex:n>=0?n:e.dayIndex,headMinutes:r}:e.kind===`move`?{...e,dayIndex:n,minutes:r}:{...e,minutes:r}))},t=e=>{let t=w.current;if(!t){C(null);return}try{if(t.kind===`select`&&s){let e=Math.min(t.anchorMinutes,t.headMinutes),n=Math.max(t.anchorMinutes,t.headMinutes),r=e,a=n===e?Math.min(1440,e+i):n,o=d[t.dayIndex]??d[0],c=new Date(o);c.setHours(0,Math.round(r),0,0);let l=new Date(o);l.setHours(0,Math.round(a),0,0),T.current=!0,s(c,l)}else if(t.kind===`move`&&o){let e=n.find(e=>String(e.id)===String(t.eventId));if(e){let n=t.dayIndex<0?0:t.dayIndex,r=t.minutes-t.grabMinuteOffset,a=Math.max(0,Math.min(1440-t.durationMin,Math.round(r/i)*i)),s=d[n]??d[0],c=new Date(s);c.setHours(0,a,0,0);let l=new Date(c.getTime()+t.durationMin*60*1e3);T.current=!0,o(e,c,l)}}else if(t.kind===`resize-top`&&o){let e=n.find(e=>String(e.id)===String(t.eventId));if(e){let n=d[t.dayIndex]??d[0],r=Math.min(t.anchorEndMin-i,Math.max(0,t.minutes)),a=new Date(n);a.setHours(0,r,0,0);let s=new Date(n);s.setHours(0,t.anchorEndMin,0,0),T.current=!0,o(e,a,s)}}else if(t.kind===`resize-bottom`&&o){let e=n.find(e=>String(e.id)===String(t.eventId));if(e){let n=d[t.dayIndex]??d[0],r=Math.max(t.anchorStartMin+i,Math.min(1440,t.minutes)),a=new Date(n);a.setHours(0,t.anchorStartMin,0,0);let s=new Date(n);s.setHours(0,r,0,0),T.current=!0,o(e,a,s)}}}finally{C(null),setTimeout(()=>{T.current=!1},50)}};return window.addEventListener(`pointermove`,e),window.addEventListener(`pointerup`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t)}},[S,d,n,i,o,s,D,E]);let O=P.useMemo(()=>d.map(e=>({weekday:e.toLocaleDateString(r,{weekday:`short`}),day:e.getDate(),month:e.toLocaleDateString(r,{month:`short`}),isToday:U(e,f)})),[d,r,f]),k=P.useMemo(()=>Array.from({length:24},(e,t)=>new Date(2024,0,1,t,0).toLocaleTimeString(r,{hour:`numeric`})),[r]),A=(e,t,n,r)=>{if(!o||e.button!==0)return;e.stopPropagation(),e.preventDefault();let i=E(e.clientY,n);C(r===`body`?{kind:`move`,eventId:t.event.id,grabMinuteOffset:Math.max(0,i-t.startMin),durationMin:t.endMin-t.startMin,dayIndex:n,minutes:i}:r===`top`?{kind:`resize-top`,eventId:t.event.id,anchorEndMin:t.endMin,dayIndex:n,minutes:i}:{kind:`resize-bottom`,eventId:t.event.id,anchorStartMin:t.startMin,dayIndex:n,minutes:i})},j=(e,t)=>{if(!s||e.button!==0)return;e.preventDefault();let n=E(e.clientY,t);C({kind:`select`,dayIndex:t,anchorMinutes:n,headMinutes:n})},ee=e=>{if(!S)return null;if(S.kind===`select`&&S.dayIndex===e){let t=Math.min(S.anchorMinutes,S.headMinutes),n=Math.max(S.anchorMinutes,S.headMinutes);return(0,F.jsx)(`div`,{className:`absolute left-1 right-1 rounded bg-primary/30 border border-primary pointer-events-none z-10`,style:{top:t/60*G,height:Math.max(l,(n-t)/60*G)},"aria-hidden":!0,children:(0,F.jsx)(`div`,{className:`px-2 py-0.5 text-xs font-medium text-primary`,children:X(d[e],t,n,r)})})}if(S.kind===`move`&&S.dayIndex===e){let t=S.minutes-S.grabMinuteOffset,n=Math.max(0,Math.min(1440-S.durationMin,Math.round(t/i)*i));return(0,F.jsx)(`div`,{className:`absolute left-1 right-1 rounded border-2 border-dashed border-primary bg-primary/10 pointer-events-none z-10`,style:{top:n/60*G,height:S.durationMin/60*G},"aria-hidden":!0,children:(0,F.jsx)(`div`,{className:`px-2 py-0.5 text-xs font-medium text-primary`,children:X(d[e],n,n+S.durationMin,r)})})}if((S.kind===`resize-top`||S.kind===`resize-bottom`)&&S.dayIndex===e){let t,n;return S.kind===`resize-top`?(t=Math.min(S.anchorEndMin-i,Math.max(0,S.minutes)),n=S.anchorEndMin):(t=S.anchorStartMin,n=Math.max(S.anchorStartMin+i,Math.min(1440,S.minutes))),(0,F.jsx)(`div`,{className:`absolute left-1 right-1 rounded border-2 border-dashed border-primary bg-primary/10 pointer-events-none z-10`,style:{top:t/60*G,height:(n-t)/60*G},"aria-hidden":!0,children:(0,F.jsx)(`div`,{className:`px-2 py-0.5 text-xs font-medium text-primary`,children:X(d[e],t,n,r)})})}return null};return(0,F.jsxs)(`div`,{className:`flex flex-col h-full`,ref:y,children:[(0,F.jsxs)(`div`,{className:`flex border-b sticky top-0 bg-background z-20`,children:[(0,F.jsx)(`div`,{className:`w-14 shrink-0 border-r`,"aria-hidden":!0}),O.map((e,t)=>(0,F.jsxs)(`div`,{role:`columnheader`,className:x(`flex-1 p-2 text-center text-sm border-r last:border-r-0`,e.isToday&&`bg-primary/5`),children:[(0,F.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.weekday}),(0,F.jsx)(`div`,{className:x(`font-medium`,e.isToday&&`inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-6 w-6 mx-auto`),children:e.day})]},t))]}),m.length>0&&(0,F.jsxs)(`div`,{className:`flex border-b bg-muted/20 max-h-[140px] overflow-y-auto`,children:[(0,F.jsx)(`div`,{className:`w-14 shrink-0 border-r flex items-start justify-end pr-1 pt-1 text-[10px] text-muted-foreground sticky left-0 bg-muted/20`,children:c(`calendar.allDay`)===`calendar.allDay`?`all-day`:c(`calendar.allDay`)}),d.map(e=>{let t=J(e);return(0,F.jsx)(`div`,{className:`flex-1 border-r last:border-r-0 min-h-[28px] p-0.5 space-y-0.5`,children:(g.get(t)??[]).map(({event:e,isStart:t,isEnd:n},r)=>{let{className:i,inlineColor:o}=B(e.color);return(0,F.jsx)(`div`,{role:`button`,title:e.title,onClick:t=>{t.stopPropagation(),a?.(e)},className:x(`text-[11px] px-2 py-0.5 truncate cursor-pointer hover:opacity-80`,t?`rounded-l`:`rounded-l-none -ml-0.5`,n?`rounded-r`:`rounded-r-none -mr-0.5`,i),style:o?{backgroundColor:o}:void 0,children:t?e.title:`\xA0`},`${e.id}-${r}`)})},t)})]}),(0,F.jsx)(`div`,{className:`flex-1 overflow-auto`,children:(0,F.jsxs)(`div`,{className:`flex`,style:{height:u},children:[(0,F.jsx)(`div`,{className:`w-14 shrink-0 border-r relative`,children:k.map((e,t)=>(0,F.jsx)(`div`,{className:`absolute right-1 text-[10px] text-muted-foreground -translate-y-1/2`,style:{top:t*G},children:t===0?``:e},t))}),d.map((e,t)=>{let n=J(e),s=v.get(n)??[];return(0,F.jsxs)(`div`,{ref:e=>{b.current[t]=e},className:`flex-1 border-r last:border-r-0 relative select-none`,style:{height:u},onPointerDown:e=>j(e,t),"aria-label":e.toLocaleDateString(r,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`}),children:[Array.from({length:24},(e,t)=>(0,F.jsx)(`div`,{className:`absolute left-0 right-0 border-t border-muted/60 pointer-events-none`,style:{top:t*G}},t)),i<60&&Array.from({length:Math.floor(1440/i)},(e,t)=>{let n=t*i;return n%60==0?null:(0,F.jsx)(`div`,{className:`absolute left-0 right-0 border-t border-dashed border-muted/30 pointer-events-none`,style:{top:n/60*G}},t)}),s.map(n=>{let i=n.startMin/60*G,s=Math.max(l,(n.endMin-n.startMin)/60*G),c=100/n.cols,u=n.col*c,{className:d,inlineColor:f}=B(n.event.color),p=S&&S.eventId===n.event.id;return(0,F.jsxs)(`div`,{role:`button`,tabIndex:0,title:n.event.title,"aria-label":n.event.title,onPointerDown:e=>A(e,n,t,`body`),onClick:e=>{if(T.current){e.stopPropagation();return}e.stopPropagation(),a?.(n.event)},className:x(`absolute rounded text-xs px-2 py-1 overflow-hidden shadow-sm`,o?`cursor-move`:`cursor-pointer`,d,p&&`opacity-40`),style:{top:i,height:s,left:`calc(${u}% + 2px)`,width:`calc(${c}% - 4px)`,...f?{backgroundColor:f}:{}},children:[(0,F.jsx)(`div`,{className:`font-medium truncate`,children:n.event.title}),(0,F.jsx)(`div`,{className:`text-[10px] opacity-80 truncate`,children:X(e,n.startMin,n.endMin,r)}),o&&n.isStart&&(0,F.jsx)(`div`,{onPointerDown:e=>A(e,n,t,`top`),className:`absolute top-0 left-0 right-0 h-1.5 cursor-ns-resize`,"aria-label":`Resize start`}),o&&n.isEnd&&(0,F.jsx)(`div`,{onPointerDown:e=>A(e,n,t,`bottom`),className:`absolute bottom-0 left-0 right-0 h-1.5 cursor-ns-resize`,"aria-label":`Resize end`})]},`${n.event.id}-${n.startMin}`)}),ee(t)]},n)})]})})]})}function X(e,t,n,r){let i=new Date(e);i.setHours(0,Math.round(t),0,0);let a=new Date(e);a.setHours(0,Math.round(n),0,0);let o=e=>e.toLocaleTimeString(r,{hour:`numeric`,minute:`2-digit`});return`${o(i)} – ${o(a)}`}function se(e){return`data`in e&&e.data?e.data:`staticData`in e&&e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function ce(e){if(e){if(typeof e==`string`){let t=e.split(` `),n=t[0],r=t[1]?.toLowerCase()===`desc`?`desc`:`asc`;return{[n]:r}}if(Array.isArray(e))return e.reduce((e,t)=>(t.field&&t.order&&(e[t.field]=t.order),e),{})}}function le(e){return`filter`in e&&e.filter&&typeof e.filter==`object`&&`calendar`in e.filter?e.filter.calendar:e.calendar?e.calendar:e.startDateField||e.dateField?{startDateField:e.startDateField||e.dateField,endDateField:e.endDateField||e.endField,titleField:e.titleField,colorField:e.colorField,allDayField:e.allDayField}:null}var Z=({schema:e,dataSource:t,className:n,data:r,loading:a,onEventClick:o,onRowClick:c,onDateClick:u,onNavigate:f,onViewChange:m,onEventDrop:_,locale:y})=>{let b=Array.isArray(r),[x,S]=(0,P.useState)(b?r:[]),[C,w]=(0,P.useState)(b?a??!1:!0),[T,k]=(0,P.useState)(null),[j,te]=(0,P.useState)(null),[I,re]=(0,P.useState)(new Date),L=O(),R=e.defaultView,[z,B]=(0,P.useState)(()=>{let e=R===`day`||!R;return typeof window<`u`&&window.innerWidth<768&&e?`month`:R||`month`});(0,P.useEffect)(()=>{L&&z===`day`&&(R===`day`||!R)&&B(`month`)},[L]);let[ie,V]=(0,P.useState)(0);(0,P.useEffect)(()=>{if(!b&&!(!t?.onMutation||!e.objectName))return t.onMutation(t=>{t.resource===e.objectName&&V(e=>e+1)})},[t,e.objectName,b]);let{ref:ae,isRefreshing:oe,pullDistance:U}=ne({onRefresh:(0,P.useCallback)(async()=>{V(e=>e+1)},[]),enabled:!!t&&!!e.objectName}),W=(0,P.useMemo)(()=>se(e),[e.data,e.staticData,e.objectName]),G=(0,P.useMemo)(()=>le(e),[e.filter,e.calendar,e.dateField,e.endField,e.titleField,e.colorField]),K=W?.provider===`value`,q=(0,P.useRef)(null);q.current=j,(0,P.useEffect)(()=>{b&&S(r)},[r,b]),(0,P.useEffect)(()=>{b&&a!==void 0&&w(a)},[a,b]),(0,P.useEffect)(()=>{if(b)return;let n=!0;return(async()=>{try{if(!n)return;if(w(!0),K&&W?.provider===`value`){n&&(S(W.items),w(!1));return}if(!t||typeof t.find!=`function`)throw Error(`DataSource required for object/api providers`);if(W?.provider===`object`){let r=W.object,i=s(q.current?.fields),a=l(await t.find(r,{$filter:e.filter,$orderby:ce(e.sort),...i.length>0?{$expand:i}:{}}));n&&S(a)}else W?.provider===`api`&&(console.warn(`API provider not yet implemented for ObjectCalendar`),n&&S([]));n&&w(!1)}catch(e){console.error(`[ObjectCalendar] Error fetching data:`,e),n&&(k(e),w(!1))}})(),()=>{n=!1}},[b,W,t,K,e.filter,e.sort,ie]),(0,P.useEffect)(()=>{!K&&t&&(async()=>{try{if(!t)return;let n=W?.provider===`object`?W.object:e.objectName;if(!n)return;te(await t.getObjectSchema(n))}catch(e){console.error(`Failed to fetch object schema:`,e)}})()},[e.objectName,t,K,W]);let J=(0,P.useMemo)(()=>{if(!G||!x.length)return[];let{startDateField:e,endDateField:t,titleField:n,colorField:r}=G,i=j?.titleFormat,a=typeof i==`string`?i:i&&typeof i==`object`&&typeof i.source==`string`?i.source:void 0,o=j?.NAME_FIELD_KEY,s=[`name`,`full_name`,`fullName`,`title`,`subject`,`label`,`display_name`,`displayName`],c=(e,t)=>{let n=`[-\\u2013\\u2014|/·,:]`,r=!1,i=e.replace(/\{([^{}]+)\}/g,(e,n)=>{let i=t[n.trim()];return i!=null&&i!==``?(r=!0,String(i)):`\0`});return r?i.replace(RegExp(`\\s*${n}\\s*`,`g`),``).replace(RegExp(`\\s*${n}\\s*`,`g`),``).replace(RegExp(`\0`,`g`),``).replace(/\s+/g,` `).trim():``},l=e=>{let t;if(n&&(t=e[n],typeof t==`string`&&(t=t.trim())),!t&&a){let n=c(a,e);n&&(t=n)}if(!t&&o){let n=e[o];typeof n==`string`?t=n.trim():n&&(t=n)}if(!t)for(let n of s){let r=e[n],i=typeof r==`string`?r.trim():r;if(i){t=i;break}}return t||`Untitled`};return x.map((n,i)=>{let a=n[e],o=t?n[t]:null,s=l(n),c=r?n[r]:void 0;return{id:n.id||n._id||`event-${i}`,title:s,start:a?new Date(a):new Date,end:o?new Date(o):void 0,color:c,allDay:!o,data:n}}).filter(e=>!isNaN(e.start.getTime()))},[x,G,j]);(0,P.useCallback)(()=>{u?.(new Date)},[u]);let Y=e.navigation??{mode:`drawer`,width:`min(960px, 60vw)`},X=Y.mode===`drawer`||Y.mode===`modal`||Y.mode===`split`||Y.mode===`popover`,Z=i({navigation:Y,objectName:e.objectName,onRowClick:X?void 0:c}),ue=(0,P.useCallback)(async(n,r,i)=>{if(!G)return;let{startDateField:a,endDateField:o}=G,s=n?.id??n?._id;if(!s||!e.objectName||!t?.update)return;let c={[a]:r.toISOString()};o&&i&&(c[o]=i.toISOString());let l=x;S(e=>e.map(e=>(e?.id??e?._id)===s?{...e,...c}:e));try{await t.update(e.objectName,s,c)}catch(e){S(l),console.error(`[ObjectCalendar] Failed to persist drag-and-drop reschedule:`,e)}},[G,e.objectName,t,x]),[Q,$]=(0,P.useState)(null),de=(0,P.useCallback)(n=>{!G||!e.objectName||!t?.create||$({start:n,title:``,submitting:!1})},[G,e.objectName,t]),fe=(0,P.useCallback)((n,r)=>{!G||!e.objectName||!t?.create||$({start:n,end:r,title:``,submitting:!1})},[G,e.objectName,t]),pe=(0,P.useCallback)(async()=>{if(!Q||!G)return;let n=Q.title.trim();if(!n){$(e=>e&&{...e,error:`Title is required`});return}if(!e.objectName||!t?.create)return;$(e=>e&&{...e,submitting:!0,error:void 0});let{startDateField:r,endDateField:i,titleField:a}=G,o={[a||`name`]:n,[r]:Q.start.toISOString()};i&&(o[i]=(Q.end??Q.start).toISOString());let s=j?.fields;if(s&&typeof s==`object`){let e=Array.isArray(s)?s.map(e=>[e.name??e.apiName,e]):Object.entries(s);for(let[t,n]of e){if(!t||t in o||!n?.required)continue;if(n.defaultValue!==void 0&&n.defaultValue!==null){o[t]=n.defaultValue;continue}let e=n.type;if(e===`select`||e===`picklist`||e===`status`){let e=(n.options||n.choices||[])[0];e!==void 0&&(o[t]=typeof e==`object`?e.value??e.id:e)}else e===`boolean`||e===`checkbox`?o[t]=!1:(e===`number`||e===`integer`||e===`decimal`||e===`currency`||e===`percent`)&&(o[t]=0)}}try{let n=await t.create(e.objectName,o),r=(n&&(n.record||n.data||n))??null;r&&(r.id!==void 0||r._id!==void 0)&&S(e=>[...e,r]),$(null)}catch(e){let t=e?.message||String(e);$(e=>e&&{...e,submitting:!1,error:t}),console.error(`[ObjectCalendar] Quick-create failed:`,e)}},[Q,G,e.objectName,t,j]);return C?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading calendar...`})})}):T?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsxs)(`div`,{className:`text-destructive`,children:[`Error: `,T.message]})})}):G?(0,F.jsxs)(`div`,{ref:ae,className:n,children:[U>0&&(0,F.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:U},children:oe?`Refreshing…`:`Pull to refresh`}),(0,F.jsx)(`div`,{className:`bg-background h-[calc(100vh-120px)] sm:h-[calc(100vh-160px)] md:h-[calc(100vh-200px)] min-h-[400px] sm:min-h-[600px]`,children:(0,F.jsx)(H,{events:J,currentDate:I,view:z,locale:y,onEventClick:e=>{Z.handleClick(e.data),X||o?.(e.data)},onDateClick:e=>{u?u(e):de(e)},onNavigate:e=>{re(e),f?.(e)},onViewChange:e=>{B(e),m?.(e)},onAddClick:void 0,onEventDrop:(e,t,n)=>{_?_(e.data,t,n):ue(e.data,t,n)},onTimeRangeSelect:fe})}),(0,F.jsx)(p,{open:!!Q,onOpenChange:e=>{e||$(null)},children:(0,F.jsxs)(h,{className:`sm:max-w-md`,children:[(0,F.jsxs)(ee,{children:[(0,F.jsx)(d,{children:`New event`}),(0,F.jsx)(g,{children:Q&&(()=>{let e=Q.end&&Q.end.getTime()!==Q.start.getTime(),t=Q.start.toLocaleDateString(y,{year:`numeric`,month:`long`,day:`numeric`});if(e){let e=e=>e.toLocaleTimeString(y,{hour:`numeric`,minute:`2-digit`});return(0,F.jsxs)(F.Fragment,{children:[t,` · `,e(Q.start),` – `,e(Q.end)]})}return(0,F.jsxs)(F.Fragment,{children:[`On `,t]})})()})]}),(0,F.jsxs)(`div`,{className:`space-y-2`,children:[(0,F.jsx)(D,{htmlFor:`quick-create-title`,children:`Title`}),(0,F.jsx)(E,{id:`quick-create-title`,autoFocus:!0,value:Q?.title??``,onChange:e=>$(t=>t&&{...t,title:e.target.value,error:void 0}),onKeyDown:e=>{e.key===`Enter`&&!Q?.submitting&&(e.preventDefault(),pe())},placeholder:`What's this event about?`,disabled:Q?.submitting}),Q?.error&&(0,F.jsx)(`p`,{className:`text-sm text-destructive`,children:Q.error})]}),(0,F.jsxs)(v,{children:[(0,F.jsx)(A,{variant:`outline`,onClick:()=>$(null),disabled:Q?.submitting,children:`Cancel`}),(0,F.jsx)(A,{onClick:()=>void pe(),disabled:Q?.submitting||!Q?.title.trim(),children:Q?.submitting?`Creating…`:`Create`})]})]})}),Z.isOverlay&&Z.isOpen&&Z.selectedRecord&&(()=>{let n=W?.provider===`object`?W.object:e.objectName,r=Z.selectedRecord,i=r.id??r._id;if(!n||i==null)return null;let a=G?.titleField?String(r[G.titleField]??`Event Details`):`Event Details`;return(0,F.jsx)(N,{open:!0,onClose:Z.close,title:a,record:r,objectName:n,recordId:i,dataSource:t,objectSchema:j,width:Z.width??`min(960px, 60vw)`,fullPageHref:M(n,i)??void 0,onFieldSave:async(e,r)=>{t?.update&&(await t.update(n,String(i),{[e]:r}),S(t=>t.map(t=>String(t.id??t._id)===String(i)?{...t,[e]:r}:t)))},onDelete:async()=>{t?.delete&&(await t.delete(n,String(i)),S(e=>e.filter(e=>String(e.id??e._id)!==String(i))))}})})()]}):(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Calendar configuration required. Please specify startDateField and titleField.`})})})};o.register(`calendar-view`,({schema:e,className:t,onAction:n,...r})=>{let i=P.useMemo(()=>!e.data||!Array.isArray(e.data)?[]:e.data.map((t,n)=>{let r=e.titleField||`title`,i=e.startDateField||`start`,a=e.endDateField||`end`,o=e.colorField||`color`,s=e.allDayField||`allDay`;return{id:t.id||t._id||n,title:t[r]||`Untitled Event`,start:new Date(t[i]),end:t[a]?new Date(t[a]):void 0,allDay:t[s],color:t[o],data:t}}),[e.data,e.titleField,e.startDateField,e.endDateField,e.colorField,e.allDayField]);return(0,F.jsx)(H,{className:t,events:i,onEventClick:e=>{n?.({type:`event-click`,payload:e})},...r})},{namespace:`plugin-calendar`,label:`Calendar View`,inputs:[{name:`data`,type:`array`,label:`Data`,description:`Array of record objects to display as events`},{name:`titleField`,type:`string`,label:`Title Field`,defaultValue:`title`,description:`Field name to use for event title`},{name:`startDateField`,type:`string`,label:`Start Date Field`,defaultValue:`start`,description:`Field name for event start date`},{name:`endDateField`,type:`string`,label:`End Date Field`,defaultValue:`end`,description:`Field name for event end date (optional)`},{name:`allDayField`,type:`string`,label:`All Day Field`,defaultValue:`allDay`,description:`Field name for all-day flag`},{name:`colorField`,type:`string`,label:`Color Field`,defaultValue:`color`,description:`Field name for event color`},{name:`colorMapping`,type:`object`,label:`Color Mapping`,description:`Map field values to colors (e.g., {meeting: "blue", deadline: "red"})`},{name:`view`,type:`enum`,enum:[`month`,`week`,`day`],defaultValue:`month`,label:`View Mode`,description:`Calendar view mode (month, week, or day)`},{name:`currentDate`,type:`string`,label:`Current Date`,description:`ISO date string for initial calendar date`},{name:`allowCreate`,type:`boolean`,label:`Allow Create`,defaultValue:!1,description:`Allow creating events by clicking on dates`},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{view:`month`,titleField:`title`,startDateField:`start`,endDateField:`end`,allDayField:`allDay`,colorField:`color`,allowCreate:!1,data:[{id:1,title:`Team Meeting`,start:new Date(new Date().setHours(10,0,0,0)).toISOString(),end:new Date(new Date().setHours(11,0,0,0)).toISOString(),color:`#3b82f6`,allDay:!1},{id:2,title:`Project Deadline`,start:new Date(new Date().setDate(new Date().getDate()+3)).toISOString(),color:`#ef4444`,allDay:!0},{id:3,title:`Conference`,start:new Date(new Date().setDate(new Date().getDate()+7)).toISOString(),end:new Date(new Date().setDate(new Date().getDate()+9)).toISOString(),color:`#10b981`,allDay:!0}],className:`h-[600px] border rounded-lg`}});var ue=t({CalendarView:()=>H,ObjectCalendar:()=>Z,ObjectCalendarRenderer:()=>Q}),Q=({schema:e,...t})=>{let{dataSource:n}=a()||{};return(0,F.jsx)(Z,{schema:e,dataSource:n,...t})};o.register(`object-calendar`,Q,{namespace:`plugin-calendar`,label:`Object Calendar`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`calendar`,type:`object`,label:`Calendar Config`,description:`startDateField, endDateField, titleField, colorField`}]}),o.register(`calendar`,Q,{namespace:`view`,label:`Calendar View`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`calendar`,type:`object`,label:`Calendar Config`,description:`startDateField, endDateField, titleField, colorField`}]});export{ue as t};
@@ -1 +1 @@
1
- import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{r as n,y as r}from"./vendor-react-BMpe6Iqg.js";import{s as i}from"./vendor-objectstack-DCNcl1ou.js";import{N as a,U as o,dt as s,ot as c,r as l,st as u}from"./framework-Bg_8y02a.js";import{C as d,Ys as f,_r as p,ar as ee,cr as m,cs as te,d as h,dr as g,ea as _,fr as v,lr as y,ls as ne,mr as b,or as x,sr as S,ta as C,u as w,ur as T,vr as E,xs as D}from"./ui-components-C7AytqY9.js";import{i as O,r as k}from"./plugins-views-BUSRnnI0.js";var A=e(r(),1),j={"gantt.column.taskName":`Task Name`,"gantt.column.start":`Start`,"gantt.column.end":`End`,"gantt.toolbar.prevPeriod":`Previous period`,"gantt.toolbar.nextPeriod":`Next period`,"gantt.toolbar.zoomIn":`Zoom in`,"gantt.toolbar.zoomOut":`Zoom out`,"gantt.toolbar.jumpToToday":`Jump to today`,"gantt.toolbar.today":`Today`,"gantt.toolbar.showTaskList":`Show task list`,"gantt.toolbar.hideTaskList":`Hide task list`},M=`gantt.column.taskName`;function N(e,t){let n=j[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}function P(){try{let e=l();return e.t(M)===M?{t:N}:{t:e.t}}catch{return{t:N}}}var F=n();function re(e){return e<640?35:e<1024?50:60}function I(e){return e<640?140:e<1024?220:320}function L(e){return e>=280}function R(e){return e<640?32:40}function z({tasks:e,startDate:t,endDate:n,onTaskClick:r,onTaskUpdate:i,className:a,inlineEdit:o=!1}){let{t:s}=P(),[c,l]=A.useState(new Date),u=A.useRef(null),{width:ee}=d(u),m=ee||(typeof window<`u`?window.innerWidth:1024),h=m<640,g=R(m),v=re(m),[y,x]=A.useState(null),S=y??v,[w,T]=A.useState(!1),O=A.useRef(!1);A.useEffect(()=>{!O.current&&h&&(T(!0),O.current=!0)},[h]);let k=w?0:I(m),j=L(k),[M,N]=A.useState(null),[z,B]=A.useState({}),[V,H]=A.useState(null),U=A.useRef(null);A.useEffect(()=>{U.current=V},[V]);let W=A.useRef(!1),G=A.useCallback(e=>{let t=1e3*60*60*24,n=t,r=e.dayDelta*t,i=new Date(e.originStart),a=new Date(e.originEnd);return e.mode===`move`?(i=new Date(e.originStart.getTime()+r),a=new Date(e.originEnd.getTime()+r)):e.mode===`resize-left`?(i=new Date(e.originStart.getTime()+r),a.getTime()-i.getTime()<n&&(i=new Date(a.getTime()-n))):e.mode===`resize-right`&&(a=new Date(e.originEnd.getTime()+r),a.getTime()-i.getTime()<n&&(a=new Date(i.getTime()+n))),{start:i,end:a}},[]);A.useEffect(()=>{if(!V)return;let t=e=>{let t=U.current;if(!t)return;let n=Math.round((e.clientX-t.originClientX)/Math.max(S,1));n!==t.dayDelta&&H({...t,dayDelta:n})},n=()=>{let t=U.current;if(t){if(t.dayDelta!==0){let n=e.find(e=>e.id===t.taskId);if(n&&i){let{start:e,end:r}=G(t);i(n,{start:e,end:r})}W.current=!0,window.setTimeout(()=>{W.current=!1},0)}H(null)}};return window.addEventListener(`pointermove`,t),window.addEventListener(`pointerup`,n),window.addEventListener(`pointercancel`,n),()=>{window.removeEventListener(`pointermove`,t),window.removeEventListener(`pointerup`,n),window.removeEventListener(`pointercancel`,n)}},[V,S,e,i,G]);let K=A.useCallback((e,t,n)=>{i&&(n.stopPropagation(),n.preventDefault(),H({taskId:e.id,mode:t,originStart:new Date(e.start),originEnd:new Date(e.end),originClientX:n.clientX,dayDelta:0}))},[i]),q=A.useMemo(()=>{let r=t?new Date(t):new Date,i=n?new Date(n):new Date;return!t&&e.length>0&&(r=new Date(Math.min(...e.map(e=>e.start.getTime()))),r.setDate(r.getDate()-7)),!n&&e.length>0&&(i=new Date(Math.max(...e.map(e=>e.end.getTime()))),i.setDate(i.getDate()+14)),r.setHours(0,0,0,0),i.setHours(23,59,59,999),{start:r,end:i}},[t,n,e]),J=A.useMemo(()=>{let e=[],t=new Date(q.start);for(;t<=q.end;)e.push({date:new Date(t),label:t.getDate().toString(),isWeekend:t.getDay()===0||t.getDay()===6}),t.setDate(t.getDate()+1);return e},[q]),Y=A.useRef(null),X=A.useRef(null),ie=A.useRef(null),Z=A.useRef(null),Q=A.useRef(null),ae=A.useCallback(e=>{if(e.touches.length===2){let t=e.touches[0].clientX-e.touches[1].clientX,n=e.touches[0].clientY-e.touches[1].clientY;Q.current={baseDistance:Math.max(1,Math.sqrt(t*t+n*n)),baseColumn:S}}},[S]),oe=A.useCallback(e=>{if(e.touches.length!==2||!Q.current)return;let t=e.touches[0].clientX-e.touches[1].clientX,n=e.touches[0].clientY-e.touches[1].clientY,r=Math.max(1,Math.sqrt(t*t+n*n))/Q.current.baseDistance;x(Math.max(15,Math.min(120,Math.round(Q.current.baseColumn*r))))},[]),se=A.useCallback(()=>{Q.current=null},[]),$=A.useMemo(()=>{let e=new Date;if(e<q.start||e>q.end)return null;let t=(e.getTime()-q.start.getTime())/(1440*60*1e3);return Math.round(t*S)},[q,S]),ce=A.useCallback(()=>{if($==null||!Z.current)return;let e=Math.max(0,$-Z.current.clientWidth/2);Z.current.scrollTo({left:e,behavior:`smooth`})},[$]),le=e=>{Y.current&&(Y.current.scrollLeft=e.currentTarget.scrollLeft),X.current&&(X.current.scrollTop=e.currentTarget.scrollTop)},ue=e=>{q.end.getTime()-q.start.getTime();let t=S,n=1e3*60*60*24,r=e.start.getTime()-q.start.getTime(),i=e.end.getTime()-e.start.getTime();return{left:r/n*t,width:Math.max(i/n*t,t)}};return(0,F.jsxs)(`div`,{ref:u,className:f(`flex flex-col h-full bg-background overflow-hidden min-w-0`,a),children:[(0,F.jsxs)(`div`,{className:`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 p-2 border-b bg-card`,children:[(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,"aria-label":s(`gantt.toolbar.prevPeriod`),children:(0,F.jsx)(ne,{className:`h-4 w-4`})}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,"aria-label":s(`gantt.toolbar.nextPeriod`),children:(0,F.jsx)(te,{className:`h-4 w-4`})}),(0,F.jsx)(`span`,{className:`font-semibold text-xs sm:text-sm`,children:q.start.toLocaleDateString(void 0,{month:`long`,year:`numeric`})})]}),(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsxs)(`div`,{className:`flex bg-muted rounded-md p-1`,children:[(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-6 w-6`,onClick:()=>x(Math.max(15,S-10)),"aria-label":s(`gantt.toolbar.zoomOut`),children:(0,F.jsx)(E,{className:`h-3 w-3`})}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-6 w-6`,onClick:()=>x(Math.min(120,S+10)),"aria-label":s(`gantt.toolbar.zoomIn`),children:(0,F.jsx)(p,{className:`h-3 w-3`})})]}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:()=>T(e=>!e),"aria-label":s(w?`gantt.toolbar.showTaskList`:`gantt.toolbar.hideTaskList`),"aria-pressed":w,"data-testid":`gantt-toggle-task-list`,children:w?(0,F.jsx)(_,{className:`h-4 w-4`}):(0,F.jsx)(C,{className:`h-4 w-4`})}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:ce,disabled:$==null,"aria-label":s(`gantt.toolbar.jumpToToday`),"data-testid":`gantt-jump-today`,children:(0,F.jsx)(D,{className:`h-4 w-4`})})]})]}),(0,F.jsxs)(`div`,{className:`flex flex-col flex-1 overflow-hidden`,children:[(0,F.jsxs)(`div`,{className:`flex border-b bg-muted/30 shrink-0 h-10 sm:h-[50px]`,children:[(0,F.jsxs)(`div`,{className:`flex items-center font-medium text-xs text-muted-foreground px-2 sm:px-4 border-r bg-card z-20 shadow-sm`,style:{width:k,minWidth:k},children:[(0,F.jsx)(`div`,{className:`flex-1 truncate`,children:s(`gantt.column.taskName`)}),j&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right`,children:s(`gantt.column.start`)}),(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right`,children:s(`gantt.column.end`)})]})]}),(0,F.jsx)(`div`,{className:`flex-1 overflow-hidden`,ref:Y,children:(0,F.jsx)(`div`,{className:`flex h-full`,style:{width:J.length*S},children:J.map((e,t)=>(0,F.jsxs)(`div`,{className:f(`flex flex-col items-center justify-center border-r text-xs text-muted-foreground h-full`,e.isWeekend&&`bg-muted/50`),style:{width:S,minWidth:S},children:[(0,F.jsx)(`span`,{className:`font-medium text-foreground`,children:e.label}),(0,F.jsx)(`span`,{className:`text-[10px] opacity-70`,children:e.date.toLocaleDateString(void 0,{weekday:`narrow`})})]},t))})})]}),(0,F.jsxs)(`div`,{className:`flex flex-1 overflow-hidden`,children:[(0,F.jsx)(`div`,{className:`overflow-hidden border-r bg-card z-10 shadow-sm`,ref:X,style:{width:k,minWidth:k},children:e.map(e=>{let t=o&&M===e.id;return(0,F.jsxs)(`div`,{className:`group/task-row flex items-center border-b px-2 sm:px-4 hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,style:{height:g},onClick:()=>!t&&r?.(e),onDoubleClick:()=>{o&&i&&(N(e.id),B({title:e.title,start:e.start.toLocaleDateString(`en-CA`),end:e.end.toLocaleDateString(`en-CA`),progress:String(e.progress)}))},children:[(0,F.jsxs)(`div`,{className:`flex-1 truncate font-medium text-xs sm:text-sm flex items-center gap-2`,children:[(0,F.jsx)(`div`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:e.color||`#3b82f6`}}),t?(0,F.jsx)(`input`,{className:`border rounded px-1 py-0.5 text-xs w-full bg-background`,value:z.title||``,onChange:e=>B(t=>({...t,title:e.target.value})),onKeyDown:t=>{t.key===`Enter`?(i?.(e,{title:z.title,start:new Date(z.start),end:new Date(z.end),progress:Number(z.progress)||0}),N(null)):t.key===`Escape`&&N(null)},onClick:e=>e.stopPropagation(),autoFocus:!0}):(0,F.jsxs)(`span`,{className:`flex flex-col min-w-0`,children:[(0,F.jsx)(`span`,{className:`truncate`,children:e.title}),(0,F.jsxs)(`span`,{className:`text-[10px] text-muted-foreground sm:hidden`,children:[e.start.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`}),` → `,e.end.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})]})]})]}),(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right text-xs text-muted-foreground hidden sm:block`,hidden:!j,style:j?void 0:{display:`none`},children:t?(0,F.jsx)(`input`,{type:`date`,className:`border rounded px-1 py-0.5 text-xs w-full bg-background`,value:z.start||``,onChange:e=>B(t=>({...t,start:e.target.value})),onClick:e=>e.stopPropagation()}):e.start.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})}),(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right text-xs text-muted-foreground hidden sm:block`,hidden:!j,style:j?void 0:{display:`none`},children:t?(0,F.jsx)(`input`,{type:`date`,className:`border rounded px-1 py-0.5 text-xs w-full bg-background`,value:z.end||``,onChange:e=>B(t=>({...t,end:e.target.value})),onClick:e=>e.stopPropagation()}):e.end.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})})]},e.id)})}),(0,F.jsx)(`div`,{className:`flex-1 overflow-auto bg-background/50 relative [-webkit-overflow-scrolling:touch]`,ref:e=>{ie.current=e,Z.current=e},onScroll:le,onTouchStart:ae,onTouchMove:oe,onTouchEnd:se,"data-testid":`gantt-timeline`,children:(0,F.jsxs)(`div`,{className:`relative`,style:{width:J.length*S},children:[$!=null&&(0,F.jsx)(`div`,{className:`absolute top-0 bottom-0 w-px bg-red-500/80 z-20 pointer-events-none`,style:{left:$},"data-testid":`gantt-today-marker`,"aria-label":s(`gantt.toolbar.today`),children:(0,F.jsx)(`div`,{className:`absolute -top-2 -translate-x-1/2 left-0 text-[10px] font-semibold text-white bg-red-500 rounded-sm px-1 py-0.5 whitespace-nowrap`,children:s(`gantt.toolbar.today`)})}),(0,F.jsxs)(`div`,{className:`relative`,children:[(0,F.jsx)(`div`,{className:`absolute inset-0 flex pointer-events-none z-0`,children:J.map((e,t)=>(0,F.jsx)(`div`,{className:f(`border-r h-full`,e.isWeekend&&`bg-muted/20`),style:{width:S,minWidth:S}},t))}),e.map(e=>{let t=ue(e),n=V?.taskId===e.id,a=t;if(n&&V){let t=G(V);a=ue({...e,start:t.start,end:t.end})}let o=!!i;return(0,F.jsxs)(`div`,{className:`relative border-b hover:bg-black/5`,style:{height:g},children:[n&&(0,F.jsx)(`div`,{className:`absolute top-1 sm:top-2 h-[calc(100%-8px)] sm:h-[calc(100%-16px)] rounded-sm border border-dashed border-primary/60 pointer-events-none`,style:{left:t.left,width:t.width,opacity:.35},"aria-hidden":`true`}),(0,F.jsxs)(`div`,{className:f(`absolute top-1 sm:top-2 h-[calc(100%-8px)] sm:h-[calc(100%-16px)] rounded-sm bg-primary border border-primary-foreground/20 shadow-sm hover:brightness-110 flex items-center px-2 group select-none`,o?`cursor-grab active:cursor-grabbing`:`cursor-pointer`,n&&`ring-2 ring-primary/60 brightness-110 z-10`),style:{left:a.left,width:a.width,backgroundColor:e.color||`#3b82f6`},"data-testid":`gantt-task-bar-${e.id}`,onClick:()=>{W.current||r?.(e)},onPointerDown:o?t=>{t.button===0&&K(e,`move`,t)}:void 0,children:[o&&a.width>=14&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`absolute left-0 top-0 bottom-0 w-1.5 cursor-ew-resize hover:bg-white/40`,"data-testid":`gantt-task-resize-left-${e.id}`,onPointerDown:t=>{t.button===0&&K(e,`resize-left`,t)},onClick:e=>e.stopPropagation()}),(0,F.jsx)(`div`,{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-ew-resize hover:bg-white/40`,"data-testid":`gantt-task-resize-right-${e.id}`,onPointerDown:t=>{t.button===0&&K(e,`resize-right`,t)},onClick:e=>e.stopPropagation()})]}),e.progress>0&&(0,F.jsx)(`div`,{className:`absolute left-0 top-0 bottom-0 bg-black/20 rounded-l-sm pointer-events-none`,style:{width:`${e.progress}%`}}),(0,F.jsx)(`span`,{className:`text-[10px] text-white font-medium truncate opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none`,children:n?`${G(V).start.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})} → ${G(V).end.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})}`:`${Math.round(e.progress)}%`})]})]},e.id)}),(0,F.jsx)(`div`,{className:`absolute top-0 bottom-0 w-px bg-red-500 z-20 pointer-events-none`,style:{left:(new Date().getTime()-q.start.getTime())/(1e3*60*60*24)*S},children:(0,F.jsx)(`div`,{className:`w-2 h-2 rounded-full bg-red-500 -ml-[3px]`})})]})]})})]})]})]})}function B(e){return e.data?e.data:e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function V(e){if(e){if(typeof e==`string`){let t=e.split(` `),n=t[0],r=t[1]?.toLowerCase()===`desc`?`desc`:`asc`;return{[n]:r}}if(Array.isArray(e))return e.reduce((e,t)=>(t.field&&t.order&&(e[t.field]=t.order),e),{})}}function H(e){let t=null;if(e.startDateField&&e.endDateField)return t={startDateField:e.startDateField,endDateField:e.endDateField,titleField:e.titleField||`name`,progressField:e.progressField,dependenciesField:e.dependenciesField||e.dependencyField,colorField:e.colorField},t;if(e.gantt&&(t=e.gantt),t){let e=i.safeParse(t);return e.success||console.warn(`[ObjectGantt] Invalid gantt configuration:`,e.error.format()),t}return null}var U=({schema:e,dataSource:t,className:n,onTaskClick:r,onRowClick:i,...o})=>{let[s,l]=(0,A.useState)([]),[d,f]=(0,A.useState)(!0),[p,te]=(0,A.useState)(null),[_,ne]=(0,A.useState)(null),b=B(e),C=(0,A.useMemo)(()=>b,[JSON.stringify(b)]),E=H(e),D=C?.provider===`value`;(0,A.useEffect)(()=>{(async()=>{try{if(f(!0),o.data&&Array.isArray(o.data)){l(o.data),f(!1);return}if(D&&C?.provider===`value`){l(C.items),f(!1);return}if(!t||typeof t.find!=`function`)throw Error(`DataSource required for object/api providers`);if(C?.provider===`object`){let n=C.object,r=c(_?.fields);l(u(await t.find(n,{$filter:e.filter,$orderby:V(e.sort),...r.length>0?{$expand:r}:{}})))}else C?.provider===`api`&&(console.warn(`API provider not yet implemented for ObjectGantt`),l([]));f(!1)}catch(e){te(e),f(!1)}})()},[C,t,D,e.filter,e.sort,_]),(0,A.useEffect)(()=>{!D&&t&&(async()=>{try{if(!t)return;let n=C?.provider===`object`?C.object:e.objectName;if(!n)return;ne(await t.getObjectSchema(n))}catch(e){console.error(`Failed to fetch object schema:`,e)}})()},[e.objectName,t,D,C]);let j=(0,A.useMemo)(()=>{if(!E||!s.length)return[];let{startDateField:e,endDateField:t,titleField:n,progressField:r,dependenciesField:i,colorField:a}=E,o=(e,t)=>{if(!t)return;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r},c=e=>{let t=[o(e,n),e?.name,e?.title,e?.subject,e?.label,e?.account?.name,e?.opportunity?.name,e?.contact&&[e.contact.first_name,e.contact.last_name].filter(Boolean).join(` `),e?.id,e?._id];for(let e of t)if(e!=null&&String(e).trim()!==``)return String(e);return`Untitled`};return s.map((n,o)=>{let s=n[e],l=n[t],u=c(n),d=r?n[r]:0,f=i?n[i]:[],p=a?n[a]:void 0;if(!p){let e=n.status??n.state??n.priority??n.severity;if(e!=null&&e!==``){let t=w(void 0,e);t&&(p=h(t))}}return{id:n.id||n._id||`task-${o}`,title:u,start:s?new Date(s):new Date,end:l?new Date(l):new Date,progress:Math.min(100,Math.max(0,d||0)),dependencies:Array.isArray(f)?f:[],color:p,data:n}}).filter(e=>!isNaN(e.start.getTime())&&!isNaN(e.end.getTime()))},[s,E]),M=e.navigation??{mode:`drawer`,width:`min(960px, 60vw)`},N=M.mode===`drawer`||M.mode===`modal`||M.mode===`split`||M.mode===`popover`,P=a({navigation:M,objectName:e.objectName,onRowClick:N?void 0:i}),re=(0,A.useCallback)(async(n,r)=>{if(!E)return;let i=C?.provider===`object`?C.object:e.objectName;if(!i||!t||typeof t.update!=`function`)return;let{startDateField:a,endDateField:o,titleField:c,progressField:u}=E,d={};if(r.start instanceof Date&&(d[a]=r.start.toISOString()),r.end instanceof Date&&(d[o]=r.end.toISOString()),typeof r.title==`string`&&c&&(d[c]=r.title),typeof r.progress==`number`&&u&&(d[u]=r.progress),Object.keys(d).length===0)return;let f=n.data?.id??n.data?._id??n.id;if(f==null)return;let p=s;l(e=>e.map(e=>String(e.id??e._id)===String(f)?{...e,...d}:e));try{await t.update(i,String(f),d)}catch(e){console.error(`[ObjectGantt] Failed to persist task update:`,e),l(p)}},[E,C,t,e.objectName,s]),[I,L]=(0,A.useState)(null),[R,U]=(0,A.useState)(!1),W=(0,A.useCallback)(e=>{L(e)},[]),G=(0,A.useCallback)(async()=>{if(!I)return;let n=C?.provider===`object`?C.object:e.objectName;if(!n||!t?.delete){L(null);return}let r=I.data?.id??I.data?._id??I.id;if(r==null){L(null);return}U(!0);let i=s;l(e=>e.filter(e=>String(e.id??e._id)!==String(r)));try{await t.delete(n,String(r)),L(null)}catch(e){console.error(`[ObjectGantt] Failed to delete:`,e),l(i),L(null)}finally{U(!1)}},[I,C,t,e.objectName,s]);return d?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading Gantt chart...`})})}):p?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsxs)(`div`,{className:`text-destructive`,children:[`Error: `,p.message]})})}):E?(0,F.jsxs)(`div`,{className:n,children:[(0,F.jsx)(`div`,{className:`h-[calc(100vh-200px)] min-h-[600px]`,children:(0,F.jsx)(z,{tasks:j,onTaskClick:e=>{P.handleClick(e.data),r?.(e.data)},onTaskUpdate:re,onTaskDelete:W,inlineEdit:!0})}),P.isOverlay&&P.isOpen&&P.selectedRecord&&(()=>{let n=C?.provider===`object`?C.object:e.objectName,r=P.selectedRecord,i=r.id??r._id;if(!n||i==null)return null;let a=E?.titleField?String(r[E.titleField]??`Task Details`):`Task Details`;return(0,F.jsx)(k,{open:!0,onClose:P.close,title:a,record:r,objectName:n,recordId:i,dataSource:t,objectSchema:_,width:P.width,fullPageHref:O(n,i)??void 0,onFieldSave:async(e,r)=>{t?.update&&(await t.update(n,String(i),{[e]:r}),l(t=>t.map(t=>String(t.id??t._id)===String(i)?{...t,[e]:r}:t)))},onDelete:async()=>{t?.delete&&(await t.delete(n,String(i)),l(e=>e.filter(e=>String(e.id??e._id)!==String(i))))}})})(),(0,F.jsx)(ee,{open:!!I,onOpenChange:e=>{!e&&!R&&L(null)},children:(0,F.jsxs)(m,{children:[(0,F.jsxs)(g,{children:[(0,F.jsx)(v,{children:`Delete this task?`}),(0,F.jsx)(y,{children:I?(0,F.jsxs)(F.Fragment,{children:[`"`,I.title,`" will be permanently removed. This action cannot be undone.`]}):null})]}),(0,F.jsxs)(T,{children:[(0,F.jsx)(S,{disabled:R,children:`Cancel`}),(0,F.jsx)(x,{onClick:e=>{e.preventDefault(),G()},disabled:R,"data-testid":`gantt-delete-confirm`,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:R?`Deleting…`:`Delete`})]})]})})]}):(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Gantt configuration required. Please specify startDateField, endDateField, and titleField.`})})})},W=t({GanttView:()=>z,ObjectGantt:()=>U,ObjectGanttRenderer:()=>G}),G=({schema:e})=>{let{dataSource:t}=o()||{};return(0,F.jsx)(U,{schema:e,dataSource:t})};s.register(`object-gantt`,G,{namespace:`plugin-gantt`,label:`Object Gantt`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`gantt`,type:`object`,label:`Gantt Config`,description:`startDateField, endDateField, titleField, progressField, percentageField, colorField, dependenciesField`}]}),s.register(`gantt`,G,{namespace:`view`,label:`Gantt View`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`gantt`,type:`object`,label:`Gantt Config`,description:`startDateField, endDateField, titleField, progressField, percentageField, colorField, dependenciesField`}]});export{W as t};
1
+ import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{r as n,y as r}from"./vendor-react-BMpe6Iqg.js";import{s as i}from"./vendor-objectstack-DCNcl1ou.js";import{N as a,U as o,dt as s,ot as c,r as l,st as u}from"./framework-Bg_8y02a.js";import{C as d,Ys as f,_r as p,ar as ee,cr as m,cs as te,d as h,dr as g,ea as _,fr as v,lr as y,ls as ne,mr as b,or as x,sr as S,ta as C,u as w,ur as T,vr as E,xs as D}from"./ui-components-C7AytqY9.js";import{i as O,r as k}from"./plugins-views-rCdZtRbk.js";var A=e(r(),1),j={"gantt.column.taskName":`Task Name`,"gantt.column.start":`Start`,"gantt.column.end":`End`,"gantt.toolbar.prevPeriod":`Previous period`,"gantt.toolbar.nextPeriod":`Next period`,"gantt.toolbar.zoomIn":`Zoom in`,"gantt.toolbar.zoomOut":`Zoom out`,"gantt.toolbar.jumpToToday":`Jump to today`,"gantt.toolbar.today":`Today`,"gantt.toolbar.showTaskList":`Show task list`,"gantt.toolbar.hideTaskList":`Hide task list`},M=`gantt.column.taskName`;function N(e,t){let n=j[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}function P(){try{let e=l();return e.t(M)===M?{t:N}:{t:e.t}}catch{return{t:N}}}var F=n();function re(e){return e<640?35:e<1024?50:60}function I(e){return e<640?140:e<1024?220:320}function L(e){return e>=280}function R(e){return e<640?32:40}function z({tasks:e,startDate:t,endDate:n,onTaskClick:r,onTaskUpdate:i,className:a,inlineEdit:o=!1}){let{t:s}=P(),[c,l]=A.useState(new Date),u=A.useRef(null),{width:ee}=d(u),m=ee||(typeof window<`u`?window.innerWidth:1024),h=m<640,g=R(m),v=re(m),[y,x]=A.useState(null),S=y??v,[w,T]=A.useState(!1),O=A.useRef(!1);A.useEffect(()=>{!O.current&&h&&(T(!0),O.current=!0)},[h]);let k=w?0:I(m),j=L(k),[M,N]=A.useState(null),[z,B]=A.useState({}),[V,H]=A.useState(null),U=A.useRef(null);A.useEffect(()=>{U.current=V},[V]);let W=A.useRef(!1),G=A.useCallback(e=>{let t=1e3*60*60*24,n=t,r=e.dayDelta*t,i=new Date(e.originStart),a=new Date(e.originEnd);return e.mode===`move`?(i=new Date(e.originStart.getTime()+r),a=new Date(e.originEnd.getTime()+r)):e.mode===`resize-left`?(i=new Date(e.originStart.getTime()+r),a.getTime()-i.getTime()<n&&(i=new Date(a.getTime()-n))):e.mode===`resize-right`&&(a=new Date(e.originEnd.getTime()+r),a.getTime()-i.getTime()<n&&(a=new Date(i.getTime()+n))),{start:i,end:a}},[]);A.useEffect(()=>{if(!V)return;let t=e=>{let t=U.current;if(!t)return;let n=Math.round((e.clientX-t.originClientX)/Math.max(S,1));n!==t.dayDelta&&H({...t,dayDelta:n})},n=()=>{let t=U.current;if(t){if(t.dayDelta!==0){let n=e.find(e=>e.id===t.taskId);if(n&&i){let{start:e,end:r}=G(t);i(n,{start:e,end:r})}W.current=!0,window.setTimeout(()=>{W.current=!1},0)}H(null)}};return window.addEventListener(`pointermove`,t),window.addEventListener(`pointerup`,n),window.addEventListener(`pointercancel`,n),()=>{window.removeEventListener(`pointermove`,t),window.removeEventListener(`pointerup`,n),window.removeEventListener(`pointercancel`,n)}},[V,S,e,i,G]);let K=A.useCallback((e,t,n)=>{i&&(n.stopPropagation(),n.preventDefault(),H({taskId:e.id,mode:t,originStart:new Date(e.start),originEnd:new Date(e.end),originClientX:n.clientX,dayDelta:0}))},[i]),q=A.useMemo(()=>{let r=t?new Date(t):new Date,i=n?new Date(n):new Date;return!t&&e.length>0&&(r=new Date(Math.min(...e.map(e=>e.start.getTime()))),r.setDate(r.getDate()-7)),!n&&e.length>0&&(i=new Date(Math.max(...e.map(e=>e.end.getTime()))),i.setDate(i.getDate()+14)),r.setHours(0,0,0,0),i.setHours(23,59,59,999),{start:r,end:i}},[t,n,e]),J=A.useMemo(()=>{let e=[],t=new Date(q.start);for(;t<=q.end;)e.push({date:new Date(t),label:t.getDate().toString(),isWeekend:t.getDay()===0||t.getDay()===6}),t.setDate(t.getDate()+1);return e},[q]),Y=A.useRef(null),X=A.useRef(null),ie=A.useRef(null),Z=A.useRef(null),Q=A.useRef(null),ae=A.useCallback(e=>{if(e.touches.length===2){let t=e.touches[0].clientX-e.touches[1].clientX,n=e.touches[0].clientY-e.touches[1].clientY;Q.current={baseDistance:Math.max(1,Math.sqrt(t*t+n*n)),baseColumn:S}}},[S]),oe=A.useCallback(e=>{if(e.touches.length!==2||!Q.current)return;let t=e.touches[0].clientX-e.touches[1].clientX,n=e.touches[0].clientY-e.touches[1].clientY,r=Math.max(1,Math.sqrt(t*t+n*n))/Q.current.baseDistance;x(Math.max(15,Math.min(120,Math.round(Q.current.baseColumn*r))))},[]),se=A.useCallback(()=>{Q.current=null},[]),$=A.useMemo(()=>{let e=new Date;if(e<q.start||e>q.end)return null;let t=(e.getTime()-q.start.getTime())/(1440*60*1e3);return Math.round(t*S)},[q,S]),ce=A.useCallback(()=>{if($==null||!Z.current)return;let e=Math.max(0,$-Z.current.clientWidth/2);Z.current.scrollTo({left:e,behavior:`smooth`})},[$]),le=e=>{Y.current&&(Y.current.scrollLeft=e.currentTarget.scrollLeft),X.current&&(X.current.scrollTop=e.currentTarget.scrollTop)},ue=e=>{q.end.getTime()-q.start.getTime();let t=S,n=1e3*60*60*24,r=e.start.getTime()-q.start.getTime(),i=e.end.getTime()-e.start.getTime();return{left:r/n*t,width:Math.max(i/n*t,t)}};return(0,F.jsxs)(`div`,{ref:u,className:f(`flex flex-col h-full bg-background overflow-hidden min-w-0`,a),children:[(0,F.jsxs)(`div`,{className:`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 p-2 border-b bg-card`,children:[(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,"aria-label":s(`gantt.toolbar.prevPeriod`),children:(0,F.jsx)(ne,{className:`h-4 w-4`})}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,"aria-label":s(`gantt.toolbar.nextPeriod`),children:(0,F.jsx)(te,{className:`h-4 w-4`})}),(0,F.jsx)(`span`,{className:`font-semibold text-xs sm:text-sm`,children:q.start.toLocaleDateString(void 0,{month:`long`,year:`numeric`})})]}),(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsxs)(`div`,{className:`flex bg-muted rounded-md p-1`,children:[(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-6 w-6`,onClick:()=>x(Math.max(15,S-10)),"aria-label":s(`gantt.toolbar.zoomOut`),children:(0,F.jsx)(E,{className:`h-3 w-3`})}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-6 w-6`,onClick:()=>x(Math.min(120,S+10)),"aria-label":s(`gantt.toolbar.zoomIn`),children:(0,F.jsx)(p,{className:`h-3 w-3`})})]}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:()=>T(e=>!e),"aria-label":s(w?`gantt.toolbar.showTaskList`:`gantt.toolbar.hideTaskList`),"aria-pressed":w,"data-testid":`gantt-toggle-task-list`,children:w?(0,F.jsx)(_,{className:`h-4 w-4`}):(0,F.jsx)(C,{className:`h-4 w-4`})}),(0,F.jsx)(b,{variant:`ghost`,size:`icon`,className:`h-8 w-8`,onClick:ce,disabled:$==null,"aria-label":s(`gantt.toolbar.jumpToToday`),"data-testid":`gantt-jump-today`,children:(0,F.jsx)(D,{className:`h-4 w-4`})})]})]}),(0,F.jsxs)(`div`,{className:`flex flex-col flex-1 overflow-hidden`,children:[(0,F.jsxs)(`div`,{className:`flex border-b bg-muted/30 shrink-0 h-10 sm:h-[50px]`,children:[(0,F.jsxs)(`div`,{className:`flex items-center font-medium text-xs text-muted-foreground px-2 sm:px-4 border-r bg-card z-20 shadow-sm`,style:{width:k,minWidth:k},children:[(0,F.jsx)(`div`,{className:`flex-1 truncate`,children:s(`gantt.column.taskName`)}),j&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right`,children:s(`gantt.column.start`)}),(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right`,children:s(`gantt.column.end`)})]})]}),(0,F.jsx)(`div`,{className:`flex-1 overflow-hidden`,ref:Y,children:(0,F.jsx)(`div`,{className:`flex h-full`,style:{width:J.length*S},children:J.map((e,t)=>(0,F.jsxs)(`div`,{className:f(`flex flex-col items-center justify-center border-r text-xs text-muted-foreground h-full`,e.isWeekend&&`bg-muted/50`),style:{width:S,minWidth:S},children:[(0,F.jsx)(`span`,{className:`font-medium text-foreground`,children:e.label}),(0,F.jsx)(`span`,{className:`text-[10px] opacity-70`,children:e.date.toLocaleDateString(void 0,{weekday:`narrow`})})]},t))})})]}),(0,F.jsxs)(`div`,{className:`flex flex-1 overflow-hidden`,children:[(0,F.jsx)(`div`,{className:`overflow-hidden border-r bg-card z-10 shadow-sm`,ref:X,style:{width:k,minWidth:k},children:e.map(e=>{let t=o&&M===e.id;return(0,F.jsxs)(`div`,{className:`group/task-row flex items-center border-b px-2 sm:px-4 hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,style:{height:g},onClick:()=>!t&&r?.(e),onDoubleClick:()=>{o&&i&&(N(e.id),B({title:e.title,start:e.start.toLocaleDateString(`en-CA`),end:e.end.toLocaleDateString(`en-CA`),progress:String(e.progress)}))},children:[(0,F.jsxs)(`div`,{className:`flex-1 truncate font-medium text-xs sm:text-sm flex items-center gap-2`,children:[(0,F.jsx)(`div`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:e.color||`#3b82f6`}}),t?(0,F.jsx)(`input`,{className:`border rounded px-1 py-0.5 text-xs w-full bg-background`,value:z.title||``,onChange:e=>B(t=>({...t,title:e.target.value})),onKeyDown:t=>{t.key===`Enter`?(i?.(e,{title:z.title,start:new Date(z.start),end:new Date(z.end),progress:Number(z.progress)||0}),N(null)):t.key===`Escape`&&N(null)},onClick:e=>e.stopPropagation(),autoFocus:!0}):(0,F.jsxs)(`span`,{className:`flex flex-col min-w-0`,children:[(0,F.jsx)(`span`,{className:`truncate`,children:e.title}),(0,F.jsxs)(`span`,{className:`text-[10px] text-muted-foreground sm:hidden`,children:[e.start.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`}),` → `,e.end.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})]})]})]}),(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right text-xs text-muted-foreground hidden sm:block`,hidden:!j,style:j?void 0:{display:`none`},children:t?(0,F.jsx)(`input`,{type:`date`,className:`border rounded px-1 py-0.5 text-xs w-full bg-background`,value:z.start||``,onChange:e=>B(t=>({...t,start:e.target.value})),onClick:e=>e.stopPropagation()}):e.start.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})}),(0,F.jsx)(`div`,{className:`w-16 sm:w-20 text-right text-xs text-muted-foreground hidden sm:block`,hidden:!j,style:j?void 0:{display:`none`},children:t?(0,F.jsx)(`input`,{type:`date`,className:`border rounded px-1 py-0.5 text-xs w-full bg-background`,value:z.end||``,onChange:e=>B(t=>({...t,end:e.target.value})),onClick:e=>e.stopPropagation()}):e.end.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})})]},e.id)})}),(0,F.jsx)(`div`,{className:`flex-1 overflow-auto bg-background/50 relative [-webkit-overflow-scrolling:touch]`,ref:e=>{ie.current=e,Z.current=e},onScroll:le,onTouchStart:ae,onTouchMove:oe,onTouchEnd:se,"data-testid":`gantt-timeline`,children:(0,F.jsxs)(`div`,{className:`relative`,style:{width:J.length*S},children:[$!=null&&(0,F.jsx)(`div`,{className:`absolute top-0 bottom-0 w-px bg-red-500/80 z-20 pointer-events-none`,style:{left:$},"data-testid":`gantt-today-marker`,"aria-label":s(`gantt.toolbar.today`),children:(0,F.jsx)(`div`,{className:`absolute -top-2 -translate-x-1/2 left-0 text-[10px] font-semibold text-white bg-red-500 rounded-sm px-1 py-0.5 whitespace-nowrap`,children:s(`gantt.toolbar.today`)})}),(0,F.jsxs)(`div`,{className:`relative`,children:[(0,F.jsx)(`div`,{className:`absolute inset-0 flex pointer-events-none z-0`,children:J.map((e,t)=>(0,F.jsx)(`div`,{className:f(`border-r h-full`,e.isWeekend&&`bg-muted/20`),style:{width:S,minWidth:S}},t))}),e.map(e=>{let t=ue(e),n=V?.taskId===e.id,a=t;if(n&&V){let t=G(V);a=ue({...e,start:t.start,end:t.end})}let o=!!i;return(0,F.jsxs)(`div`,{className:`relative border-b hover:bg-black/5`,style:{height:g},children:[n&&(0,F.jsx)(`div`,{className:`absolute top-1 sm:top-2 h-[calc(100%-8px)] sm:h-[calc(100%-16px)] rounded-sm border border-dashed border-primary/60 pointer-events-none`,style:{left:t.left,width:t.width,opacity:.35},"aria-hidden":`true`}),(0,F.jsxs)(`div`,{className:f(`absolute top-1 sm:top-2 h-[calc(100%-8px)] sm:h-[calc(100%-16px)] rounded-sm bg-primary border border-primary-foreground/20 shadow-sm hover:brightness-110 flex items-center px-2 group select-none`,o?`cursor-grab active:cursor-grabbing`:`cursor-pointer`,n&&`ring-2 ring-primary/60 brightness-110 z-10`),style:{left:a.left,width:a.width,backgroundColor:e.color||`#3b82f6`},"data-testid":`gantt-task-bar-${e.id}`,onClick:()=>{W.current||r?.(e)},onPointerDown:o?t=>{t.button===0&&K(e,`move`,t)}:void 0,children:[o&&a.width>=14&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`absolute left-0 top-0 bottom-0 w-1.5 cursor-ew-resize hover:bg-white/40`,"data-testid":`gantt-task-resize-left-${e.id}`,onPointerDown:t=>{t.button===0&&K(e,`resize-left`,t)},onClick:e=>e.stopPropagation()}),(0,F.jsx)(`div`,{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-ew-resize hover:bg-white/40`,"data-testid":`gantt-task-resize-right-${e.id}`,onPointerDown:t=>{t.button===0&&K(e,`resize-right`,t)},onClick:e=>e.stopPropagation()})]}),e.progress>0&&(0,F.jsx)(`div`,{className:`absolute left-0 top-0 bottom-0 bg-black/20 rounded-l-sm pointer-events-none`,style:{width:`${e.progress}%`}}),(0,F.jsx)(`span`,{className:`text-[10px] text-white font-medium truncate opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none`,children:n?`${G(V).start.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})} → ${G(V).end.toLocaleDateString(void 0,{month:`numeric`,day:`numeric`})}`:`${Math.round(e.progress)}%`})]})]},e.id)}),(0,F.jsx)(`div`,{className:`absolute top-0 bottom-0 w-px bg-red-500 z-20 pointer-events-none`,style:{left:(new Date().getTime()-q.start.getTime())/(1e3*60*60*24)*S},children:(0,F.jsx)(`div`,{className:`w-2 h-2 rounded-full bg-red-500 -ml-[3px]`})})]})]})})]})]})]})}function B(e){return e.data?e.data:e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function V(e){if(e){if(typeof e==`string`){let t=e.split(` `),n=t[0],r=t[1]?.toLowerCase()===`desc`?`desc`:`asc`;return{[n]:r}}if(Array.isArray(e))return e.reduce((e,t)=>(t.field&&t.order&&(e[t.field]=t.order),e),{})}}function H(e){let t=null;if(e.startDateField&&e.endDateField)return t={startDateField:e.startDateField,endDateField:e.endDateField,titleField:e.titleField||`name`,progressField:e.progressField,dependenciesField:e.dependenciesField||e.dependencyField,colorField:e.colorField},t;if(e.gantt&&(t=e.gantt),t){let e=i.safeParse(t);return e.success||console.warn(`[ObjectGantt] Invalid gantt configuration:`,e.error.format()),t}return null}var U=({schema:e,dataSource:t,className:n,onTaskClick:r,onRowClick:i,...o})=>{let[s,l]=(0,A.useState)([]),[d,f]=(0,A.useState)(!0),[p,te]=(0,A.useState)(null),[_,ne]=(0,A.useState)(null),b=B(e),C=(0,A.useMemo)(()=>b,[JSON.stringify(b)]),E=H(e),D=C?.provider===`value`;(0,A.useEffect)(()=>{(async()=>{try{if(f(!0),o.data&&Array.isArray(o.data)){l(o.data),f(!1);return}if(D&&C?.provider===`value`){l(C.items),f(!1);return}if(!t||typeof t.find!=`function`)throw Error(`DataSource required for object/api providers`);if(C?.provider===`object`){let n=C.object,r=c(_?.fields);l(u(await t.find(n,{$filter:e.filter,$orderby:V(e.sort),...r.length>0?{$expand:r}:{}})))}else C?.provider===`api`&&(console.warn(`API provider not yet implemented for ObjectGantt`),l([]));f(!1)}catch(e){te(e),f(!1)}})()},[C,t,D,e.filter,e.sort,_]),(0,A.useEffect)(()=>{!D&&t&&(async()=>{try{if(!t)return;let n=C?.provider===`object`?C.object:e.objectName;if(!n)return;ne(await t.getObjectSchema(n))}catch(e){console.error(`Failed to fetch object schema:`,e)}})()},[e.objectName,t,D,C]);let j=(0,A.useMemo)(()=>{if(!E||!s.length)return[];let{startDateField:e,endDateField:t,titleField:n,progressField:r,dependenciesField:i,colorField:a}=E,o=(e,t)=>{if(!t)return;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r},c=e=>{let t=[o(e,n),e?.name,e?.title,e?.subject,e?.label,e?.account?.name,e?.opportunity?.name,e?.contact&&[e.contact.first_name,e.contact.last_name].filter(Boolean).join(` `),e?.id,e?._id];for(let e of t)if(e!=null&&String(e).trim()!==``)return String(e);return`Untitled`};return s.map((n,o)=>{let s=n[e],l=n[t],u=c(n),d=r?n[r]:0,f=i?n[i]:[],p=a?n[a]:void 0;if(!p){let e=n.status??n.state??n.priority??n.severity;if(e!=null&&e!==``){let t=w(void 0,e);t&&(p=h(t))}}return{id:n.id||n._id||`task-${o}`,title:u,start:s?new Date(s):new Date,end:l?new Date(l):new Date,progress:Math.min(100,Math.max(0,d||0)),dependencies:Array.isArray(f)?f:[],color:p,data:n}}).filter(e=>!isNaN(e.start.getTime())&&!isNaN(e.end.getTime()))},[s,E]),M=e.navigation??{mode:`drawer`,width:`min(960px, 60vw)`},N=M.mode===`drawer`||M.mode===`modal`||M.mode===`split`||M.mode===`popover`,P=a({navigation:M,objectName:e.objectName,onRowClick:N?void 0:i}),re=(0,A.useCallback)(async(n,r)=>{if(!E)return;let i=C?.provider===`object`?C.object:e.objectName;if(!i||!t||typeof t.update!=`function`)return;let{startDateField:a,endDateField:o,titleField:c,progressField:u}=E,d={};if(r.start instanceof Date&&(d[a]=r.start.toISOString()),r.end instanceof Date&&(d[o]=r.end.toISOString()),typeof r.title==`string`&&c&&(d[c]=r.title),typeof r.progress==`number`&&u&&(d[u]=r.progress),Object.keys(d).length===0)return;let f=n.data?.id??n.data?._id??n.id;if(f==null)return;let p=s;l(e=>e.map(e=>String(e.id??e._id)===String(f)?{...e,...d}:e));try{await t.update(i,String(f),d)}catch(e){console.error(`[ObjectGantt] Failed to persist task update:`,e),l(p)}},[E,C,t,e.objectName,s]),[I,L]=(0,A.useState)(null),[R,U]=(0,A.useState)(!1),W=(0,A.useCallback)(e=>{L(e)},[]),G=(0,A.useCallback)(async()=>{if(!I)return;let n=C?.provider===`object`?C.object:e.objectName;if(!n||!t?.delete){L(null);return}let r=I.data?.id??I.data?._id??I.id;if(r==null){L(null);return}U(!0);let i=s;l(e=>e.filter(e=>String(e.id??e._id)!==String(r)));try{await t.delete(n,String(r)),L(null)}catch(e){console.error(`[ObjectGantt] Failed to delete:`,e),l(i),L(null)}finally{U(!1)}},[I,C,t,e.objectName,s]);return d?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading Gantt chart...`})})}):p?(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsxs)(`div`,{className:`text-destructive`,children:[`Error: `,p.message]})})}):E?(0,F.jsxs)(`div`,{className:n,children:[(0,F.jsx)(`div`,{className:`h-[calc(100vh-200px)] min-h-[600px]`,children:(0,F.jsx)(z,{tasks:j,onTaskClick:e=>{P.handleClick(e.data),r?.(e.data)},onTaskUpdate:re,onTaskDelete:W,inlineEdit:!0})}),P.isOverlay&&P.isOpen&&P.selectedRecord&&(()=>{let n=C?.provider===`object`?C.object:e.objectName,r=P.selectedRecord,i=r.id??r._id;if(!n||i==null)return null;let a=E?.titleField?String(r[E.titleField]??`Task Details`):`Task Details`;return(0,F.jsx)(k,{open:!0,onClose:P.close,title:a,record:r,objectName:n,recordId:i,dataSource:t,objectSchema:_,width:P.width,fullPageHref:O(n,i)??void 0,onFieldSave:async(e,r)=>{t?.update&&(await t.update(n,String(i),{[e]:r}),l(t=>t.map(t=>String(t.id??t._id)===String(i)?{...t,[e]:r}:t)))},onDelete:async()=>{t?.delete&&(await t.delete(n,String(i)),l(e=>e.filter(e=>String(e.id??e._id)!==String(i))))}})})(),(0,F.jsx)(ee,{open:!!I,onOpenChange:e=>{!e&&!R&&L(null)},children:(0,F.jsxs)(m,{children:[(0,F.jsxs)(g,{children:[(0,F.jsx)(v,{children:`Delete this task?`}),(0,F.jsx)(y,{children:I?(0,F.jsxs)(F.Fragment,{children:[`"`,I.title,`" will be permanently removed. This action cannot be undone.`]}):null})]}),(0,F.jsxs)(T,{children:[(0,F.jsx)(S,{disabled:R,children:`Cancel`}),(0,F.jsx)(x,{onClick:e=>{e.preventDefault(),G()},disabled:R,"data-testid":`gantt-delete-confirm`,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:R?`Deleting…`:`Delete`})]})]})})]}):(0,F.jsx)(`div`,{className:n,children:(0,F.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,F.jsx)(`div`,{className:`text-muted-foreground`,children:`Gantt configuration required. Please specify startDateField, endDateField, and titleField.`})})})},W=t({GanttView:()=>z,ObjectGantt:()=>U,ObjectGanttRenderer:()=>G}),G=({schema:e})=>{let{dataSource:t}=o()||{};return(0,F.jsx)(U,{schema:e,dataSource:t})};s.register(`object-gantt`,G,{namespace:`plugin-gantt`,label:`Object Gantt`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`gantt`,type:`object`,label:`Gantt Config`,description:`startDateField, endDateField, titleField, progressField, percentageField, colorField, dependenciesField`}]}),s.register(`gantt`,G,{namespace:`view`,label:`Gantt View`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`gantt`,type:`object`,label:`Gantt Config`,description:`startDateField, endDateField, titleField, progressField, percentageField, colorField, dependenciesField`}]});export{W as t};
@@ -0,0 +1,6 @@
1
+ import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{r as n,v as r,y as i}from"./vendor-react-BMpe6Iqg.js";import{D as a,H as o,I as s,L as c,N as l,Q as u,R as d,U as f,at as p,dt as m,ot as h,r as g}from"./framework-Bg_8y02a.js";import{$t as _,A as v,Ao as y,B as ee,Bn as b,Bt as x,Ci as S,D as C,Da as te,E as w,Fn as ne,Fr as T,Go as re,Ht as E,In as ie,Jr as D,Ln as O,Mo as k,Mr as A,N as j,Pr as ae,Q as oe,Qn as se,Qs as ce,Qt as le,Rn as ue,Rr as M,Rt as N,S as de,Si as fe,Ti as pe,Us as me,Ut as P,Vs as he,Vt as F,Wr as ge,Xa as _e,Xt as ve,Y as I,Yo as ye,Ys as L,Zt as be,a as xe,ai as Se,an as Ce,at as R,bs as we,c as Te,cn as z,cs as Ee,ct as De,en as Oe,f as ke,i as Ae,in as je,is as Me,it as Ne,kr as Pe,l as B,lt as Fe,m as Ie,mn as Le,mr as V,ns as H,on as Re,ot as ze,q as Be,r as Ve,ri as He,rt as Ue,s as We,st as Ge,us as Ke,wi as qe,xr as Je,yo as Ye,zn as U,zt as W}from"./ui-components-C7AytqY9.js";var G=e(i(),1),K={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},q=[`xs`,`sm`,`md`,`lg`,`xl`,`2xl`];function J(e){for(let t=q.length-1;t>=0;t--){let n=q[t];if(e>=K[n])return n}return`xs`}function Xe(){let[e,t]=(0,G.useState)(()=>typeof window<`u`?window.innerWidth:1024);(0,G.useEffect)(()=>{if(typeof window>`u`)return;let e,n=()=>{clearTimeout(e),e=setTimeout(()=>{t(window.innerWidth)},100)};return window.addEventListener(`resize`,n),()=>{clearTimeout(e),window.removeEventListener(`resize`,n)}},[]);let n=J(e),r=q.indexOf(n);return{breakpoint:n,width:e,isMobile:r<q.indexOf(`md`),isTablet:r>=q.indexOf(`md`)&&r<q.indexOf(`lg`),isDesktop:r>=q.indexOf(`lg`),isAbove:t=>e>=K[t],isBelow:t=>e<K[t]}}function Ze(e){let{onRefresh:t,threshold:n=80,enabled:r=!0}=e,i=(0,G.useRef)(null),[a,o]=(0,G.useState)(!1),[s,c]=(0,G.useState)(0),l=(0,G.useRef)(0),u=(0,G.useCallback)(e=>{if(!r||a)return;let t=i.current;t&&t.scrollTop===0&&(l.current=e.touches[0].clientY)},[r,a]),d=(0,G.useCallback)(e=>{if(!r||a||!l.current)return;let t=e.touches[0].clientY-l.current;t>0&&c(Math.min(t,n*1.5))},[r,a,n]),f=(0,G.useCallback)(async()=>{if(!r||a)return;let e=s;if(c(0),l.current=0,e>=n){o(!0);try{await t()}finally{o(!1)}}},[r,a,s,n,t]);return(0,G.useEffect)(()=>{let e=i.current;if(!(!e||!r))return e.addEventListener(`touchstart`,u,{passive:!0}),e.addEventListener(`touchmove`,d,{passive:!0}),e.addEventListener(`touchend`,f,{passive:!0}),()=>{e.removeEventListener(`touchstart`,u),e.removeEventListener(`touchmove`,d),e.removeEventListener(`touchend`,f)}},[u,d,f,r]),{ref:i,isRefreshing:a,pullDistance:s}}var Y=n(),X=(0,G.createContext)(null);X.displayName=`MobileContext`;function Qe({pwa:e,offline:t,children:n}){let r=Xe(),i=(0,G.useMemo)(()=>({...r,pwa:e,offline:t}),[r,e,t]);return(0,Y.jsx)(X.Provider,{value:i,children:n})}var $e={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 Z(e){return e.startsWith(`bg-`)?e:$e[e.toLowerCase().trim()]}function et(e){return(0,G.useCallback)(t=>{if(!e?.field||!e.colors)return;let n=String(t[e.field]??``),r=e.colors[n];if(r)return Z(r)},[e?.field,e?.colors])}function tt(e){if(e==null||e===``)return``;if(Array.isArray(e))return e.map(e=>tt(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 nt(e,t){return tt(e[t])}function rt(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 rt(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 it(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 at(e,t,n){let r=e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`});return n===`desc`?-r:r}function ot(e,t,n,r){let i=e?.fields,a=!!(i&&i.length>0),[o,s]=(0,G.useState)({});return{groups:(0,G.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=nt(e,c.field);l.has(t)||(l.set(t,{label:rt(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)=>at(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?it(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,G.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 st=({groupKey:e,label:t,count:n,collapsed:r,aggregations:i,fieldLabel:a,labelColorClass:o,onToggle:s,children:c})=>{let l=o?L(`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium`,o):`inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs font-medium text-foreground`;return(0,Y.jsxs)(`div`,{"data-testid":`group-row-${e}`,className:`group/grouprow`,children:[a&&(0,Y.jsx)(`div`,{className:`px-1 pb-1 text-[11px] font-medium text-muted-foreground tracking-wide group-label-caption`,children:a}),(0,Y.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:()=>s(e),"aria-expanded":!r,children:[r?(0,Y.jsx)(Ee,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Y.jsx)(Ke,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:L(l,`group-label`),children:t}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums group-count`,children:n}),i&&i.length>0&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground group-aggregations`,children:i.map(e=>(0,Y.jsxs)(`span`,{className:`mr-2`,children:[e.type,`: `,Number.isInteger(e.value)?e.value:e.value.toFixed(2)]},`${e.field}-${e.type}`))})]}),!r&&(0,Y.jsx)(`div`,{className:`mt-1 ml-1.5 pl-3 border-l border-border/60`,children:c})]})};function ct(e){return typeof e==`string`?{type:e}:e}function lt(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 ut(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 dt(e,t,n){return(0,G.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=ct(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=lt(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:ut(e.type,s,l)})}return{summaries:r,hasSummary:r.size>0}},[e,t,n])}var ft={"grid.openMenu":`Open menu`,"grid.edit":`Edit`,"grid.delete":`Delete`};function pt(){try{let{t:e}=g();return t=>{let n=e(t);return n===t?ft[t]??t:n}}catch{return e=>ft[e]??e}}function mt(e){return e.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var ht=({def:e,row:t,onActionDef:n})=>{let r=c(s(e.visible),t);return e.visible&&!r?null:(0,Y.jsx)(z,{onClick:()=>n?.(e,t),"data-testid":`row-action-${e.name}`,className:e.variant===`danger`?`text-destructive focus:text-destructive`:void 0,children:e.label??mt(e.name)})};function gt(e){switch(e){case`danger`:return`destructive`;case`secondary`:return`secondary`;case`ghost`:return`ghost`;case`link`:return`link`;default:return`default`}}var Q=({def:e,row:t,onActionDef:n})=>{let r=c(s(e.visible),t);return e.visible&&!r?null:(0,Y.jsx)(V,{variant:gt(e.variant),size:`sm`,className:`h-8`,"data-testid":`row-action-inline-${e.name}`,onClick:r=>{r.stopPropagation(),n?.(e,t)},children:e.label??mt(e.name)})},_t=({row:e,rowActions:t,rowActionDefs:n,canEdit:r,canDelete:i,onEdit:a,onDelete:o,onAction:s,onActionDef:c})=>{let l=pt(),u=(n??[]).filter(e=>e.variant===`primary`),d=(n??[]).filter(e=>e.variant!==`primary`),f=!!(r&&a||i&&o||d.length>0||(t?.length??0)>0);return(0,Y.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[u.map(t=>(0,Y.jsx)(Q,{def:t,row:e,onActionDef:c},t.name)),f&&(0,Y.jsxs)(Ce,{children:[(0,Y.jsx)(Le,{asChild:!0,children:(0,Y.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,Y.jsx)(y,{className:`h-4 w-4`}),(0,Y.jsx)(`span`,{className:`sr-only`,children:l(`grid.openMenu`)})]})}),(0,Y.jsxs)(Re,{align:`end`,onClick:e=>e.stopPropagation(),children:[r&&a&&(0,Y.jsxs)(z,{onClick:()=>a(e),children:[(0,Y.jsx)(He,{className:`mr-2 h-4 w-4`}),l(`grid.edit`)]}),i&&o&&(0,Y.jsxs)(z,{onClick:()=>o(e),children:[(0,Y.jsx)(M,{className:`mr-2 h-4 w-4`}),l(`grid.delete`)]}),d.map(t=>(0,Y.jsx)(ht,{def:t,row:e,onActionDef:c},t.name)),t?.map(t=>(0,Y.jsx)(z,{onClick:()=>s?.(t,e),"data-testid":`row-action-${t}`,children:mt(t)},t))]})]})]})},vt=({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,Y.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,Y.jsx)(`div`,{className:`flex items-center gap-2 text-[11px] text-muted-foreground`,"data-testid":`bulk-cross-page-banner`,children:c?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Se,{className:`h-3 w-3 text-primary shrink-0`}),(0,Y.jsxs)(`span`,{children:[`All `,s,` matching records are selected.`]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`span`,{children:[`All `,o,` on this page are selected.`]}),(0,Y.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,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(Se,{className:`h-3.5 w-3.5 text-primary shrink-0`}),(0,Y.jsx)(`span`,{className:`font-medium tabular-nums`,children:(0,Y.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,Y.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?I(t.icon):null;return(0,Y.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,Y.jsx)(Be,{name:r,className:`h-3 w-3`}):n?(0,Y.jsx)(M,{className:`h-3 w-3`}):null,t.label??mt(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?M:null;return(0,Y.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,Y.jsx)(a,{className:`h-3 w-3`}),mt(t)]},t)})]}),(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs ml-auto gap-1`,onClick:a,children:[(0,Y.jsx)(Je,{className:`h-3 w-3`}),`Clear`]})]})]})};function yt({resource:e,dataSource:t}){let[n,r]=(0,G.useState)({total:0,done:0,failed:0,inFlight:!1}),[i,a]=(0,G.useState)(null),o=(0,G.useRef)([]),s=(0,G.useRef)(null),c=(0,G.useCallback)(()=>{r({total:0,done:0,failed:0,inFlight:!1}),a(null),o.current=[],s.current=null},[]);return{run:(0,G.useCallback)(async(n,i,c)=>{let l=i.length,d=Math.max(1,n.batchSize??200),f=[],p=0,m=0;a(null),r({total:l,done:0,failed:0,inFlight:!0});let h=()=>({...n.patch??{},...c}),g=[];if(n.operation===`update`){let e=Object.keys(h());for(let t of i){let n=String(t.id??``);if(!n)continue;let r={};for(let n of e)r[n]=t[n];g.push({id:n,prev:r})}}for(let a=0;a<i.length;a+=d){let o=i.slice(a,a+d),s=[];for(let e=0;e<o.length;e+=1){let t=o[e].id==null?``:String(o[e].id);t?s.push(t):(m+=1,f.push({id:`index_${a+e}`,error:`Missing record id`}))}if(s.length===0){r({total:l,done:p,failed:m,inFlight:!0});continue}let c=s.length>=2,g,_=`bulk`;n.operation===`update`&&typeof t.bulkUpdate==`function`?(g=n=>t.bulkUpdate(e,n,h()),_=`bulk update`):n.operation===`delete`&&typeof t.bulkDelete==`function`&&(g=n=>t.bulkDelete(e,n),_=`bulk delete`);let v=await u({ids:s,originalSize:o.length,offset:a,allowBulk:c,label:_},{bulkCall:g,perRow:r=>{switch(n.operation){case`delete`:return t.delete(e,r);case`update`:return t.update(e,r,h());case`custom`:return Promise.resolve();default:return Promise.reject(Error(`Unknown operation: ${n.operation}`))}}});p+=v.succeeded,m+=v.failed,f.push(...v.errors),r({total:l,done:p,failed:m,inFlight:!0})}let _={total:l,succeeded:p,failed:m,errors:f},v=new Set(f.map(e=>e.id));return o.current=g.filter(e=>!v.has(e.id)),s.current={def:n,rows:i,params:c},r({total:l,done:p,failed:m,inFlight:!1}),a(_),p>0&&w.invalidate(e),_},[e,t]),undo:(0,G.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,G.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 bt=({def:e,rows:t,resource:n,dataSource:r,open:i,onClose:a,labelKey:o=`name`})=>{let s=e?.params??[],c=(0,G.useMemo)(()=>{let e={};for(let t of s)t.default!==void 0&&(e[t.name]=t.default);return e},[e?.name]),[l,u]=(0,G.useState)(`params`),[d,f]=(0,G.useState)(c),[p,m]=(0,G.useState)({}),{run:h,undo:g,retry:_,progress:v,result:y,reset:ee}=yt({resource:n,dataSource:r}),[x,S]=(0,G.useState)(null),[C,w]=(0,G.useState)(!1),[re,E]=(0,G.useState)(null);(0,G.useEffect)(()=>{i&&(ee(),f(c),E(null),w(!1),S(null),u(s.length===0?`confirm`:`params`))},[i,e?.name,c,s.length,ee]),(0,G.useEffect)(()=>{if(!i||typeof r.find!=`function`)return;let e=s.filter(e=>e.type===`lookup`&&e.object&&!p[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||m(e=>({...e,...n}))})(),()=>{t=!0}},[i,e?.name]);let D=(0,G.useMemo)(()=>{for(let e of s)if(e.required){let t=d[e.name];if(t==null||t===``)return!1}return!0},[s,d]),k=e?.maxRecords??1/0,A=t.length>k,j=(0,G.useCallback)(async()=>{e&&(u(`running`),await h(e,t,d),u(`result`))},[e,t,d,h]),ae=(0,G.useCallback)(()=>{if(!y?.errors?.length)return;let t=[`record_id,error_message`,...y.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)},[y,e?.name]),oe=!!e&&e.operation===`update`&&!!y&&y.succeeded>0&&re===null,se=(0,G.useCallback)(async()=>{w(!0);try{await g()&&E(Date.now())}finally{w(!1)}},[g]),ce=(0,G.useCallback)(async e=>{S(e);try{await _(e)}finally{S(null)}},[_]);if(!e)return null;let le=e.label??e.name,M=t.slice(0,5),N=Math.max(0,t.length-M.length);return(0,Y.jsx)(ne,{open:i,onOpenChange:e=>{e||a(y)},children:(0,Y.jsxs)(ie,{className:`max-w-md`,children:[(0,Y.jsxs)(U,{children:[(0,Y.jsxs)(b,{className:`flex items-center gap-2`,children:[l===`running`&&(0,Y.jsx)(te,{className:`h-4 w-4 animate-spin`}),le]}),l===`confirm`&&(0,Y.jsx)(O,{children:e.confirmText??`This will apply to ${t.length} record${t.length===1?``:`s`}.`})]}),l===`params`&&(0,Y.jsx)(`div`,{className:`space-y-3`,children:s.map(e=>(0,Y.jsx)(St,{param:e,value:d[e.name],lookupOptions:p[e.name],onChange:t=>f(n=>({...n,[e.name]:t}))},e.name))}),l===`confirm`&&(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[A&&(0,Y.jsxs)(`div`,{className:`rounded-md bg-destructive/10 text-destructive px-3 py-2 flex items-start gap-2`,children:[(0,Y.jsx)(T,{className:`h-4 w-4 mt-0.5 shrink-0`}),(0,Y.jsxs)(`div`,{children:[`Selection (`,t.length,`) exceeds the action limit (`,k,`). Reduce the selection to proceed.`]})]}),(0,Y.jsxs)(`div`,{className:`text-muted-foreground`,children:[`Affected records (`,t.length,`):`]}),(0,Y.jsx)(P,{className:`max-h-32 rounded border bg-muted/30 p-2`,children:(0,Y.jsxs)(`ul`,{className:`text-xs space-y-1`,children:[M.map((e,t)=>(0,Y.jsxs)(`li`,{className:`truncate`,children:[`• `,String(e[o]??e.id??`Row ${t+1}`)]},String(e.id??t))),N>0&&(0,Y.jsxs)(`li`,{className:`text-muted-foreground`,children:[`… and `,N,` more`]})]})}),Object.keys(d).length>0&&(0,Y.jsx)(`div`,{className:`rounded border bg-muted/30 p-2 text-xs space-y-0.5`,children:Object.entries(d).map(([e,t])=>(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`span`,{className:`text-muted-foreground`,children:[e,`:`]}),` `,xt(t)]},e))})]}),l===`running`&&(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(ve,{value:v.total?(v.done+v.failed)/v.total*100:0}),(0,Y.jsxs)(`div`,{className:`text-xs text-muted-foreground text-center`,children:[v.done+v.failed,` / `,v.total,` processed`,v.failed>0&&` · ${v.failed} failed`]})]}),l===`result`&&y&&(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[y.failed===0?(0,Y.jsx)(H,{className:`h-5 w-5 text-emerald-500`}):(0,Y.jsx)(T,{className:`h-5 w-5 text-amber-500`}),(0,Y.jsxs)(`span`,{children:[re===null?``:`Undone — `,`Succeeded `,y.succeeded,` / `,y.total,y.failed>0&&` · Failed ${y.failed}`]})]}),y.errors.length>0&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(P,{className:`max-h-48 rounded border bg-destructive/5 p-2`,"data-testid":`bulk-error-inspector`,children:(0,Y.jsx)(`ul`,{className:`text-xs space-y-1.5`,children:y.errors.map(t=>(0,Y.jsxs)(`li`,{className:`flex items-start gap-2`,"data-testid":`bulk-error-row-${t.id}`,children:[(0,Y.jsx)(ye,{className:`h-3 w-3 mt-0.5 shrink-0 text-destructive`}),(0,Y.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Y.jsxs)(`div`,{className:`truncate`,children:[(0,Y.jsxs)(`span`,{className:`text-muted-foreground`,children:[t.id,`:`]}),` `,t.error]})}),e.operation!==`custom`&&(0,Y.jsx)(V,{variant:`ghost`,size:`sm`,className:`h-5 px-1.5 text-[10px]`,onClick:()=>ce(t.id),disabled:x===t.id,"data-testid":`bulk-error-retry-${t.id}`,children:x===t.id?`…`:`Retry`})]},t.id))})}),(0,Y.jsx)(V,{variant:`outline`,size:`sm`,onClick:ae,children:`Download error CSV`})]})]}),(0,Y.jsxs)(ue,{children:[l===`params`&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(V,{variant:`ghost`,onClick:()=>a(),children:`Cancel`}),(0,Y.jsx)(V,{onClick:()=>u(`confirm`),disabled:!D,children:`Next`})]}),l===`confirm`&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(V,{variant:`ghost`,onClick:()=>s.length?u(`params`):a(),children:s.length?`Back`:`Cancel`}),(0,Y.jsx)(V,{variant:e.variant===`danger`?`destructive`:`default`,onClick:j,disabled:A,children:e.confirmLabel??`Run`})]}),l===`running`&&(0,Y.jsx)(V,{variant:`ghost`,disabled:!0,children:`Running…`}),l===`result`&&(0,Y.jsxs)(Y.Fragment,{children:[oe&&(0,Y.jsx)(V,{variant:`outline`,onClick:se,disabled:C,"data-testid":`bulk-undo-button`,children:C?`Undoing…`:`Undo`}),(0,Y.jsx)(V,{onClick:()=>a(y),children:`Done`})]})]})]})})};function xt(e){return e==null||e===``?`—`:typeof e==`boolean`?e?`Yes`:`No`:String(e)}var St=({param:e,value:t,onChange:n,lookupOptions:r})=>{let i=`bulk-param-${e.name}`,a=(0,Y.jsxs)(je,{htmlFor:i,className:`text-xs`,children:[e.label??e.name,e.required&&(0,Y.jsx)(`span`,{className:`text-destructive ml-0.5`,children:`*`})]}),o=null;switch(e.type){case`boolean`:o=(0,Y.jsx)(Fe,{id:i,checked:!!t,onCheckedChange:n});break;case`textarea`:o=(0,Y.jsx)(oe,{id:i,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder});break;case`select`:{let r=e.options??[];o=(0,Y.jsxs)(N,{value:t==null?``:String(t),onValueChange:n,children:[(0,Y.jsx)(F,{id:i,children:(0,Y.jsx)(E,{placeholder:e.placeholder??`Select…`})}),(0,Y.jsx)(W,{children:r.map(e=>(0,Y.jsx)(x,{value:String(e.value),children:e.label},String(e.value)))})]});break}case`lookup`:{let a=r??[];o=(0,Y.jsxs)(N,{value:t??``,onValueChange:n,children:[(0,Y.jsx)(F,{id:i,children:(0,Y.jsx)(E,{placeholder:a.length===0?`Loading…`:e.placeholder??`Select…`})}),(0,Y.jsx)(W,{children:a.map(e=>(0,Y.jsx)(x,{value:e.value,children:e.label},e.value))})]});break}case`number`:o=(0,Y.jsx)(Oe,{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,Y.jsx)(Oe,{id:i,type:`text`,value:t??``,onChange:e=>n(e.target.value),placeholder:e.placeholder})}return(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(`div`,{className:`flex items-center justify-between`,children:a}),o,e.help&&(0,Y.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e.help})]})},Ct=({testId:e,onActivate:t,children:n})=>(0,Y.jsx)(`span`,{role:`link`,tabIndex:0,"data-testid":e,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer truncate block max-w-full`,onClick:e=>{e.stopPropagation(),t()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),t())},children:n}),wt={"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 Tt(){try{let e=g();return e.t(`grid.actions`)===`grid.actions`?{t:(e,t)=>{let n=wt[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=wt[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}}}function Et(e){if(e!=null)return typeof e==`string`?e:void 0}function Dt(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 Ot(e){if(!(!e||e.length===0))return typeof e[0]==`object`&&e[0],e}var kt=({schema:e,dataSource:t,onEdit:n,onDelete:r,onBulkDelete:i,onRowSelect:s,onRowClick:c,onCellChange:u,onRowSave:f,onBatchSave:m,onAddRecord:g,...y})=>{let[b,x]=(0,G.useState)([]),[te,w]=(0,G.useState)(!0),[ne,T]=(0,G.useState)(null),{t:E}=Tt(),{fieldLabel:ie,translateOptions:O}=ce(),[A,oe]=(0,G.useState)(null),[ue,M]=(0,G.useState)(!1),[N,fe]=(0,G.useState)(0),[me,P]=(0,G.useState)(!1),[he,F]=(0,G.useState)(!1),ve=de({dataSource:t}),[I,ye]=(0,G.useState)(e.rowHeight??`compact`),[L,Ce]=(0,G.useState)([]),[R,z]=(0,G.useState)(!1),[Ee,De]=(0,G.useState)(void 0),[Oe,je]=(0,G.useState)(null),[Me,Ne]=(0,G.useState)([]),Fe=G.useRef(null);G.useEffect(()=>{e.rowHeight&&e.rowHeight!==I&&ye(e.rowHeight)},[e.rowHeight]);let Le=G.useMemo(()=>e.id?`grid-columns-${e.objectName}-${e.id}`:`grid-columns-${e.objectName}`,[e.objectName,e.id]),[H,Re]=(0,G.useState)(()=>{let t=e.columnState;if(t&&typeof t==`object`)return t;try{let e=localStorage.getItem(Le);return e?JSON.parse(e):{}}catch{return{}}}),ze=G.useMemo(()=>JSON.stringify(e.columnState??null),[e.columnState]);G.useEffect(()=>{let t=e.columnState;t&&typeof t==`object`&&Re(t)},[ze]);let Be=(0,G.useCallback)(e=>{Re(e);try{localStorage.setItem(Le,JSON.stringify(e))}catch(e){console.warn(`Failed to persist column state:`,e)}let t=y.onColumnStateChange;if(typeof t==`function`)try{t(e)}catch(e){console.warn(`onColumnStateChange threw:`,e)}},[Le,y]),{ref:He,isRefreshing:Ue,pullDistance:Ge}=Ze({onRefresh:(0,G.useCallback)(async()=>{fe(e=>e+1)},[]),enabled:!!t&&!!e.objectName});(0,G.useEffect)(()=>{let e=()=>M(window.innerWidth<480);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let Ke=y.data,Je=o(e.bind),Ye=Dt(e),U=G.useMemo(()=>Ke&&Array.isArray(Ke)?{provider:`value`,items:Ke}:Je&&Array.isArray(Je)?{provider:`value`,items:Je}:Ye,[JSON.stringify(Ye),Je,Ke]),W=U?.provider===`value`,K=U?.provider===`object`&&U&&`object`in U?U.object:e.objectName,q=e.fields,J=e.columns,Xe=e.filter,X=e.sort,Qe=e.pagination,$e=e.pageSize;(0,G.useEffect)(()=>{W&&U?.provider===`value`&&(x(e=>{let t=U.items;return JSON.stringify(e)===JSON.stringify(t)?e:t}),w(!1))},[W,U]),(0,G.useEffect)(()=>{if(!W||!K||!t)return;let e=!1;return(async()=>{try{if(typeof t.getObjectSchema!=`function`)return;let n=await t.getObjectSchema(K);e||oe(n)}catch(e){console.warn(`[ObjectGrid] Failed to fetch objectSchema for inline data (objectName: ${K}):`,e)}})(),()=>{e=!0}},[W,K,t]),(0,G.useEffect)(()=>{if(W)return;let n=!1;return(async()=>{w(!0),T(null);try{let r=null,i=Ot(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||oe(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};Xe&&Array.isArray(Xe)?i.$filter=Xe: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=h(r?.fields,J??q);a.length>0&&(i.$expand=a);let o=await t.find(K,i);if(n)return;x(o.data||[]);let s=o.total;De(typeof s==`number`?s:void 0),Fe.current={...i},z(!1)}}catch(e){n||T(e)}finally{n||w(!1)}})(),()=>{n=!0}},[K,q,J,Xe,X,Qe,$e,t,W,U,N]);let Z=l({navigation:e.navigation,objectName:e.objectName,onNavigate:e.onNavigate,onRowClick:c}),{execute:tt}=a(),nt=et(e.rowColor),rt=(0,G.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=p(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]),it=G.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=A?.fields?.[t],a=Ot(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 E(`grid.booleanTrue`,`Yes`);if(t===!1||t===`false`)return E(`grid.booleanFalse`,`No`)}}}},[e.grouping,e.columns,e.objectName,A,O,E]),{groups:at,isGrouped:ct,toggleGroup:lt}=ot(e.grouping,b,e.aggregations,it),{summaries:ut,hasSummary:ft}=dt(G.useMemo(()=>{let t=Ot(e.columns);if(t&&t.length>0&&typeof t[0]==`object`)return t},[e.columns]),b,A?.fields),pt=(0,G.useCallback)(()=>{let t=e=>e&&{text:(0,Y.jsx)(ae,{className:`h-3.5 w-3.5`}),number:(0,Y.jsx)(_e,{className:`h-3.5 w-3.5`}),currency:(0,Y.jsx)(_e,{className:`h-3.5 w-3.5`}),percent:(0,Y.jsx)(_e,{className:`h-3.5 w-3.5`}),date:(0,Y.jsx)(we,{className:`h-3.5 w-3.5`}),datetime:(0,Y.jsx)(re,{className:`h-3.5 w-3.5`}),boolean:(0,Y.jsx)(Se,{className:`h-3.5 w-3.5`}),user:(0,Y.jsx)(Pe,{className:`h-3.5 w-3.5`}),select:(0,Y.jsx)(D,{className:`h-3.5 w-3.5`})}[e]||(0,Y.jsx)(ae,{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(b.length>0){let t=b.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))&&b.length>0&&typeof b.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`percent`;if([`status`,`priority`,`category`,`stage`,`type`,`severity`,`level`].some(e=>t.includes(e))&&b.length>0){let t=new Set(b.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))&&b.length>0&&typeof b.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`currency`;if(b.length>0){let t=b.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=Ot(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=B(i),o={name:r.accessorKey,type:i};return i===`select`&&(o.options=Array.from(new Set(b.map(e=>e[r.accessorKey]).filter(Boolean))).map(e=>({value:e,label:ke(String(e))}))),r.appearance!=null&&(o.appearance=r.appearance),{...r,...e.showColumnTypeIcons&&{headerIcon:t(i)},cell:e=>(0,Y.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=Et(r.label)||r.field.charAt(0).toUpperCase()+r.field.slice(1).replace(/_/g,` `),o=e.objectName?ie(e.objectName,r.field,a):a,s,c=A?.fields?.[r.field],l=r.type||c?.type||n({field:r.field})||null,u=r.format??c?.format,d=l?Ie({type:l,format:u}):null,f=d?B(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(b.map(e=>e[r.field]).filter(Boolean))).map(e=>({value:e,label:ke(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,Y.jsx)(Ct,{testId:h?`primary-field-link`:`link-cell`,onActivate:()=>Z.handleClick(t),children:f?(0,Y.jsx)(f,{value:e,field:p}):e!=null&&e!==``?String(e):(0,Y.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):r.action?(e,t)=>(0,Y.jsx)(V,{variant:`outline`,size:`sm`,className:`h-7 text-xs`,"data-testid":`action-cell`,onClick:n=>{n.stopPropagation(),tt({type:r.action,params:{record:t,field:r.field,value:e}})},children:mt(r.action)}):f?e=>(0,Y.jsx)(f,{value:e,field:p}):e=>e!=null&&e!==``?(0,Y.jsx)(`span`,{children:String(e)}):(0,Y.jsx)(ee,{});let _=r.prefix;if(_?.field){let e=s,t=_.type===`badge`?B(`select`):null;s=(n,r)=>{let i=r[_.field];return(0,Y.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[i!=null&&i!==``?t?(0,Y.jsx)(t,{value:i,field:{name:_.field,type:`select`}}):(0,Y.jsx)(`span`,{className:`text-muted-foreground text-xs mr-1.5`,children:String(i)}):null,e(n,r)]})}}let v=[`number`,`currency`,`percent`],y=d||r.type,x=r.align||(y&&v.includes(y)?`right`:void 0),S=i===0||r.essential===!0;return{header:o,accessorKey:r.field,...e.showColumnTypeIcons&&{headerIcon:t(d)},...!S&&{className:`hidden sm:table-cell`},...r.width&&{width:r.width},...x&&{align:x},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=A?.fields?.[r],o=a?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),s=e.objectName?ie(e.objectName,r,o):o,c=a?.type||n({field:r})||null,l=c?B(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(b.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:ke(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,Y.jsx)(Ct,{testId:`primary-field-link`,onActivate:()=>Z.handleClick(t),children:(0,Y.jsx)(l,{value:e,field:u})}):f?p=(e,t)=>(0,Y.jsx)(Ct,{testId:`primary-field-link`,onActivate:()=>Z.handleClick(t),children:e!=null&&e!==``?String(e):(0,Y.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):l&&(p=e=>(0,Y.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(W){let r=U?.provider===`value`?U.items:[];if(r.length>0)return(q||Object.keys(r[0])).map(r=>{let i=A?.fields?.[r],a=i?.type||n({field:r})||null,o=a?B(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(b.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:ke(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,Y.jsx)(o,{value:e,field:c})},sortable:i?.sortable!==!1}})}if(!A)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=A?.compactLayout,s=Object.keys(A.fields||{}),c;if(q)c=q;else if(o?.length)c=o.filter(e=>A.fields?.[e]);else{let e=s.filter(e=>{let t=A.fields?.[e];return!(!t||t.hidden||t.readonly&&a.has(e))});c=[...e.filter(e=>!a.has(e)),...e.filter(e=>a.has(e))]}return c.forEach(t=>{let n=A.fields?.[t];if(!n||n.permissions&&n.permissions.read===!1)return;let r=B(n.type),a=[`number`,`currency`,`percent`],o=n.options?{...n,options:O(e.objectName,t,n.options)}:n;i.push({header:e.objectName?ie(e.objectName,t,n.label||t):n.label||t,accessorKey:t,...a.includes(n.type)&&{align:`right`},cell:e=>(0,Y.jsx)(r,{value:e,field:o}),sortable:n.sortable!==!1})}),i},[A,q,J,U,W,Z.handleClick,tt,b,ie,O,e.objectName]),ht=(0,G.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`)&&ve.isSupported&&e.objectName&&!W&&n?.streaming!==!1){let n=pt().filter(e=>e.accessorKey!==`_actions`).map(e=>e.accessorKey).filter(Boolean);P(!1),F(!0),ve.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?b.slice(0,r):b,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=pt().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)},[b,e.exportOptions,e.objectName,pt,ve,W]);if(ne)return(0,Y.jsxs)(`div`,{className:`p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md`,children:[(0,Y.jsx)(`h3`,{className:`text-red-800 font-semibold`,children:E(`grid.errorLoading`)}),(0,Y.jsx)(`p`,{className:`text-red-600 text-sm mt-1`,children:ne.message})]});if(te&&b.length===0)return ue?(0,Y.jsx)(`div`,{className:`space-y-2 p-2`,children:[1,2,3].map(e=>(0,Y.jsxs)(`div`,{className:`border rounded-lg p-3 bg-card animate-pulse`,children:[(0,Y.jsx)(`div`,{className:`h-5 bg-muted rounded w-3/4 mb-3`}),(0,Y.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Y.jsx)(`div`,{className:`h-4 bg-muted rounded w-1/4`}),(0,Y.jsx)(`div`,{className:`h-5 bg-muted rounded-full w-20`})]}),(0,Y.jsx)(`div`,{className:`h-3 bg-muted rounded w-1/3`})]},e))}):(0,Y.jsxs)(`div`,{className:`p-4 sm:p-8 text-center`,children:[(0,Y.jsx)(`div`,{className:`inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-foreground`}),(0,Y.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:E(`grid.loading`)})]});let gt=[...pt()];if(H.widths&&(gt=gt.map(e=>{let t=H.widths?.[e.accessorKey];return t?{...e,size:t}:e})),H.order&&H.order.length>0){let e=new Map(H.order.map((e,t)=>[e,t]));gt.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},yt=Array.isArray(e.rowActions)?e.rowActions:[],xt=Array.isArray(e.rowActionDefs)?e.rowActionDefs:[],St=yt.includes(`edit`),wt=yt.includes(`delete`),kt=yt.filter(e=>e!==`edit`&&e!==`delete`),At=!!((Q?.update||St)&&n),jt=!!((Q?.delete||wt)&&r),$=!!(Q&&(Q.update||Q.delete)),Mt=kt.length>0||xt.length>0||St||wt,Nt=$||Mt?[...gt,{header:E(`grid.actions`),accessorKey:`_actions`,cell:(e,t)=>(0,Y.jsx)(_t,{row:t,rowActions:kt,rowActionDefs:xt,canEdit:At,canDelete:jt,onEdit:n,onDelete:r,onAction:(e,t)=>tt({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},tt(i)}}),sortable:!1}]:gt,Pt=Nt.filter(e=>e.pinned===`left`),Ft=Nt.filter(e=>e.pinned===`right`),It=Nt.filter(e=>!e.pinned),Lt=Pt.length>0||Ft.length>0,Rt=`sticky right-0 z-10 bg-background border-l border-border`,zt=I===`compact`?`px-3 py-1 h-9 text-[13px] leading-tight`:I===`short`?`px-3 py-1 h-9 text-[13px] leading-normal`:I===`tall`?`px-3 py-2.5 h-14 text-sm`:I===`extra_tall`?`px-3 py-3.5 h-16 text-sm leading-relaxed`:`px-3 py-1.5 h-11 text-[13px] leading-normal`,Bt=e=>({...e,cellClassName:[zt,e.cellClassName].filter(Boolean).join(` `)}),Vt=Lt?[...Pt.map(Bt),...It.map(Bt),...Ft.map(e=>({...Bt(e),className:[e.className,Rt].filter(Boolean).join(` `),cellClassName:[zt,e.cellClassName,Rt].filter(Boolean).join(` `)}))]:Nt.map(Bt),Ht=Lt?Pt.length:e.frozenColumns??1,Ut=e.batchActions??e.bulkActions,Wt=Array.isArray(e.bulkActionDefs)?e.bulkActionDefs:[],Gt=Ut&&Ut.length>0?Ut:jt&&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(!R)return n;let r=e.objectName;if(!t||!r)return n;let i={...Fe.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),Ce([]),z(!1);return}tt({type:e,params:{records:n}})})()},Xt=(e,t)=>{(async()=>{let n=await Jt(t);je(e),Ne(n)})()},Zt=e=>{je(null),Ne([]),e&&(Ce([]),z(!1),fe(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:Vt,data:b,pagination:Qt,pageSize:$t,searchable:en,selectable:qt,sortable:!0,exportable:Q?.export,borderless:!0,rowActions:!!(e.editable&&$),resizableColumns:e.resizable??e.resizableColumns??!0,reorderableColumns:e.reorderableColumns??!1,editable:e.editable??!1,singleClickEdit:e.singleClickEdit??!0,className:e.className,cellClassName:I===`compact`?`px-3 py-1 text-[13px] leading-tight`:I===`short`?`px-3 py-1 text-[13px] leading-normal`:I===`tall`?`px-3 py-2.5 text-sm`:I===`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:g,rowClassName:e.rowColor?(e,t)=>nt(e):void 0,rowStyle:e.conditionalFormatting?.length?(e,t)=>rt(e):void 0,frozenColumns:Ht,onSelectionChange:e=>{Ce(e),s?.(e)},onRowClick:Z.handleClick,onCellChange:u,onRowSave:f,onBatchSave:m,onColumnResize:(e,t)=>{Be({...H,widths:{...H.widths,[e]:t}})},onColumnReorder:e=>{Be({...H,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(ue&&b.length>0&&!ct){let e=pt().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,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`space-y-2 p-2`,children:b.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,Y.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,Y.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,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[a&&(0,Y.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:typeof t[a.accessorKey]==`number`?Ve(t[a.accessorKey]):t[a.accessorKey]!=null&&typeof t[a.accessorKey]==`object`?String(t[a.accessorKey]):t[a.accessorKey]??`—`}),o&&t[o.accessorKey]&&(0,Y.jsx)(se,{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,Y.jsxs)(`div`,{className:`flex items-center justify-between py-0.5 text-xs text-muted-foreground`,children:[u[0]&&(0,Y.jsx)(`span`,{className:`tabular-nums`,children:t[u[0].accessorKey]?xe(t[u[0].accessorKey],`short`):`—`}),d[0]&&t[d[0].accessorKey]!=null&&(0,Y.jsx)(`span`,{className:`tabular-nums`,children:We(Number(t[d[0].accessorKey]))})]}),u.slice(1).map(e=>(0,Y.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground tabular-nums`,children:t[e.accessorKey]?xe(t[e.accessorKey],`short`):`—`})]},e.accessorKey)),f.map(e=>{let n=t[e.accessorKey];return n==null||n===``?null:(0,Y.jsxs)(`div`,{className:`flex justify-between items-center py-0.5`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.header}),(0,Y.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,Y.jsx)(j,{...Z,title:rn,children:e=>(0,Y.jsx)(`div`,{className:`space-y-3`,children:Object.entries(e).map(([e,t])=>(0,Y.jsxs)(`div`,{className:`flex flex-col`,children:[(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:e.replace(/_/g,` `)}),(0,Y.jsx)(`span`,{className:`text-sm`,children:String(t??`—`)})]},e))})})]})}let an=()=>{ye(e=>e===`compact`?`short`:e===`short`?`medium`:e===`medium`?`tall`:e===`tall`?`extra_tall`:`compact`)},on={compact:S,short:qe,medium:pe,tall:ge,extra_tall:ge}[I],sn=e.rowHeight!==void 0&&!e.hideRowHeightToggle,cn=e.exportOptions||sn?(0,Y.jsxs)(`div`,{className:`flex items-center justify-end gap-1 px-2 py-1`,children:[sn&&(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,onClick:an,title:`Row height: ${I}`,children:[(0,Y.jsx)(on,{className:`h-3.5 w-3.5 mr-1.5`}),(0,Y.jsx)(`span`,{className:`hidden sm:inline capitalize`,children:I})]}),e.exportOptions&&(0,Y.jsxs)(be,{open:me,onOpenChange:P,children:[(0,Y.jsx)(_,{asChild:!0,children:(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,children:[(0,Y.jsx)(k,{className:`h-3.5 w-3.5 mr-1.5`}),(0,Y.jsx)(`span`,{className:`hidden sm:inline`,children:E(`grid.export`)})]})}),(0,Y.jsx)(le,{align:`end`,className:`w-48 p-2`,children:(0,Y.jsx)(`div`,{className:`space-y-1`,children:(e.exportOptions.formats||[`csv`,`json`]).map(e=>(0,Y.jsxs)(V,{variant:`ghost`,size:`sm`,className:`w-full justify-start h-8 text-xs`,onClick:()=>ht(e),children:[(0,Y.jsx)(k,{className:`h-3.5 w-3.5 mr-2`}),E(`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=>A?.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,Y.jsx)(`span`,{className:`text-muted-foreground/50 text-sm italic`,children:E(`grid.empty`)});let n=A?.fields?.[e];if(n?.type){let e=B(n.type);if(e)return(0,Y.jsx)(e,{value:t,field:n})}return typeof t==`boolean`?(0,Y.jsx)(se,{variant:t?`default`:`outline`,children:E(t?`grid.yes`:`grid.no`)}):typeof t==`string`&&!isNaN(Date.parse(t))&&(e.includes(`date`)||e.includes(`_at`)||e.includes(`time`))?(0,Y.jsx)(`span`,{className:`text-sm tabular-nums`,children:xe(t)}):typeof t==`number`&&[`amount`,`price`,`total`,`revenue`,`cost`,`value`,`budget`,`salary`].some(t=>e.toLowerCase().includes(t))?(0,Y.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:Ae(t)}):(0,Y.jsx)(`span`,{className:`text-sm break-words`,children:String(t)})};return(0,Y.jsxs)(`div`,{className:`space-y-4`,"data-testid":`record-detail-panel`,children:[(0,Y.jsx)(`div`,{className:`rounded-lg border bg-card`,children:(0,Y.jsx)(`div`,{className:`divide-y`,children:i.map(([e,t])=>(0,Y.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-start gap-1 sm:gap-4 px-4 py-3`,children:[(0,Y.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,Y.jsx)(`div`,{className:`flex-1 min-w-0`,children:s(e,t)})]},e))})}),a.length>0&&(0,Y.jsxs)(`div`,{className:`rounded-lg border bg-muted/30`,children:[(0,Y.jsx)(`div`,{className:`px-4 py-2 border-b`,children:(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:E(`grid.systemFields`)})}),(0,Y.jsx)(`div`,{className:`divide-y divide-border/50`,children:a.map(([e,t])=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-4 px-4 py-2`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground w-1/3 text-right shrink-0`,children:o(e)}),(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1 min-w-0 break-words`,children:String(t??``)})]},e))})]})]})},un=ft?(0,Y.jsx)(`div`,{className:`border-t bg-muted/30 px-2 py-1.5`,"data-testid":`column-summary-footer`,children:(0,Y.jsx)(`div`,{className:`flex gap-4 text-xs text-muted-foreground font-medium`,children:Vt.filter(e=>ut.has(e.accessorKey)).map(e=>{let t=ut.get(e.accessorKey);return(0,Y.jsxs)(`span`,{"data-testid":`summary-${e.accessorKey}`,children:[e.header,`: `,t.label]},e.accessorKey)})})}):null,dn=(t,n)=>{let r=A?.fields?.[t],i=e.objectName?ie(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=Te(o?.color,o?.value??n)}return{fieldLabel:i,labelColorClass:a}},fn=e=>{let{fieldLabel:t,labelColorClass:n}=dn(e.field,e.label);return(0,Y.jsx)(`div`,{children:(0,Y.jsx)(st,{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:lt,children:e.subgroups.length>0?(0,Y.jsx)(`div`,{className:`space-y-4 mt-2`,children:e.subgroups.map(fn)}):(0,Y.jsx)(d,{schema:nn(e.rows)})})},e.key)},pn=ct?(0,Y.jsx)(`div`,{className:`space-y-4 px-3 sm:px-4 pt-2 pb-4`,children:at.map(fn)}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(d,{schema:tn}),un]}),mn=(0,Y.jsx)(C,{open:he,onOpenChange:F,job:ve,filename:`${e.exportOptions?.fileNamePrefix||e.objectName||`export`}.${ve.progress?.format||`csv`}`,closeAfterDownloadMs:400}),hn=(0,Y.jsx)(bt,{def:Oe,rows:Me,open:!!Oe,onClose:Zt,dataSource:t,resource:e.objectName??``});return Z.isOverlay&&Z.mode===`split`?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(j,{...Z,title:rn,mainContent:(0,Y.jsxs)(Y.Fragment,{children:[cn,pn,(0,Y.jsx)(vt,{selectedRows:L,actions:Gt??[],actionDefs:Wt,onAction:Yt,onActionDef:Xt,onClearSelection:()=>{Ce([]),z(!1)},pageSize:b.length,totalMatching:Ee,allMatchingSelected:R,onSelectAllMatching:()=>z(!0)})]}),children:e=>ln(e)}),mn,hn]}):(0,Y.jsxs)(`div`,{ref:He,className:`relative h-full`,children:[(0,Y.jsx)(v,{active:te&&b.length>0}),Ge>0&&(0,Y.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:Ge},children:E(Ue?`grid.refreshing`:`grid.pullToRefresh`)}),cn,pn,(0,Y.jsx)(vt,{selectedRows:L,actions:Gt??[],actionDefs:Wt,onAction:Yt,onActionDef:Xt,onClearSelection:()=>{Ce([]),z(!1)},pageSize:b.length,totalMatching:Ee,allMatchingSelected:R,onSelectAllMatching:()=>z(!0)}),Z.isOverlay&&(0,Y.jsx)(j,{...Z,title:rn,children:e=>ln(e)}),mn,hn]})},At=e(r(),1);function jt(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 $(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 Mt(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Nt=(e,t)=>Math.abs(e-t)<1.01,Pt=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Ft,It=()=>{if(Ft!==void 0)return Ft;if(typeof navigator>`u`)return Ft=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Ft=!0;let e=navigator.maxTouchPoints;return Ft=navigator.platform===`MacIntel`&&e!==void 0&&e>0},Lt=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Rt=e=>e,zt=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},Bt=(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(Lt(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(Lt(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Vt={passive:!0},Ht=typeof window>`u`?!0:`onscrollend`in window,Ut=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Ht,o=0,s=a?null:Pt(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,Vt),a&&r.addEventListener(`scrollend`,u,Vt),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Wt=(e,t)=>Ut(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Gt=(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`]},Kt=(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})},qt=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:Rt,rangeExtractor:zt,onChange:()=>{},measureElement:Gt,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=$(()=>(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,!(!It()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Vt),e.addEventListener(`touchend`,n,Vt),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=$(()=>[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=$(()=>[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=jt(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=$(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?Yt({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=$(()=>{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))&&(It()&&(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=$(()=>[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 Mt(t[Jt(0,t.length-1,r?e=>n[e*2]:e=>Mt(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&&Nt(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()}},Jt=(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 Yt({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=Jt(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 Xt=typeof document<`u`?G.useLayoutEffect:G.useEffect;function Zt({useFlushSync:e=!0,...t}){let n=G.useReducer(e=>e+1,0)[1],r={...t,onChange:(r,i)=>{var a;e&&i?(0,At.flushSync)(n):n(),(a=t.onChange)==null||a.call(t,r,i)}},[i]=G.useState(()=>new qt(r));return i.setOptions(r),Xt(()=>i._didMount(),[]),Xt(()=>i._willUpdate()),i}function Qt(e){return Zt({observeElementRect:Bt,observeElementOffset:Wt,scrollToFn:Kt,...e})}var $t={"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 en(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 tn(){let e=(e,t)=>en($t[e]??e,t);try{let t=g();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 nn=10;function rn(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 an(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 on(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 sn(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function cn(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 ln(e,t,n){if(e)try{e.setItem(t,JSON.stringify(n))}catch{}}function un(e,t){let n={};return Object.entries(t).forEach(([t,r])=>{let i=e[Number(t)];i&&(n[i.trim().toLowerCase()]=r)}),n}function dn(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 fn(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&&!an(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 pn=({onFileLoaded:e})=>{let{t}=tn(),[n,r]=(0,G.useState)(!1),[i,a]=(0,G.useState)(null),o=(0,G.useCallback)(n=>{if(a(null),!n.name.endsWith(`.csv`)){a(t(`grid.import.onlyCsv`));return}let r=new FileReader;r.onload=n=>{let r=rn(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,Y.jsxs)(`div`,{className:`flex flex-col items-center gap-4 py-6`,children:[(0,Y.jsxs)(`div`,{className:L(`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,Y.jsx)(A,{className:`h-10 w-10 text-muted-foreground`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`grid.import.dragDrop`)}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`input`,{type:`file`,accept:`.csv`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&o(t)}}),(0,Y.jsx)(V,{variant:`outline`,size:`sm`,asChild:!0,children:(0,Y.jsx)(`span`,{children:t(`grid.import.browseFiles`)})})]})]}),i&&(0,Y.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-destructive`,children:[(0,Y.jsx)(Me,{className:`h-4 w-4`}),` `,i]})]})},mn=({templates:e,selectedId:t,onSelect:n,onSaveAs:r,onDelete:i,disabled:a})=>{let{t:o}=tn(),[s,c]=(0,G.useState)(``),[l,u]=(0,G.useState)(!1);return(0,Y.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,Y.jsx)(fe,{className:`h-4 w-4 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:o(`grid.import.mappingTemplate`)}),(0,Y.jsxs)(N,{value:t??`__none__`,onValueChange:e=>e!==`__none__`&&n(e),children:[(0,Y.jsx)(F,{className:`h-7 w-48 text-xs`,"data-testid":`import-template-select`,children:(0,Y.jsx)(E,{placeholder:e.length?o(`grid.import.chooseTemplate`):o(`grid.import.noSavedTemplates`)})}),(0,Y.jsxs)(W,{children:[(0,Y.jsx)(x,{value:`__none__`,disabled:e.length===0,children:e.length?o(`grid.import.noneOption`):o(`grid.import.noSavedTemplates`)}),e.map(e=>(0,Y.jsx)(x,{value:e.id,children:e.name},e.id))]})]}),l?(0,Y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Y.jsx)(Oe,{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,Y.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,Y.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{u(!1),c(``)},children:o(`grid.import.cancel`)})]}):(0,Y.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,Y.jsx)(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:i,"aria-label":o(`grid.import.deleteTemplate`),"data-testid":`import-template-delete-btn`,children:(0,Y.jsx)(M,{className:`h-3.5 w-3.5`})})]})},hn=({headers:e,fields:t,mapping:n,onMappingChange:r,templates:i,selectedTemplateId:a,onSelectTemplate:o,onSaveTemplate:s,onDeleteTemplate:c})=>{let{t:l}=tn(),u=(0,G.useMemo)(()=>new Set(Object.values(n)),[n]),d=(0,G.useCallback)((e,t)=>{let i={...n};t===`__skip__`?delete i[e]:i[e]=t,r(i)},[n,r]);return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(mn,{templates:i,selectedId:a,onSelect:o,onSaveAs:s,onDelete:c,disabled:Object.keys(n).length===0}),(0,Y.jsx)(`div`,{className:`max-h-[420px] overflow-auto`,children:(0,Y.jsxs)(Ue,{children:[(0,Y.jsx)(Ge,{children:(0,Y.jsxs)(De,{children:[(0,Y.jsx)(ze,{children:l(`grid.import.csvColumn`)}),(0,Y.jsx)(ze,{children:l(`grid.import.mapsTo`)}),(0,Y.jsx)(ze,{className:`w-24 text-center`,children:l(`grid.import.status`)})]})}),(0,Y.jsx)(Ne,{children:e.map((e,r)=>(0,Y.jsxs)(De,{children:[(0,Y.jsx)(R,{className:`font-medium`,children:e}),(0,Y.jsx)(R,{children:(0,Y.jsxs)(N,{value:n[r]??`__skip__`,onValueChange:e=>d(r,e),children:[(0,Y.jsx)(F,{className:`h-8 w-56`,children:(0,Y.jsx)(E,{placeholder:l(`grid.import.skipColumn`)})}),(0,Y.jsxs)(W,{children:[(0,Y.jsx)(x,{value:`__skip__`,children:l(`grid.import.skip`)}),t.map(e=>(0,Y.jsxs)(x,{value:e.name,disabled:u.has(e.name)&&n[r]!==e.name,children:[e.label,e.required?` *`:``]},e.name))]})]})}),(0,Y.jsx)(R,{className:`text-center`,children:n[r]?(0,Y.jsx)(se,{variant:`default`,className:`text-xs`,children:l(`grid.import.mapped`)}):(0,Y.jsx)(se,{variant:`secondary`,className:`text-xs`,children:l(`grid.import.skipped`)})})]},r))})]})})]})},gn=({headers:e,rows:t,mapping:n,fields:r,corrections:i,onCorrect:a})=>{let{t:o}=tn(),s=(0,G.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,nn),l=(0,G.useCallback)((e,t)=>{let n=i[e]?.[t];return n===void 0?c[e]?.[t]??``:n},[i,c]),u=(0,G.useMemo)(()=>c.map((e,t)=>{let n={};for(let e of s){let r=l(t,e.csvIdx);e.field.required&&!r?n[e.csvIdx]=o(`grid.import.required`):r&&!an(r,e.field.type)&&(n[e.csvIdx]=o(`grid.import.invalidType`,{type:e.field.type}))}return n}),[c,s,l,o]),d=u.filter(e=>Object.keys(e).length>0).length,f=Object.keys(i).length;return(0,Y.jsxs)(`div`,{className:`max-h-[440px] overflow-auto`,children:[(d>0||f>0)&&(0,Y.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs`,"data-testid":`import-preview-status`,children:[d>0&&(0,Y.jsxs)(`span`,{className:`flex items-center gap-1 text-destructive`,children:[(0,Y.jsx)(Me,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsWithErrors`,{count:d})]}),f>0&&(0,Y.jsxs)(`span`,{className:`flex items-center gap-1 text-emerald-600`,children:[(0,Y.jsx)(H,{className:`h-3.5 w-3.5`}),` `,o(`grid.import.rowsCorrected`,{count:f})]}),(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:o(`grid.import.clickToFix`)})]}),(0,Y.jsxs)(Ue,{children:[(0,Y.jsx)(Ge,{children:(0,Y.jsxs)(De,{children:[(0,Y.jsx)(ze,{className:`w-12`,children:`#`}),s.map(e=>(0,Y.jsx)(ze,{children:e.field.label},e.csvIdx))]})}),(0,Y.jsx)(Ne,{children:c.map((e,t)=>{let n=u[t],r=Object.keys(n).length>0,o=i[t]!==void 0;return(0,Y.jsxs)(De,{className:L(r&&`bg-destructive/5`,!r&&o&&`bg-emerald-50 dark:bg-emerald-950/20`),"data-testid":`import-preview-row-${t}`,children:[(0,Y.jsx)(R,{className:`text-xs text-muted-foreground`,children:t+1}),s.map(e=>{let r=l(t,e.csvIdx),o=n[e.csvIdx],s=i[t]?.[e.csvIdx]!==void 0;return(0,Y.jsx)(R,{className:L(o&&`text-destructive`,s&&!o&&`text-emerald-600`),title:o,children:(0,Y.jsx)(Oe,{value:r,onChange:n=>a(t,e.csvIdx,n.target.value),className:L(`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,Y.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:o(`grid.import.showingRows`,{shown:c.length,total:t.length})})]})},_n=({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,G.useState)(`upload`),[p,m]=(0,G.useState)([]),[h,g]=(0,G.useState)([]),[_,v]=(0,G.useState)({}),[y,ee]=(0,G.useState)(!1),[x,S]=(0,G.useState)(0),[C,te]=(0,G.useState)(null),[w,T]=(0,G.useState)({}),re=t??e,E=(0,G.useMemo)(()=>u===void 0?sn():u,[u]),D=l??`objectui:import-templates:${e}`,[k,A]=(0,G.useState)(()=>cn(E,D)),[j,ae]=(0,G.useState)(null);(0,G.useEffect)(()=>{A(cn(E,D))},[E,D]);let oe=(0,G.useCallback)(e=>{let t=k.find(t=>t.id===e);t&&(ae(e),v(dn(t,p,n)))},[k,p,n]),ce=(0,G.useCallback)(e=>{let t={id:`tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:e,mapping:un(p,_),updatedAt:Date.now()},n=[...k,t];A(n),ae(t.id),ln(E,D,n)},[k,p,_,E,D]),le=(0,G.useCallback)(()=>{if(!j)return;let e=k.filter(e=>e.id!==j);A(e),ae(null),ln(E,D,e)},[k,j,E,D]),M=(0,G.useCallback)((e,t,n)=>{T(r=>{let i={...r},a={...i[e]??{}};return n===(h[e]?.[t]??``)?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,i})},[h]),N=(0,G.useMemo)(()=>{let e=new Set(Object.values(_));return n.filter(t=>t.required&&!e.has(t.name))},[n,_]),de=(0,G.useCallback)((e,t)=>{m(e),g(t),v(on(e,n)),T({}),f(`mapping`)},[n]),fe=(0,G.useCallback)(async()=>{ee(!0),S(0);let t=[],a=0,o=0,s=Object.entries(_).map(([e,t])=>({csvIdx:Number(e),field:n.find(e=>e.name===t)}));for(let n=0;n<h.length;n++){let i=h[n],l=w[n],{record:u,errors:d}=fn(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}S(Math.round((n+1)/h.length*100))}let l={totalRows:h.length,importedRows:a,skippedRows:o,errors:t};te(l),ee(!1),i?.(l)},[h,_,n,r,e,i,c,w]),pe=(0,G.useCallback)(()=>{f(`upload`),m([]),g([]),v({}),S(0),te(null),T({}),ae(null)},[]),P=(0,G.useCallback)(()=>{pe(),s?.(!1),a?.()},[pe,s,a]),{t:F}=tn();return(0,Y.jsx)(ne,{open:o,onOpenChange:e=>{e?s?.(e):P()},children:(0,Y.jsxs)(ie,{className:`flex max-h-[85vh] flex-col gap-4 overflow-hidden sm:max-w-4xl`,children:[(0,Y.jsxs)(U,{children:[(0,Y.jsxs)(b,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(Ye,{className:`h-5 w-5`}),` `,F(`grid.import.title`,{object:re})]}),(0,Y.jsxs)(O,{children:[d===`upload`&&F(`grid.import.uploadDescription`),d===`mapping`&&F(`grid.import.mappingDescription`),d===`preview`&&F(`grid.import.previewDescription`)]})]}),(0,Y.jsx)(`div`,{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground`,children:[`upload`,`mapping`,`preview`].map((e,t)=>(0,Y.jsxs)(G.Fragment,{children:[t>0&&(0,Y.jsx)(he,{className:`h-3 w-3`}),(0,Y.jsxs)(`span`,{className:L(`rounded-full px-3 py-1`,d===e?`bg-primary text-primary-foreground`:`bg-muted`),children:[t+1,`. `,F(e===`upload`?`grid.import.stepUpload`:e===`mapping`?`grid.import.stepMapping`:`grid.import.stepPreview`)]})]},e))}),(0,Y.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:C?(0,Y.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:[(0,Y.jsx)(H,{className:`h-10 w-10 text-green-500`}),(0,Y.jsx)(`p`,{className:`text-lg font-semibold`,children:F(`grid.import.importComplete`)}),(0,Y.jsxs)(`div`,{className:`flex gap-3`,children:[(0,Y.jsx)(se,{variant:`default`,children:F(`grid.import.imported`,{count:C.importedRows})}),C.skippedRows>0&&(0,Y.jsx)(se,{variant:`destructive`,children:F(`grid.import.skippedCount`,{count:C.skippedRows})})]}),C.errors.length>0&&(0,Y.jsxs)(`div`,{className:`max-h-32 w-full overflow-auto rounded border p-2 text-xs`,children:[C.errors.slice(0,10).map((e,t)=>(0,Y.jsxs)(`p`,{className:`text-destructive`,children:[`Row `,e.row,e.field?` (${e.field})`:``,`: `,e.message]},t)),C.errors.length>10&&(0,Y.jsx)(`p`,{className:`text-muted-foreground`,children:F(`grid.import.moreErrors`,{count:C.errors.length-10})})]})]}):(0,Y.jsxs)(Y.Fragment,{children:[d===`upload`&&(0,Y.jsx)(pn,{onFileLoaded:de}),d===`mapping`&&(0,Y.jsx)(hn,{headers:p,fields:n,mapping:_,onMappingChange:v,templates:k,selectedTemplateId:j,onSelectTemplate:oe,onSaveTemplate:ce,onDeleteTemplate:le}),d===`preview`&&(0,Y.jsx)(gn,{headers:p,rows:h,mapping:_,fields:n,corrections:w,onCorrect:M}),y&&(0,Y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,Y.jsx)(ve,{value:x,className:`h-2`}),(0,Y.jsx)(`p`,{className:`text-center text-xs text-muted-foreground`,children:F(`grid.import.importing`,{progress:x})})]})]})}),(0,Y.jsx)(ue,{className:`gap-2 sm:gap-0`,children:C?(0,Y.jsx)(V,{onClick:P,children:F(`grid.import.close`)}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(V,{variant:`ghost`,onClick:P,disabled:y,children:[(0,Y.jsx)(Je,{className:`mr-1 h-4 w-4`}),` `,F(`grid.import.cancel`)]}),(d===`mapping`||d===`preview`)&&(0,Y.jsxs)(V,{variant:`outline`,onClick:()=>f(d===`mapping`?`upload`:`mapping`),disabled:y,children:[(0,Y.jsx)(me,{className:`mr-1 h-4 w-4`}),` `,F(`grid.import.back`)]}),d===`mapping`&&(0,Y.jsxs)(V,{onClick:()=>f(`preview`),disabled:Object.keys(_).length===0||N.length>0,children:[F(`grid.import.next`),` `,(0,Y.jsx)(he,{className:`ml-1 h-4 w-4`})]}),d===`preview`&&(0,Y.jsx)(V,{onClick:fe,disabled:y,children:y?F(`grid.import.importingProgress`):F(`grid.import.importNRows`,{count:h.length})})]})})]})})},vn=t({ImportWizard:()=>_n,ObjectGrid:()=>kt,ObjectGridRenderer:()=>yn}),yn=({schema:e,...t})=>{let{dataSource:n}=f()||{};return(0,Y.jsx)(kt,{schema:e,dataSource:n,...t})};m.register(`object-grid`,yn,{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`}]}),m.register(`grid`,yn,{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`}]}),m.register(`import-wizard`,({schema:e,...t})=>{let{dataSource:n}=f()||{};return(0,Y.jsx)(_n,{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{Ze as a,Qe as i,Qt as n,kt as r,vn as t};