@object-ui/plugin-grid 3.4.0 → 4.0.3

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.
@@ -1,15 +1,15 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`react`),require(`@object-ui/core`),require(`@object-ui/react`),require(`@object-ui/fields`),require(`@object-ui/components`),require(`lucide-react`),require(`react-dom`)):typeof define==`function`&&define.amd?define([`exports`,`react`,`@object-ui/core`,`@object-ui/react`,`@object-ui/fields`,`@object-ui/components`,`lucide-react`,`react-dom`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.ObjectUIPluginGrid={},e.React,e._object_ui_core,e._object_ui_react,e._object_ui_fields,e._object_ui_components,e.lucide_react,e.ReactDOM))})(this,function(e,t,n,r,i,a,o,s){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var c=Object.create,l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,d=Object.getOwnPropertyNames,f=Object.getPrototypeOf,p=Object.prototype.hasOwnProperty,m=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),h=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=d(t),a=0,o=i.length,s;a<o;a++)s=i[a],!p.call(e,s)&&s!==n&&l(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=u(t,s))||r.enumerable});return e};t=((e,t,n)=>(n=e==null?{}:c(f(e)),h(t||!e||!e.__esModule?l(n,`default`,{value:e,enumerable:!0}):n,e)))(t,1);function g(e){let{onRefresh:n,threshold:r=80,enabled:i=!0}=e,a=(0,t.useRef)(null),[o,s]=(0,t.useState)(!1),[c,l]=(0,t.useState)(0),u=(0,t.useRef)(0),d=(0,t.useCallback)(e=>{if(!i||o)return;let t=a.current;t&&t.scrollTop===0&&(u.current=e.touches[0].clientY)},[i,o]),f=(0,t.useCallback)(e=>{if(!i||o||!u.current)return;let t=e.touches[0].clientY-u.current;t>0&&l(Math.min(t,r*1.5))},[i,o,r]),p=(0,t.useCallback)(async()=>{if(!i||o)return;let e=c;if(l(0),u.current=0,e>=r){s(!0);try{await n()}finally{s(!1)}}},[i,o,c,r,n]);return(0,t.useEffect)(()=>{let e=a.current;if(!(!e||!i))return e.addEventListener(`touchstart`,d,{passive:!0}),e.addEventListener(`touchmove`,f,{passive:!0}),e.addEventListener(`touchend`,p,{passive:!0}),()=>{e.removeEventListener(`touchstart`,d),e.removeEventListener(`touchmove`,f),e.removeEventListener(`touchend`,p)}},[d,f,p,i]),{ref:a,isRefreshing:o,pullDistance:c}}var _=m((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),v=m((e=>{process.env.NODE_ENV!==`production`&&(function(){function t(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===ee?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case _:return`Fragment`;case y:return`Profiler`;case v:return`StrictMode`;case C:return`Suspense`;case w:return`SuspenseList`;case D:return`Activity`}if(typeof e==`object`)switch(typeof e.tag==`number`&&console.error(`Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.`),e.$$typeof){case g:return`Portal`;case x:return e.displayName||`Context`;case b:return(e._context.displayName||`Context`)+`.Consumer`;case S:var n=e.render;return e=e.displayName,e||=(e=n.displayName||n.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case T:return n=e.displayName||null,n===null?t(e.type)||`Memo`:n;case E:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function n(e){return``+e}function r(e){try{n(e);var t=!1}catch{t=!0}if(t){t=console;var r=t.error,i=typeof Symbol==`function`&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||`Object`;return r.call(t,`The provided key is an unsupported type %s. This value must be coerced to a string before using it here.`,i),n(e)}}function i(e){if(e===_)return`<>`;if(typeof e==`object`&&e&&e.$$typeof===E)return`<...>`;try{var n=t(e);return n?`<`+n+`>`:`<...>`}catch{return`<...>`}}function a(){var e=O.A;return e===null?null:e.getOwner()}function o(){return Error(`react-stack-top-frame`)}function s(e){if(k.call(e,`key`)){var t=Object.getOwnPropertyDescriptor(e,`key`).get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function c(e,t){function n(){M||(M=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}n.isReactWarning=!0,Object.defineProperty(e,`key`,{get:n,configurable:!0})}function l(){var e=t(this.type);return N[e]||(N[e]=!0,console.error(`Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.`)),e=this.props.ref,e===void 0?null:e}function u(e,t,n,r,i,a){var o=n.ref;return e={$$typeof:h,type:e,key:t,props:n,_owner:r},(o===void 0?null:o)===null?Object.defineProperty(e,`ref`,{enumerable:!1,value:null}):Object.defineProperty(e,`ref`,{enumerable:!1,get:l}),e._store={},Object.defineProperty(e._store,`validated`,{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,`_debugInfo`,{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,`_debugStack`,{configurable:!1,enumerable:!1,writable:!0,value:i}),Object.defineProperty(e,`_debugTask`,{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function d(e,n,i,o,l,d){var p=n.children;if(p!==void 0)if(o)if(A(p)){for(o=0;o<p.length;o++)f(p[o]);Object.freeze&&Object.freeze(p)}else console.error(`React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.`);else f(p);if(k.call(n,`key`)){p=t(e);var m=Object.keys(n).filter(function(e){return e!==`key`});o=0<m.length?`{key: someKey, `+m.join(`: ..., `)+`: ...}`:`{key: someKey}`,I[p+o]||(m=0<m.length?`{`+m.join(`: ..., `)+`: ...}`:`{}`,console.error(`A props object containing a "key" prop is being spread into JSX:
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`react`),require(`@object-ui/core`),require(`@object-ui/react`),require(`@object-ui/fields`),require(`@object-ui/components`),require(`lucide-react`),require(`react-dom`)):typeof define==`function`&&define.amd?define([`exports`,`react`,`@object-ui/core`,`@object-ui/react`,`@object-ui/fields`,`@object-ui/components`,`lucide-react`,`react-dom`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.ObjectUIPluginGrid={},e.React,e._object_ui_core,e._object_ui_react,e._object_ui_fields,e._object_ui_components,e.lucide_react,e.ReactDOM))})(this,function(e,t,n,r,i,a,o,s){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var c=Object.create,l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,d=Object.getOwnPropertyNames,f=Object.getPrototypeOf,p=Object.prototype.hasOwnProperty,m=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),h=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=d(t),a=0,o=i.length,s;a<o;a++)s=i[a],!p.call(e,s)&&s!==n&&l(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=u(t,s))||r.enumerable});return e};t=((e,t,n)=>(n=e==null?{}:c(f(e)),h(t||!e||!e.__esModule?l(n,`default`,{value:e,enumerable:!0}):n,e)))(t,1);function g(e){let{onRefresh:n,threshold:r=80,enabled:i=!0}=e,a=(0,t.useRef)(null),[o,s]=(0,t.useState)(!1),[c,l]=(0,t.useState)(0),u=(0,t.useRef)(0),d=(0,t.useCallback)(e=>{if(!i||o)return;let t=a.current;t&&t.scrollTop===0&&(u.current=e.touches[0].clientY)},[i,o]),f=(0,t.useCallback)(e=>{if(!i||o||!u.current)return;let t=e.touches[0].clientY-u.current;t>0&&l(Math.min(t,r*1.5))},[i,o,r]),p=(0,t.useCallback)(async()=>{if(!i||o)return;let e=c;if(l(0),u.current=0,e>=r){s(!0);try{await n()}finally{s(!1)}}},[i,o,c,r,n]);return(0,t.useEffect)(()=>{let e=a.current;if(!(!e||!i))return e.addEventListener(`touchstart`,d,{passive:!0}),e.addEventListener(`touchmove`,f,{passive:!0}),e.addEventListener(`touchend`,p,{passive:!0}),()=>{e.removeEventListener(`touchstart`,d),e.removeEventListener(`touchmove`,f),e.removeEventListener(`touchend`,p)}},[d,f,p,i]),{ref:a,isRefreshing:o,pullDistance:c}}var _=m((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),v=m((e=>{process.env.NODE_ENV!==`production`&&(function(){function t(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===O?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case _:return`Fragment`;case y:return`Profiler`;case v:return`StrictMode`;case C:return`Suspense`;case w:return`SuspenseList`;case D:return`Activity`}if(typeof e==`object`)switch(typeof e.tag==`number`&&console.error(`Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.`),e.$$typeof){case g:return`Portal`;case x:return e.displayName||`Context`;case b:return(e._context.displayName||`Context`)+`.Consumer`;case S:var n=e.render;return e=e.displayName,e||=(e=n.displayName||n.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case T:return n=e.displayName||null,n===null?t(e.type)||`Memo`:n;case E:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function n(e){return``+e}function r(e){try{n(e);var t=!1}catch{t=!0}if(t){t=console;var r=t.error,i=typeof Symbol==`function`&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||`Object`;return r.call(t,`The provided key is an unsupported type %s. This value must be coerced to a string before using it here.`,i),n(e)}}function i(e){if(e===_)return`<>`;if(typeof e==`object`&&e&&e.$$typeof===E)return`<...>`;try{var n=t(e);return n?`<`+n+`>`:`<...>`}catch{return`<...>`}}function a(){var e=k.A;return e===null?null:e.getOwner()}function o(){return Error(`react-stack-top-frame`)}function s(e){if(A.call(e,`key`)){var t=Object.getOwnPropertyDescriptor(e,`key`).get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function c(e,t){function n(){N||(N=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}n.isReactWarning=!0,Object.defineProperty(e,`key`,{get:n,configurable:!0})}function l(){var e=t(this.type);return P[e]||(P[e]=!0,console.error(`Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.`)),e=this.props.ref,e===void 0?null:e}function u(e,t,n,r,i,a){var o=n.ref;return e={$$typeof:h,type:e,key:t,props:n,_owner:r},(o===void 0?null:o)===null?Object.defineProperty(e,`ref`,{enumerable:!1,value:null}):Object.defineProperty(e,`ref`,{enumerable:!1,get:l}),e._store={},Object.defineProperty(e._store,`validated`,{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,`_debugInfo`,{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,`_debugStack`,{configurable:!1,enumerable:!1,writable:!0,value:i}),Object.defineProperty(e,`_debugTask`,{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function d(e,n,i,o,l,d){var p=n.children;if(p!==void 0)if(o)if(j(p)){for(o=0;o<p.length;o++)f(p[o]);Object.freeze&&Object.freeze(p)}else console.error(`React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.`);else f(p);if(A.call(n,`key`)){p=t(e);var m=Object.keys(n).filter(function(e){return e!==`key`});o=0<m.length?`{key: someKey, `+m.join(`: ..., `)+`: ...}`:`{key: someKey}`,L[p+o]||(m=0<m.length?`{`+m.join(`: ..., `)+`: ...}`:`{}`,console.error(`A props object containing a "key" prop is being spread into JSX:
2
2
  let props = %s;
3
3
  <%s {...props} />
4
4
  React keys must be passed directly to JSX without using spread:
5
5
  let props = %s;
6
- <%s key={someKey} {...props} />`,o,p,m,p),I[p+o]=!0)}if(p=null,i!==void 0&&(r(i),p=``+i),s(n)&&(r(n.key),p=``+n.key),`key`in n)for(var h in i={},n)h!==`key`&&(i[h]=n[h]);else i=n;return p&&c(i,typeof e==`function`?e.displayName||e.name||`Unknown`:e),u(e,p,i,a(),l,d)}function f(e){p(e)?e._store&&(e._store.validated=1):typeof e==`object`&&e&&e.$$typeof===E&&(e._payload.status===`fulfilled`?p(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function p(e){return typeof e==`object`&&!!e&&e.$$typeof===h}var m=require(`react`),h=Symbol.for(`react.transitional.element`),g=Symbol.for(`react.portal`),_=Symbol.for(`react.fragment`),v=Symbol.for(`react.strict_mode`),y=Symbol.for(`react.profiler`),b=Symbol.for(`react.consumer`),x=Symbol.for(`react.context`),S=Symbol.for(`react.forward_ref`),C=Symbol.for(`react.suspense`),w=Symbol.for(`react.suspense_list`),T=Symbol.for(`react.memo`),E=Symbol.for(`react.lazy`),D=Symbol.for(`react.activity`),ee=Symbol.for(`react.client.reference`),O=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,k=Object.prototype.hasOwnProperty,A=Array.isArray,j=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(e){return e()}};var M,N={},P=m.react_stack_bottom_frame.bind(m,o)(),F=j(i(o)),I={};e.Fragment=_,e.jsx=function(e,t,n){var r=1e4>O.recentlyCreatedOwnerStacks++;return d(e,t,n,!1,r?Error(`react-stack-top-frame`):P,r?j(i(e)):F)},e.jsxs=function(e,t,n){var r=1e4>O.recentlyCreatedOwnerStacks++;return d(e,t,n,!0,r?Error(`react-stack-top-frame`):P,r?j(i(e)):F)}})()})),y=m(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=_():t.exports=v()}))(),b=(0,t.createContext)(null);b.displayName=`MobileContext`;var x={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 S(e){return e.startsWith(`bg-`)?e:x[e.toLowerCase().trim()]}function C(e){return(0,t.useCallback)(t=>{if(!e?.field||!e.colors)return;let n=String(t[e.field]??``),r=e.colors[n];if(r)return S(r)},[e?.field,e?.colors])}function w(e,t){return t.map(t=>String(e[t.field]??``)).join(` / `)}function T(e,t){return t.map(t=>{let n=e[t.field];return n!=null&&n!==``?String(n):`(empty)`}).join(` / `)}function E(e,t){return t.map(({field:t,type:n})=>{let r=e.map(e=>Number(e[t])).filter(e=>Number.isFinite(e)),i;switch(n){case`count`:i=r.length;break;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 D(e,t,n){let r=e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`});return n===`desc`?-r:r}function ee(e,n,r){let i=e?.fields,a=!!(i&&i.length>0),[o,s]=(0,t.useState)({}),c=(0,t.useMemo)(()=>i?i.some(e=>e.collapsed):!1,[i]);return{groups:(0,t.useMemo)(()=>{if(!a||!i)return[];let e=new Map,t=[];for(let r of n){let n=w(r,i);e.has(n)||(e.set(n,{label:T(r,i),rows:[]}),t.push(n)),e.get(n).rows.push(r)}let s=i[0]?.order??`asc`;return t.sort((e,t)=>D(e,t,s)),t.map(t=>{let n=e.get(t),i=t in o?o[t]:c,a=r&&r.length>0?E(n.rows,r):[];return{key:t,label:n.label,rows:n.rows,collapsed:i,aggregations:a}})},[n,i,a,o,c,r]),isGrouped:a,toggleGroup:(0,t.useCallback)(e=>{s(t=>({...t,[e]:t[e]===void 0?!c:!t[e]}))},[c])}}var O=({groupKey:e,label:t,count:n,collapsed:r,aggregations:i,onToggle:a,children:s})=>(0,y.jsxs)(`div`,{className:`border rounded-md`,"data-testid":`group-row-${e}`,children:[(0,y.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 px-3 py-2 text-sm font-medium text-left bg-muted/50 hover:bg-muted transition-colors`,onClick:()=>a(e),"aria-expanded":!r,children:[r?(0,y.jsx)(o.ChevronRight,{className:`h-4 w-4 shrink-0`}):(0,y.jsx)(o.ChevronDown,{className:`h-4 w-4 shrink-0`}),(0,y.jsx)(`span`,{className:`group-label`,children:t}),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}`))}),(0,y.jsxs)(`span`,{className:`ml-auto text-xs text-muted-foreground group-count`,children:[`(`,n,`)`]})]}),!r&&s]});function k(e){return typeof e==`string`?{type:e}:e}function A(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 j(e,t){return t===null?``:`${{count:`Count`,sum:`Sum`,avg:`Avg`,min:`Min`,max:`Max`}[e]||e}: ${e===`avg`?t.toLocaleString(void 0,{maximumFractionDigits:2}):t.toLocaleString()}`}function M(e,n){return(0,t.useMemo)(()=>{let t=new Map;if(!e||e.length===0||n.length===0)return{summaries:t,hasSummary:!1};for(let r of e){if(!r.summary)continue;let e=k(r.summary),i=e.field||r.field,a=[];for(let e of n){let t=e[i];if(t!=null&&typeof t==`number`&&!isNaN(t))a.push(t);else if(t!=null&&typeof t==`string`){let e=parseFloat(t);isNaN(e)||a.push(e)}}let o;if(e.type===`count`){let e=n.filter(e=>e[i]!=null&&e[i]!==``).length;o=e>0?e:null}else o=A(e.type,a);t.set(r.field,{field:r.field,value:o,label:j(e.type,o)})}return{summaries:t,hasSummary:t.size>0}},[e,n])}function N(e){return e.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var P=({row:e,rowActions:t,canEdit:n,canDelete:r,onEdit:i,onDelete:s,onAction:c})=>(0,y.jsxs)(a.DropdownMenu,{children:[(0,y.jsx)(a.DropdownMenuTrigger,{asChild:!0,children:(0,y.jsxs)(a.Button,{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)(o.MoreVertical,{className:`h-4 w-4`}),(0,y.jsx)(`span`,{className:`sr-only`,children:`Open menu`})]})}),(0,y.jsxs)(a.DropdownMenuContent,{align:`end`,children:[n&&i&&(0,y.jsxs)(a.DropdownMenuItem,{onClick:()=>i(e),children:[(0,y.jsx)(o.Edit,{className:`mr-2 h-4 w-4`}),`Edit`]}),r&&s&&(0,y.jsxs)(a.DropdownMenuItem,{onClick:()=>s(e),children:[(0,y.jsx)(o.Trash2,{className:`mr-2 h-4 w-4`}),`Delete`]}),t?.map(t=>(0,y.jsx)(a.DropdownMenuItem,{onClick:()=>c?.(t,e),"data-testid":`row-action-${t}`,children:N(t)},t))]})]}),F=({selectedRows:e,actions:t,onAction:n,onClearSelection:r})=>!t||t.length===0||e.length===0?null:(0,y.jsxs)(`div`,{className:`border-t px-4 py-1.5 flex items-center gap-2 text-xs bg-primary/5 shrink-0`,"data-testid":`bulk-actions-bar`,children:[(0,y.jsxs)(`span`,{className:`text-muted-foreground font-medium`,children:[e.length,` selected`]}),(0,y.jsx)(`div`,{className:`flex items-center gap-1 ml-2`,children:t.map(t=>(0,y.jsx)(a.Button,{variant:`outline`,size:`sm`,className:`h-6 px-2 text-xs`,onClick:()=>n?.(t,e),"data-testid":`bulk-action-${t}`,children:N(t)},t))}),(0,y.jsx)(a.Button,{variant:`ghost`,size:`sm`,className:`h-6 px-2 text-xs ml-auto`,onClick:r,children:`Clear`})]}),I={"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`};function te(){try{let e=(0,r.useObjectTranslation)();return e.t(`grid.actions`)===`grid.actions`?{t:(e,t)=>{let n=I[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=I[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}}}function ne(e){if(e!=null)return typeof e==`string`?e:void 0}function re(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 ie(e){if(!(!e||e.length===0))return typeof e[0]==`object`&&e[0],e}var ae=({schema:e,dataSource:s,onEdit:c,onDelete:l,onRowSelect:u,onRowClick:d,onCellChange:f,onRowSave:p,onBatchSave:m,onAddRecord:h,..._})=>{let[v,b]=(0,t.useState)([]),[x,S]=(0,t.useState)(!0),[w,T]=(0,t.useState)(null),{t:E}=te(),{fieldLabel:D,translateOptions:k}=(0,r.useSafeFieldLabel)(),[A,j]=(0,t.useState)(null),[I,ae]=(0,t.useState)(!1),[L,oe]=(0,t.useState)(0),[se,R]=(0,t.useState)(!1),[ce,le]=(0,t.useState)(!1),z=(0,a.useExportJob)({dataSource:s}),[B,ue]=(0,t.useState)(e.rowHeight??`compact`),[de,fe]=(0,t.useState)([]),pe=t.default.useMemo(()=>e.id?`grid-columns-${e.objectName}-${e.id}`:`grid-columns-${e.objectName}`,[e.objectName,e.id]),[V,me]=(0,t.useState)(()=>{try{let e=localStorage.getItem(pe);return e?JSON.parse(e):{}}catch{return{}}}),he=(0,t.useCallback)(e=>{me(e);try{localStorage.setItem(pe,JSON.stringify(e))}catch(e){console.warn(`Failed to persist column state:`,e)}},[pe]),{ref:ge,isRefreshing:_e,pullDistance:ve}=g({onRefresh:(0,t.useCallback)(async()=>{oe(e=>e+1)},[]),enabled:!!s&&!!e.objectName});(0,t.useEffect)(()=>{let e=()=>ae(window.innerWidth<480);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ye=_.data,be=(0,r.useDataScope)(e.bind),xe=re(e),H=t.default.useMemo(()=>ye&&Array.isArray(ye)?{provider:`value`,items:ye}:be&&Array.isArray(be)?{provider:`value`,items:be}:xe,[JSON.stringify(xe),be,ye]),U=H?.provider===`value`,W=H?.provider===`object`&&H&&`object`in H?H.object:e.objectName,G=e.fields,K=e.columns,q=e.filter,J=e.sort,Se=e.pagination,Ce=e.pageSize;(0,t.useEffect)(()=>{U&&H?.provider===`value`&&(b(e=>{let t=H.items;return JSON.stringify(e)===JSON.stringify(t)?e:t}),S(!1))},[U,H]),(0,t.useEffect)(()=>{if(!U||!W||!s)return;let e=!1;return(async()=>{try{if(typeof s.getObjectSchema!=`function`)return;let t=await s.getObjectSchema(W);e||j(t)}catch(e){console.warn(`[ObjectGrid] Failed to fetch objectSchema for inline data (objectName: ${W}):`,e)}})(),()=>{e=!0}},[U,W,s]),(0,t.useEffect)(()=>{if(U)return;let t=!1;return(async()=>{S(!0),T(null);try{let r=null,i=ie(K)||G;if(W&&s)if(typeof s.getObjectSchema==`function`){let e=await s.getObjectSchema(W);if(t)return;r=e}else r={name:W,fields:{}};else if(i&&W)r={name:W,fields:{}};else if(W)throw Error(`DataSource required`);else throw Error(`Object name required for data fetching`);if(t||j(r),s&&W){let i={$select:(()=>{if(G)return G;if(K&&Array.isArray(K))return K.map(e=>typeof e==`string`?e:e.field)})(),$top:Se?.pageSize||Ce||50};q&&Array.isArray(q)?i.$filter=q:e.defaultFilters&&(i.$filter=e.defaultFilters),J?typeof J==`string`?i.$orderby=J:Array.isArray(J)&&(i.$orderby=J.map(e=>`${e.field} ${e.order}`).join(`, `)):e.defaultSort&&(i.$orderby=`${e.defaultSort.field} ${e.defaultSort.order}`);let a=(0,n.buildExpandFields)(r?.fields,K??G);a.length>0&&(i.$expand=a);let o=await s.find(W,i);if(t)return;b(o.data||[])}}catch(e){t||T(e)}finally{t||S(!1)}})(),()=>{t=!0}},[W,G,K,q,J,Se,Ce,s,U,H,L]);let Y=(0,r.useNavigationOverlay)({navigation:e.navigation,objectName:e.objectName,onNavigate:e.onNavigate,onRowClick:d}),{execute:X}=(0,r.useAction)(),we=C(e.rowColor),Te=(0,t.useCallback)(t=>{let r=e.conditionalFormatting;if(!(!r||r.length===0))for(let e of r){let r=!1,i=(`condition`in e?e.condition:void 0)||(`expression`in e?e.expression:void 0)||void 0;if(i)r=(0,n.evaluatePlainCondition)(i,t);else if(`field`in e&&`operator`in e&&e.field&&e.operator){let n=e,i=t[n.field];switch(n.operator){case`equals`:r=i===n.value;break;case`not_equals`:r=i!==n.value;break;case`contains`:r=typeof i==`string`&&typeof n.value==`string`&&i.includes(n.value);break;case`greater_than`:r=typeof i==`number`&&typeof n.value==`number`&&i>n.value;break;case`less_than`:r=typeof i==`number`&&typeof n.value==`number`&&i<n.value;break;case`in`:r=Array.isArray(n.value)&&n.value.includes(i);break}}if(r){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]),{groups:Ee,isGrouped:De,toggleGroup:Oe}=ee(e.grouping,v),{summaries:ke,hasSummary:Ae}=M(t.default.useMemo(()=>{let t=ie(e.columns);if(t&&t.length>0&&typeof t[0]==`object`)return t},[e.columns]),v),Z=(0,t.useCallback)(()=>{let t=e=>e&&{text:(0,y.jsx)(o.Type,{className:`h-3.5 w-3.5`}),number:(0,y.jsx)(o.Hash,{className:`h-3.5 w-3.5`}),currency:(0,y.jsx)(o.Hash,{className:`h-3.5 w-3.5`}),percent:(0,y.jsx)(o.Hash,{className:`h-3.5 w-3.5`}),date:(0,y.jsx)(o.Calendar,{className:`h-3.5 w-3.5`}),datetime:(0,y.jsx)(o.Clock,{className:`h-3.5 w-3.5`}),boolean:(0,y.jsx)(o.CheckSquare,{className:`h-3.5 w-3.5`}),user:(0,y.jsx)(o.User,{className:`h-3.5 w-3.5`}),select:(0,y.jsx)(o.Tag,{className:`h-3.5 w-3.5`})}[e]||(0,y.jsx)(o.Type,{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(v.length>0){let t=v.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))&&v.length>0&&typeof v.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`percent`;if([`status`,`priority`,`category`,`stage`,`type`,`severity`,`level`].some(e=>t.includes(e))&&v.length>0){let t=new Set(v.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))&&v.length>0&&typeof v.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`currency`;if(v.length>0){let t=v.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=ie(K);if(r){if(r.length>0&&typeof r[0]==`object`&&r[0]!==null){let o=r[0];if(`accessorKey`in o)return r.map(r=>{if(r.cell)return r;let a=n({field:r.accessorKey,label:r.header,type:r.type});if(!a)return r;let o=(0,i.getCellRenderer)(a),s={name:r.accessorKey,type:a};return a===`select`&&(s.options=Array.from(new Set(v.map(e=>e[r.accessorKey]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))}))),{...r,...e.showColumnTypeIcons&&{headerIcon:t(a)},cell:e=>(0,y.jsx)(o,{value:e,field:s})}});if(`field`in o)return r.filter(e=>e?.field&&typeof e.field==`string`&&!e.hidden).map((r,o)=>{let s=ne(r.label)||r.field.charAt(0).toUpperCase()+r.field.slice(1).replace(/_/g,` `),c=e.objectName?D(e.objectName,r.field,s):s,l,u=A?.fields?.[r.field],d=r.type||u?.type||n({field:r.field})||null,f=d?(0,i.getCellRenderer)(d):null,p={name:r.field,type:d||`text`};u&&(u.label&&(p.label=u.label),u.currency&&(p.currency=u.currency),u.precision!==void 0&&(p.precision=u.precision),u.format&&(p.format=u.format),u.options&&(p.options=k(e.objectName,r.field,u.options))),d===`select`&&!p.options&&(p.options=Array.from(new Set(v.map(e=>e[r.field]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))}))),r.options&&(p.options=k(e.objectName,r.field,r.options));let m=o===0&&!r.link&&!r.action,h=r.link||m;l=r.link&&r.action||m&&r.action||h?(e,t)=>(0,y.jsx)(`button`,{type:`button`,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit`,"data-testid":m?`primary-field-link`:`link-cell`,onClick:e=>{e.stopPropagation(),Y.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)(a.Button,{variant:`outline`,size:`sm`,className:`h-7 text-xs`,"data-testid":`action-cell`,onClick:n=>{n.stopPropagation(),X({type:r.action,params:{record:t,field:r.field,value:e}})},children:N(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)(a.EmptyValue,{});let g=r.prefix;if(g?.field){let e=l,t=g.type===`badge`?(0,i.getCellRenderer)(`select`):null;l=(n,r)=>{let i=r[g.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:g.field,type:`select`}}):(0,y.jsx)(`span`,{className:`text-muted-foreground text-xs mr-1.5`,children:String(i)}):null,e(n,r)]})}}let _=[`number`,`currency`,`percent`],b=d||r.type,x=r.align||(b&&_.includes(b)?`right`:void 0),S=o===0||r.essential===!0;return{header:c,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},...l&&{cell:l},...r.pinned&&{pinned:r.pinned}}})}return r.filter(e=>typeof e==`string`&&e.trim().length>0).map((r,a)=>{let o=A?.fields?.[r],s=o?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),c=e.objectName?D(e.objectName,r,s):s,l=o?.type||n({field:r})||null,u=l?(0,i.getCellRenderer)(l):null,d={name:r,type:l||`text`};o&&(o.label&&(d.label=o.label),o.currency&&(d.currency=o.currency),o.precision!==void 0&&(d.precision=o.precision),o.format&&(d.format=o.format),o.options&&(d.options=k(e.objectName,r,o.options))),l===`select`&&!d.options&&(d.options=Array.from(new Set(v.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))})));let f=l&&[`number`,`currency`,`percent`].includes(l)?`right`:void 0,p=a===0,m;return p&&u?m=(e,t)=>(0,y.jsx)(`button`,{type:`button`,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit`,"data-testid":`primary-field-link`,onClick:e=>{e.stopPropagation(),Y.handleClick(t)},children:(0,y.jsx)(u,{value:e,field:d})}):p?m=(e,t)=>(0,y.jsx)(`button`,{type:`button`,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit`,"data-testid":`primary-field-link`,onClick:e=>{e.stopPropagation(),Y.handleClick(t)},children:e!=null&&e!==``?String(e):(0,y.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):u&&(m=e=>(0,y.jsx)(u,{value:e,field:d})),{header:c,accessorKey:r,...e.showColumnTypeIcons&&l&&{headerIcon:t(l)},...f&&{align:f},...m&&{cell:m},sortable:o?.sortable!==!1}})}if(U){let r=H?.provider===`value`?H.items:[];if(r.length>0)return(G||Object.keys(r[0])).map(r=>{let a=A?.fields?.[r],o=a?.type||n({field:r})||null,s=o?(0,i.getCellRenderer)(o):null,c=a?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),l={name:r,type:o||`text`};a&&(a.label&&(l.label=a.label),a.currency&&(l.currency=a.currency),a.precision!==void 0&&(l.precision=a.precision),a.format&&(l.format=a.format),a.options&&(l.options=k(e.objectName,r,a.options))),o===`select`&&!l.options&&(l.options=Array.from(new Set(v.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))})));let u=o&&[`number`,`currency`,`percent`].includes(o)?`right`:void 0;return{header:c,accessorKey:r,...e.showColumnTypeIcons&&o&&{headerIcon:t(o)},...u&&{align:u},...s&&{cell:e=>(0,y.jsx)(s,{value:e,field:l})},sortable:a?.sortable!==!1}})}if(!A)return[];let s=[],c=new Set([`id`,`created_at`,`createdAt`,`updated_at`,`updatedAt`,`deleted_at`,`deletedAt`,`created_by`,`createdBy`,`updated_by`,`updatedBy`,`_version`,`_rev`]),l=A?.compactLayout,u=Object.keys(A.fields||{}),d;if(G)d=G;else if(l?.length)d=l.filter(e=>A.fields?.[e]);else{let e=u.filter(e=>{let t=A.fields?.[e];return!(!t||t.hidden||t.readonly&&c.has(e))});d=[...e.filter(e=>!c.has(e)),...e.filter(e=>c.has(e))]}return d.forEach(t=>{let n=A.fields?.[t];if(!n||n.permissions&&n.permissions.read===!1)return;let r=(0,i.getCellRenderer)(n.type),a=[`number`,`currency`,`percent`],o=n.options?{...n,options:k(e.objectName,t,n.options)}:n;s.push({header:e.objectName?D(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})}),s},[A,G,K,H,U,Y.handleClick,X,v,D,k,e.objectName]),je=(0,t.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`)&&z.isSupported&&e.objectName&&!U&&n?.streaming!==!1){let n=Z().filter(e=>e.accessorKey!==`_actions`).map(e=>e.accessorKey).filter(Boolean);R(!1),le(!0),z.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?v.slice(0,r):v,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(`
7
- `)||t.includes(`\r`)?`"${t.replace(/"/g,`""`)}"`:t};if(t===`csv`){let e=Z().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(`
8
- `)],{type:`text/csv;charset=utf-8;`}),`${a}.csv`)}else t===`json`&&s(new Blob([JSON.stringify(o,null,2)],{type:`application/json`}),`${a}.json`);R(!1)},[v,e.exportOptions,e.objectName,Z,z,U]);if(w)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:w.message})]});if(x&&v.length===0)return I?(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 Q=[...Z()];if(V.widths&&(Q=Q.map(e=>{let t=V.widths?.[e.accessorKey];return t?{...e,size:t}:e})),V.order&&V.order.length>0){let e=new Map(V.order.map((e,t)=>[e,t]));Q.sort((t,n)=>(e.get(t.accessorKey)??1/0)-(e.get(n.accessorKey)??1/0))}let $=`operations`in e?e.operations:void 0,Me=$&&($.update||$.delete),Ne=e.rowActions&&e.rowActions.length>0,Pe=Me||Ne?[...Q,{header:E(`grid.actions`),accessorKey:`_actions`,cell:(t,n)=>(0,y.jsx)(P,{row:n,rowActions:e.rowActions,canEdit:!!($?.update&&c),canDelete:!!($?.delete&&l),onEdit:c,onDelete:l,onAction:(e,t)=>X({type:e,params:{record:t}})}),sortable:!1}]:Q,Fe=Pe.filter(e=>e.pinned===`left`),Ie=Pe.filter(e=>e.pinned===`right`),Le=Pe.filter(e=>!e.pinned),Re=Fe.length>0||Ie.length>0,ze=`sticky right-0 z-10 bg-background border-l border-border`,Be=Re?[...Fe,...Le,...Ie.map(e=>({...e,className:[e.className,ze].filter(Boolean).join(` `),cellClassName:[e.cellClassName,ze].filter(Boolean).join(` `)}))]:Pe,Ve=Re?Fe.length:e.frozenColumns??1,He=e.batchActions??e.bulkActions,Ue=He&&He.length>0,We=!1;e.selection?.type?We=e.selection.type===`none`?!1:e.selection.type:e.selectable===void 0?Ue&&(We=`multiple`):We=e.selectable;let Ge=e.pagination===void 0?e.showPagination===void 0?!0:e.showPagination:!0,Ke=e.pagination?.pageSize||e.pageSize||10,qe=e.searchableFields===void 0?e.showSearch===void 0?!0:e.showSearch:e.searchableFields.length>0,Je={type:`data-table`,caption:e.label||e.title,columns:Be,data:v,pagination:Ge,pageSize:Ke,searchable:qe,selectable:We,sortable:!0,exportable:$?.export,rowActions:!!(e.editable&&Me),resizableColumns:e.resizable??e.resizableColumns??!0,reorderableColumns:e.reorderableColumns??!1,editable:e.editable??!1,singleClickEdit:e.singleClickEdit??!0,className:e.className,cellClassName:B===`compact`?`px-3 py-1 text-[13px] leading-tight`:B===`short`?`px-3 py-1 text-[13px] leading-normal`:B===`tall`?`px-3 py-2.5 text-sm`:B===`extra_tall`?`px-3 py-3.5 text-sm leading-relaxed`:`px-3 py-1.5 text-[13px] leading-normal`,showRowNumbers:!0,showAddRow:!!$?.create,onAddRecord:h,rowClassName:e.rowColor?(e,t)=>we(e):void 0,rowStyle:e.conditionalFormatting?.length?(e,t)=>Te(e):void 0,frozenColumns:Ve,onSelectionChange:e=>{fe(e),u?.(e)},onRowClick:Y.handleClick,onCellChange:f,onRowSave:p,onBatchSave:m,onColumnResize:(e,t)=>{he({...V,widths:{...V.widths,[e]:t}})},onColumnReorder:e=>{he({...V,order:e})}},Ye=e=>({...Je,caption:void 0,data:e,pagination:!1,searchable:!1}),Xe=e.label?`${e.label} Detail`:e.objectName?`${e.objectName.charAt(0).toUpperCase()+e.objectName.slice(1)} Detail`:`Record Detail`;if(I&&v.length>0&&!De){let e=Z().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`],o=[`stage`,`status`,`priority`,`category`,`severity`,`level`],s=[`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`],c=[`probability`,`percent`,`rate`,`ratio`,`confidence`,`score`],l=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`},u=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`},d=e=>{let t=e.toLowerCase();return r.some(e=>t.includes(e))?`amount`:o.some(e=>t.includes(e))?`stage`:s.some(e=>t.includes(e))?`date`:c.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:v.map((t,r)=>{let o=e.slice(1,5),s=o.find(e=>d(e.accessorKey)===`amount`),c=o.find(e=>d(e.accessorKey)===`stage`),f=o.filter(e=>d(e.accessorKey)===`date`),p=o.filter(e=>d(e.accessorKey)===`percent`),m=o.filter(e=>e!==s&&e!==c&&!f.includes(e)&&!p.includes(e)),h=c?String(t[c.accessorKey]??``):``,g=h?u(h):``;return(0,y.jsxs)(`div`,{className:[`border rounded-lg p-2.5 bg-card hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,g?`border-l-[3px] ${g}`:``].filter(Boolean).join(` `),onClick:()=>Y.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]??`—`}),(s||c)&&(0,y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[s&&(0,y.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:typeof t[s.accessorKey]==`number`?(0,i.formatCompactCurrency)(t[s.accessorKey]):t[s.accessorKey]!=null&&typeof t[s.accessorKey]==`object`?String(t[s.accessorKey]):t[s.accessorKey]??`—`}),c&&t[c.accessorKey]&&(0,y.jsx)(a.Badge,{variant:`outline`,className:`text-xs shrink-0 max-w-[140px] truncate ${l(String(t[c.accessorKey]))}`,children:String(t[c.accessorKey])})]}),(f.length>0||p.length>0)&&(0,y.jsxs)(`div`,{className:`flex items-center justify-between py-0.5 text-xs text-muted-foreground`,children:[f[0]&&(0,y.jsx)(`span`,{className:`tabular-nums`,children:t[f[0].accessorKey]?(0,i.formatDate)(t[f[0].accessorKey],`short`):`—`}),p[0]&&t[p[0].accessorKey]!=null&&(0,y.jsx)(`span`,{className:`tabular-nums`,children:(0,i.formatPercent)(Number(t[p[0].accessorKey]))})]}),f.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]?(0,i.formatDate)(t[e.accessorKey],`short`):`—`})]},e.accessorKey)),m.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)})}),Y.isOverlay&&(0,y.jsx)(a.NavigationOverlay,{...Y,title:Xe,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 Ze=()=>{ue(e=>e===`compact`?`short`:e===`short`?`medium`:e===`medium`?`tall`:e===`tall`?`extra_tall`:`compact`)},Qe={compact:o.Rows4,short:o.Rows3,medium:o.Rows2,tall:o.AlignJustify,extra_tall:o.AlignJustify}[B],$e=e.rowHeight!==void 0,et=e.exportOptions||$e?(0,y.jsxs)(`div`,{className:`flex items-center justify-end gap-1 px-2 py-1`,children:[$e&&(0,y.jsxs)(a.Button,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,onClick:Ze,title:`Row height: ${B}`,children:[(0,y.jsx)(Qe,{className:`h-3.5 w-3.5 mr-1.5`}),(0,y.jsx)(`span`,{className:`hidden sm:inline capitalize`,children:B})]}),e.exportOptions&&(0,y.jsxs)(a.Popover,{open:se,onOpenChange:R,children:[(0,y.jsx)(a.PopoverTrigger,{asChild:!0,children:(0,y.jsxs)(a.Button,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,children:[(0,y.jsx)(o.Download,{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)(a.PopoverContent,{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)(a.Button,{variant:`ghost`,size:`sm`,className:`w-full justify-start h-8 text-xs`,onClick:()=>je(e),children:[(0,y.jsx)(o.Download,{className:`h-3.5 w-3.5 mr-2`}),E(`grid.exportAs`,{format:e.toUpperCase()})]},e))})})]})]}):null,tt=e=>{let t=[`_id`,`id`,`created_at`,`updated_at`,`created_by`,`updated_by`],n=Object.entries(e),r=n.filter(([e])=>!t.includes(e)),o=n.filter(([e])=>t.includes(e)&&e!==`_id`&&e!==`id`),s=e=>e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `),c=(e,t)=>{if(t==null||t===``)return(0,y.jsx)(`span`,{className:`text-muted-foreground/50 text-sm italic`,children:`Empty`});let n=A?.fields?.[e];if(n?.type){let e=(0,i.getCellRenderer)(n.type);if(e)return(0,y.jsx)(e,{value:t,field:n})}return typeof t==`boolean`?(0,y.jsx)(a.Badge,{variant:t?`default`:`outline`,children:t?`Yes`:`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:(0,i.formatDate)(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:(0,i.formatCurrency)(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:r.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:s(e)}),(0,y.jsx)(`div`,{className:`flex-1 min-w-0`,children:c(e,t)})]},e))})}),o.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:`System`})}),(0,y.jsx)(`div`,{className:`divide-y divide-border/50`,children:o.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:s(e)}),(0,y.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1 min-w-0 break-words`,children:String(t??``)})]},e))})]})]})},nt=Ae?(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:Be.filter(e=>ke.has(e.accessorKey)).map(e=>{let t=ke.get(e.accessorKey);return(0,y.jsxs)(`span`,{"data-testid":`summary-${e.accessorKey}`,children:[e.header,`: `,t.label]},e.accessorKey)})})}):null,rt=De?(0,y.jsx)(`div`,{className:`space-y-2`,children:Ee.map(e=>(0,y.jsx)(O,{groupKey:e.key,label:e.label,count:e.rows.length,collapsed:e.collapsed,aggregations:e.aggregations,onToggle:Oe,children:(0,y.jsx)(r.SchemaRenderer,{schema:Ye(e.rows)})},e.key))}):(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(r.SchemaRenderer,{schema:Je}),nt]}),it=(0,y.jsx)(a.ExportProgressDialog,{open:ce,onOpenChange:le,job:z,filename:`${e.exportOptions?.fileNamePrefix||e.objectName||`export`}.${z.progress?.format||`csv`}`,closeAfterDownloadMs:400});return Y.isOverlay&&Y.mode===`split`?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(a.NavigationOverlay,{...Y,title:Xe,mainContent:(0,y.jsxs)(y.Fragment,{children:[et,rt,(0,y.jsx)(F,{selectedRows:de,actions:He??[],onAction:(e,t)=>X({type:e,params:{records:t}}),onClearSelection:()=>fe([])})]}),children:e=>tt(e)}),it]}):(0,y.jsxs)(`div`,{ref:ge,className:`relative h-full`,children:[ve>0&&(0,y.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:ve},children:E(_e?`grid.refreshing`:`grid.pullToRefresh`)}),et,rt,(0,y.jsx)(F,{selectedRows:de,actions:He??[],onAction:(e,t)=>X({type:e,params:{records:t}}),onClearSelection:()=>fe([])}),Y.isOverlay&&(0,y.jsx)(a.NavigationOverlay,{...Y,title:Xe,children:e=>tt(e)}),it]})};function L(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o;n.key&&n.debug?.call(n)&&(o=Date.now());let s=e();if(!(s.length!==r.length||s.some((e,t)=>r[t]!==e)))return i;r=s;let c;if(n.key&&n.debug?.call(n)&&(c=Date.now()),i=t(...s),n.key&&n.debug?.call(n)){let e=Math.round((Date.now()-o)*100)/100,t=Math.round((Date.now()-c)*100)/100,r=t/16,i=(e,t)=>{for(e=String(e);e.length<t;)e=` `+e;return e};console.info(`%c⏱ ${i(t,5)} /${i(e,5)} ms`,`
6
+ <%s key={someKey} {...props} />`,o,p,m,p),L[p+o]=!0)}if(p=null,i!==void 0&&(r(i),p=``+i),s(n)&&(r(n.key),p=``+n.key),`key`in n)for(var h in i={},n)h!==`key`&&(i[h]=n[h]);else i=n;return p&&c(i,typeof e==`function`?e.displayName||e.name||`Unknown`:e),u(e,p,i,a(),l,d)}function f(e){p(e)?e._store&&(e._store.validated=1):typeof e==`object`&&e&&e.$$typeof===E&&(e._payload.status===`fulfilled`?p(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function p(e){return typeof e==`object`&&!!e&&e.$$typeof===h}var m=require(`react`),h=Symbol.for(`react.transitional.element`),g=Symbol.for(`react.portal`),_=Symbol.for(`react.fragment`),v=Symbol.for(`react.strict_mode`),y=Symbol.for(`react.profiler`),b=Symbol.for(`react.consumer`),x=Symbol.for(`react.context`),S=Symbol.for(`react.forward_ref`),C=Symbol.for(`react.suspense`),w=Symbol.for(`react.suspense_list`),T=Symbol.for(`react.memo`),E=Symbol.for(`react.lazy`),D=Symbol.for(`react.activity`),O=Symbol.for(`react.client.reference`),k=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,A=Object.prototype.hasOwnProperty,j=Array.isArray,M=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(e){return e()}};var N,P={},F=m.react_stack_bottom_frame.bind(m,o)(),I=M(i(o)),L={};e.Fragment=_,e.jsx=function(e,t,n){var r=1e4>k.recentlyCreatedOwnerStacks++;return d(e,t,n,!1,r?Error(`react-stack-top-frame`):F,r?M(i(e)):I)},e.jsxs=function(e,t,n){var r=1e4>k.recentlyCreatedOwnerStacks++;return d(e,t,n,!0,r?Error(`react-stack-top-frame`):F,r?M(i(e)):I)}})()})),y=m(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=_():t.exports=v()}))(),b=(0,t.createContext)(null);b.displayName=`MobileContext`;var x={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 S(e){return e.startsWith(`bg-`)?e:x[e.toLowerCase().trim()]}function C(e){return(0,t.useCallback)(t=>{if(!e?.field||!e.colors)return;let n=String(t[e.field]??``),r=e.colors[n];if(r)return S(r)},[e?.field,e?.colors])}function w(e){if(e==null||e===``)return``;if(Array.isArray(e))return e.map(e=>w(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 T(e,t){return w(e[t])}function E(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 E(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 D(e,t){return t.map(({field:t,type:n})=>{let r=e.map(e=>Number(e[t])).filter(e=>Number.isFinite(e)),i;switch(n){case`count`:i=r.length;break;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 O(e,t,n){let r=e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`});return n===`desc`?-r:r}function k(e,n,r,i){let a=e?.fields,o=!!(a&&a.length>0),[s,c]=(0,t.useState)({});return{groups:(0,t.useMemo)(()=>{if(!o||!a)return[];let e=(t,n,o)=>{if(n>=a.length)return[];let c=a[n],l=new Map,u=[];for(let e of t){let t=T(e,c.field);l.has(t)||(l.set(t,{label:E(e[c.field],c.field,i),rows:[]}),u.push(t)),l.get(t).rows.push(e)}let d=c.order??`asc`;return u.sort((e,t)=>O(l.get(e)?.label??e,l.get(t)?.label??t,d)),u.map(t=>{let i=l.get(t),u=o?`${o}__${n}:${t}`:`${n}:${t}`,d=!!c.collapsed,f=u in s?s[u]:d,p=r&&r.length>0?D(i.rows,r):[],m=n+1<a.length?e(i.rows,n+1,u):[];return{key:u,label:i.label,field:c.field,depth:n,rows:i.rows,collapsed:f,aggregations:p,subgroups:m}})};return e(n,0,``)},[n,a,o,s,r,i]),isGrouped:o,toggleGroup:(0,t.useCallback)(e=>{c(t=>{let n=e.split(`__`).pop()||``,r=/^(\d+):/.exec(n),i=r?Number(r[1]):0,o=!!a?.[i]?.collapsed;return{...t,[e]:t[e]===void 0?!o:!t[e]}})},[a])}}var A=({groupKey:e,label:t,count:n,collapsed:r,aggregations:i,onToggle:a,children:s})=>(0,y.jsxs)(`div`,{className:`border rounded-md`,"data-testid":`group-row-${e}`,children:[(0,y.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 px-3 py-2 text-sm font-medium text-left bg-muted/50 hover:bg-muted transition-colors`,onClick:()=>a(e),"aria-expanded":!r,children:[r?(0,y.jsx)(o.ChevronRight,{className:`h-4 w-4 shrink-0`}):(0,y.jsx)(o.ChevronDown,{className:`h-4 w-4 shrink-0`}),(0,y.jsx)(`span`,{className:`group-label`,children:t}),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}`))}),(0,y.jsxs)(`span`,{className:`ml-auto text-xs text-muted-foreground group-count`,children:[`(`,n,`)`]})]}),!r&&s]});function j(e){return typeof e==`string`?{type:e}:e}function M(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 N(e,t){return t===null?``:`${{count:`Count`,sum:`Sum`,avg:`Avg`,min:`Min`,max:`Max`}[e]||e}: ${e===`avg`?t.toLocaleString(void 0,{maximumFractionDigits:2}):t.toLocaleString()}`}function P(e,n){return(0,t.useMemo)(()=>{let t=new Map;if(!e||e.length===0||n.length===0)return{summaries:t,hasSummary:!1};for(let r of e){if(!r.summary)continue;let e=j(r.summary),i=e.field||r.field,a=[];for(let e of n){let t=e[i];if(t!=null&&typeof t==`number`&&!isNaN(t))a.push(t);else if(t!=null&&typeof t==`string`){let e=parseFloat(t);isNaN(e)||a.push(e)}}let o;if(e.type===`count`){let e=n.filter(e=>e[i]!=null&&e[i]!==``).length;o=e>0?e:null}else o=M(e.type,a);t.set(r.field,{field:r.field,value:o,label:N(e.type,o)})}return{summaries:t,hasSummary:t.size>0}},[e,n])}function F(e){return e.replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var I=({row:e,rowActions:t,canEdit:n,canDelete:r,onEdit:i,onDelete:s,onAction:c})=>(0,y.jsxs)(a.DropdownMenu,{children:[(0,y.jsx)(a.DropdownMenuTrigger,{asChild:!0,children:(0,y.jsxs)(a.Button,{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)(o.MoreVertical,{className:`h-4 w-4`}),(0,y.jsx)(`span`,{className:`sr-only`,children:`Open menu`})]})}),(0,y.jsxs)(a.DropdownMenuContent,{align:`end`,children:[n&&i&&(0,y.jsxs)(a.DropdownMenuItem,{onClick:()=>i(e),children:[(0,y.jsx)(o.Edit,{className:`mr-2 h-4 w-4`}),`Edit`]}),r&&s&&(0,y.jsxs)(a.DropdownMenuItem,{onClick:()=>s(e),children:[(0,y.jsx)(o.Trash2,{className:`mr-2 h-4 w-4`}),`Delete`]}),t?.map(t=>(0,y.jsx)(a.DropdownMenuItem,{onClick:()=>c?.(t,e),"data-testid":`row-action-${t}`,children:F(t)},t))]})]}),L=({selectedRows:e,actions:t,onAction:n,onClearSelection:r})=>!t||t.length===0||e.length===0?null:(0,y.jsxs)(`div`,{className:`border-t px-4 py-1.5 flex items-center gap-2 text-xs bg-primary/5 shrink-0`,"data-testid":`bulk-actions-bar`,children:[(0,y.jsxs)(`span`,{className:`text-muted-foreground font-medium`,children:[e.length,` selected`]}),(0,y.jsx)(`div`,{className:`flex items-center gap-1 ml-2`,children:t.map(t=>(0,y.jsx)(a.Button,{variant:`outline`,size:`sm`,className:`h-6 px-2 text-xs`,onClick:()=>n?.(t,e),"data-testid":`bulk-action-${t}`,children:F(t)},t))}),(0,y.jsx)(a.Button,{variant:`ghost`,size:`sm`,className:`h-6 px-2 text-xs ml-auto`,onClick:r,children:`Clear`})]}),ee={"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`};function te(){try{let e=(0,r.useObjectTranslation)();return e.t(`grid.actions`)===`grid.actions`?{t:(e,t)=>{let n=ee[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=ee[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n}}}}function ne(e){if(e!=null)return typeof e==`string`?e:void 0}function re(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 ie(e){if(!(!e||e.length===0))return typeof e[0]==`object`&&e[0],e}var ae=({schema:e,dataSource:s,onEdit:c,onDelete:l,onRowSelect:u,onRowClick:d,onCellChange:f,onRowSave:p,onBatchSave:m,onAddRecord:h,..._})=>{let[v,b]=(0,t.useState)([]),[x,S]=(0,t.useState)(!0),[w,T]=(0,t.useState)(null),{t:E}=te(),{fieldLabel:D,translateOptions:O}=(0,r.useSafeFieldLabel)(),[j,M]=(0,t.useState)(null),[N,ee]=(0,t.useState)(!1),[ae,R]=(0,t.useState)(0),[oe,z]=(0,t.useState)(!1),[se,ce]=(0,t.useState)(!1),B=(0,a.useExportJob)({dataSource:s}),[V,le]=(0,t.useState)(e.rowHeight??`compact`),[ue,de]=(0,t.useState)([]),fe=t.default.useMemo(()=>e.id?`grid-columns-${e.objectName}-${e.id}`:`grid-columns-${e.objectName}`,[e.objectName,e.id]),[H,pe]=(0,t.useState)(()=>{try{let e=localStorage.getItem(fe);return e?JSON.parse(e):{}}catch{return{}}}),me=(0,t.useCallback)(e=>{pe(e);try{localStorage.setItem(fe,JSON.stringify(e))}catch(e){console.warn(`Failed to persist column state:`,e)}},[fe]),{ref:he,isRefreshing:ge,pullDistance:_e}=g({onRefresh:(0,t.useCallback)(async()=>{R(e=>e+1)},[]),enabled:!!s&&!!e.objectName});(0,t.useEffect)(()=>{let e=()=>ee(window.innerWidth<480);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let ve=_.data,ye=(0,r.useDataScope)(e.bind),be=re(e),U=t.default.useMemo(()=>ve&&Array.isArray(ve)?{provider:`value`,items:ve}:ye&&Array.isArray(ye)?{provider:`value`,items:ye}:be,[JSON.stringify(be),ye,ve]),W=U?.provider===`value`,G=U?.provider===`object`&&U&&`object`in U?U.object:e.objectName,K=e.fields,q=e.columns,J=e.filter,Y=e.sort,xe=e.pagination,Se=e.pageSize;(0,t.useEffect)(()=>{W&&U?.provider===`value`&&(b(e=>{let t=U.items;return JSON.stringify(e)===JSON.stringify(t)?e:t}),S(!1))},[W,U]),(0,t.useEffect)(()=>{if(!W||!G||!s)return;let e=!1;return(async()=>{try{if(typeof s.getObjectSchema!=`function`)return;let t=await s.getObjectSchema(G);e||M(t)}catch(e){console.warn(`[ObjectGrid] Failed to fetch objectSchema for inline data (objectName: ${G}):`,e)}})(),()=>{e=!0}},[W,G,s]),(0,t.useEffect)(()=>{if(W)return;let t=!1;return(async()=>{S(!0),T(null);try{let r=null,i=ie(q)||K;if(G&&s)if(typeof s.getObjectSchema==`function`){let e=await s.getObjectSchema(G);if(t)return;r=e}else r={name:G,fields:{}};else if(i&&G)r={name:G,fields:{}};else if(G)throw Error(`DataSource required`);else throw Error(`Object name required for data fetching`);if(t||M(r),s&&G){let i={$select:(()=>{if(K)return K;if(q&&Array.isArray(q))return q.map(e=>typeof e==`string`?e:e.field)})(),$top:xe?.pageSize||Se||50};J&&Array.isArray(J)?i.$filter=J:e.defaultFilters&&(i.$filter=e.defaultFilters),Y?typeof Y==`string`?i.$orderby=Y:Array.isArray(Y)&&(i.$orderby=Y.map(e=>`${e.field} ${e.order}`).join(`, `)):e.defaultSort&&(i.$orderby=`${e.defaultSort.field} ${e.defaultSort.order}`);let a=(0,n.buildExpandFields)(r?.fields,q??K);a.length>0&&(i.$expand=a);let o=await s.find(G,i);if(t)return;b(o.data||[])}}catch(e){t||T(e)}finally{t||S(!1)}})(),()=>{t=!0}},[G,K,q,J,Y,xe,Se,s,W,U,ae]);let X=(0,r.useNavigationOverlay)({navigation:e.navigation,objectName:e.objectName,onNavigate:e.onNavigate,onRowClick:d}),{execute:Z}=(0,r.useAction)(),Ce=C(e.rowColor),we=(0,t.useCallback)(t=>{let r=e.conditionalFormatting;if(!(!r||r.length===0))for(let e of r){let r=!1,i=(`condition`in e?e.condition:void 0)||(`expression`in e?e.expression:void 0)||void 0;if(i)r=(0,n.evaluatePlainCondition)(i,t);else if(`field`in e&&`operator`in e&&e.field&&e.operator){let n=e,i=t[n.field];switch(n.operator){case`equals`:r=i===n.value;break;case`not_equals`:r=i!==n.value;break;case`contains`:r=typeof i==`string`&&typeof n.value==`string`&&i.includes(n.value);break;case`greater_than`:r=typeof i==`number`&&typeof n.value==`number`&&i>n.value;break;case`less_than`:r=typeof i==`number`&&typeof n.value==`number`&&i<n.value;break;case`in`:r=Array.isArray(n.value)&&n.value.includes(i);break}}if(r){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]),Te=t.default.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=j?.fields?.[t],a=ie(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,j,O,E]),{groups:Ee,isGrouped:De,toggleGroup:Oe}=k(e.grouping,v,void 0,Te),{summaries:ke,hasSummary:Ae}=P(t.default.useMemo(()=>{let t=ie(e.columns);if(t&&t.length>0&&typeof t[0]==`object`)return t},[e.columns]),v),Q=(0,t.useCallback)(()=>{let t=e=>e&&{text:(0,y.jsx)(o.Type,{className:`h-3.5 w-3.5`}),number:(0,y.jsx)(o.Hash,{className:`h-3.5 w-3.5`}),currency:(0,y.jsx)(o.Hash,{className:`h-3.5 w-3.5`}),percent:(0,y.jsx)(o.Hash,{className:`h-3.5 w-3.5`}),date:(0,y.jsx)(o.Calendar,{className:`h-3.5 w-3.5`}),datetime:(0,y.jsx)(o.Clock,{className:`h-3.5 w-3.5`}),boolean:(0,y.jsx)(o.CheckSquare,{className:`h-3.5 w-3.5`}),user:(0,y.jsx)(o.User,{className:`h-3.5 w-3.5`}),select:(0,y.jsx)(o.Tag,{className:`h-3.5 w-3.5`})}[e]||(0,y.jsx)(o.Type,{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(v.length>0){let t=v.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))&&v.length>0&&typeof v.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`percent`;if([`status`,`priority`,`category`,`stage`,`type`,`severity`,`level`].some(e=>t.includes(e))&&v.length>0){let t=new Set(v.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))&&v.length>0&&typeof v.find(t=>t[e.field]!=null)?.[e.field]==`number`)return`currency`;if(v.length>0){let t=v.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=ie(q);if(r){if(r.length>0&&typeof r[0]==`object`&&r[0]!==null){let o=r[0];if(`accessorKey`in o)return r.map(r=>{if(r.cell)return r;let a=n({field:r.accessorKey,label:r.header,type:r.type});if(!a)return r;let o=(0,i.getCellRenderer)(a),s={name:r.accessorKey,type:a};return a===`select`&&(s.options=Array.from(new Set(v.map(e=>e[r.accessorKey]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))}))),{...r,...e.showColumnTypeIcons&&{headerIcon:t(a)},cell:e=>(0,y.jsx)(o,{value:e,field:s})}});if(`field`in o)return r.filter(e=>e?.field&&typeof e.field==`string`&&!e.hidden).map((r,o)=>{let s=ne(r.label)||r.field.charAt(0).toUpperCase()+r.field.slice(1).replace(/_/g,` `),c=e.objectName?D(e.objectName,r.field,s):s,l,u=j?.fields?.[r.field],d=r.type||u?.type||n({field:r.field})||null,f=d?(0,i.getCellRenderer)(d):null,p={name:r.field,type:d||`text`};u&&(u.label&&(p.label=u.label),u.currency&&(p.currency=u.currency),u.precision!==void 0&&(p.precision=u.precision),u.format&&(p.format=u.format),u.options&&(p.options=O(e.objectName,r.field,u.options))),d===`select`&&!p.options&&(p.options=Array.from(new Set(v.map(e=>e[r.field]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))}))),r.options&&(p.options=O(e.objectName,r.field,r.options));let m=o===0&&!r.link&&!r.action,h=r.link||m;l=r.link&&r.action||m&&r.action||h?(e,t)=>(0,y.jsx)(`button`,{type:`button`,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit`,"data-testid":m?`primary-field-link`:`link-cell`,onClick:e=>{e.stopPropagation(),X.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)(a.Button,{variant:`outline`,size:`sm`,className:`h-7 text-xs`,"data-testid":`action-cell`,onClick:n=>{n.stopPropagation(),Z({type:r.action,params:{record:t,field:r.field,value:e}})},children:F(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)(a.EmptyValue,{});let g=r.prefix;if(g?.field){let e=l,t=g.type===`badge`?(0,i.getCellRenderer)(`select`):null;l=(n,r)=>{let i=r[g.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:g.field,type:`select`}}):(0,y.jsx)(`span`,{className:`text-muted-foreground text-xs mr-1.5`,children:String(i)}):null,e(n,r)]})}}let _=[`number`,`currency`,`percent`],b=d||r.type,x=r.align||(b&&_.includes(b)?`right`:void 0),S=o===0||r.essential===!0;return{header:c,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},...l&&{cell:l},...r.pinned&&{pinned:r.pinned}}})}return r.filter(e=>typeof e==`string`&&e.trim().length>0).map((r,a)=>{let o=j?.fields?.[r],s=o?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),c=e.objectName?D(e.objectName,r,s):s,l=o?.type||n({field:r})||null,u=l?(0,i.getCellRenderer)(l):null,d={name:r,type:l||`text`};o&&(o.label&&(d.label=o.label),o.currency&&(d.currency=o.currency),o.precision!==void 0&&(d.precision=o.precision),o.format&&(d.format=o.format),o.options&&(d.options=O(e.objectName,r,o.options))),l===`select`&&!d.options&&(d.options=Array.from(new Set(v.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))})));let f=l&&[`number`,`currency`,`percent`].includes(l)?`right`:void 0,p=a===0,m;return p&&u?m=(e,t)=>(0,y.jsx)(`button`,{type:`button`,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit`,"data-testid":`primary-field-link`,onClick:e=>{e.stopPropagation(),X.handleClick(t)},children:(0,y.jsx)(u,{value:e,field:d})}):p?m=(e,t)=>(0,y.jsx)(`button`,{type:`button`,className:`text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit`,"data-testid":`primary-field-link`,onClick:e=>{e.stopPropagation(),X.handleClick(t)},children:e!=null&&e!==``?String(e):(0,y.jsx)(`span`,{className:`text-muted-foreground/50 text-xs italic`,children:`—`})}):u&&(m=e=>(0,y.jsx)(u,{value:e,field:d})),{header:c,accessorKey:r,...e.showColumnTypeIcons&&l&&{headerIcon:t(l)},...f&&{align:f},...m&&{cell:m},sortable:o?.sortable!==!1}})}if(W){let r=U?.provider===`value`?U.items:[];if(r.length>0)return(K||Object.keys(r[0])).map(r=>{let a=j?.fields?.[r],o=a?.type||n({field:r})||null,s=o?(0,i.getCellRenderer)(o):null,c=a?.label||r.charAt(0).toUpperCase()+r.slice(1).replace(/_/g,` `),l={name:r,type:o||`text`};a&&(a.label&&(l.label=a.label),a.currency&&(l.currency=a.currency),a.precision!==void 0&&(l.precision=a.precision),a.format&&(l.format=a.format),a.options&&(l.options=O(e.objectName,r,a.options))),o===`select`&&!l.options&&(l.options=Array.from(new Set(v.map(e=>e[r]).filter(Boolean))).map(e=>({value:e,label:(0,i.humanizeLabel)(String(e))})));let u=o&&[`number`,`currency`,`percent`].includes(o)?`right`:void 0;return{header:c,accessorKey:r,...e.showColumnTypeIcons&&o&&{headerIcon:t(o)},...u&&{align:u},...s&&{cell:e=>(0,y.jsx)(s,{value:e,field:l})},sortable:a?.sortable!==!1}})}if(!j)return[];let s=[],c=new Set([`id`,`created_at`,`createdAt`,`updated_at`,`updatedAt`,`deleted_at`,`deletedAt`,`created_by`,`createdBy`,`updated_by`,`updatedBy`,`_version`,`_rev`]),l=j?.compactLayout,u=Object.keys(j.fields||{}),d;if(K)d=K;else if(l?.length)d=l.filter(e=>j.fields?.[e]);else{let e=u.filter(e=>{let t=j.fields?.[e];return!(!t||t.hidden||t.readonly&&c.has(e))});d=[...e.filter(e=>!c.has(e)),...e.filter(e=>c.has(e))]}return d.forEach(t=>{let n=j.fields?.[t];if(!n||n.permissions&&n.permissions.read===!1)return;let r=(0,i.getCellRenderer)(n.type),a=[`number`,`currency`,`percent`],o=n.options?{...n,options:O(e.objectName,t,n.options)}:n;s.push({header:e.objectName?D(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})}),s},[j,K,q,U,W,X.handleClick,Z,v,D,O,e.objectName]),je=(0,t.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`)&&B.isSupported&&e.objectName&&!W&&n?.streaming!==!1){let n=Q().filter(e=>e.accessorKey!==`_actions`).map(e=>e.accessorKey).filter(Boolean);z(!1),ce(!0),B.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?v.slice(0,r):v,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(`
7
+ `)||t.includes(`\r`)?`"${t.replace(/"/g,`""`)}"`:t};if(t===`csv`){let e=Q().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(`
8
+ `)],{type:`text/csv;charset=utf-8;`}),`${a}.csv`)}else t===`json`&&s(new Blob([JSON.stringify(o,null,2)],{type:`application/json`}),`${a}.json`);z(!1)},[v,e.exportOptions,e.objectName,Q,B,W]);if(w)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:w.message})]});if(x&&v.length===0)return N?(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 Me=[...Q()];if(H.widths&&(Me=Me.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]));Me.sort((t,n)=>(e.get(t.accessorKey)??1/0)-(e.get(n.accessorKey)??1/0))}let $=`operations`in e?e.operations:void 0,Ne=$&&($.update||$.delete),Pe=e.rowActions&&e.rowActions.length>0,Fe=Ne||Pe?[...Me,{header:E(`grid.actions`),accessorKey:`_actions`,cell:(t,n)=>(0,y.jsx)(I,{row:n,rowActions:e.rowActions,canEdit:!!($?.update&&c),canDelete:!!($?.delete&&l),onEdit:c,onDelete:l,onAction:(e,t)=>Z({type:e,params:{record:t}})}),sortable:!1}]:Me,Ie=Fe.filter(e=>e.pinned===`left`),Le=Fe.filter(e=>e.pinned===`right`),Re=Fe.filter(e=>!e.pinned),ze=Ie.length>0||Le.length>0,Be=`sticky right-0 z-10 bg-background border-l border-border`,Ve=ze?[...Ie,...Re,...Le.map(e=>({...e,className:[e.className,Be].filter(Boolean).join(` `),cellClassName:[e.cellClassName,Be].filter(Boolean).join(` `)}))]:Fe,He=ze?Ie.length:e.frozenColumns??1,Ue=e.batchActions??e.bulkActions,We=Ue&&Ue.length>0,Ge=!1;e.selection?.type?Ge=e.selection.type===`none`?!1:e.selection.type:e.selectable===void 0?We&&(Ge=`multiple`):Ge=e.selectable;let Ke=e.pagination===void 0?e.showPagination===void 0?!0:e.showPagination:!0,qe=e.pagination?.pageSize||e.pageSize||10,Je=e.searchableFields===void 0?e.showSearch===void 0?!0:e.showSearch:e.searchableFields.length>0,Ye={type:`data-table`,caption:e.label||e.title,columns:Ve,data:v,pagination:Ke,pageSize:qe,searchable:Je,selectable:Ge,sortable:!0,exportable:$?.export,rowActions:!!(e.editable&&Ne),resizableColumns:e.resizable??e.resizableColumns??!0,reorderableColumns:e.reorderableColumns??!1,editable:e.editable??!1,singleClickEdit:e.singleClickEdit??!0,className:e.className,cellClassName:V===`compact`?`px-3 py-1 text-[13px] leading-tight`:V===`short`?`px-3 py-1 text-[13px] leading-normal`:V===`tall`?`px-3 py-2.5 text-sm`:V===`extra_tall`?`px-3 py-3.5 text-sm leading-relaxed`:`px-3 py-1.5 text-[13px] leading-normal`,showRowNumbers:!0,showAddRow:!!$?.create,onAddRecord:h,rowClassName:e.rowColor?(e,t)=>Ce(e):void 0,rowStyle:e.conditionalFormatting?.length?(e,t)=>we(e):void 0,frozenColumns:He,onSelectionChange:e=>{de(e),u?.(e)},onRowClick:X.handleClick,onCellChange:f,onRowSave:p,onBatchSave:m,onColumnResize:(e,t)=>{me({...H,widths:{...H.widths,[e]:t}})},onColumnReorder:e=>{me({...H,order:e})}},Xe=e=>({...Ye,caption:void 0,data:e,pagination:!1,searchable:!1}),Ze=e.label?`${e.label} Detail`:e.objectName?`${e.objectName.charAt(0).toUpperCase()+e.objectName.slice(1)} Detail`:`Record Detail`;if(N&&v.length>0&&!De){let e=Q().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`],o=[`stage`,`status`,`priority`,`category`,`severity`,`level`],s=[`date`,`due`,`created`,`updated`,`deadline`,`start`,`end`,`expires`],c=[`probability`,`percent`,`rate`,`ratio`,`confidence`,`score`],l=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`},u=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`},d=e=>{let t=e.toLowerCase();return r.some(e=>t.includes(e))?`amount`:o.some(e=>t.includes(e))?`stage`:s.some(e=>t.includes(e))?`date`:c.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:v.map((t,r)=>{let o=e.slice(1,5),s=o.find(e=>d(e.accessorKey)===`amount`),c=o.find(e=>d(e.accessorKey)===`stage`),f=o.filter(e=>d(e.accessorKey)===`date`),p=o.filter(e=>d(e.accessorKey)===`percent`),m=o.filter(e=>e!==s&&e!==c&&!f.includes(e)&&!p.includes(e)),h=c?String(t[c.accessorKey]??``):``,g=h?u(h):``;return(0,y.jsxs)(`div`,{className:[`border rounded-lg p-2.5 bg-card hover:bg-accent/50 cursor-pointer transition-colors touch-manipulation`,g?`border-l-[3px] ${g}`:``].filter(Boolean).join(` `),onClick:()=>X.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]??`—`}),(s||c)&&(0,y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[s&&(0,y.jsx)(`span`,{className:`text-sm tabular-nums font-medium`,children:typeof t[s.accessorKey]==`number`?(0,i.formatCompactCurrency)(t[s.accessorKey]):t[s.accessorKey]!=null&&typeof t[s.accessorKey]==`object`?String(t[s.accessorKey]):t[s.accessorKey]??`—`}),c&&t[c.accessorKey]&&(0,y.jsx)(a.Badge,{variant:`outline`,className:`text-xs shrink-0 max-w-[140px] truncate ${l(String(t[c.accessorKey]))}`,children:String(t[c.accessorKey])})]}),(f.length>0||p.length>0)&&(0,y.jsxs)(`div`,{className:`flex items-center justify-between py-0.5 text-xs text-muted-foreground`,children:[f[0]&&(0,y.jsx)(`span`,{className:`tabular-nums`,children:t[f[0].accessorKey]?(0,i.formatDate)(t[f[0].accessorKey],`short`):`—`}),p[0]&&t[p[0].accessorKey]!=null&&(0,y.jsx)(`span`,{className:`tabular-nums`,children:(0,i.formatPercent)(Number(t[p[0].accessorKey]))})]}),f.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]?(0,i.formatDate)(t[e.accessorKey],`short`):`—`})]},e.accessorKey)),m.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)})}),X.isOverlay&&(0,y.jsx)(a.NavigationOverlay,{...X,title:Ze,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 Qe=()=>{le(e=>e===`compact`?`short`:e===`short`?`medium`:e===`medium`?`tall`:e===`tall`?`extra_tall`:`compact`)},$e={compact:o.Rows4,short:o.Rows3,medium:o.Rows2,tall:o.AlignJustify,extra_tall:o.AlignJustify}[V],et=e.rowHeight!==void 0,tt=e.exportOptions||et?(0,y.jsxs)(`div`,{className:`flex items-center justify-end gap-1 px-2 py-1`,children:[et&&(0,y.jsxs)(a.Button,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,onClick:Qe,title:`Row height: ${V}`,children:[(0,y.jsx)($e,{className:`h-3.5 w-3.5 mr-1.5`}),(0,y.jsx)(`span`,{className:`hidden sm:inline capitalize`,children:V})]}),e.exportOptions&&(0,y.jsxs)(a.Popover,{open:oe,onOpenChange:z,children:[(0,y.jsx)(a.PopoverTrigger,{asChild:!0,children:(0,y.jsxs)(a.Button,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-muted-foreground hover:text-primary text-xs`,children:[(0,y.jsx)(o.Download,{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)(a.PopoverContent,{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)(a.Button,{variant:`ghost`,size:`sm`,className:`w-full justify-start h-8 text-xs`,onClick:()=>je(e),children:[(0,y.jsx)(o.Download,{className:`h-3.5 w-3.5 mr-2`}),E(`grid.exportAs`,{format:e.toUpperCase()})]},e))})})]})]}):null,nt=e=>{let t=[`_id`,`id`,`created_at`,`updated_at`,`created_by`,`updated_by`],n=Object.entries(e),r=n.filter(([e])=>!t.includes(e)),o=n.filter(([e])=>t.includes(e)&&e!==`_id`&&e!==`id`),s=e=>e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `),c=(e,t)=>{if(t==null||t===``)return(0,y.jsx)(`span`,{className:`text-muted-foreground/50 text-sm italic`,children:`Empty`});let n=j?.fields?.[e];if(n?.type){let e=(0,i.getCellRenderer)(n.type);if(e)return(0,y.jsx)(e,{value:t,field:n})}return typeof t==`boolean`?(0,y.jsx)(a.Badge,{variant:t?`default`:`outline`,children:t?`Yes`:`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:(0,i.formatDate)(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:(0,i.formatCurrency)(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:r.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:s(e)}),(0,y.jsx)(`div`,{className:`flex-1 min-w-0`,children:c(e,t)})]},e))})}),o.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:`System`})}),(0,y.jsx)(`div`,{className:`divide-y divide-border/50`,children:o.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:s(e)}),(0,y.jsx)(`span`,{className:`text-xs text-muted-foreground flex-1 min-w-0 break-words`,children:String(t??``)})]},e))})]})]})},rt=Ae?(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:Ve.filter(e=>ke.has(e.accessorKey)).map(e=>{let t=ke.get(e.accessorKey);return(0,y.jsxs)(`span`,{"data-testid":`summary-${e.accessorKey}`,children:[e.header,`: `,t.label]},e.accessorKey)})})}):null,it=e=>(0,y.jsx)(`div`,{style:e.depth>0?{marginLeft:e.depth*16}:void 0,children:(0,y.jsx)(A,{groupKey:e.key,label:e.label,count:e.rows.length,collapsed:e.collapsed,aggregations:e.aggregations,onToggle:Oe,children:e.subgroups.length>0?(0,y.jsx)(`div`,{className:`space-y-2 p-2`,children:e.subgroups.map(it)}):(0,y.jsx)(r.SchemaRenderer,{schema:Xe(e.rows)})})},e.key),at=De?(0,y.jsx)(`div`,{className:`space-y-2`,children:Ee.map(it)}):(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(r.SchemaRenderer,{schema:Ye}),rt]}),ot=(0,y.jsx)(a.ExportProgressDialog,{open:se,onOpenChange:ce,job:B,filename:`${e.exportOptions?.fileNamePrefix||e.objectName||`export`}.${B.progress?.format||`csv`}`,closeAfterDownloadMs:400});return X.isOverlay&&X.mode===`split`?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(a.NavigationOverlay,{...X,title:Ze,mainContent:(0,y.jsxs)(y.Fragment,{children:[tt,at,(0,y.jsx)(L,{selectedRows:ue,actions:Ue??[],onAction:(e,t)=>Z({type:e,params:{records:t}}),onClearSelection:()=>de([])})]}),children:e=>nt(e)}),ot]}):(0,y.jsxs)(`div`,{ref:he,className:`relative h-full`,children:[_e>0&&(0,y.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:_e},children:E(ge?`grid.refreshing`:`grid.pullToRefresh`)}),tt,at,(0,y.jsx)(L,{selectedRows:ue,actions:Ue??[],onAction:(e,t)=>Z({type:e,params:{records:t}}),onClearSelection:()=>de([])}),X.isOverlay&&(0,y.jsx)(a.NavigationOverlay,{...X,title:Ze,children:e=>nt(e)}),ot]})};function R(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o;n.key&&n.debug?.call(n)&&(o=Date.now());let s=e();if(!(s.length!==r.length||s.some((e,t)=>r[t]!==e)))return i;r=s;let c;if(n.key&&n.debug?.call(n)&&(c=Date.now()),i=t(...s),n.key&&n.debug?.call(n)){let e=Math.round((Date.now()-o)*100)/100,t=Math.round((Date.now()-c)*100)/100,r=t/16,i=(e,t)=>{for(e=String(e);e.length<t;)e=` `+e;return e};console.info(`%c⏱ ${i(t,5)} /${i(e,5)} ms`,`
9
9
  font-size: .6rem;
10
10
  font-weight: bold;
11
- color: hsl(${Math.max(0,Math.min(120-120*r,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i}return o.updateDeps=e=>{r=e},o}function oe(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var se=(e,t)=>Math.abs(e-t)<1.01,R=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},ce=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},le=e=>e,z=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let e=t;e<=n;e++)r.push(e);return r},B=(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(ce(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(ce(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},ue={passive:!0},de=typeof window>`u`?!0:`onscrollend`in window,fe=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=0,a=e.options.useScrollendEvent&&de?()=>void 0:R(r,()=>{t(i,!1)},e.options.isScrollingResetDelay),o=r=>()=>{let{horizontal:o,isRtl:s}=e.options;i=o?n.scrollLeft*(s&&-1||1):n.scrollTop,a(),t(i,r)},s=o(!0),c=o(!1);n.addEventListener(`scroll`,s,ue);let l=e.options.useScrollendEvent&&de;return l&&n.addEventListener(`scrollend`,c,ue),()=>{n.removeEventListener(`scroll`,s),l&&n.removeEventListener(`scrollend`,c)}},pe=(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`]},V=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;let o=e+t;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:o,behavior:n})},me=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,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);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=>{Object.entries(e).forEach(([t,n])=>{n===void 0&&delete e[t]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:le,rangeExtractor:z,onChange:()=>{},measureElement:pe,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`,...e}},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=L(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:process.env.NODE_ENV!==`production`&&`maybeNotify`,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}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.scrollAdjustments=0,this.scrollDirection=t?this.getScrollOffset()<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,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=L(()=>[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.pendingMeasuredCacheIndexes=[],{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=L(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{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.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let c=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1);let l=this.measurementsCache.slice(0,c),u=Array(a).fill(void 0);for(let e=0;e<c;e++){let t=l[e];t&&(u[t.lane]=e)}for(let i=c;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),c,d,f=o===`estimate`||s.has(e);if(a!==void 0&&this.options.lanes>1){c=a;let e=u[c],r=e===void 0?void 0:l[e];d=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?l[i-1]:this.getFurthestMeasurement(l,i);d=e?e.end+this.options.gap:t+n,c=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,c)}let p=s.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=d+m;l[i]={index:i,start:d,size:m,end:h,key:e,lane:c},u[c]=i}return this.measurementsCache=l,l},{key:process.env.NODE_ENV!==`production`&&`getMeasurements`,debug:()=>this.options.debug}),this.calculateRange=L(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?ge({measurements:e,outerSize:t,scrollOffset:n,lanes:r}):null,{key:process.env.NODE_ENV!==`production`&&`calculateRange`,debug:()=>this.options.debug}),this.getVirtualIndexes=L(()=>{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:process.env.NODE_ENV!==`production`&&`getVirtualIndexes`,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)=>{let n=this.measurementsCache[e];if(!n)return;let r=t-(this.itemSizeCache.get(n.key)??n.size);r!==0&&(this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?n.start<this.getScrollOffset()+this.scrollAdjustments:this.shouldAdjustScrollPositionOnItemSizeChange(n,r,this))&&(process.env.NODE_ENV!==`production`&&this.options.debug&&console.info(`correction`,r),this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=r,behavior:void 0})),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,t)),this.notify(!1))},this.getVirtualItems=L(()=>[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:process.env.NODE_ENV!==`production`&&`getVirtualItems`,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length!==0)return oe(t[he(0,t.length-1,e=>oe(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)t=e[e.length-1]?.end??0;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._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,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&&se(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior=`auto`,this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}));this.scheduleScrollReconcile()}},he=(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 ge({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){let i=e.length-1,a=t=>e[t].start;if(e.length<=r)return{startIndex:0,endIndex:i};let o=he(0,i,a,n),s=o;if(r===1)for(;s<i&&e[s].end<n+t;)s++;else if(r>1){let a=Array(r).fill(0);for(;s<i&&a.some(e=>e<n+t);){let t=e[s];a[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(i,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var _e=typeof document<`u`?t.useLayoutEffect:t.useEffect;function ve({useFlushSync:e=!0,...n}){let r=t.useReducer(()=>({}),{})[1],i={...n,onChange:(t,i)=>{var a;e&&i?(0,s.flushSync)(r):r(),(a=n.onChange)==null||a.call(n,t,i)}},[a]=t.useState(()=>new me(i));return a.setOptions(i),_e(()=>a._didMount(),[]),_e(()=>a._willUpdate()),a}function ye(e){return ve({observeElementRect:B,observeElementOffset:fe,scrollToFn:V,...e})}var be=({data:e,columns:n,rowHeight:r=40,height:i=600,className:a=``,headerClassName:o=``,rowClassName:s,onRowClick:c,overscan:l=5})=>{let u=(0,t.useRef)(null),d=ye({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>r,overscan:l}),f=d.getVirtualItems();return(0,y.jsxs)(`div`,{className:a,children:[(0,y.jsx)(`div`,{className:`grid border-b sticky top-0 bg-muted/30 z-10 ${o}`,style:{gridTemplateColumns:n.map(e=>e.width||`1fr`).join(` `)},children:n.map((e,t)=>(0,y.jsx)(`div`,{className:`px-4 py-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70 ${e.align===`center`?`text-center`:e.align===`right`?`text-right`:`text-left`}`,children:e.header},t))}),(0,y.jsx)(`div`,{ref:u,className:`overflow-auto`,style:{height:typeof i==`number`?`${i}px`:i,contain:`strict`},children:(0,y.jsx)(`div`,{style:{height:`${d.getTotalSize()}px`,width:`100%`,position:`relative`},children:f.map(t=>{let r=e[t.index];return(0,y.jsx)(`div`,{className:`grid border-b hover:bg-muted/50 cursor-pointer ${typeof s==`function`?s(r,t.index):s||``}`,style:{position:`absolute`,top:0,left:0,width:`100%`,height:`${t.size}px`,transform:`translateY(${t.start}px)`,gridTemplateColumns:n.map(e=>e.width||`1fr`).join(` `)},onClick:()=>c?.(r,t.index),children:n.map((e,t)=>{let n=r[e.accessorKey],i=e.cell?e.cell(n,r):typeof n==`object`&&n?String(n):n;return(0,y.jsx)(`div`,{className:`px-4 py-2 text-sm flex items-center ${e.align===`center`?`text-center justify-center`:e.align===`right`?`text-right justify-end`:`text-left justify-start`}`,children:i},t)})},t.key)})})}),(0,y.jsxs)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground border-t`,children:[`Showing `,f.length,` of `,e.length,` rows (virtual scrolling enabled)`]})]})},xe=10;function H(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===`
11
+ color: hsl(${Math.max(0,Math.min(120-120*r,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i}return o.updateDeps=e=>{r=e},o}function oe(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var z=(e,t)=>Math.abs(e-t)<1.01,se=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},ce=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},B=e=>e,V=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let e=t;e<=n;e++)r.push(e);return r},le=(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(ce(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(ce(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},ue={passive:!0},de=typeof window>`u`?!0:`onscrollend`in window,fe=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=0,a=e.options.useScrollendEvent&&de?()=>void 0:se(r,()=>{t(i,!1)},e.options.isScrollingResetDelay),o=r=>()=>{let{horizontal:o,isRtl:s}=e.options;i=o?n.scrollLeft*(s&&-1||1):n.scrollTop,a(),t(i,r)},s=o(!0),c=o(!1);n.addEventListener(`scroll`,s,ue);let l=e.options.useScrollendEvent&&de;return l&&n.addEventListener(`scrollend`,c,ue),()=>{n.removeEventListener(`scroll`,s),l&&n.removeEventListener(`scrollend`,c)}},H=(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`]},pe=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;let o=e+t;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:o,behavior:n})},me=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,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);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=>{Object.entries(e).forEach(([t,n])=>{n===void 0&&delete e[t]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:B,rangeExtractor:V,onChange:()=>{},measureElement:H,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`,...e}},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=R(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:process.env.NODE_ENV!==`production`&&`maybeNotify`,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}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.scrollAdjustments=0,this.scrollDirection=t?this.getScrollOffset()<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,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=R(()=>[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.pendingMeasuredCacheIndexes=[],{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o}),{key:!1}),this.getMeasurements=R(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o},s)=>{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.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let c=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1);let l=this.measurementsCache.slice(0,c),u=Array(a).fill(void 0);for(let e=0;e<c;e++){let t=l[e];t&&(u[t.lane]=e)}for(let i=c;i<e;i++){let e=r(i),a=this.laneAssignments.get(i),c,d,f=o===`estimate`||s.has(e);if(a!==void 0&&this.options.lanes>1){c=a;let e=u[c],r=e===void 0?void 0:l[e];d=r?r.end+this.options.gap:t+n}else{let e=this.options.lanes===1?l[i-1]:this.getFurthestMeasurement(l,i);d=e?e.end+this.options.gap:t+n,c=e?e.lane:i%this.options.lanes,this.options.lanes>1&&f&&this.laneAssignments.set(i,c)}let p=s.get(e),m=typeof p==`number`?p:this.options.estimateSize(i),h=d+m;l[i]={index:i,start:d,size:m,end:h,key:e,lane:c},u[c]=i}return this.measurementsCache=l,l},{key:process.env.NODE_ENV!==`production`&&`getMeasurements`,debug:()=>this.options.debug}),this.calculateRange=R(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>this.range=e.length>0&&t>0?ge({measurements:e,outerSize:t,scrollOffset:n,lanes:r}):null,{key:process.env.NODE_ENV!==`production`&&`calculateRange`,debug:()=>this.options.debug}),this.getVirtualIndexes=R(()=>{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:process.env.NODE_ENV!==`production`&&`getVirtualIndexes`,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)=>{let n=this.measurementsCache[e];if(!n)return;let r=t-(this.itemSizeCache.get(n.key)??n.size);r!==0&&(this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?n.start<this.getScrollOffset()+this.scrollAdjustments:this.shouldAdjustScrollPositionOnItemSizeChange(n,r,this))&&(process.env.NODE_ENV!==`production`&&this.options.debug&&console.info(`correction`,r),this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=r,behavior:void 0})),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,t)),this.notify(!1))},this.getVirtualItems=R(()=>[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:process.env.NODE_ENV!==`production`&&`getVirtualItems`,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length!==0)return oe(t[he(0,t.length-1,e=>oe(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)t=e[e.length-1]?.end??0;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._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,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&&z(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.scrollState=null;return}}else this.scrollState.stableFrames=0,n&&(this.scrollState.lastTargetOffset=t,this.scrollState.behavior=`auto`,this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}));this.scheduleScrollReconcile()}},he=(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 ge({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){let i=e.length-1,a=t=>e[t].start;if(e.length<=r)return{startIndex:0,endIndex:i};let o=he(0,i,a,n),s=o;if(r===1)for(;s<i&&e[s].end<n+t;)s++;else if(r>1){let a=Array(r).fill(0);for(;s<i&&a.some(e=>e<n+t);){let t=e[s];a[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(i,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var _e=typeof document<`u`?t.useLayoutEffect:t.useEffect;function ve({useFlushSync:e=!0,...n}){let r=t.useReducer(()=>({}),{})[1],i={...n,onChange:(t,i)=>{var a;e&&i?(0,s.flushSync)(r):r(),(a=n.onChange)==null||a.call(n,t,i)}},[a]=t.useState(()=>new me(i));return a.setOptions(i),_e(()=>a._didMount(),[]),_e(()=>a._willUpdate()),a}function ye(e){return ve({observeElementRect:le,observeElementOffset:fe,scrollToFn:pe,...e})}var be=({data:e,columns:n,rowHeight:r=40,height:i=600,className:a=``,headerClassName:o=``,rowClassName:s,onRowClick:c,overscan:l=5})=>{let u=(0,t.useRef)(null),d=ye({count:e.length,getScrollElement:()=>u.current,estimateSize:()=>r,overscan:l}),f=d.getVirtualItems();return(0,y.jsxs)(`div`,{className:a,children:[(0,y.jsx)(`div`,{className:`grid border-b sticky top-0 bg-muted/30 z-10 ${o}`,style:{gridTemplateColumns:n.map(e=>e.width||`1fr`).join(` `)},children:n.map((e,t)=>(0,y.jsx)(`div`,{className:`px-4 py-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70 ${e.align===`center`?`text-center`:e.align===`right`?`text-right`:`text-left`}`,children:e.header},t))}),(0,y.jsx)(`div`,{ref:u,className:`overflow-auto`,style:{height:typeof i==`number`?`${i}px`:i,contain:`strict`},children:(0,y.jsx)(`div`,{style:{height:`${d.getTotalSize()}px`,width:`100%`,position:`relative`},children:f.map(t=>{let r=e[t.index];return(0,y.jsx)(`div`,{className:`grid border-b hover:bg-muted/50 cursor-pointer ${typeof s==`function`?s(r,t.index):s||``}`,style:{position:`absolute`,top:0,left:0,width:`100%`,height:`${t.size}px`,transform:`translateY(${t.start}px)`,gridTemplateColumns:n.map(e=>e.width||`1fr`).join(` `)},onClick:()=>c?.(r,t.index),children:n.map((e,t)=>{let n=r[e.accessorKey],i=e.cell?e.cell(n,r):typeof n==`object`&&n?String(n):n;return(0,y.jsx)(`div`,{className:`px-4 py-2 text-sm flex items-center ${e.align===`center`?`text-center justify-center`:e.align===`right`?`text-right justify-end`:`text-left justify-start`}`,children:i},t)})},t.key)})})}),(0,y.jsxs)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground border-t`,children:[`Showing `,f.length,` of `,e.length,` rows (virtual scrolling enabled)`]})]})},U=10;function W(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===`
12
12
  `||o===`\r`&&s===`
13
- `?(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 U(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 W(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 G(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function K(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 q(e,t,n){if(e)try{e.setItem(t,JSON.stringify(n))}catch{}}function J(e,t){let n={};return Object.entries(t).forEach(([t,r])=>{let i=e[Number(t)];i&&(n[i.trim().toLowerCase()]=r)}),n}function Se(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 Ce(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&&!U(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 Y=({onFileLoaded:e})=>{let[n,r]=(0,t.useState)(!1),[i,s]=(0,t.useState)(null),c=(0,t.useCallback)(t=>{if(s(null),!t.name.endsWith(`.csv`)){s(`Only CSV files are supported.`);return}let n=new FileReader;n.onload=t=>{let n=H(t.target?.result);if(n.length<2){s(`File must contain a header row and at least one data row.`);return}e(n[0],n.slice(1))},n.readAsText(t)},[e]);return(0,y.jsxs)(`div`,{className:`flex flex-col items-center gap-4 py-6`,children:[(0,y.jsxs)(`div`,{className:(0,a.cn)(`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&&c(t)},children:[(0,y.jsx)(o.Upload,{className:`h-10 w-10 text-muted-foreground`}),(0,y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Drag & drop a CSV file here, or click to browse`}),(0,y.jsxs)(`label`,{children:[(0,y.jsx)(`input`,{type:`file`,accept:`.csv`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&c(t)}}),(0,y.jsx)(a.Button,{variant:`outline`,size:`sm`,asChild:!0,children:(0,y.jsx)(`span`,{children:`Browse Files`})})]})]}),i&&(0,y.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-destructive`,children:[(0,y.jsx)(o.AlertCircle,{className:`h-4 w-4`}),` `,i]})]})},X=({templates:e,selectedId:n,onSelect:r,onSaveAs:i,onDelete:s,disabled:c})=>{let[l,u]=(0,t.useState)(``),[d,f]=(0,t.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)(o.Save,{className:`h-4 w-4 text-muted-foreground`}),(0,y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Mapping template:`}),(0,y.jsxs)(a.Select,{value:n??`__none__`,onValueChange:e=>e!==`__none__`&&r(e),children:[(0,y.jsx)(a.SelectTrigger,{className:`h-7 w-48 text-xs`,"data-testid":`import-template-select`,children:(0,y.jsx)(a.SelectValue,{placeholder:e.length?`Choose template…`:`No saved templates`})}),(0,y.jsxs)(a.SelectContent,{children:[(0,y.jsx)(a.SelectItem,{value:`__none__`,disabled:e.length===0,children:e.length?`— None —`:`No saved templates`}),e.map(e=>(0,y.jsx)(a.SelectItem,{value:e.id,children:e.name},e.id))]})]}),d?(0,y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,y.jsx)(a.Input,{value:l,onChange:e=>u(e.target.value),placeholder:`Template name`,className:`h-7 w-40 text-xs`,"data-testid":`import-template-name-input`,autoFocus:!0}),(0,y.jsx)(a.Button,{type:`button`,size:`sm`,onClick:()=>{l.trim()&&(i(l.trim()),u(``),f(!1))},disabled:!l.trim()||c,"data-testid":`import-template-confirm-save`,children:`Save`}),(0,y.jsx)(a.Button,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{f(!1),u(``)},children:`Cancel`})]}):(0,y.jsx)(a.Button,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>f(!0),disabled:c,"data-testid":`import-template-save-btn`,children:`Save current`}),n&&(0,y.jsx)(a.Button,{type:`button`,variant:`ghost`,size:`sm`,onClick:s,"aria-label":`Delete template`,"data-testid":`import-template-delete-btn`,children:(0,y.jsx)(o.Trash2,{className:`h-3.5 w-3.5`})})]})},we=({headers:e,fields:n,mapping:r,onMappingChange:i,templates:o,selectedTemplateId:s,onSelectTemplate:c,onSaveTemplate:l,onDeleteTemplate:u})=>{let d=(0,t.useMemo)(()=>new Set(Object.values(r)),[r]),f=(0,t.useCallback)((e,t)=>{let n={...r};t===`__skip__`?delete n[e]:n[e]=t,i(n)},[r,i]);return(0,y.jsxs)(`div`,{children:[(0,y.jsx)(X,{templates:o,selectedId:s,onSelect:c,onSaveAs:l,onDelete:u,disabled:Object.keys(r).length===0}),(0,y.jsx)(`div`,{className:`max-h-[320px] overflow-auto`,children:(0,y.jsxs)(a.Table,{children:[(0,y.jsx)(a.TableHeader,{children:(0,y.jsxs)(a.TableRow,{children:[(0,y.jsx)(a.TableHead,{children:`CSV Column`}),(0,y.jsx)(a.TableHead,{children:`Maps To`}),(0,y.jsx)(a.TableHead,{className:`w-24 text-center`,children:`Status`})]})}),(0,y.jsx)(a.TableBody,{children:e.map((e,t)=>(0,y.jsxs)(a.TableRow,{children:[(0,y.jsx)(a.TableCell,{className:`font-medium`,children:e}),(0,y.jsx)(a.TableCell,{children:(0,y.jsxs)(a.Select,{value:r[t]??`__skip__`,onValueChange:e=>f(t,e),children:[(0,y.jsx)(a.SelectTrigger,{className:`h-8 w-56`,children:(0,y.jsx)(a.SelectValue,{placeholder:`Skip column`})}),(0,y.jsxs)(a.SelectContent,{children:[(0,y.jsx)(a.SelectItem,{value:`__skip__`,children:`— Skip —`}),n.map(e=>(0,y.jsxs)(a.SelectItem,{value:e.name,disabled:d.has(e.name)&&r[t]!==e.name,children:[e.label,e.required?` *`:``]},e.name))]})]})}),(0,y.jsx)(a.TableCell,{className:`text-center`,children:r[t]?(0,y.jsx)(a.Badge,{variant:`default`,className:`text-xs`,children:`Mapped`}):(0,y.jsx)(a.Badge,{variant:`secondary`,className:`text-xs`,children:`Skipped`})})]},t))})]})})]})},Te=({headers:e,rows:n,mapping:r,fields:i,corrections:s,onCorrect:c})=>{let l=(0,t.useMemo)(()=>Object.entries(r).map(([t,n])=>({csvIdx:Number(t),header:e[Number(t)],field:i.find(e=>e.name===n)})),[r,e,i]),u=n.slice(0,xe),d=(0,t.useCallback)((e,t)=>{let n=s[e]?.[t];return n===void 0?u[e]?.[t]??``:n},[s,u]),f=(0,t.useMemo)(()=>u.map((e,t)=>{let n={};for(let e of l){let r=d(t,e.csvIdx);e.field.required&&!r?n[e.csvIdx]=`Required`:r&&!U(r,e.field.type)&&(n[e.csvIdx]=`Invalid ${e.field.type}`)}return n}),[u,l,d]),p=f.filter(e=>Object.keys(e).length>0).length,m=Object.keys(s).length;return(0,y.jsxs)(`div`,{className:`max-h-[360px] overflow-auto`,children:[(p>0||m>0)&&(0,y.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs`,"data-testid":`import-preview-status`,children:[p>0&&(0,y.jsxs)(`span`,{className:`flex items-center gap-1 text-destructive`,children:[(0,y.jsx)(o.AlertCircle,{className:`h-3.5 w-3.5`}),` `,p,` row(s) with errors`]}),m>0&&(0,y.jsxs)(`span`,{className:`flex items-center gap-1 text-emerald-600`,children:[(0,y.jsx)(o.CheckCircle2,{className:`h-3.5 w-3.5`}),` `,m,` row(s) corrected`]}),(0,y.jsx)(`span`,{className:`text-muted-foreground`,children:`— click a highlighted cell to fix it inline.`})]}),(0,y.jsxs)(a.Table,{children:[(0,y.jsx)(a.TableHeader,{children:(0,y.jsxs)(a.TableRow,{children:[(0,y.jsx)(a.TableHead,{className:`w-12`,children:`#`}),l.map(e=>(0,y.jsx)(a.TableHead,{children:e.field.label},e.csvIdx))]})}),(0,y.jsx)(a.TableBody,{children:u.map((e,t)=>{let n=f[t],r=Object.keys(n).length>0,i=s[t]!==void 0;return(0,y.jsxs)(a.TableRow,{className:(0,a.cn)(r&&`bg-destructive/5`,!r&&i&&`bg-emerald-50 dark:bg-emerald-950/20`),"data-testid":`import-preview-row-${t}`,children:[(0,y.jsx)(a.TableCell,{className:`text-xs text-muted-foreground`,children:t+1}),l.map(e=>{let r=d(t,e.csvIdx),i=n[e.csvIdx],o=s[t]?.[e.csvIdx]!==void 0;return(0,y.jsx)(a.TableCell,{className:(0,a.cn)(i&&`text-destructive`,o&&!i&&`text-emerald-600`),title:i,children:(0,y.jsx)(a.Input,{value:r,onChange:n=>c(t,e.csvIdx,n.target.value),className:(0,a.cn)(`h-7 px-1 text-xs`,i&&`border-destructive`,o&&!i&&`border-emerald-500`),"data-testid":`import-preview-cell-${t}-${e.csvIdx}`,"aria-invalid":i?`true`:`false`,"aria-label":`${e.field.label} for row ${t+1}`})},e.csvIdx)})]},t)})})]}),(0,y.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[`Showing `,u.length,` of `,n.length,` rows`]})]})},Ee=({objectName:e,objectLabel:n,fields:r,dataSource:i,onComplete:s,onCancel:c,open:l,onOpenChange:u,onErrorMode:d=`skip`,templateStorageKey:f,templateStorage:p})=>{let[m,h]=(0,t.useState)(`upload`),[g,_]=(0,t.useState)([]),[v,b]=(0,t.useState)([]),[x,S]=(0,t.useState)({}),[C,w]=(0,t.useState)(!1),[T,E]=(0,t.useState)(0),[D,ee]=(0,t.useState)(null),[O,k]=(0,t.useState)({}),A=n??e,j=(0,t.useMemo)(()=>p===void 0?G():p,[p]),M=f??`objectui:import-templates:${e}`,[N,P]=(0,t.useState)(()=>K(j,M)),[F,I]=(0,t.useState)(null);(0,t.useEffect)(()=>{P(K(j,M))},[j,M]);let te=(0,t.useCallback)(e=>{let t=N.find(t=>t.id===e);t&&(I(e),S(Se(t,g,r)))},[N,g,r]),ne=(0,t.useCallback)(e=>{let t={id:`tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:e,mapping:J(g,x),updatedAt:Date.now()},n=[...N,t];P(n),I(t.id),q(j,M,n)},[N,g,x,j,M]),re=(0,t.useCallback)(()=>{if(!F)return;let e=N.filter(e=>e.id!==F);P(e),I(null),q(j,M,e)},[N,F,j,M]),ie=(0,t.useCallback)((e,t,n)=>{k(r=>{let i={...r},a={...i[e]??{}};return n===(v[e]?.[t]??``)?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,i})},[v]),ae=(0,t.useMemo)(()=>{let e=new Set(Object.values(x));return r.filter(t=>t.required&&!e.has(t.name))},[r,x]),L=(0,t.useCallback)((e,t)=>{_(e),b(t),S(W(e,r)),k({}),h(`mapping`)},[r]),oe=(0,t.useCallback)(async()=>{w(!0),E(0);let t=[],n=0,a=0,o=Object.entries(x).map(([e,t])=>({csvIdx:Number(e),field:r.find(e=>e.name===t)}));for(let r=0;r<v.length;r++){let s=v[r],c=O[r],{record:l,errors:u}=Ce(c?s.map((e,t)=>c[t]===void 0?e:c[t]):s,o,r+1);if(u.length>0){if(a++,t.push(...u),d===`stop`)break}else try{i?.create&&await i.create(e,l),n++}catch(e){a++;let n=e instanceof Error?e.message:`Failed to create record`;if(t.push({row:r+1,field:``,message:n}),d===`stop`)break}E(Math.round((r+1)/v.length*100))}let c={totalRows:v.length,importedRows:n,skippedRows:a,errors:t};ee(c),w(!1),s?.(c)},[v,x,r,i,e,s,d,O]),se=(0,t.useCallback)(()=>{h(`upload`),_([]),b([]),S({}),E(0),ee(null),k({}),I(null)},[]),R=(0,t.useCallback)(()=>{se(),u?.(!1),c?.()},[se,u,c]);return(0,y.jsx)(a.Dialog,{open:l,onOpenChange:e=>{e?u?.(e):R()},children:(0,y.jsxs)(a.DialogContent,{className:`sm:max-w-2xl`,children:[(0,y.jsxs)(a.DialogHeader,{children:[(0,y.jsxs)(a.DialogTitle,{className:`flex items-center gap-2`,children:[(0,y.jsx)(o.FileSpreadsheet,{className:`h-5 w-5`}),` Import `,A]}),(0,y.jsxs)(a.DialogDescription,{children:[m===`upload`&&`Upload a CSV file to get started.`,m===`mapping`&&`Map CSV columns to object fields.`,m===`preview`&&`Review data before importing.`]})]}),(0,y.jsx)(`div`,{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground`,children:[`upload`,`mapping`,`preview`].map((e,n)=>(0,y.jsxs)(t.default.Fragment,{children:[n>0&&(0,y.jsx)(o.ArrowRight,{className:`h-3 w-3`}),(0,y.jsxs)(`span`,{className:(0,a.cn)(`rounded-full px-3 py-1`,m===e?`bg-primary text-primary-foreground`:`bg-muted`),children:[n+1,`. `,e===`upload`?`Upload`:e===`mapping`?`Mapping`:`Preview`]})]},e))}),D?(0,y.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:[(0,y.jsx)(o.CheckCircle2,{className:`h-10 w-10 text-green-500`}),(0,y.jsx)(`p`,{className:`text-lg font-semibold`,children:`Import Complete`}),(0,y.jsxs)(`div`,{className:`flex gap-3`,children:[(0,y.jsxs)(a.Badge,{variant:`default`,children:[D.importedRows,` imported`]}),D.skippedRows>0&&(0,y.jsxs)(a.Badge,{variant:`destructive`,children:[D.skippedRows,` skipped`]})]}),D.errors.length>0&&(0,y.jsxs)(`div`,{className:`max-h-32 w-full overflow-auto rounded border p-2 text-xs`,children:[D.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)),D.errors.length>10&&(0,y.jsxs)(`p`,{className:`text-muted-foreground`,children:[`…and `,D.errors.length-10,` more errors`]})]})]}):(0,y.jsxs)(y.Fragment,{children:[m===`upload`&&(0,y.jsx)(Y,{onFileLoaded:L}),m===`mapping`&&(0,y.jsx)(we,{headers:g,fields:r,mapping:x,onMappingChange:S,templates:N,selectedTemplateId:F,onSelectTemplate:te,onSaveTemplate:ne,onDeleteTemplate:re}),m===`preview`&&(0,y.jsx)(Te,{headers:g,rows:v,mapping:x,fields:r,corrections:O,onCorrect:ie}),C&&(0,y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,y.jsx)(a.Progress,{value:T,className:`h-2`}),(0,y.jsxs)(`p`,{className:`text-center text-xs text-muted-foreground`,children:[`Importing… `,T,`%`]})]})]}),(0,y.jsx)(a.DialogFooter,{className:`gap-2 sm:gap-0`,children:D?(0,y.jsx)(a.Button,{onClick:R,children:`Close`}):(0,y.jsxs)(y.Fragment,{children:[(0,y.jsxs)(a.Button,{variant:`ghost`,onClick:R,disabled:C,children:[(0,y.jsx)(o.X,{className:`mr-1 h-4 w-4`}),` Cancel`]}),(m===`mapping`||m===`preview`)&&(0,y.jsxs)(a.Button,{variant:`outline`,onClick:()=>h(m===`mapping`?`upload`:`mapping`),disabled:C,children:[(0,y.jsx)(o.ArrowLeft,{className:`mr-1 h-4 w-4`}),` Back`]}),m===`mapping`&&(0,y.jsxs)(a.Button,{onClick:()=>h(`preview`),disabled:Object.keys(x).length===0||ae.length>0,children:[`Next `,(0,y.jsx)(o.ArrowRight,{className:`ml-1 h-4 w-4`})]}),m===`preview`&&(0,y.jsx)(a.Button,{onClick:oe,disabled:C,children:C?`Importing…`:`Import ${v.length} Rows`})]})})]})})};function De({value:e,onSave:n,onCancel:r,validate:i,type:s=`text`,placeholder:c,editing:l=!1,className:u,disabled:d=!1}){let[f,p]=(0,t.useState)(l),[m,h]=(0,t.useState)(String(e??``)),[g,_]=(0,t.useState)(),[v,b]=(0,t.useState)(!1),x=(0,t.useRef)(null);(0,t.useEffect)(()=>{f||h(String(e??``))},[e,f]),(0,t.useEffect)(()=>{f&&x.current&&(x.current.focus(),x.current.select())},[f]);let S=(0,t.useCallback)(()=>{d||(p(!0),h(String(e??``)),_(void 0))},[d,e]),C=(0,t.useCallback)(()=>{p(!1),h(String(e??``)),_(void 0),r?.()},[e,r]),w=(0,t.useCallback)(async()=>{if(i){let e=i(m);if(e){_(e);return}}let e=s===`number`?Number(m):m;b(!0);try{let t=await n(e);if(typeof t==`string`){_(t),b(!1);return}p(!1),_(void 0)}catch(e){_(e?.message||`Save failed`)}finally{b(!1)}},[m,i,s,n]),T=(0,t.useCallback)(e=>{e.key===`Enter`?(e.preventDefault(),w()):e.key===`Escape`&&(e.preventDefault(),C())},[w,C]);return f?(0,y.jsxs)(`div`,{"data-slot":`inline-editing`,className:(0,a.cn)(`relative flex items-center gap-1`,u),children:[(0,y.jsxs)(`div`,{className:`flex-1 relative`,children:[(0,y.jsx)(`input`,{ref:x,"data-slot":`inline-editing-input`,type:s,value:m,onChange:e=>{h(e.target.value),g&&_(void 0)},onKeyDown:T,placeholder:c,disabled:v,"aria-invalid":!!g,"aria-describedby":g?`inline-editing-error`:void 0,className:(0,a.cn)(`w-full rounded border px-2 py-1 text-sm outline-none transition-colors`,`focus:ring-2 focus:ring-ring focus:border-input`,g?`border-destructive focus:ring-destructive/30`:`border-input`,v&&`opacity-50`)}),g&&(0,y.jsx)(`p`,{id:`inline-editing-error`,"data-slot":`inline-editing-error`,className:`absolute left-0 top-full mt-0.5 text-xs text-destructive`,role:`alert`,children:g})]}),(0,y.jsx)(`button`,{"data-slot":`inline-editing-save`,type:`button`,onClick:w,disabled:v,"aria-label":`Save`,className:(0,a.cn)(`inline-flex h-6 w-6 items-center justify-center rounded text-primary hover:bg-primary/10 transition-colors`,v&&`opacity-50 cursor-not-allowed`),children:(0,y.jsx)(o.Check,{className:`h-3.5 w-3.5`})}),(0,y.jsx)(`button`,{"data-slot":`inline-editing-cancel`,type:`button`,onClick:C,disabled:v,"aria-label":`Cancel`,className:`inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,y.jsx)(o.X,{className:`h-3.5 w-3.5`})})]}):(0,y.jsx)(`div`,{"data-slot":`inline-editing`,className:(0,a.cn)(`group relative cursor-pointer rounded px-2 py-1 hover:bg-muted/50 transition-colors min-h-[1.75rem] flex items-center`,d&&`cursor-default opacity-60`,u),onClick:S,role:`button`,tabIndex:d?-1:0,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),S())},"aria-label":`Edit value: ${String(e??``)}`,children:(0,y.jsx)(`span`,{"data-slot":`inline-editing-display`,className:`truncate text-sm`,children:e!=null&&String(e)!==``?String(e):(0,y.jsx)(`span`,{className:`text-muted-foreground italic`,children:c||`Click to edit`})})})}function Oe(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function ke({data:e,columns:n,onPaste:r,enabled:i=!0}){let[a,o]=(0,t.useState)(null),s=(0,t.useCallback)(()=>{if(!i||!a)return;let{startRow:t,startCol:r,endRow:o,endCol:s}=Oe(a),c=[];for(let i=t;i<=o;i++){let t=e[i];if(!t)continue;let a=[];for(let e=r;e<=s;e++){let r=n[e];a.push(r?String(t[r]??``):``)}c.push(a.join(` `))}let l=c.join(`
13
+ `?(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 G(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 K(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 q(){if(typeof window>`u`)return null;try{return window.localStorage}catch{return null}}function J(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 Y(e,t,n){if(e)try{e.setItem(t,JSON.stringify(n))}catch{}}function xe(e,t){let n={};return Object.entries(t).forEach(([t,r])=>{let i=e[Number(t)];i&&(n[i.trim().toLowerCase()]=r)}),n}function Se(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 X(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&&!G(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 Z=({onFileLoaded:e})=>{let[n,r]=(0,t.useState)(!1),[i,s]=(0,t.useState)(null),c=(0,t.useCallback)(t=>{if(s(null),!t.name.endsWith(`.csv`)){s(`Only CSV files are supported.`);return}let n=new FileReader;n.onload=t=>{let n=W(t.target?.result);if(n.length<2){s(`File must contain a header row and at least one data row.`);return}e(n[0],n.slice(1))},n.readAsText(t)},[e]);return(0,y.jsxs)(`div`,{className:`flex flex-col items-center gap-4 py-6`,children:[(0,y.jsxs)(`div`,{className:(0,a.cn)(`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&&c(t)},children:[(0,y.jsx)(o.Upload,{className:`h-10 w-10 text-muted-foreground`}),(0,y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Drag & drop a CSV file here, or click to browse`}),(0,y.jsxs)(`label`,{children:[(0,y.jsx)(`input`,{type:`file`,accept:`.csv`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&c(t)}}),(0,y.jsx)(a.Button,{variant:`outline`,size:`sm`,asChild:!0,children:(0,y.jsx)(`span`,{children:`Browse Files`})})]})]}),i&&(0,y.jsxs)(`p`,{className:`flex items-center gap-1 text-sm text-destructive`,children:[(0,y.jsx)(o.AlertCircle,{className:`h-4 w-4`}),` `,i]})]})},Ce=({templates:e,selectedId:n,onSelect:r,onSaveAs:i,onDelete:s,disabled:c})=>{let[l,u]=(0,t.useState)(``),[d,f]=(0,t.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)(o.Save,{className:`h-4 w-4 text-muted-foreground`}),(0,y.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Mapping template:`}),(0,y.jsxs)(a.Select,{value:n??`__none__`,onValueChange:e=>e!==`__none__`&&r(e),children:[(0,y.jsx)(a.SelectTrigger,{className:`h-7 w-48 text-xs`,"data-testid":`import-template-select`,children:(0,y.jsx)(a.SelectValue,{placeholder:e.length?`Choose template…`:`No saved templates`})}),(0,y.jsxs)(a.SelectContent,{children:[(0,y.jsx)(a.SelectItem,{value:`__none__`,disabled:e.length===0,children:e.length?`— None —`:`No saved templates`}),e.map(e=>(0,y.jsx)(a.SelectItem,{value:e.id,children:e.name},e.id))]})]}),d?(0,y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,y.jsx)(a.Input,{value:l,onChange:e=>u(e.target.value),placeholder:`Template name`,className:`h-7 w-40 text-xs`,"data-testid":`import-template-name-input`,autoFocus:!0}),(0,y.jsx)(a.Button,{type:`button`,size:`sm`,onClick:()=>{l.trim()&&(i(l.trim()),u(``),f(!1))},disabled:!l.trim()||c,"data-testid":`import-template-confirm-save`,children:`Save`}),(0,y.jsx)(a.Button,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{f(!1),u(``)},children:`Cancel`})]}):(0,y.jsx)(a.Button,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>f(!0),disabled:c,"data-testid":`import-template-save-btn`,children:`Save current`}),n&&(0,y.jsx)(a.Button,{type:`button`,variant:`ghost`,size:`sm`,onClick:s,"aria-label":`Delete template`,"data-testid":`import-template-delete-btn`,children:(0,y.jsx)(o.Trash2,{className:`h-3.5 w-3.5`})})]})},we=({headers:e,fields:n,mapping:r,onMappingChange:i,templates:o,selectedTemplateId:s,onSelectTemplate:c,onSaveTemplate:l,onDeleteTemplate:u})=>{let d=(0,t.useMemo)(()=>new Set(Object.values(r)),[r]),f=(0,t.useCallback)((e,t)=>{let n={...r};t===`__skip__`?delete n[e]:n[e]=t,i(n)},[r,i]);return(0,y.jsxs)(`div`,{children:[(0,y.jsx)(Ce,{templates:o,selectedId:s,onSelect:c,onSaveAs:l,onDelete:u,disabled:Object.keys(r).length===0}),(0,y.jsx)(`div`,{className:`max-h-[320px] overflow-auto`,children:(0,y.jsxs)(a.Table,{children:[(0,y.jsx)(a.TableHeader,{children:(0,y.jsxs)(a.TableRow,{children:[(0,y.jsx)(a.TableHead,{children:`CSV Column`}),(0,y.jsx)(a.TableHead,{children:`Maps To`}),(0,y.jsx)(a.TableHead,{className:`w-24 text-center`,children:`Status`})]})}),(0,y.jsx)(a.TableBody,{children:e.map((e,t)=>(0,y.jsxs)(a.TableRow,{children:[(0,y.jsx)(a.TableCell,{className:`font-medium`,children:e}),(0,y.jsx)(a.TableCell,{children:(0,y.jsxs)(a.Select,{value:r[t]??`__skip__`,onValueChange:e=>f(t,e),children:[(0,y.jsx)(a.SelectTrigger,{className:`h-8 w-56`,children:(0,y.jsx)(a.SelectValue,{placeholder:`Skip column`})}),(0,y.jsxs)(a.SelectContent,{children:[(0,y.jsx)(a.SelectItem,{value:`__skip__`,children:`— Skip —`}),n.map(e=>(0,y.jsxs)(a.SelectItem,{value:e.name,disabled:d.has(e.name)&&r[t]!==e.name,children:[e.label,e.required?` *`:``]},e.name))]})]})}),(0,y.jsx)(a.TableCell,{className:`text-center`,children:r[t]?(0,y.jsx)(a.Badge,{variant:`default`,className:`text-xs`,children:`Mapped`}):(0,y.jsx)(a.Badge,{variant:`secondary`,className:`text-xs`,children:`Skipped`})})]},t))})]})})]})},Te=({headers:e,rows:n,mapping:r,fields:i,corrections:s,onCorrect:c})=>{let l=(0,t.useMemo)(()=>Object.entries(r).map(([t,n])=>({csvIdx:Number(t),header:e[Number(t)],field:i.find(e=>e.name===n)})),[r,e,i]),u=n.slice(0,U),d=(0,t.useCallback)((e,t)=>{let n=s[e]?.[t];return n===void 0?u[e]?.[t]??``:n},[s,u]),f=(0,t.useMemo)(()=>u.map((e,t)=>{let n={};for(let e of l){let r=d(t,e.csvIdx);e.field.required&&!r?n[e.csvIdx]=`Required`:r&&!G(r,e.field.type)&&(n[e.csvIdx]=`Invalid ${e.field.type}`)}return n}),[u,l,d]),p=f.filter(e=>Object.keys(e).length>0).length,m=Object.keys(s).length;return(0,y.jsxs)(`div`,{className:`max-h-[360px] overflow-auto`,children:[(p>0||m>0)&&(0,y.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 text-xs`,"data-testid":`import-preview-status`,children:[p>0&&(0,y.jsxs)(`span`,{className:`flex items-center gap-1 text-destructive`,children:[(0,y.jsx)(o.AlertCircle,{className:`h-3.5 w-3.5`}),` `,p,` row(s) with errors`]}),m>0&&(0,y.jsxs)(`span`,{className:`flex items-center gap-1 text-emerald-600`,children:[(0,y.jsx)(o.CheckCircle2,{className:`h-3.5 w-3.5`}),` `,m,` row(s) corrected`]}),(0,y.jsx)(`span`,{className:`text-muted-foreground`,children:`— click a highlighted cell to fix it inline.`})]}),(0,y.jsxs)(a.Table,{children:[(0,y.jsx)(a.TableHeader,{children:(0,y.jsxs)(a.TableRow,{children:[(0,y.jsx)(a.TableHead,{className:`w-12`,children:`#`}),l.map(e=>(0,y.jsx)(a.TableHead,{children:e.field.label},e.csvIdx))]})}),(0,y.jsx)(a.TableBody,{children:u.map((e,t)=>{let n=f[t],r=Object.keys(n).length>0,i=s[t]!==void 0;return(0,y.jsxs)(a.TableRow,{className:(0,a.cn)(r&&`bg-destructive/5`,!r&&i&&`bg-emerald-50 dark:bg-emerald-950/20`),"data-testid":`import-preview-row-${t}`,children:[(0,y.jsx)(a.TableCell,{className:`text-xs text-muted-foreground`,children:t+1}),l.map(e=>{let r=d(t,e.csvIdx),i=n[e.csvIdx],o=s[t]?.[e.csvIdx]!==void 0;return(0,y.jsx)(a.TableCell,{className:(0,a.cn)(i&&`text-destructive`,o&&!i&&`text-emerald-600`),title:i,children:(0,y.jsx)(a.Input,{value:r,onChange:n=>c(t,e.csvIdx,n.target.value),className:(0,a.cn)(`h-7 px-1 text-xs`,i&&`border-destructive`,o&&!i&&`border-emerald-500`),"data-testid":`import-preview-cell-${t}-${e.csvIdx}`,"aria-invalid":i?`true`:`false`,"aria-label":`${e.field.label} for row ${t+1}`})},e.csvIdx)})]},t)})})]}),(0,y.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[`Showing `,u.length,` of `,n.length,` rows`]})]})},Ee=({objectName:e,objectLabel:n,fields:r,dataSource:i,onComplete:s,onCancel:c,open:l,onOpenChange:u,onErrorMode:d=`skip`,templateStorageKey:f,templateStorage:p})=>{let[m,h]=(0,t.useState)(`upload`),[g,_]=(0,t.useState)([]),[v,b]=(0,t.useState)([]),[x,S]=(0,t.useState)({}),[C,w]=(0,t.useState)(!1),[T,E]=(0,t.useState)(0),[D,O]=(0,t.useState)(null),[k,A]=(0,t.useState)({}),j=n??e,M=(0,t.useMemo)(()=>p===void 0?q():p,[p]),N=f??`objectui:import-templates:${e}`,[P,F]=(0,t.useState)(()=>J(M,N)),[I,L]=(0,t.useState)(null);(0,t.useEffect)(()=>{F(J(M,N))},[M,N]);let ee=(0,t.useCallback)(e=>{let t=P.find(t=>t.id===e);t&&(L(e),S(Se(t,g,r)))},[P,g,r]),te=(0,t.useCallback)(e=>{let t={id:`tpl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:e,mapping:xe(g,x),updatedAt:Date.now()},n=[...P,t];F(n),L(t.id),Y(M,N,n)},[P,g,x,M,N]),ne=(0,t.useCallback)(()=>{if(!I)return;let e=P.filter(e=>e.id!==I);F(e),L(null),Y(M,N,e)},[P,I,M,N]),re=(0,t.useCallback)((e,t,n)=>{A(r=>{let i={...r},a={...i[e]??{}};return n===(v[e]?.[t]??``)?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,i})},[v]),ie=(0,t.useMemo)(()=>{let e=new Set(Object.values(x));return r.filter(t=>t.required&&!e.has(t.name))},[r,x]),ae=(0,t.useCallback)((e,t)=>{_(e),b(t),S(K(e,r)),A({}),h(`mapping`)},[r]),R=(0,t.useCallback)(async()=>{w(!0),E(0);let t=[],n=0,a=0,o=Object.entries(x).map(([e,t])=>({csvIdx:Number(e),field:r.find(e=>e.name===t)}));for(let r=0;r<v.length;r++){let s=v[r],c=k[r],{record:l,errors:u}=X(c?s.map((e,t)=>c[t]===void 0?e:c[t]):s,o,r+1);if(u.length>0){if(a++,t.push(...u),d===`stop`)break}else try{i?.create&&await i.create(e,l),n++}catch(e){a++;let n=e instanceof Error?e.message:`Failed to create record`;if(t.push({row:r+1,field:``,message:n}),d===`stop`)break}E(Math.round((r+1)/v.length*100))}let c={totalRows:v.length,importedRows:n,skippedRows:a,errors:t};O(c),w(!1),s?.(c)},[v,x,r,i,e,s,d,k]),oe=(0,t.useCallback)(()=>{h(`upload`),_([]),b([]),S({}),E(0),O(null),A({}),L(null)},[]),z=(0,t.useCallback)(()=>{oe(),u?.(!1),c?.()},[oe,u,c]);return(0,y.jsx)(a.Dialog,{open:l,onOpenChange:e=>{e?u?.(e):z()},children:(0,y.jsxs)(a.DialogContent,{className:`sm:max-w-2xl`,children:[(0,y.jsxs)(a.DialogHeader,{children:[(0,y.jsxs)(a.DialogTitle,{className:`flex items-center gap-2`,children:[(0,y.jsx)(o.FileSpreadsheet,{className:`h-5 w-5`}),` Import `,j]}),(0,y.jsxs)(a.DialogDescription,{children:[m===`upload`&&`Upload a CSV file to get started.`,m===`mapping`&&`Map CSV columns to object fields.`,m===`preview`&&`Review data before importing.`]})]}),(0,y.jsx)(`div`,{className:`flex items-center justify-center gap-2 text-xs text-muted-foreground`,children:[`upload`,`mapping`,`preview`].map((e,n)=>(0,y.jsxs)(t.default.Fragment,{children:[n>0&&(0,y.jsx)(o.ArrowRight,{className:`h-3 w-3`}),(0,y.jsxs)(`span`,{className:(0,a.cn)(`rounded-full px-3 py-1`,m===e?`bg-primary text-primary-foreground`:`bg-muted`),children:[n+1,`. `,e===`upload`?`Upload`:e===`mapping`?`Mapping`:`Preview`]})]},e))}),D?(0,y.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-4`,children:[(0,y.jsx)(o.CheckCircle2,{className:`h-10 w-10 text-green-500`}),(0,y.jsx)(`p`,{className:`text-lg font-semibold`,children:`Import Complete`}),(0,y.jsxs)(`div`,{className:`flex gap-3`,children:[(0,y.jsxs)(a.Badge,{variant:`default`,children:[D.importedRows,` imported`]}),D.skippedRows>0&&(0,y.jsxs)(a.Badge,{variant:`destructive`,children:[D.skippedRows,` skipped`]})]}),D.errors.length>0&&(0,y.jsxs)(`div`,{className:`max-h-32 w-full overflow-auto rounded border p-2 text-xs`,children:[D.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)),D.errors.length>10&&(0,y.jsxs)(`p`,{className:`text-muted-foreground`,children:[`…and `,D.errors.length-10,` more errors`]})]})]}):(0,y.jsxs)(y.Fragment,{children:[m===`upload`&&(0,y.jsx)(Z,{onFileLoaded:ae}),m===`mapping`&&(0,y.jsx)(we,{headers:g,fields:r,mapping:x,onMappingChange:S,templates:P,selectedTemplateId:I,onSelectTemplate:ee,onSaveTemplate:te,onDeleteTemplate:ne}),m===`preview`&&(0,y.jsx)(Te,{headers:g,rows:v,mapping:x,fields:r,corrections:k,onCorrect:re}),C&&(0,y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,y.jsx)(a.Progress,{value:T,className:`h-2`}),(0,y.jsxs)(`p`,{className:`text-center text-xs text-muted-foreground`,children:[`Importing… `,T,`%`]})]})]}),(0,y.jsx)(a.DialogFooter,{className:`gap-2 sm:gap-0`,children:D?(0,y.jsx)(a.Button,{onClick:z,children:`Close`}):(0,y.jsxs)(y.Fragment,{children:[(0,y.jsxs)(a.Button,{variant:`ghost`,onClick:z,disabled:C,children:[(0,y.jsx)(o.X,{className:`mr-1 h-4 w-4`}),` Cancel`]}),(m===`mapping`||m===`preview`)&&(0,y.jsxs)(a.Button,{variant:`outline`,onClick:()=>h(m===`mapping`?`upload`:`mapping`),disabled:C,children:[(0,y.jsx)(o.ArrowLeft,{className:`mr-1 h-4 w-4`}),` Back`]}),m===`mapping`&&(0,y.jsxs)(a.Button,{onClick:()=>h(`preview`),disabled:Object.keys(x).length===0||ie.length>0,children:[`Next `,(0,y.jsx)(o.ArrowRight,{className:`ml-1 h-4 w-4`})]}),m===`preview`&&(0,y.jsx)(a.Button,{onClick:R,disabled:C,children:C?`Importing…`:`Import ${v.length} Rows`})]})})]})})};function De({value:e,onSave:n,onCancel:r,validate:i,type:s=`text`,placeholder:c,editing:l=!1,className:u,disabled:d=!1}){let[f,p]=(0,t.useState)(l),[m,h]=(0,t.useState)(String(e??``)),[g,_]=(0,t.useState)(),[v,b]=(0,t.useState)(!1),x=(0,t.useRef)(null);(0,t.useEffect)(()=>{f||h(String(e??``))},[e,f]),(0,t.useEffect)(()=>{f&&x.current&&(x.current.focus(),x.current.select())},[f]);let S=(0,t.useCallback)(()=>{d||(p(!0),h(String(e??``)),_(void 0))},[d,e]),C=(0,t.useCallback)(()=>{p(!1),h(String(e??``)),_(void 0),r?.()},[e,r]),w=(0,t.useCallback)(async()=>{if(i){let e=i(m);if(e){_(e);return}}let e=s===`number`?Number(m):m;b(!0);try{let t=await n(e);if(typeof t==`string`){_(t),b(!1);return}p(!1),_(void 0)}catch(e){_(e?.message||`Save failed`)}finally{b(!1)}},[m,i,s,n]),T=(0,t.useCallback)(e=>{e.key===`Enter`?(e.preventDefault(),w()):e.key===`Escape`&&(e.preventDefault(),C())},[w,C]);return f?(0,y.jsxs)(`div`,{"data-slot":`inline-editing`,className:(0,a.cn)(`relative flex items-center gap-1`,u),children:[(0,y.jsxs)(`div`,{className:`flex-1 relative`,children:[(0,y.jsx)(`input`,{ref:x,"data-slot":`inline-editing-input`,type:s,value:m,onChange:e=>{h(e.target.value),g&&_(void 0)},onKeyDown:T,placeholder:c,disabled:v,"aria-invalid":!!g,"aria-describedby":g?`inline-editing-error`:void 0,className:(0,a.cn)(`w-full rounded border px-2 py-1 text-sm outline-none transition-colors`,`focus:ring-2 focus:ring-ring focus:border-input`,g?`border-destructive focus:ring-destructive/30`:`border-input`,v&&`opacity-50`)}),g&&(0,y.jsx)(`p`,{id:`inline-editing-error`,"data-slot":`inline-editing-error`,className:`absolute left-0 top-full mt-0.5 text-xs text-destructive`,role:`alert`,children:g})]}),(0,y.jsx)(`button`,{"data-slot":`inline-editing-save`,type:`button`,onClick:w,disabled:v,"aria-label":`Save`,className:(0,a.cn)(`inline-flex h-6 w-6 items-center justify-center rounded text-primary hover:bg-primary/10 transition-colors`,v&&`opacity-50 cursor-not-allowed`),children:(0,y.jsx)(o.Check,{className:`h-3.5 w-3.5`})}),(0,y.jsx)(`button`,{"data-slot":`inline-editing-cancel`,type:`button`,onClick:C,disabled:v,"aria-label":`Cancel`,className:`inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,y.jsx)(o.X,{className:`h-3.5 w-3.5`})})]}):(0,y.jsx)(`div`,{"data-slot":`inline-editing`,className:(0,a.cn)(`group relative cursor-pointer rounded px-2 py-1 hover:bg-muted/50 transition-colors min-h-[1.75rem] flex items-center`,d&&`cursor-default opacity-60`,u),onClick:S,role:`button`,tabIndex:d?-1:0,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),S())},"aria-label":`Edit value: ${String(e??``)}`,children:(0,y.jsx)(`span`,{"data-slot":`inline-editing-display`,className:`truncate text-sm`,children:e!=null&&String(e)!==``?String(e):(0,y.jsx)(`span`,{className:`text-muted-foreground italic`,children:c||`Click to edit`})})})}function Oe(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function ke({data:e,columns:n,onPaste:r,enabled:i=!0}){let[a,o]=(0,t.useState)(null),s=(0,t.useCallback)(()=>{if(!i||!a)return;let{startRow:t,startCol:r,endRow:o,endCol:s}=Oe(a),c=[];for(let i=t;i<=o;i++){let t=e[i];if(!t)continue;let a=[];for(let e=r;e<=s;e++){let r=n[e];a.push(r?String(t[r]??``):``)}c.push(a.join(` `))}let l=c.join(`
14
14
  `);navigator.clipboard.writeText(l)},[i,a,e,n]),c=(0,t.useCallback)(()=>{if(!i||!a||!r)return;let{startRow:t,startCol:o}=Oe(a);navigator.clipboard.readText().then(i=>{let a=[],s=i.split(`
15
- `);for(let r=0;r<s.length;r++){let i=s[r].split(` `);for(let s=0;s<i.length;s++){let c=t+r,l=n[o+s];l&&c<e.length&&a.push({rowIndex:c,field:l,value:i[s]})}}a.length>0&&r(a)})},[i,a,n,e.length,r]),l=(0,t.useCallback)(e=>{if(!i)return;let t=e.metaKey||e.ctrlKey;t&&e.key===`c`?(e.preventDefault(),s()):t&&e.key===`v`&&(e.preventDefault(),c())},[i,s,c]);return(0,t.useEffect)(()=>{i||o(null)},[i]),{selectedRange:a,setSelectedRange:o,onCopy:s,onPaste:c,onKeyDown:l}}var Ae=[{position:0,className:`bg-green-100`},{position:.5,className:`bg-yellow-100`},{position:1,className:`bg-red-100`}];function Z(e,t){let n=1/0,r=-1/0;for(let i of e){let e=Number(i[t]);Number.isFinite(e)&&(e<n&&(n=e),e>r&&(r=e))}return Number.isFinite(n)?[n,r]:[0,0]}function je(e,t){if(t.length===0)return``;if(t.length===1)return t[0].className;let n=t[0],r=Math.abs(e-n.position);for(let i=1;i<t.length;i++){let a=Math.abs(e-t[i].position);a<r&&(n=t[i],r=a)}return n.className}function Q(e){let{field:n,data:r,min:i,max:a,stops:o=Ae}=e,[s,c]=(0,t.useMemo)(()=>Z(r,n),[r,n]),l=i??s,u=a??c;return(0,t.useCallback)(e=>{let t=Number(e[n]);if(Number.isFinite(t))return u===l?o.length>0?o[0].className:void 0:je(Math.max(0,Math.min(1,(t-l)/(u-l))),o)},[n,l,u,o])}var $=`text/x-group-key`;function Me({groupKeys:e}){let[n,r]=(0,t.useState)(e),[i,a]=(0,t.useState)(null);return(0,t.useEffect)(()=>{r(t=>{let n=new Set(t),r=new Set(e);if(t.length===e.length&&t.every((t,n)=>t===e[n]))return t;let i=t.filter(e=>r.has(e)),a=e.filter(e=>!n.has(e));return[...i,...a]})},[e]),{groupOrder:n,moveGroup:(0,t.useCallback)((e,t)=>{r(n=>{if(e<0||e>=n.length||t<0||t>=n.length||e===t)return n;let r=[...n],[i]=r.splice(e,1);return r.splice(t,0,i),r})},[]),onDragStart:(0,t.useCallback)((e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData($,t),a(t)},[]),onDragOver:(0,t.useCallback)(e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`},[]),onDrop:(0,t.useCallback)((e,t)=>{e.preventDefault();let n=e.dataTransfer.getData($);!n||n===t||r(e=>{let r=e.indexOf(n),i=e.indexOf(t);if(r===-1||i===-1)return e;let a=[...e],[o]=a.splice(r,1);return a.splice(i,0,o),a})},[]),onDragEnd:(0,t.useCallback)(()=>{a(null)},[]),draggingKey:i}}function Ne({value:e,onChange:n,onConfirm:r,onCancel:i,activeCell:s,disabled:c=!1,className:l}){let[u,d]=(0,t.useState)(!1),[f,p]=(0,t.useState)(e),m=(0,t.useRef)(null);(0,t.useEffect)(()=>{u||p(e)},[e,u]),(0,t.useEffect)(()=>{u&&m.current&&(m.current.focus(),m.current.select())},[u]);let h=(0,t.useCallback)(()=>{c||(d(!0),p(e))},[c,e]),g=(0,t.useCallback)(()=>{d(!1),n?.(f),r?.(f)},[f,n,r]),_=(0,t.useCallback)(()=>{d(!1),p(e),i?.()},[e,i]),v=(0,t.useCallback)(e=>{e.key===`Enter`?(e.preventDefault(),g()):e.key===`Escape`&&(e.preventDefault(),_())},[g,_]);return(0,y.jsxs)(`div`,{className:(0,a.cn)(`flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5`,l),children:[(0,y.jsx)(o.FunctionSquare,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),s&&(0,y.jsx)(`span`,{className:`min-w-[4rem] shrink-0 rounded bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground`,children:s}),(0,y.jsx)(`input`,{ref:m,type:`text`,value:u?f:e,readOnly:!u,disabled:c,onClick:h,onChange:e=>p(e.target.value),onKeyDown:v,className:(0,a.cn)(`flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`,u&&`rounded ring-1 ring-ring px-1`,c&&`cursor-not-allowed opacity-50`)}),u&&(0,y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,y.jsx)(`button`,{type:`button`,onClick:g,className:`rounded p-0.5 text-green-600 hover:bg-green-100`,"aria-label":`Confirm`,children:(0,y.jsx)(o.Check,{className:`h-4 w-4`})}),(0,y.jsx)(`button`,{type:`button`,onClick:_,className:`rounded p-0.5 text-red-600 hover:bg-red-100`,"aria-label":`Cancel`,children:(0,y.jsx)(o.X,{className:`h-4 w-4`})})]})]})}function Pe({frozenWidth:e,onResize:n,minFrozenWidth:r=100,minScrollableWidth:i=200,left:s,right:c,className:l}){let u=(0,t.useRef)(null),[d,f]=(0,t.useState)(e),p=(0,t.useRef)(!1),m=(0,t.useRef)(0),h=(0,t.useRef)(0),g=n?e:d,_=(0,t.useCallback)(e=>{e.preventDefault(),p.current=!0,m.current=e.clientX,h.current=g;let t=e=>{if(!p.current||!u.current)return;let t=u.current.offsetWidth,a=e.clientX-m.current,o=h.current+a;o=Math.max(o,r),o=Math.min(o,t-i),n?n(o):f(o)},a=()=>{p.current=!1,document.removeEventListener(`pointermove`,t),document.removeEventListener(`pointerup`,a)};document.addEventListener(`pointermove`,t),document.addEventListener(`pointerup`,a)},[g,r,i,n]);return(0,y.jsxs)(`div`,{ref:u,className:(0,a.cn)(`flex h-full w-full overflow-hidden`,l),children:[(0,y.jsx)(`div`,{className:`shrink-0 overflow-auto`,style:{width:g},children:s}),(0,y.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,onPointerDown:_,className:(0,a.cn)(`flex w-2 cursor-col-resize items-center justify-center`,`border-x border-border bg-muted/50 hover:bg-muted`,`transition-colors`),children:(0,y.jsx)(o.GripVertical,{className:`h-4 w-4 text-muted-foreground`})}),(0,y.jsx)(`div`,{className:`min-w-0 flex-1 overflow-auto`,children:c})]})}var Fe=({schema:e,...t})=>{let{dataSource:n}=(0,r.useSchemaContext)()||{};return(0,y.jsx)(ae,{schema:e,dataSource:n,...t})};n.ComponentRegistry.register(`object-grid`,Fe,{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`}]}),n.ComponentRegistry.register(`grid`,Fe,{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`}]}),n.ComponentRegistry.register(`import-wizard`,({schema:e,...t})=>{let{dataSource:n}=(0,r.useSchemaContext)()||{};return(0,y.jsx)(Ee,{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}]}),e.BulkActionBar=F,e.FormulaBar=Ne,e.GroupRow=O,e.ImportWizard=Ee,e.InlineEditing=De,e.ObjectGrid=ae,e.ObjectGridRenderer=Fe,e.RowActionMenu=P,e.SplitPaneGrid=Pe,e.VirtualGrid=be,e.formatActionLabel=N,e.useCellClipboard=ke,e.useColumnSummary=M,e.useGradientColor=Q,e.useGroupReorder=Me,e.useGroupedData=ee,e.useRowColor=C});
15
+ `);for(let r=0;r<s.length;r++){let i=s[r].split(` `);for(let s=0;s<i.length;s++){let c=t+r,l=n[o+s];l&&c<e.length&&a.push({rowIndex:c,field:l,value:i[s]})}}a.length>0&&r(a)})},[i,a,n,e.length,r]),l=(0,t.useCallback)(e=>{if(!i)return;let t=e.metaKey||e.ctrlKey;t&&e.key===`c`?(e.preventDefault(),s()):t&&e.key===`v`&&(e.preventDefault(),c())},[i,s,c]);return(0,t.useEffect)(()=>{i||o(null)},[i]),{selectedRange:a,setSelectedRange:o,onCopy:s,onPaste:c,onKeyDown:l}}var Ae=[{position:0,className:`bg-green-100`},{position:.5,className:`bg-yellow-100`},{position:1,className:`bg-red-100`}];function Q(e,t){let n=1/0,r=-1/0;for(let i of e){let e=Number(i[t]);Number.isFinite(e)&&(e<n&&(n=e),e>r&&(r=e))}return Number.isFinite(n)?[n,r]:[0,0]}function je(e,t){if(t.length===0)return``;if(t.length===1)return t[0].className;let n=t[0],r=Math.abs(e-n.position);for(let i=1;i<t.length;i++){let a=Math.abs(e-t[i].position);a<r&&(n=t[i],r=a)}return n.className}function Me(e){let{field:n,data:r,min:i,max:a,stops:o=Ae}=e,[s,c]=(0,t.useMemo)(()=>Q(r,n),[r,n]),l=i??s,u=a??c;return(0,t.useCallback)(e=>{let t=Number(e[n]);if(Number.isFinite(t))return u===l?o.length>0?o[0].className:void 0:je(Math.max(0,Math.min(1,(t-l)/(u-l))),o)},[n,l,u,o])}var $=`text/x-group-key`;function Ne({groupKeys:e}){let[n,r]=(0,t.useState)(e),[i,a]=(0,t.useState)(null);return(0,t.useEffect)(()=>{r(t=>{let n=new Set(t),r=new Set(e);if(t.length===e.length&&t.every((t,n)=>t===e[n]))return t;let i=t.filter(e=>r.has(e)),a=e.filter(e=>!n.has(e));return[...i,...a]})},[e]),{groupOrder:n,moveGroup:(0,t.useCallback)((e,t)=>{r(n=>{if(e<0||e>=n.length||t<0||t>=n.length||e===t)return n;let r=[...n],[i]=r.splice(e,1);return r.splice(t,0,i),r})},[]),onDragStart:(0,t.useCallback)((e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData($,t),a(t)},[]),onDragOver:(0,t.useCallback)(e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`},[]),onDrop:(0,t.useCallback)((e,t)=>{e.preventDefault();let n=e.dataTransfer.getData($);!n||n===t||r(e=>{let r=e.indexOf(n),i=e.indexOf(t);if(r===-1||i===-1)return e;let a=[...e],[o]=a.splice(r,1);return a.splice(i,0,o),a})},[]),onDragEnd:(0,t.useCallback)(()=>{a(null)},[]),draggingKey:i}}function Pe({value:e,onChange:n,onConfirm:r,onCancel:i,activeCell:s,disabled:c=!1,className:l}){let[u,d]=(0,t.useState)(!1),[f,p]=(0,t.useState)(e),m=(0,t.useRef)(null);(0,t.useEffect)(()=>{u||p(e)},[e,u]),(0,t.useEffect)(()=>{u&&m.current&&(m.current.focus(),m.current.select())},[u]);let h=(0,t.useCallback)(()=>{c||(d(!0),p(e))},[c,e]),g=(0,t.useCallback)(()=>{d(!1),n?.(f),r?.(f)},[f,n,r]),_=(0,t.useCallback)(()=>{d(!1),p(e),i?.()},[e,i]),v=(0,t.useCallback)(e=>{e.key===`Enter`?(e.preventDefault(),g()):e.key===`Escape`&&(e.preventDefault(),_())},[g,_]);return(0,y.jsxs)(`div`,{className:(0,a.cn)(`flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5`,l),children:[(0,y.jsx)(o.FunctionSquare,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),s&&(0,y.jsx)(`span`,{className:`min-w-[4rem] shrink-0 rounded bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground`,children:s}),(0,y.jsx)(`input`,{ref:m,type:`text`,value:u?f:e,readOnly:!u,disabled:c,onClick:h,onChange:e=>p(e.target.value),onKeyDown:v,className:(0,a.cn)(`flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`,u&&`rounded ring-1 ring-ring px-1`,c&&`cursor-not-allowed opacity-50`)}),u&&(0,y.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,y.jsx)(`button`,{type:`button`,onClick:g,className:`rounded p-0.5 text-green-600 hover:bg-green-100`,"aria-label":`Confirm`,children:(0,y.jsx)(o.Check,{className:`h-4 w-4`})}),(0,y.jsx)(`button`,{type:`button`,onClick:_,className:`rounded p-0.5 text-red-600 hover:bg-red-100`,"aria-label":`Cancel`,children:(0,y.jsx)(o.X,{className:`h-4 w-4`})})]})]})}function Fe({frozenWidth:e,onResize:n,minFrozenWidth:r=100,minScrollableWidth:i=200,left:s,right:c,className:l}){let u=(0,t.useRef)(null),[d,f]=(0,t.useState)(e),p=(0,t.useRef)(!1),m=(0,t.useRef)(0),h=(0,t.useRef)(0),g=n?e:d,_=(0,t.useCallback)(e=>{e.preventDefault(),p.current=!0,m.current=e.clientX,h.current=g;let t=e=>{if(!p.current||!u.current)return;let t=u.current.offsetWidth,a=e.clientX-m.current,o=h.current+a;o=Math.max(o,r),o=Math.min(o,t-i),n?n(o):f(o)},a=()=>{p.current=!1,document.removeEventListener(`pointermove`,t),document.removeEventListener(`pointerup`,a)};document.addEventListener(`pointermove`,t),document.addEventListener(`pointerup`,a)},[g,r,i,n]);return(0,y.jsxs)(`div`,{ref:u,className:(0,a.cn)(`flex h-full w-full overflow-hidden`,l),children:[(0,y.jsx)(`div`,{className:`shrink-0 overflow-auto`,style:{width:g},children:s}),(0,y.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,onPointerDown:_,className:(0,a.cn)(`flex w-2 cursor-col-resize items-center justify-center`,`border-x border-border bg-muted/50 hover:bg-muted`,`transition-colors`),children:(0,y.jsx)(o.GripVertical,{className:`h-4 w-4 text-muted-foreground`})}),(0,y.jsx)(`div`,{className:`min-w-0 flex-1 overflow-auto`,children:c})]})}var Ie=({schema:e,...t})=>{let{dataSource:n}=(0,r.useSchemaContext)()||{};return(0,y.jsx)(ae,{schema:e,dataSource:n,...t})};n.ComponentRegistry.register(`object-grid`,Ie,{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`}]}),n.ComponentRegistry.register(`grid`,Ie,{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`}]}),n.ComponentRegistry.register(`import-wizard`,({schema:e,...t})=>{let{dataSource:n}=(0,r.useSchemaContext)()||{};return(0,y.jsx)(Ee,{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}]}),e.BulkActionBar=L,e.FormulaBar=Pe,e.GroupRow=A,e.ImportWizard=Ee,e.InlineEditing=De,e.ObjectGrid=ae,e.ObjectGridRenderer=Ie,e.RowActionMenu=I,e.SplitPaneGrid=Fe,e.VirtualGrid=be,e.formatActionLabel=F,e.useCellClipboard=ke,e.useColumnSummary=P,e.useGradientColor=Me,e.useGroupReorder=Ne,e.useGroupedData=k,e.useRowColor=C});
@@ -18,16 +18,28 @@ export interface AggregationResult {
18
18
  value: number;
19
19
  }
20
20
  export interface GroupEntry {
21
- /** Composite key identifying this group (field values joined by ' / ') */
21
+ /** Composite key identifying this group (unique across all levels) */
22
22
  key: string;
23
- /** Display label for the group header */
23
+ /** Display label for the group header (current level only) */
24
24
  label: string;
25
- /** Rows belonging to this group */
25
+ /** Field name this group is bucketed by */
26
+ field: string;
27
+ /** Nesting depth (0 = top-level) */
28
+ depth: number;
29
+ /** Rows belonging to this group (flattened across subgroups) */
26
30
  rows: any[];
27
31
  /** Whether the group section is collapsed */
28
32
  collapsed: boolean;
29
33
  /** Computed aggregations for this group (empty when no aggregations configured). */
30
34
  aggregations: AggregationResult[];
35
+ /**
36
+ * Nested subgroups for the next grouping field.
37
+ *
38
+ * Empty array (not undefined) when this is the deepest level so consumers
39
+ * can switch on `subgroups.length` to decide whether to render a child
40
+ * `GroupRow` or the data table.
41
+ */
42
+ subgroups: GroupEntry[];
31
43
  }
32
44
  export interface UseGroupedDataResult {
33
45
  /** Grouped entries (empty when grouping is not configured) */
@@ -37,6 +49,12 @@ export interface UseGroupedDataResult {
37
49
  /** Toggle the collapsed state of a group by its key */
38
50
  toggleGroup: (key: string) => void;
39
51
  }
52
+ /**
53
+ * Optional per-field value formatter. Returning `undefined` falls back to the
54
+ * default stringification, so resolvers can opt out for individual values
55
+ * (e.g. unknown select values).
56
+ */
57
+ export type GroupValueFormatter = (field: string, value: any) => string | undefined;
40
58
  /**
41
59
  * Hook that groups a flat data array by the fields specified in GroupingConfig.
42
60
  *
@@ -47,5 +65,8 @@ export interface UseGroupedDataResult {
47
65
  * @param config - GroupingConfig from the grid schema (optional)
48
66
  * @param data - flat data rows
49
67
  * @param aggregations - optional aggregation definitions to compute per group
68
+ * @param formatValue - optional per-field formatter that maps raw values to
69
+ * display labels (e.g. resolves select option codes
70
+ * to their human-readable labels)
50
71
  */
51
- export declare function useGroupedData(config: GroupingConfig | undefined, data: any[], aggregations?: AggregationConfig[]): UseGroupedDataResult;
72
+ export declare function useGroupedData(config: GroupingConfig | undefined, data: any[], aggregations?: AggregationConfig[], formatValue?: GroupValueFormatter): UseGroupedDataResult;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@object-ui/plugin-grid",
3
- "version": "3.4.0",
3
+ "version": "4.0.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Grid plugin for Object UI",
@@ -17,12 +17,12 @@
17
17
  "dependencies": {
18
18
  "@tanstack/react-virtual": "^3.13.24",
19
19
  "lucide-react": "^1.14.0",
20
- "@object-ui/components": "3.4.0",
21
- "@object-ui/core": "3.4.0",
22
- "@object-ui/fields": "3.4.0",
23
- "@object-ui/mobile": "3.4.0",
24
- "@object-ui/react": "3.4.0",
25
- "@object-ui/types": "3.4.0"
20
+ "@object-ui/components": "4.0.3",
21
+ "@object-ui/core": "4.0.3",
22
+ "@object-ui/fields": "4.0.3",
23
+ "@object-ui/mobile": "4.0.3",
24
+ "@object-ui/react": "4.0.3",
25
+ "@object-ui/types": "4.0.3"
26
26
  },
27
27
  "peerDependencies": {
28
28
  "react": "^18.0.0 || ^19.0.0",
@@ -34,7 +34,7 @@
34
34
  "typescript": "^6.0.3",
35
35
  "vite": "^8.0.10",
36
36
  "vite-plugin-dts": "^5.0.0",
37
- "@object-ui/data-objectstack": "3.4.0"
37
+ "@object-ui/data-objectstack": "4.0.3"
38
38
  },
39
39
  "keywords": [
40
40
  "objectui",