@standardbeagle/edit-db 0.4.484 → 0.4.581
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/common/fetcher.d.ts +7 -2
- package/dist/common/saved-objects.d.ts +40 -0
- package/dist/common/schema-queries.d.ts +1 -0
- package/dist/components/bulk-edit-dialog.d.ts +18 -0
- package/dist/components/content-panel.d.ts +5 -2
- package/dist/components/content-viewer.d.ts +8 -1
- package/dist/components/content-viewer.test.d.ts +1 -0
- package/dist/components/data-table.d.ts +49 -2
- package/dist/components/detail-panel.d.ts +2 -2
- package/dist/components/export-button.d.ts +19 -0
- package/dist/components/export-button.test.d.ts +1 -0
- package/dist/components/filters/fk-filter.d.ts +2 -0
- package/dist/components/filters/fk-filter.test.d.ts +1 -0
- package/dist/components/filters/number-filter.d.ts +8 -0
- package/dist/components/filters/number-filter.test.d.ts +1 -0
- package/dist/components/fk-cell-popover.d.ts +12 -5
- package/dist/components/fk-cell-popover.test.d.ts +1 -0
- package/dist/components/form-runner-host.d.ts +14 -0
- package/dist/components/form-runner.d.ts +43 -0
- package/dist/components/form-runner.test.d.ts +0 -0
- package/dist/components/form-subform.d.ts +11 -0
- package/dist/components/form-subform.test.d.ts +0 -0
- package/dist/components/grouped-grid-summary.d.ts +17 -0
- package/dist/components/grouped-grid-summary.test.d.ts +0 -0
- package/dist/components/m2m-panel.d.ts +4 -5
- package/dist/components/ui/table.test.d.ts +1 -0
- package/dist/data-edit.d.ts +25 -4
- package/dist/data-panel.d.ts +0 -11
- package/dist/edit-db.css +1 -1
- package/dist/editor.d.ts +22 -1
- package/dist/editor.es.js +7368 -4589
- package/dist/editor.stories.d.ts +0 -1
- package/dist/editor.umd.cjs +48 -27
- package/dist/hooks/useColumnNav.d.ts +3 -3
- package/dist/hooks/useColumnSizingPersistence.d.ts +19 -0
- package/dist/hooks/useColumnVisibilityPersistence.d.ts +34 -0
- package/dist/hooks/useColumnVisibilityPersistence.test.d.ts +1 -0
- package/dist/hooks/useCompositeTableRef.d.ts +20 -2
- package/dist/hooks/useCompositeTableRef.test.d.ts +1 -0
- package/dist/hooks/useDataTable.d.ts +59 -6
- package/dist/hooks/useDebouncedCommit.d.ts +19 -0
- package/dist/hooks/useDebouncedCommit.test.d.ts +1 -0
- package/dist/hooks/useDeltaMutation.d.ts +20 -0
- package/dist/hooks/useDeltaMutation.test.d.ts +0 -0
- package/dist/hooks/useEditorConfig.d.ts +27 -0
- package/dist/hooks/useFitMode.d.ts +23 -0
- package/dist/hooks/useFitMode.test.d.ts +1 -0
- package/dist/hooks/usePanelSize.d.ts +28 -0
- package/dist/hooks/usePanelSize.test.d.ts +1 -0
- package/dist/hooks/usePath.d.ts +2 -5
- package/dist/hooks/useRowHoverActions.d.ts +26 -0
- package/dist/hooks/useSchema.d.ts +8 -2
- package/dist/hooks/useSchemaFilter.test.d.ts +1 -0
- package/dist/hooks/useTableExport.d.ts +13 -0
- package/dist/hooks/useTableMutation.d.ts +1 -4
- package/dist/hooks/useTableMutation.test.d.ts +0 -0
- package/dist/hooks/useTableRef.d.ts +23 -2
- package/dist/hooks/useTableRef.test.d.ts +1 -0
- package/dist/hooks/useTableStats.d.ts +7 -24
- package/dist/hooks/useToast.d.ts +15 -0
- package/dist/index.d.ts +13 -1
- package/dist/lib/column-order.d.ts +17 -0
- package/dist/lib/column-order.test.d.ts +1 -0
- package/dist/lib/content-detect.d.ts +39 -0
- package/dist/lib/content-detect.sniff.test.d.ts +1 -0
- package/dist/lib/date-input.d.ts +21 -0
- package/dist/lib/date-input.test.d.ts +1 -0
- package/dist/lib/drill-stack.d.ts +19 -2
- package/dist/lib/export.d.ts +122 -0
- package/dist/lib/export.test.d.ts +1 -0
- package/dist/lib/field-validation.d.ts +16 -0
- package/dist/lib/fk.d.ts +23 -2
- package/dist/lib/form-definition.d.ts +57 -0
- package/dist/lib/form-definition.test.d.ts +1 -0
- package/dist/lib/form-runner-nav.d.ts +19 -0
- package/dist/lib/form-runner-nav.test.d.ts +1 -0
- package/dist/lib/form-subform.d.ts +12 -0
- package/dist/lib/form-subform.test.d.ts +1 -0
- package/dist/lib/form-widget.d.ts +36 -0
- package/dist/lib/form-widget.test.d.ts +1 -0
- package/dist/lib/format-value.d.ts +26 -0
- package/dist/lib/grid-grouping.d.ts +63 -0
- package/dist/lib/grid-grouping.test.d.ts +1 -0
- package/dist/lib/invalidate.d.ts +7 -0
- package/dist/lib/invalidate.test.d.ts +1 -0
- package/dist/lib/label-match.d.ts +13 -0
- package/dist/lib/label-match.test.d.ts +1 -0
- package/dist/lib/m2m.d.ts +45 -6
- package/dist/lib/mutation-payload.d.ts +37 -0
- package/dist/lib/mutation-payload.test.d.ts +1 -0
- package/dist/lib/query-builder.d.ts +137 -8
- package/dist/lib/row-id.d.ts +20 -0
- package/dist/lib/rows-by-pk-query.test.d.ts +1 -0
- package/dist/lib/scalar-types.d.ts +30 -0
- package/dist/lib/scalar-types.test.d.ts +1 -0
- package/dist/lib/table-action.d.ts +24 -0
- package/dist/lib/table-ref.d.ts +45 -0
- package/dist/lib/table-ref.test.d.ts +1 -0
- package/dist/{tableList.d.ts → table-list.d.ts} +1 -1
- package/dist/table-list.test.d.ts +0 -0
- package/dist/table-view.chart.test.d.ts +1 -0
- package/dist/table-view.d.ts +22 -0
- package/dist/table-view.test.d.ts +0 -0
- package/dist/types/schema.d.ts +54 -10
- package/package.json +2 -4
- package/dist/common/schema.d.ts +0 -2
- package/dist/data-data-table.d.ts +0 -17
- package/dist/error-panel.d.ts +0 -1
- /package/dist/common/{schema.test.d.ts → saved-objects.test.d.ts} +0 -0
- /package/dist/{components/table-dimensions.test.d.ts → common/schema-queries.test.d.ts} +0 -0
- /package/dist/{tableList.test.d.ts → components/bulk-edit-dialog.test.d.ts} +0 -0
package/dist/editor.umd.cjs
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`+
|
|
3
|
-
`),
|
|
4
|
-
`),
|
|
5
|
-
`+
|
|
1
|
+
(function(ae,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react"),require("@tanstack/react-query"),require("lucide-react"),require("radix-ui"),require("@radix-ui/react-slot"),require("@tanstack/react-form"),require("@tanstack/react-table")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","lucide-react","radix-ui","@radix-ui/react-slot","@tanstack/react-form","@tanstack/react-table"],u):(ae=typeof globalThis<"u"?globalThis:ae||self,u(ae.editor={},ae.React,ae.ReactQuery,ae.LucideReact,ae.RadixUI,ae.RadixReactSlot,ae.ReactForm,ae.ReactTable))})(this,(function(ae,u,de,C,R,ka,Tn,$n){"use strict";function Sa(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ve=Sa(u);var En={exports:{}},sn={};var ls;function Ta(){if(ls)return sn;ls=1;var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,m){var d,f={},p=null,x=null;m!==void 0&&(p=""+m),c.key!==void 0&&(p=""+c.key),c.ref!==void 0&&(x=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(f[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)f[d]===void 0&&(f[d]=c[d]);return{$$typeof:t,type:l,key:p,ref:x,props:f,_owner:o.current}}return sn.Fragment=r,sn.jsx=a,sn.jsxs=a,sn}var on={};var cs;function $a(){return cs||(cs=1,process.env.NODE_ENV!=="production"&&(function(){var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),h=Symbol.iterator,y="@@iterator";function N(g){if(g===null||typeof g!="object")return null;var M=h&&g[h]||g[y];return typeof M=="function"?M:null}var T=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(g){{for(var M=arguments.length,G=new Array(M>1?M-1:0),te=1;te<M;te++)G[te-1]=arguments[te];$("error",g,G)}}function $(g,M,G){{var te=T.ReactDebugCurrentFrame,pe=te.getStackAddendum();pe!==""&&(M+="%s",G=G.concat([pe]));var ge=G.map(function(ue){return String(ue)});ge.unshift("Warning: "+M),Function.prototype.apply.call(console[g],console,ge)}}var b=!1,v=!1,w=!1,F=!1,j=!1,V;V=Symbol.for("react.module.reference");function S(g){return!!(typeof g=="string"||typeof g=="function"||g===s||g===i||j||g===o||g===m||g===d||F||g===x||b||v||w||typeof g=="object"&&g!==null&&(g.$$typeof===p||g.$$typeof===f||g.$$typeof===a||g.$$typeof===l||g.$$typeof===c||g.$$typeof===V||g.getModuleId!==void 0))}function L(g,M,G){var te=g.displayName;if(te)return te;var pe=M.displayName||M.name||"";return pe!==""?G+"("+pe+")":G}function A(g){return g.displayName||"Context"}function D(g){if(g==null)return null;if(typeof g.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof g=="function")return g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case o:return"StrictMode";case m:return"Suspense";case d:return"SuspenseList"}if(typeof g=="object")switch(g.$$typeof){case l:var M=g;return A(M)+".Consumer";case a:var G=g;return A(G._context)+".Provider";case c:return L(g,g.render,"ForwardRef");case f:var te=g.displayName||null;return te!==null?te:D(g.type)||"Memo";case p:{var pe=g,ge=pe._payload,ue=pe._init;try{return D(ue(ge))}catch{return null}}}return null}var B=Object.assign,X=0,E,P,q,U,_,ce,he;function Ue(){}Ue.__reactDisabledLog=!0;function Pe(){{if(X===0){E=console.log,P=console.info,q=console.warn,U=console.error,_=console.group,ce=console.groupCollapsed,he=console.groupEnd;var g={configurable:!0,enumerable:!0,value:Ue,writable:!0};Object.defineProperties(console,{info:g,log:g,warn:g,error:g,group:g,groupCollapsed:g,groupEnd:g})}X++}}function ie(){{if(X--,X===0){var g={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:B({},g,{value:E}),info:B({},g,{value:P}),warn:B({},g,{value:q}),error:B({},g,{value:U}),group:B({},g,{value:_}),groupCollapsed:B({},g,{value:ce}),groupEnd:B({},g,{value:he})})}X<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var se=T.ReactCurrentDispatcher,ke;function Ae(g,M,G){{if(ke===void 0)try{throw Error()}catch(pe){var te=pe.stack.trim().match(/\n( *(at )?)/);ke=te&&te[1]||""}return`
|
|
2
|
+
`+ke+g}}var re=!1,Ee;{var Ie=typeof WeakMap=="function"?WeakMap:Map;Ee=new Ie}function Le(g,M){if(!g||re)return"";{var G=Ee.get(g);if(G!==void 0)return G}var te;re=!0;var pe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ge;ge=se.current,se.current=null,Pe();try{if(M){var ue=function(){throw Error()};if(Object.defineProperty(ue.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ue,[])}catch(Re){te=Re}Reflect.construct(g,[],ue)}else{try{ue.call()}catch(Re){te=Re}g.call(ue.prototype)}}else{try{throw Error()}catch(Re){te=Re}g()}}catch(Re){if(Re&&te&&typeof Re.stack=="string"){for(var le=Re.stack.split(`
|
|
3
|
+
`),We=te.stack.split(`
|
|
4
|
+
`),Te=le.length-1,Fe=We.length-1;Te>=1&&Fe>=0&&le[Te]!==We[Fe];)Fe--;for(;Te>=1&&Fe>=0;Te--,Fe--)if(le[Te]!==We[Fe]){if(Te!==1||Fe!==1)do if(Te--,Fe--,Fe<0||le[Te]!==We[Fe]){var at=`
|
|
5
|
+
`+le[Te].replace(" at new "," at ");return g.displayName&&at.includes("<anonymous>")&&(at=at.replace("<anonymous>",g.displayName)),typeof g=="function"&&Ee.set(g,at),at}while(Te>=1&&Fe>=0);break}}}finally{re=!1,se.current=ge,ie(),Error.prepareStackTrace=pe}var rn=g?g.displayName||g.name:"",Yt=rn?Ae(rn):"";return typeof g=="function"&&Ee.set(g,Yt),Yt}function Ge(g,M,G){return Le(g,!1)}function Oe(g){var M=g.prototype;return!!(M&&M.isReactComponent)}function ye(g,M,G){if(g==null)return"";if(typeof g=="function")return Le(g,Oe(g));if(typeof g=="string")return Ae(g);switch(g){case m:return Ae("Suspense");case d:return Ae("SuspenseList")}if(typeof g=="object")switch(g.$$typeof){case c:return Ge(g.render);case f:return ye(g.type,M,G);case p:{var te=g,pe=te._payload,ge=te._init;try{return ye(ge(pe),M,G)}catch{}}}return""}var ze=Object.prototype.hasOwnProperty,O={},Z=T.ReactDebugCurrentFrame;function ee(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);Z.setExtraStackFrame(G)}else Z.setExtraStackFrame(null)}function Ce(g,M,G,te,pe){{var ge=Function.call.bind(ze);for(var ue in g)if(ge(g,ue)){var le=void 0;try{if(typeof g[ue]!="function"){var We=Error((te||"React class")+": "+G+" type `"+ue+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof g[ue]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw We.name="Invariant Violation",We}le=g[ue](M,ue,te,G,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Te){le=Te}le&&!(le instanceof Error)&&(ee(pe),k("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",te||"React class",G,ue,typeof le),ee(null)),le instanceof Error&&!(le.message in O)&&(O[le.message]=!0,ee(pe),k("Failed %s type: %s",G,le.message),ee(null))}}}var xe=Array.isArray;function qe(g){return xe(g)}function W(g){{var M=typeof Symbol=="function"&&Symbol.toStringTag,G=M&&g[Symbol.toStringTag]||g.constructor.name||"Object";return G}}function me(g){try{return Ne(g),!1}catch{return!0}}function Ne(g){return""+g}function ve(g){if(me(g))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",W(g)),Ne(g)}var rt=T.ReactCurrentOwner,Mt={key:!0,ref:!0,__self:!0,__source:!0},be,ft;function Nt(g){if(ze.call(g,"ref")){var M=Object.getOwnPropertyDescriptor(g,"ref").get;if(M&&M.isReactWarning)return!1}return g.ref!==void 0}function Ye(g){if(ze.call(g,"key")){var M=Object.getOwnPropertyDescriptor(g,"key").get;if(M&&M.isReactWarning)return!1}return g.key!==void 0}function Xe(g,M){typeof g.ref=="string"&&rt.current}function Qt(g,M){{var G=function(){be||(be=!0,k("%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://reactjs.org/link/special-props)",M))};G.isReactWarning=!0,Object.defineProperty(g,"key",{get:G,configurable:!0})}}function kn(g,M){{var G=function(){ft||(ft=!0,k("%s: `ref` 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://reactjs.org/link/special-props)",M))};G.isReactWarning=!0,Object.defineProperty(g,"ref",{get:G,configurable:!0})}}var Sn=function(g,M,G,te,pe,ge,ue){var le={$$typeof:t,type:g,key:M,ref:G,props:ue,_owner:ge};return le._store={},Object.defineProperty(le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:te}),Object.defineProperty(le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:pe}),Object.freeze&&(Object.freeze(le.props),Object.freeze(le)),le};function Ht(g,M,G,te,pe){{var ge,ue={},le=null,We=null;G!==void 0&&(ve(G),le=""+G),Ye(M)&&(ve(M.key),le=""+M.key),Nt(M)&&(We=M.ref,Xe(M,pe));for(ge in M)ze.call(M,ge)&&!Mt.hasOwnProperty(ge)&&(ue[ge]=M[ge]);if(g&&g.defaultProps){var Te=g.defaultProps;for(ge in Te)ue[ge]===void 0&&(ue[ge]=Te[ge])}if(le||We){var Fe=typeof g=="function"?g.displayName||g.name||"Unknown":g;le&&Qt(ue,Fe),We&&kn(ue,Fe)}return Sn(g,le,We,pe,te,rt.current,ue)}}var pt=T.ReactCurrentOwner,It=T.ReactDebugCurrentFrame;function st(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);It.setExtraStackFrame(G)}else It.setExtraStackFrame(null)}var Ut;Ut=!1;function Lt(g){return typeof g=="object"&&g!==null&&g.$$typeof===t}function z(){{if(pt.current){var g=D(pt.current.type);if(g)return`
|
|
6
6
|
|
|
7
|
-
Check the render method of \``+
|
|
7
|
+
Check the render method of \``+g+"`."}return""}}function H(g){return""}var I={};function ne(g){{var M=z();if(!M){var G=typeof g=="string"?g:g.displayName||g.name;G&&(M=`
|
|
8
8
|
|
|
9
|
-
Check the top-level render call using <`+
|
|
9
|
+
Check the top-level render call using <`+G+">.")}return M}}function Se(g,M){{if(!g._store||g._store.validated||g.key!=null)return;g._store.validated=!0;var G=ne(M);if(I[G])return;I[G]=!0;var te="";g&&g._owner&&g._owner!==pt.current&&(te=" It was passed a child from "+D(g._owner.type)+"."),st(g),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',G,te),st(null)}}function De(g,M){{if(typeof g!="object")return;if(qe(g))for(var G=0;G<g.length;G++){var te=g[G];Lt(te)&&Se(te,M)}else if(Lt(g))g._store&&(g._store.validated=!0);else if(g){var pe=N(g);if(typeof pe=="function"&&pe!==g.entries)for(var ge=pe.call(g),ue;!(ue=ge.next()).done;)Lt(ue.value)&&Se(ue.value,M)}}}function ot(g){{var M=g.type;if(M==null||typeof M=="string")return;var G;if(typeof M=="function")G=M.propTypes;else if(typeof M=="object"&&(M.$$typeof===c||M.$$typeof===f))G=M.propTypes;else return;if(G){var te=D(M);Ce(G,g.props,"prop",te,g)}else if(M.PropTypes!==void 0&&!Ut){Ut=!0;var pe=D(M);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",pe||"Unknown")}typeof M.getDefaultProps=="function"&&!M.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ht(g){{for(var M=Object.keys(g.props),G=0;G<M.length;G++){var te=M[G];if(te!=="children"&&te!=="key"){st(g),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",te),st(null);break}}g.ref!==null&&(st(g),k("Invalid attribute `ref` supplied to `React.Fragment`."),st(null))}}var Ke={};function kt(g,M,G,te,pe,ge){{var ue=S(g);if(!ue){var le="";(g===void 0||typeof g=="object"&&g!==null&&Object.keys(g).length===0)&&(le+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var We=H();We?le+=We:le+=z();var Te;g===null?Te="null":qe(g)?Te="array":g!==void 0&&g.$$typeof===t?(Te="<"+(D(g.type)||"Unknown")+" />",le=" Did you accidentally export a JSX literal instead of a component?"):Te=typeof g,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Te,le)}var Fe=Ht(g,M,G,pe,ge);if(Fe==null)return Fe;if(ue){var at=M.children;if(at!==void 0)if(te)if(qe(at)){for(var rn=0;rn<at.length;rn++)De(at[rn],g);Object.freeze&&Object.freeze(at)}else k("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 De(at,g)}if(ze.call(M,"key")){var Yt=D(g),Re=Object.keys(M).filter(function(wm){return wm!=="key"}),is=Re.length>0?"{key: someKey, "+Re.join(": ..., ")+": ...}":"{key: someKey}";if(!Ke[Yt+is]){var jm=Re.length>0?"{"+Re.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
|
|
10
10
|
let props = %s;
|
|
11
11
|
<%s {...props} />
|
|
12
12
|
React keys must be passed directly to JSX without using spread:
|
|
13
13
|
let props = %s;
|
|
14
|
-
<%s key={someKey} {...props} />`,
|
|
14
|
+
<%s key={someKey} {...props} />`,is,Yt,jm,Yt),Ke[Yt+is]=!0}}return g===s?ht(Fe):ot(Fe),Fe}}function gt(g,M,G){return kt(g,M,G,!0)}function nn(g,M,G){return kt(g,M,G,!1)}var Me=nn,as=gt;on.Fragment=s,on.jsx=Me,on.jsxs=as})()),on}var us;function Ea(){return us||(us=1,process.env.NODE_ENV==="production"?En.exports=Ta():En.exports=$a()),En.exports}var n=Ea();const ds={path:"/",history:[],location:0},ms={path:"*",data:{},hash:"",query:""},Fn=u.createContext(ds),ar=u.createContext(null),an=u.createContext(ms),fs=e=>({type:"NAVIGATE",payload:e}),Fa=(e=1)=>({type:"BACK",payload:e}),_a=(e=1)=>({type:"FORWARD",payload:e}),Pa=100;function za(e,t){switch(t.type){case"NAVIGATE":{let{history:r,location:s}=e;return s>0&&(r=r.slice(s)),{path:La(e.path,t.payload),history:[t.payload,...r].slice(0,Pa),location:0}}case"BACK":{const r=e.location+t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}case"FORWARD":{const r=e.location-t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}default:return e}}function ps(){return u.useContext(Fn).path}function _n(){const e=u.useContext(ar);return u.useCallback(t=>e?.(fs(t)),[e])}function Da(){const e=u.useContext(ar),t=u.useContext(Fn);return u.useMemo(()=>({navigate:r=>e?.(fs(r)),back:(r=1)=>e?.(Fa(r)),forward:(r=1)=>e?.(_a(r)),hasBack:t.location<t.history.length-1,...t}),[e,t])}function ir(){return u.useContext(an).data}function hs(){const{query:e,hash:t}=u.useContext(an);return u.useMemo(()=>({search:new URLSearchParams(e),hash:t}),[e,t])}function Ma({path:e,children:t}){const r=e?{path:e,history:[],location:0}:ds,[s,o]=u.useReducer(za,r);return n.jsx(Fn.Provider,{value:s,children:n.jsx(ar.Provider,{value:o,children:n.jsx(an.Provider,{value:ms,children:t})})})}const Pn=u.forwardRef(({to:e,children:t,...r},s)=>{const o=_n(),i=a=>{a.defaultPrevented||a.preventDefault(),o(e)};return n.jsx("a",{...r,href:e,ref:s,onClick:i,children:t})});function lr({children:e}){const t=u.useContext(an),r=u.useContext(Fn),s=xs(e,t.path),o=Ia(s.map(a=>a.route),r.path);if(!o)return n.jsx(n.Fragment,{});const i=s.find(a=>a.route===o.route).element;return n.jsx(an.Provider,{value:{...o.match},children:i})}function gs(e){let t=0;for(const r of e.split("/"))r===""||r==="*"||(t+=r.startsWith(":")?1:100);return t}function Ia(e,t){let r=null;for(const s of e){const o=qa(s,t);o.isMatch&&(r===null||gs(s)>gs(r.route))&&(r={route:s,match:o})}return r}function Be({path:e,element:t}){return n.jsx(n.Fragment,{})}function xs(e,t){const r=[];return u.Children.map(e,s=>{if(!u.isValidElement(s))return;if(s.type===u.Fragment){r.push.apply(r,xs(s.props.children,t));return}const o=s.props;return r.push({route:Aa(t,o.path),element:o.element}),s}),r}const La=(e,t)=>{if(t.startsWith("/"))return t;if(t.startsWith("?")){const[o]=e?.split("?")??[""];return o+t}let r=0;const s=t.split("/").filter(o=>o!=="");for(;s.length>0&&(s[0]==="."||s[0]==="..");)s.shift()==".."&&++r;return Oa(e,s.join("/"),r)},Oa=(e,t,r)=>{const s=e.split("/").filter(a=>a!==""),o=t.split("/").filter(a=>a!=="");return`/${[...s.slice(0,Math.max(0,s.length-r)),...o].join("/")}`},Aa=(e,t)=>{const r=e.split("/").filter(o=>o!==""),s=t.split("/").filter(o=>o!=="");return r.length>0&&r.at(-1)==="*"&&r.pop(),r.length===0?`/${s.join("/")}`:`/${r.join("/")}/${s.join("/")}`},qa=(e,t)=>{let r=e.split("/"),s=t.split("/");if(r.at(-1)===""&&(r=r.slice(0,-1)),s.at(-1)===""&&(s=s.slice(0,-1)),r.length>s.length)return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};if(r.length<s.length&&r.at(-1)!=="*")return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};let o={},i="",a="";for(let l=0;l<r.length;++l){const c=r[l],d=[...s[l].matchAll(/([?#]?)((?:(?![?#]).)*)/g)],f=d?.find(p=>p[1]==="")?.[2]??"";if(i=d?.find(p=>p[1]==="?")?.[2]??"",a=d?.find(p=>p[1]==="#")?.[2]??"",c.startsWith(":")&&f&&f!==""){o[c.substring(1)]=f;continue}if(c==="*"){const x=[...s.slice(l).join("/").matchAll(/([?#]?)((?:(?![?#]).)*)/g)];return{isMatch:!0,data:o,remainer:x.find(h=>h[1]==="")?.[2]??"",query:x.find(h=>h[1]==="?")?.[2]??"",hash:x.find(h=>h[1]==="#")?.[2]??"",path:s.slice(0,l).join("/")}}if(c!==f)return{isMatch:!1,data:{},remainer:"",query:"",hash:"",path:""}}return{isMatch:!0,remainer:"",data:o,query:i,hash:a,path:t?.split("?")?.[0]??""}},Va=`
|
|
15
15
|
query dbSchema {
|
|
16
16
|
_dbSchema {
|
|
17
17
|
dbName
|
|
@@ -32,11 +32,14 @@ query dbSchema {
|
|
|
32
32
|
isIdentity
|
|
33
33
|
isNullable
|
|
34
34
|
isReadOnly
|
|
35
|
+
isLargeValue
|
|
35
36
|
maxLength
|
|
36
37
|
minLength
|
|
37
38
|
min
|
|
38
39
|
max
|
|
39
40
|
step
|
|
41
|
+
precision
|
|
42
|
+
scale
|
|
40
43
|
pattern
|
|
41
44
|
patternMessage
|
|
42
45
|
inputType
|
|
@@ -73,29 +76,47 @@ query dbSchema {
|
|
|
73
76
|
targetColumnNames
|
|
74
77
|
hasPayload
|
|
75
78
|
}
|
|
79
|
+
indexes {
|
|
80
|
+
name
|
|
81
|
+
isUnique
|
|
82
|
+
isClustered
|
|
83
|
+
isPrimaryKey
|
|
84
|
+
columns
|
|
85
|
+
}
|
|
76
86
|
}
|
|
77
|
-
}`;class xo extends Error{constructor(n,r){super(n.map(s=>s.message).join("; ")),this.errors=n,this.data=r,this.name="GraphQLRequestError"}errors;data}class Zn{constructor(n){this.uri=n}uri;async query(n,r){const s=await fetch(this.uri,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:n,variables:r})});if(!s.ok)throw new Error(`GraphQL request failed: ${s.status} ${s.statusText}`);const o=await s.json();if(o.errors?.length)throw new xo(o.errors,o.data);return o.data}}const er=f.createContext(null),go=er.Provider;function ve(){const e=f.useContext(er);if(!e)throw new Error("useFetcher must be used within a FetcherProvider");return e}function bo(e){const n=e.lastIndexOf(".");return n>=0?e.slice(n+1):e}function yo(e){return bo(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[_\-\s]+/).filter(Boolean)}function vo(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function It(e){return e&&yo(e).map(vo).join(" ")}const tr=f.createContext({loading:!0,error:null,data:[],findTable:()=>{}}),jo=({children:e})=>{const n=No();return t.jsx(tr.Provider,{value:n,children:e})};function je(){return f.useContext(tr)}function No(){const e=ve(),{isLoading:n,error:r,data:s}=le.useQuery({queryKey:["dbSchema"],queryFn:()=>e.query(ho),staleTime:1/0});return f.useMemo(()=>{if(n)return{loading:!0,error:null,data:[],findTable:()=>{}};if(r)return{loading:!1,error:{message:r.message},data:[],findTable:()=>{}};if(!s)return{loading:!1,error:null,data:[],findTable:()=>{}};const o=s._dbSchema.map(a=>({...a,name:a.graphQlName,label:It(a.dbName),metadata:nr(a.metadata),columns:a.columns.map(l=>({...l,name:l.graphQlName,label:It(l.dbName),metadata:nr(l.metadata),inputType:To(l.inputType)}))}));return{loading:!1,error:null,data:o,findTable:a=>o.find(l=>l.graphQlName===a)}},[n,r,s])}function nr(e){return e.reduce((n,r)=>({...n,[r.key]:Co(r)}),{})}function Co({key:e,value:n}){return e==="type"?wo(n):n}function wo(e){const n=e.match(/lookup\s*\(\s*(?<id>\w+)\s*,\s*(?<label>\w+)\s*\)/m);if(n?.groups?.id&&n?.groups?.label)return{type:"lookup",id:n.groups.id,label:n.groups.label}}const ko=["text","email","url","tel","date","datetime-local","number","password","search"];function To(e){if(e&&ko.includes(e))return e}function rr(e){var n,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(n=0;n<o;n++)e[n]&&(r=rr(e[n]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function sr(){for(var e,n,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(n=rr(e))&&(s&&(s+=" "),s+=n);return s}const or=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,ar=sr,ir=(e,n)=>r=>{var s;if(n?.variants==null)return ar(e,r?.class,r?.className);const{variants:o,defaultVariants:i}=n,a=Object.keys(o).map(m=>{const p=r?.[m],d=i?.[m];if(p===null)return null;const h=or(p)||or(d);return o[m][h]}),l=r&&Object.entries(r).reduce((m,p)=>{let[d,h]=p;return h===void 0||(m[d]=h),m},{}),c=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((m,p)=>{let{class:d,className:h,...y}=p;return Object.entries(y).every(g=>{let[b,N]=g;return Array.isArray(N)?N.includes({...i,...l}[b]):{...i,...l}[b]===N})?[...m,d,h]:m},[]);return ar(e,a,c,r?.class,r?.className)},So=(e,n)=>{const r=new Array(e.length+n.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<n.length;s++)r[e.length+s]=n[s];return r},Fo=(e,n)=>({classGroupId:e,validator:n}),lr=(e=new Map,n=null,r)=>({nextPart:e,validators:n,classGroupId:r}),Mt="-",cr=[],$o="arbitrary..",_o=e=>{const n=Po(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return zo(a);const l=a.split(Mt),c=l[0]===""&&l.length>1?1:0;return dr(l,c,n)},getConflictingClassGroupIds:(a,l)=>{if(l){const c=s[a],m=r[a];return c?m?So(m,c):c:m||cr}return r[a]||cr}}},dr=(e,n,r)=>{if(e.length-n===0)return r.classGroupId;const o=e[n],i=r.nextPart.get(o);if(i){const m=dr(e,n+1,i);if(m)return m}const a=r.validators;if(a===null)return;const l=n===0?e.join(Mt):e.slice(n).join(Mt),c=a.length;for(let m=0;m<c;m++){const p=a[m];if(p.validator(l))return p.classGroupId}},zo=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const n=e.slice(1,-1),r=n.indexOf(":"),s=n.slice(0,r);return s?$o+s:void 0})(),Po=e=>{const{theme:n,classGroups:r}=e;return Eo(r,n)},Eo=(e,n)=>{const r=lr();for(const s in e){const o=e[s];ln(o,r,s,n)}return r},ln=(e,n,r,s)=>{const o=e.length;for(let i=0;i<o;i++){const a=e[i];Do(a,n,r,s)}},Do=(e,n,r,s)=>{if(typeof e=="string"){Io(e,n,r);return}if(typeof e=="function"){Mo(e,n,r,s);return}Lo(e,n,r,s)},Io=(e,n,r)=>{const s=e===""?n:ur(n,e);s.classGroupId=r},Mo=(e,n,r,s)=>{if(Oo(e)){ln(e(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(Fo(r,e))},Lo=(e,n,r,s)=>{const o=Object.entries(e),i=o.length;for(let a=0;a<i;a++){const[l,c]=o[a];ln(c,ur(n,l),r,s)}},ur=(e,n)=>{let r=e;const s=n.split(Mt),o=s.length;for(let i=0;i<o;i++){const a=s[i];let l=r.nextPart.get(a);l||(l=lr(),r.nextPart.set(a,l)),r=l}return r},Oo=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Ao=e=>{if(e<1)return{get:()=>{},set:()=>{}};let n=0,r=Object.create(null),s=Object.create(null);const o=(i,a)=>{r[i]=a,n++,n>e&&(n=0,s=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=s[i])!==void 0)return o(i,a),a},set(i,a){i in r?r[i]=a:o(i,a)}}},cn="!",mr=":",qo=[],fr=(e,n,r,s,o)=>({modifiers:e,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),Vo=e=>{const{prefix:n,experimentalParseClassName:r}=e;let s=o=>{const i=[];let a=0,l=0,c=0,m;const p=o.length;for(let b=0;b<p;b++){const N=o[b];if(a===0&&l===0){if(N===mr){i.push(o.slice(c,b)),c=b+1;continue}if(N==="/"){m=b;continue}}N==="["?a++:N==="]"?a--:N==="("?l++:N===")"&&l--}const d=i.length===0?o:o.slice(c);let h=d,y=!1;d.endsWith(cn)?(h=d.slice(0,-1),y=!0):d.startsWith(cn)&&(h=d.slice(1),y=!0);const g=m&&m>c?m-c:void 0;return fr(i,y,h,g)};if(n){const o=n+mr,i=s;s=a=>a.startsWith(o)?i(a.slice(o.length)):fr(qo,!1,a,void 0,!0)}if(r){const o=s;s=i=>r({className:i,parseClassName:o})}return s},Bo=e=>{const n=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{n.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",c=n.has(a);l||c?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(a)):o.push(a)}return o.length>0&&(o.sort(),s.push(...o)),s}},Go=e=>({cache:Ao(e.cacheSize),parseClassName:Vo(e),sortModifiers:Bo(e),postfixLookupClassGroupIds:Ko(e),..._o(e)}),Ko=e=>{const n=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let s=0;s<r.length;s++)n[r[s]]=!0;return n},Wo=/\s+/,Jo=(e,n)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:i,postfixLookupClassGroupIds:a}=n,l=[],c=e.trim().split(Wo);let m="";for(let p=c.length-1;p>=0;p-=1){const d=c[p],{isExternal:h,modifiers:y,hasImportantModifier:g,baseClassName:b,maybePostfixModifierPosition:N}=r(d);if(h){m=d+(m.length>0?" "+m:m);continue}let T=!!N,j;if(T){const L=b.substring(0,N);j=s(L);const x=j&&a[j]?s(b):void 0;x&&x!==j&&(j=x,T=!1)}else j=s(b);if(!j){if(!T){m=d+(m.length>0?" "+m:m);continue}if(j=s(b),!j){m=d+(m.length>0?" "+m:m);continue}T=!1}const $=y.length===0?"":y.length===1?y[0]:i(y).join(":"),S=g?$+cn:$,D=S+j;if(l.indexOf(D)>-1)continue;l.push(D);const w=o(j,T);for(let L=0;L<w.length;++L){const x=w[L];l.push(S+x)}m=d+(m.length>0?" "+m:m)}return m},Ho=(...e)=>{let n=0,r,s,o="";for(;n<e.length;)(r=e[n++])&&(s=pr(r))&&(o&&(o+=" "),o+=s);return o},pr=e=>{if(typeof e=="string")return e;let n,r="";for(let s=0;s<e.length;s++)e[s]&&(n=pr(e[s]))&&(r&&(r+=" "),r+=n);return r},Qo=(e,...n)=>{let r,s,o,i;const a=c=>{const m=n.reduce((p,d)=>d(p),e());return r=Go(m),s=r.cache.get,o=r.cache.set,i=l,l(c)},l=c=>{const m=s(c);if(m)return m;const p=Jo(c,r);return o(c,p),p};return i=a,(...c)=>i(Ho(...c))},Ro=[],ce=e=>{const n=r=>r[e]||Ro;return n.isThemeGetter=!0,n},hr=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,xr=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Yo=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Xo=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Uo=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Zo=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ea=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ta=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Le=e=>Yo.test(e),R=e=>!!e&&!Number.isNaN(Number(e)),$e=e=>!!e&&Number.isInteger(Number(e)),dn=e=>e.endsWith("%")&&R(e.slice(0,-1)),De=e=>Xo.test(e),gr=()=>!0,na=e=>Uo.test(e)&&!Zo.test(e),un=()=>!1,ra=e=>ea.test(e),sa=e=>ta.test(e),oa=e=>!z(e)&&!P(e),aa=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),ia=e=>Oe(e,Cr,un),z=e=>hr.test(e),Be=e=>Oe(e,wr,na),br=e=>Oe(e,ha,R),la=e=>Oe(e,Tr,gr),ca=e=>Oe(e,kr,un),yr=e=>Oe(e,jr,un),da=e=>Oe(e,Nr,sa),Lt=e=>Oe(e,Sr,ra),P=e=>xr.test(e),ut=e=>Ge(e,wr),ua=e=>Ge(e,kr),vr=e=>Ge(e,jr),ma=e=>Ge(e,Cr),fa=e=>Ge(e,Nr),Ot=e=>Ge(e,Sr,!0),pa=e=>Ge(e,Tr,!0),Oe=(e,n,r)=>{const s=hr.exec(e);return s?s[1]?n(s[1]):r(s[2]):!1},Ge=(e,n,r=!1)=>{const s=xr.exec(e);return s?s[1]?n(s[1]):r:!1},jr=e=>e==="position"||e==="percentage",Nr=e=>e==="image"||e==="url",Cr=e=>e==="length"||e==="size"||e==="bg-size",wr=e=>e==="length",ha=e=>e==="number",kr=e=>e==="family-name",Tr=e=>e==="number"||e==="weight",Sr=e=>e==="shadow",xa=Qo(()=>{const e=ce("color"),n=ce("font"),r=ce("text"),s=ce("font-weight"),o=ce("tracking"),i=ce("leading"),a=ce("breakpoint"),l=ce("container"),c=ce("spacing"),m=ce("radius"),p=ce("shadow"),d=ce("inset-shadow"),h=ce("text-shadow"),y=ce("drop-shadow"),g=ce("blur"),b=ce("perspective"),N=ce("aspect"),T=ce("ease"),j=ce("animate"),$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],S=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],D=()=>[...S(),P,z],w=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto","contain","none"],x=()=>[P,z,c],k=()=>[Le,"full","auto",...x()],V=()=>[$e,"none","subgrid",P,z],I=()=>["auto",{span:["full",$e,P,z]},$e,P,z],A=()=>[$e,"auto",P,z],W=()=>["auto","min","max","fr",P,z],H=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...x()],Y=()=>[Le,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...x()],se=()=>[Le,"screen","full","dvw","lvw","svw","min","max","fit",...x()],ue=()=>[Le,"screen","full","lh","dvh","lvh","svh","min","max","fit",...x()],M=()=>[e,P,z],we=()=>[...S(),vr,yr,{position:[P,z]}],ke=()=>["no-repeat",{repeat:["","x","y","space","round"]}],ye=()=>["auto","cover","contain",ma,ia,{size:[P,z]}],me=()=>[dn,ut,Be],O=()=>["","none","full",m,P,z],Q=()=>["",R,ut,Be],oe=()=>["solid","dashed","dotted","double"],ge=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[R,dn,vr,yr],Ie=()=>["","none",g,P,z],Me=()=>["none",R,P,z],Se=()=>["none",R,P,z],Fe=()=>[R,P,z],de=()=>[Le,"full",...x()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[De],breakpoint:[De],color:[gr],container:[De],"drop-shadow":[De],ease:["in","out","in-out"],font:[oa],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[De],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[De],shadow:[De],spacing:["px",R],text:[De],"text-shadow":[De],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Le,z,P,N]}],container:["container"],"container-type":[{"@container":["","normal","size",P,z]}],"container-named":[aa],columns:[{columns:[R,z,P,l]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:D()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:L()}],"overscroll-x":[{"overscroll-x":L()}],"overscroll-y":[{"overscroll-y":L()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:k()}],"inset-x":[{"inset-x":k()}],"inset-y":[{"inset-y":k()}],start:[{"inset-s":k(),start:k()}],end:[{"inset-e":k(),end:k()}],"inset-bs":[{"inset-bs":k()}],"inset-be":[{"inset-be":k()}],top:[{top:k()}],right:[{right:k()}],bottom:[{bottom:k()}],left:[{left:k()}],visibility:["visible","invisible","collapse"],z:[{z:[$e,"auto",P,z]}],basis:[{basis:[Le,"full","auto",l,...x()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[R,Le,"auto","initial","none",z]}],grow:[{grow:["",R,P,z]}],shrink:[{shrink:["",R,P,z]}],order:[{order:[$e,"first","last","none",P,z]}],"grid-cols":[{"grid-cols":V()}],"col-start-end":[{col:I()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":V()}],"row-start-end":[{row:I()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:x()}],"gap-x":[{"gap-x":x()}],"gap-y":[{"gap-y":x()}],"justify-content":[{justify:[...H(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...H()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":H()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:x()}],px:[{px:x()}],py:[{py:x()}],ps:[{ps:x()}],pe:[{pe:x()}],pbs:[{pbs:x()}],pbe:[{pbe:x()}],pt:[{pt:x()}],pr:[{pr:x()}],pb:[{pb:x()}],pl:[{pl:x()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":x()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":x()}],"space-y-reverse":["space-y-reverse"],size:[{size:Y()}],"inline-size":[{inline:["auto",...se()]}],"min-inline-size":[{"min-inline":["auto",...se()]}],"max-inline-size":[{"max-inline":["none",...se()]}],"block-size":[{block:["auto",...ue()]}],"min-block-size":[{"min-block":["auto",...ue()]}],"max-block-size":[{"max-block":["none",...ue()]}],w:[{w:[l,"screen",...Y()]}],"min-w":[{"min-w":[l,"screen","none",...Y()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...Y()]}],h:[{h:["screen","lh",...Y()]}],"min-h":[{"min-h":["screen","lh","none",...Y()]}],"max-h":[{"max-h":["screen","lh",...Y()]}],"font-size":[{text:["base",r,ut,Be]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,pa,la]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",dn,z]}],"font-family":[{font:[ua,ca,n]}],"font-features":[{"font-features":[z]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,P,z]}],"line-clamp":[{"line-clamp":[R,"none",P,br]}],leading:[{leading:[i,...x()]}],"list-image":[{"list-image":["none",P,z]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",P,z]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:M()}],"text-color":[{text:M()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...oe(),"wavy"]}],"text-decoration-thickness":[{decoration:[R,"from-font","auto",P,Be]}],"text-decoration-color":[{decoration:M()}],"underline-offset":[{"underline-offset":[R,"auto",P,z]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:x()}],"tab-size":[{tab:[$e,P,z]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",P,z]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",P,z]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:we()}],"bg-repeat":[{bg:ke()}],"bg-size":[{bg:ye()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},$e,P,z],radial:["",P,z],conic:[$e,P,z]},fa,da]}],"bg-color":[{bg:M()}],"gradient-from-pos":[{from:me()}],"gradient-via-pos":[{via:me()}],"gradient-to-pos":[{to:me()}],"gradient-from":[{from:M()}],"gradient-via":[{via:M()}],"gradient-to":[{to:M()}],rounded:[{rounded:O()}],"rounded-s":[{"rounded-s":O()}],"rounded-e":[{"rounded-e":O()}],"rounded-t":[{"rounded-t":O()}],"rounded-r":[{"rounded-r":O()}],"rounded-b":[{"rounded-b":O()}],"rounded-l":[{"rounded-l":O()}],"rounded-ss":[{"rounded-ss":O()}],"rounded-se":[{"rounded-se":O()}],"rounded-ee":[{"rounded-ee":O()}],"rounded-es":[{"rounded-es":O()}],"rounded-tl":[{"rounded-tl":O()}],"rounded-tr":[{"rounded-tr":O()}],"rounded-br":[{"rounded-br":O()}],"rounded-bl":[{"rounded-bl":O()}],"border-w":[{border:Q()}],"border-w-x":[{"border-x":Q()}],"border-w-y":[{"border-y":Q()}],"border-w-s":[{"border-s":Q()}],"border-w-e":[{"border-e":Q()}],"border-w-bs":[{"border-bs":Q()}],"border-w-be":[{"border-be":Q()}],"border-w-t":[{"border-t":Q()}],"border-w-r":[{"border-r":Q()}],"border-w-b":[{"border-b":Q()}],"border-w-l":[{"border-l":Q()}],"divide-x":[{"divide-x":Q()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Q()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...oe(),"hidden","none"]}],"divide-style":[{divide:[...oe(),"hidden","none"]}],"border-color":[{border:M()}],"border-color-x":[{"border-x":M()}],"border-color-y":[{"border-y":M()}],"border-color-s":[{"border-s":M()}],"border-color-e":[{"border-e":M()}],"border-color-bs":[{"border-bs":M()}],"border-color-be":[{"border-be":M()}],"border-color-t":[{"border-t":M()}],"border-color-r":[{"border-r":M()}],"border-color-b":[{"border-b":M()}],"border-color-l":[{"border-l":M()}],"divide-color":[{divide:M()}],"outline-style":[{outline:[...oe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[R,P,z]}],"outline-w":[{outline:["",R,ut,Be]}],"outline-color":[{outline:M()}],shadow:[{shadow:["","none",p,Ot,Lt]}],"shadow-color":[{shadow:M()}],"inset-shadow":[{"inset-shadow":["none",d,Ot,Lt]}],"inset-shadow-color":[{"inset-shadow":M()}],"ring-w":[{ring:Q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:M()}],"ring-offset-w":[{"ring-offset":[R,Be]}],"ring-offset-color":[{"ring-offset":M()}],"inset-ring-w":[{"inset-ring":Q()}],"inset-ring-color":[{"inset-ring":M()}],"text-shadow":[{"text-shadow":["none",h,Ot,Lt]}],"text-shadow-color":[{"text-shadow":M()}],opacity:[{opacity:[R,P,z]}],"mix-blend":[{"mix-blend":[...ge(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ge()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[R]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":M()}],"mask-image-linear-to-color":[{"mask-linear-to":M()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":M()}],"mask-image-t-to-color":[{"mask-t-to":M()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":M()}],"mask-image-r-to-color":[{"mask-r-to":M()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":M()}],"mask-image-b-to-color":[{"mask-b-to":M()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":M()}],"mask-image-l-to-color":[{"mask-l-to":M()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":M()}],"mask-image-x-to-color":[{"mask-x-to":M()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":M()}],"mask-image-y-to-color":[{"mask-y-to":M()}],"mask-image-radial":[{"mask-radial":[P,z]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":M()}],"mask-image-radial-to-color":[{"mask-radial-to":M()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":S()}],"mask-image-conic-pos":[{"mask-conic":[R]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":M()}],"mask-image-conic-to-color":[{"mask-conic-to":M()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:we()}],"mask-repeat":[{mask:ke()}],"mask-size":[{mask:ye()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",P,z]}],filter:[{filter:["","none",P,z]}],blur:[{blur:Ie()}],brightness:[{brightness:[R,P,z]}],contrast:[{contrast:[R,P,z]}],"drop-shadow":[{"drop-shadow":["","none",y,Ot,Lt]}],"drop-shadow-color":[{"drop-shadow":M()}],grayscale:[{grayscale:["",R,P,z]}],"hue-rotate":[{"hue-rotate":[R,P,z]}],invert:[{invert:["",R,P,z]}],saturate:[{saturate:[R,P,z]}],sepia:[{sepia:["",R,P,z]}],"backdrop-filter":[{"backdrop-filter":["","none",P,z]}],"backdrop-blur":[{"backdrop-blur":Ie()}],"backdrop-brightness":[{"backdrop-brightness":[R,P,z]}],"backdrop-contrast":[{"backdrop-contrast":[R,P,z]}],"backdrop-grayscale":[{"backdrop-grayscale":["",R,P,z]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[R,P,z]}],"backdrop-invert":[{"backdrop-invert":["",R,P,z]}],"backdrop-opacity":[{"backdrop-opacity":[R,P,z]}],"backdrop-saturate":[{"backdrop-saturate":[R,P,z]}],"backdrop-sepia":[{"backdrop-sepia":["",R,P,z]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":x()}],"border-spacing-x":[{"border-spacing-x":x()}],"border-spacing-y":[{"border-spacing-y":x()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",P,z]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[R,"initial",P,z]}],ease:[{ease:["linear","initial",T,P,z]}],delay:[{delay:[R,P,z]}],animate:[{animate:["none",j,P,z]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[b,P,z]}],"perspective-origin":[{"perspective-origin":D()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:Se()}],"scale-x":[{"scale-x":Se()}],"scale-y":[{"scale-y":Se()}],"scale-z":[{"scale-z":Se()}],"scale-3d":["scale-3d"],skew:[{skew:Fe()}],"skew-x":[{"skew-x":Fe()}],"skew-y":[{"skew-y":Fe()}],transform:[{transform:[P,z,"","none","gpu","cpu"]}],"transform-origin":[{origin:D()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:de()}],"translate-x":[{"translate-x":de()}],"translate-y":[{"translate-y":de()}],"translate-z":[{"translate-z":de()}],"translate-none":["translate-none"],zoom:[{zoom:[$e,P,z]}],accent:[{accent:M()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:M()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",P,z]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":M()}],"scrollbar-track-color":[{"scrollbar-track":M()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":x()}],"scroll-mx":[{"scroll-mx":x()}],"scroll-my":[{"scroll-my":x()}],"scroll-ms":[{"scroll-ms":x()}],"scroll-me":[{"scroll-me":x()}],"scroll-mbs":[{"scroll-mbs":x()}],"scroll-mbe":[{"scroll-mbe":x()}],"scroll-mt":[{"scroll-mt":x()}],"scroll-mr":[{"scroll-mr":x()}],"scroll-mb":[{"scroll-mb":x()}],"scroll-ml":[{"scroll-ml":x()}],"scroll-p":[{"scroll-p":x()}],"scroll-px":[{"scroll-px":x()}],"scroll-py":[{"scroll-py":x()}],"scroll-ps":[{"scroll-ps":x()}],"scroll-pe":[{"scroll-pe":x()}],"scroll-pbs":[{"scroll-pbs":x()}],"scroll-pbe":[{"scroll-pbe":x()}],"scroll-pt":[{"scroll-pt":x()}],"scroll-pr":[{"scroll-pr":x()}],"scroll-pb":[{"scroll-pb":x()}],"scroll-pl":[{"scroll-pl":x()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",P,z]}],fill:[{fill:["none",...M()]}],"stroke-w":[{stroke:[R,ut,Be,br]}],stroke:[{stroke:["none",...M()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function K(...e){return xa(sr(e))}const ga=ir("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function mt({className:e,variant:n,...r}){return t.jsx("div",{"data-slot":"alert",role:"alert",className:K(ga({variant:n}),e),...r})}function Fr({className:e,...n}){return t.jsx("div",{"data-slot":"alert-title",className:K("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...n})}function ft({className:e,...n}){return t.jsx("div",{"data-slot":"alert-description",className:K("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",e),...n})}const Ne=pe.forwardRef(({className:e,type:n,...r},s)=>t.jsx("input",{type:n,ref:s,"data-slot":"input",className:K("h-9 w-full min-w-0 rounded-md border border-input bg-transparent text-foreground px-3 py-0 text-sm shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...r}));Ne.displayName="Input";function ba(e){return e.length===0?null:`query GetTableRowCounts { ${e.map(r=>`${r}: ${r}(limit: 1) { total }`).join(" ")} }`}function ya(e=!0){const{data:n,loading:r,error:s}=je(),o=ve(),i=f.useMemo(()=>n.map(d=>d.name),[n]),a=f.useMemo(()=>ba(i),[i]),{data:l,isLoading:c,error:m}=le.useQuery({queryKey:["tableRowCounts",i],queryFn:()=>o.query(a),enabled:e&&!!a&&i.length>0,staleTime:300*1e3});return{stats:f.useMemo(()=>{const d={};for(const h of n){const g=l?.[h.name]?.total??null;d[h.name]={columnCount:h.columns.length,rowCount:g,fkCount:h.singleJoins.length,isLoading:c,error:m?m.message:null}}return d},[n,l,c,m]),isLoading:r||c,error:s}}function va(e){if(e===null)return"—";if(e===0)return"0";if(e<1e3)return e.toString();if(e<1e6){const r=e/1e3;return r%1===0?`${r.toFixed(0)}k`:`${r.toFixed(1)}k`}const n=e/1e6;return n%1===0?`${n.toFixed(0)}M`:`${n.toFixed(1)}M`}const ja={showStats:!1},$r=f.createContext(ja);function Na({config:e,children:n}){return t.jsx($r.Provider,{value:e,children:n})}function Ca(){return f.useContext($r)}const At=50;function wa(e,n){return e===null||n<=0?0:Math.max(2,Math.min(100,Math.round(e/n*100)))}function ka({percent:e,label:n}){return t.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",role:"img","aria-label":n,title:n,children:t.jsx("span",{className:"block h-full rounded-full bg-emerald-500/70 dark:bg-emerald-400/70",style:{width:`${e}%`}})})}function mn({count:e}){return e<=0?null:t.jsxs("span",{className:"shrink-0 rounded px-1 py-px text-[0.85em] tabular-nums bg-blue-100 text-blue-700 dark:bg-blue-900/60 dark:text-blue-300",children:[e," FK"]})}function Ta({stats:e,maxRowCount:n}){const r=wa(e.rowCount,n),s="flex items-center gap-1.5 text-xs leading-none min-w-0";return e.isLoading?t.jsxs("div",{className:`${s} text-muted-foreground`,children:[t.jsxs("span",{className:"tabular-nums shrink-0",children:[e.columnCount,"c"]}),t.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",children:t.jsx("span",{className:"block h-full w-1/3 rounded-full bg-muted-foreground/30 animate-pulse"})}),t.jsx(v.Loader2,{className:"size-[1em] shrink-0 animate-spin"}),t.jsx(mn,{count:e.fkCount})]}):e.error?t.jsxs("div",{className:s,children:[t.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground",children:[e.columnCount,"c"]}),t.jsx("span",{className:"flex-1 text-destructive truncate",title:e.error,children:"err"}),t.jsx(mn,{count:e.fkCount})]}):t.jsxs("div",{className:s,children:[t.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground/70",children:[e.columnCount,"c"]}),t.jsx(ka,{percent:r,label:`${e.rowCount?.toLocaleString()??"unknown"} rows`}),t.jsx("span",{className:"tabular-nums shrink-0 text-right text-muted-foreground",children:va(e.rowCount)}),t.jsx(mn,{count:e.fkCount})]})}function Sa({table:e,stats:n,maxRowCount:r,showStats:s,active:o}){return t.jsx(dt,{to:`/${e.name}`,"aria-current":o?"page":void 0,className:`plain-link block no-underline py-1.5 px-2 text-sm font-medium border-l-2 ${o?"bg-accent text-accent-foreground border-primary":"text-foreground border-transparent hover:bg-muted/50 hover:text-primary"}`,children:t.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[t.jsx("span",{className:"truncate",title:e.label,children:e.label}),s&&t.jsx(Ta,{stats:n,maxRowCount:r})]})})}function fn(e){const n=e.dbName.lastIndexOf(".");return n>0?e.dbName.slice(0,n):null}function _r({schema:e,count:n,collapsed:r,context:s,onToggle:o}){const i=r?v.ChevronRight:v.ChevronDown,a=t.jsxs(t.Fragment,{children:[t.jsx(i,{className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"truncate font-semibold",title:e,children:e}),t.jsx("span",{className:"ml-auto shrink-0 tabular-nums text-[0.85em] text-muted-foreground",children:n})]}),l="flex items-center gap-1.5 w-full px-2 py-1 text-xs uppercase tracking-wide text-muted-foreground bg-muted/40 border-y border-border sticky top-0 z-10";return s?t.jsx("div",{className:l,"aria-hidden":"true",children:a}):t.jsx("button",{type:"button",onClick:o,"aria-expanded":!r,className:`${l} hover:bg-muted/70 text-left`,children:a})}function Fa(){const{showStats:e}=Ca(),{loading:n,error:r,data:s}=je(),{stats:o,isLoading:i}=ya(e),[a,l]=f.useState(""),[c,m]=f.useState(new Set),[p,d]=f.useState(0),h=Rn(),y=decodeURIComponent(h.split("/")[1]??""),g=f.useMemo(()=>{const I=Object.values(o).map(A=>A.rowCount).filter(A=>A!==null);return I.length>0?Math.max(...I):0},[o]),b=a.trim().length>0,N=f.useMemo(()=>{const I=a.trim().toLowerCase();return I?s.filter(A=>{const W=fn(A);return A.label.toLowerCase().includes(I)||A.dbName.toLowerCase().includes(I)||(W?.toLowerCase().includes(I)??!1)}):s},[s,a]),{schemas:T,grouped:j,multiSchema:$}=f.useMemo(()=>{const I=new Map;for(const W of N){const H=fn(W),U=I.get(H)??[];U.push(W),I.set(H,U)}const A=[...I.keys()].filter(W=>W!==null).sort((W,H)=>W.localeCompare(H));return{schemas:A,grouped:I,multiSchema:A.length>1}},[N]),S=f.useMemo(()=>{const I=[];if($){const A=[...T,...j.has(null)?[null]:[]];for(const W of A){const H=j.get(W===void 0?null:W)??[],U=!b&&c.has(W);if(I.push({kind:"group",schema:W??"(no schema)",count:H.length,collapsed:U}),!U)for(const E of H)I.push({kind:"table",schema:W,table:E})}}else for(const A of N)I.push({kind:"table",schema:fn(A),table:A});return I},[$,T,j,N,c,b]);f.useEffect(()=>{d(0)},[a]);const D=Math.max(1,Math.ceil(S.length/At)),w=Math.min(p,D-1),L=w*At,x=S.slice(L,L+At),k=$&&x[0]?.kind==="table"&&x[0].schema?x[0].schema:null,V=I=>m(A=>{const W=new Set(A);return W.has(I)?W.delete(I):W.add(I),W});return n?t.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[t.jsx(v.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?t.jsx(mt,{variant:"destructive",className:"m-2",children:t.jsxs(ft,{children:["Error: ",r.message]})}):s.length===0?t.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{className:"font-medium",children:"No tables found"}),t.jsx("p",{className:"mt-1",children:"The database may be empty or the connection may have failed."})]}):t.jsxs("div",{className:"@container min-w-0 flex flex-col h-full",children:[t.jsxs("div",{className:"sticky top-0 z-20 bg-background p-2 border-b border-border",children:[t.jsxs("div",{className:"relative",children:[t.jsx(v.Search,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none"}),t.jsx(Ne,{type:"search",value:a,onChange:I=>l(I.target.value),placeholder:"Search tables...","aria-label":"Search tables",className:"pl-8 pr-8 h-8 text-sm"}),b&&t.jsx("button",{type:"button",onClick:()=>l(""),"aria-label":"Clear search",className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted",children:t.jsx(v.X,{className:"size-4"})})]}),b&&t.jsxs("p",{className:"mt-1 px-0.5 text-xs text-muted-foreground",children:[N.length," match",N.length!==1?"es":""]})]}),t.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:S.length===0?t.jsxs("p",{className:"p-4 text-center text-sm text-muted-foreground",children:["No tables match “",a,"”."]}):t.jsxs(t.Fragment,{children:[k&&t.jsx(_r,{schema:k,count:j.get(k)?.length??0,collapsed:!1,context:!0}),x.map(I=>I.kind==="group"?t.jsx(_r,{schema:I.schema,count:I.count,collapsed:I.collapsed,onToggle:()=>V(I.schema)},`g:${I.schema}`):t.jsx(Sa,{table:I.table,stats:o[I.table.name]??{columnCount:I.table.columns.length,rowCount:null,fkCount:I.table.singleJoins.length,isLoading:i,error:null},maxRowCount:g,showStats:e,active:I.table.name===y},`t:${I.table.name}`))]})}),D>1&&t.jsxs("div",{className:"sticky bottom-0 z-20 bg-background border-t border-border flex items-center justify-between gap-2 px-2 py-1.5",children:[t.jsx("button",{type:"button",onClick:()=>d(I=>Math.max(0,I-1)),disabled:w===0,"aria-label":"Previous page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:t.jsx(v.ChevronLeft,{className:"size-4"})}),t.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[L+1,"–",Math.min(L+At,S.length)," of ",S.length]}),t.jsx("button",{type:"button",onClick:()=>d(I=>Math.min(D-1,I+1)),disabled:w>=D-1,"aria-label":"Next page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:t.jsx(v.ChevronRight,{className:"size-4"})})]})]})}const $a=ir("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),q=pe.forwardRef(({className:e,variant:n,size:r,asChild:s=!1,...o},i)=>{const a=s?Ps.Slot:"button";return t.jsx(a,{className:K($a({variant:n,size:r,className:e})),ref:i,...o})});q.displayName="Button";function zr({...e}){return t.jsx(G.DropdownMenu.Root,{"data-slot":"dropdown-menu",...e})}function Pr({...e}){return t.jsx(G.DropdownMenu.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function Er({className:e,sideOffset:n=4,...r}){return t.jsx(G.DropdownMenu.Portal,{children:t.jsx(G.DropdownMenu.Content,{"data-slot":"dropdown-menu-content",sideOffset:n,className:K("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...r})})}function pt({className:e,inset:n,variant:r="default",...s}){return t.jsx(G.DropdownMenu.Item,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":r,className:K("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...s})}function _a({className:e,children:n,checked:r,...s}){return t.jsxs(G.DropdownMenu.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:K("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:r,...s,children:[t.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:t.jsx(G.DropdownMenu.ItemIndicator,{children:t.jsx(v.CheckIcon,{className:"size-4"})})}),n]})}function Ke({className:e,...n}){return t.jsx(G.DropdownMenu.Separator,{"data-slot":"dropdown-menu-separator",className:K("-mx-1 my-1 h-px bg-border",e),...n})}function ht({...e}){return t.jsx(G.DropdownMenu.Sub,{"data-slot":"dropdown-menu-sub",...e})}function xt({className:e,inset:n,children:r,...s}){return t.jsxs(G.DropdownMenu.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":n,className:K("flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,t.jsx(v.ChevronRightIcon,{className:"ml-auto size-4"})]})}function gt({className:e,...n}){return t.jsx(G.DropdownMenu.SubContent,{"data-slot":"dropdown-menu-sub-content",className:K("z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...n})}const bt=pe.forwardRef(({...e},n)=>t.jsx(G.HoverCard.Root,{"data-slot":"hover-card",...e}));bt.displayName="HoverCard";const yt=pe.forwardRef(({...e},n)=>t.jsx(G.HoverCard.Trigger,{"data-slot":"hover-card-trigger",...e}));yt.displayName="HoverCardTrigger";const vt=pe.forwardRef(({className:e,align:n="center",sideOffset:r=4,...s},o)=>t.jsx(G.HoverCard.Portal,{children:t.jsx(G.HoverCard.Content,{ref:o,"data-slot":"hover-card-content",align:n,sideOffset:r,className:K("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));vt.displayName="HoverCardContent";function _e({...e}){return t.jsx(G.Select.Root,{"data-slot":"select",...e})}function ze({...e}){return t.jsx(G.Select.Value,{"data-slot":"select-value",...e})}function Pe({className:e,size:n="default",children:r,...s}){return t.jsxs(G.Select.Trigger,{"data-slot":"select-trigger","data-size":n,className:K("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,t.jsx(G.Select.Icon,{asChild:!0,children:t.jsx(v.ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function Ee({className:e,children:n,position:r="item-aligned",align:s="center",...o}){return t.jsx(G.Select.Portal,{children:t.jsxs(G.Select.Content,{"data-slot":"select-content",className:K("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,align:s,...o,children:[t.jsx(za,{}),t.jsx(G.Select.Viewport,{className:K("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:n}),t.jsx(Pa,{})]})})}function Ce({className:e,children:n,...r}){return t.jsxs(G.Select.Item,{"data-slot":"select-item",className:K("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[t.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:t.jsx(G.Select.ItemIndicator,{children:t.jsx(v.CheckIcon,{className:"size-4"})})}),t.jsx(G.Select.ItemText,{children:n})]})}function za({className:e,...n}){return t.jsx(G.Select.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:K("flex cursor-default items-center justify-center py-1",e),...n,children:t.jsx(v.ChevronUpIcon,{className:"size-4"})})}function Pa({className:e,...n}){return t.jsx(G.Select.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:K("flex cursor-default items-center justify-center py-1",e),...n,children:t.jsx(v.ChevronDownIcon,{className:"size-4"})})}const Dr={_contains:"Contains",_starts_with:"Starts with",_ends_with:"Ends with",_eq:"Equals",_neq:"Not equals",_null:"Is null"},Ea=300;function Da({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(g=>g in Dr),s=e.getFilterValue(),[o,i]=f.useState(s?.operator??"_contains"),[a,l]=f.useState(s?.operator==="_null"?"":String(s?.value??"")),c=f.useRef(),m=o==="_null";f.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]);const p=(g,b)=>{if(c.current&&clearTimeout(c.current),g==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!b){e.setFilterValue(void 0);return}c.current=setTimeout(()=>{e.setFilterValue({operator:g,value:b})},Ea)},d=g=>{i(g),g==="_null"?(l(""),e.setFilterValue({operator:"_null",value:!0})):a?p(g,a):e.setFilterValue(void 0)},h=g=>{l(g),p(o,g)},y=()=>{c.current&&clearTimeout(c.current),i("_contains"),l(""),e.setFilterValue(void 0)};return r.length===0?null:t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(_e,{value:o,onValueChange:d,children:[t.jsx(Pe,{size:"sm",className:"w-full text-xs",children:t.jsx(ze,{})}),t.jsx(Ee,{children:r.map(g=>t.jsx(Ce,{value:g,children:Dr[g]},g))})]}),!m&&t.jsx(Ne,{placeholder:"Filter value...",value:a,onChange:g=>h(g.target.value),className:"h-8 text-xs",autoFocus:!0}),s!==void 0&&t.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:y,children:[t.jsx(v.X,{className:"size-3"}),"Clear filter"]})]})}const Ir={_eq:"Equals",_neq:"Not equals",_gt:"Greater than",_gte:"Greater or equal",_lt:"Less than",_lte:"Less or equal",_between:"Between",_null:"Is null"},Mr=300;function Ia(e){return(e.columnDef.meta?.paramType??"").replace("!","")==="Int"}function pn(e,n){if(e===""||e==="-")return null;const r=n?parseInt(e,10):parseFloat(e);return Number.isNaN(r)?null:r}function Ma({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(x=>x in Ir),s=Ia(e),o=e.getFilterValue(),i=o?.operator??"_eq",[a,l]=f.useState(i),[c,m]=f.useState(()=>!o||o.operator==="_null"||o.operator==="_between"?"":String(o.value??"")),[p,d]=f.useState(()=>o?.operator==="_between"&&Array.isArray(o.value)?String(o.value[0]??""):""),[h,y]=f.useState(()=>o?.operator==="_between"&&Array.isArray(o.value)?String(o.value[1]??""):""),g=f.useRef();f.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const b=(x,k)=>{if(g.current&&clearTimeout(g.current),x==="_null"){e.setFilterValue({operator:"_null",value:!0});return}const V=pn(k,s);if(V===null){e.setFilterValue(void 0);return}g.current=setTimeout(()=>{e.setFilterValue({operator:x,value:V})},Mr)},N=(x,k)=>{g.current&&clearTimeout(g.current);const V=pn(x,s),I=pn(k,s);if(V===null||I===null){e.setFilterValue(void 0);return}g.current=setTimeout(()=>{e.setFilterValue({operator:"_between",value:[V,I]})},Mr)},T=x=>{l(x),x==="_null"?(m(""),d(""),y(""),e.setFilterValue({operator:"_null",value:!0})):x==="_between"?(m(""),p&&h?N(p,h):e.setFilterValue(void 0)):(d(""),y(""),c?b(x,c):e.setFilterValue(void 0))},j=x=>{m(x),b(a,x)},$=x=>{d(x),N(x,h)},S=x=>{y(x),N(p,x)},D=()=>{g.current&&clearTimeout(g.current),l("_eq"),m(""),d(""),y(""),e.setFilterValue(void 0)};if(r.length===0)return null;const w=a==="_between",L=a==="_null";return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(_e,{value:a,onValueChange:T,children:[t.jsx(Pe,{size:"sm",className:"w-full text-xs",children:t.jsx(ze,{})}),t.jsx(Ee,{children:r.map(x=>t.jsx(Ce,{value:x,children:Ir[x]},x))})]}),!L&&!w&&t.jsx(Ne,{type:"number",placeholder:"Filter value...",value:c,onChange:x=>j(x.target.value),className:"h-8 text-xs",autoFocus:!0}),w&&t.jsxs("div",{className:"flex gap-2",children:[t.jsx(Ne,{type:"number",placeholder:"Min",value:p,onChange:x=>$(x.target.value),className:"h-8 text-xs",autoFocus:!0}),t.jsx(Ne,{type:"number",placeholder:"Max",value:h,onChange:x=>S(x.target.value),className:"h-8 text-xs"})]}),o!==void 0&&t.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:D,children:[t.jsx(v.X,{className:"size-3"}),"Clear filter"]})]})}const Lr={_eq:"On",_neq:"Not on",_gt:"After",_gte:"On or after",_lt:"Before",_lte:"On or before",_between:"Between",_null:"Is null"};function La({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(w=>w in Lr),s=e.getFilterValue(),o=s?.operator??"_eq",[i,a]=f.useState(o),[l,c]=f.useState(()=>!s||s.operator==="_null"||s.operator==="_between"?"":String(s.value??"")),[m,p]=f.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[0]??""):""),[d,h]=f.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[1]??""):""),y=(w,L)=>{if(w==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!L){e.setFilterValue(void 0);return}e.setFilterValue({operator:w,value:L})},g=(w,L)=>{if(!w||!L){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_between",value:[w,L]})},b=w=>{a(w),w==="_null"?(c(""),p(""),h(""),e.setFilterValue({operator:"_null",value:!0})):w==="_between"?(c(""),m&&d?g(m,d):e.setFilterValue(void 0)):(p(""),h(""),l?y(w,l):e.setFilterValue(void 0))},N=w=>{c(w),y(i,w)},T=w=>{p(w),g(w,d)},j=w=>{h(w),g(m,w)},$=()=>{a("_eq"),c(""),p(""),h(""),e.setFilterValue(void 0)};if(r.length===0)return null;const S=i==="_between",D=i==="_null";return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(_e,{value:i,onValueChange:b,children:[t.jsx(Pe,{size:"sm",className:"w-full text-xs",children:t.jsx(ze,{})}),t.jsx(Ee,{children:r.map(w=>t.jsx(Ce,{value:w,children:Lr[w]},w))})]}),!D&&!S&&t.jsx(Ne,{type:"date",value:l,onChange:w=>N(w.target.value),className:"h-8 text-xs"}),S&&t.jsxs("div",{className:"flex gap-2",children:[t.jsx(Ne,{type:"date",value:m,onChange:w=>T(w.target.value),className:"h-8 text-xs"}),t.jsx(Ne,{type:"date",value:d,onChange:w=>j(w.target.value),className:"h-8 text-xs"})]}),s!==void 0&&t.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:$,children:[t.jsx(v.X,{className:"size-3"}),"Clear filter"]})]})}const Oa={all:"All",true:"True",false:"False",_null:"Is null"};function Aa(e){return e?e.operator==="_null"?"_null":e.operator==="_eq"&&e.value===!0?"true":e.operator==="_eq"&&e.value===!1?"false":"all":"all"}function qa({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).includes("_null"),s=e.getFilterValue(),o=Aa(s),i=r?["all","true","false","_null"]:["all","true","false"],a=c=>{switch(c){case"true":e.setFilterValue({operator:"_eq",value:!0});break;case"false":e.setFilterValue({operator:"_eq",value:!1});break;case"_null":e.setFilterValue({operator:"_null",value:!0});break;default:e.setFilterValue(void 0)}},l=()=>{e.setFilterValue(void 0)};return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(_e,{value:o,onValueChange:a,children:[t.jsx(Pe,{size:"sm",className:"w-full text-xs",children:t.jsx(ze,{})}),t.jsx(Ee,{children:i.map(c=>t.jsx(Ce,{value:c,children:Oa[c]},c))})]}),s!==void 0&&t.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:l,children:[t.jsx(v.X,{className:"size-3"}),"Clear filter"]})]})}function Va({column:e,joinTable:n,joinLabelColumn:r,joinFkColumn:s}){const o=ve(),a=je().findTable(n),l=`query Lookup${n} { ${n}(sort: [${r}_asc], limit: 100) { data { id: ${s} label: ${r} } } }`,{data:c}=le.useQuery({queryKey:["fkLookup",n,r],queryFn:()=>o.query(l),staleTime:300*1e3,enabled:!!a}),m=c?.[n]?.data??[],p=e.getFilterValue(),d=p?.operator==="_eq"&&p.value!=null?String(p.value):"all",h=g=>{if(g==="all"){e.setFilterValue(void 0);return}const b=Number(g),N=Number.isNaN(b)?g:b;e.setFilterValue({operator:"_eq",value:N})},y=()=>{e.setFilterValue(void 0)};return t.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[t.jsxs(_e,{value:d,onValueChange:h,children:[t.jsx(Pe,{size:"sm",className:"w-full text-xs",children:t.jsx(ze,{})}),t.jsxs(Ee,{children:[t.jsx(Ce,{value:"all",children:"All"}),m.map(g=>t.jsx(Ce,{value:String(g.id),children:String(g.label)},String(g.id)))]})]}),p!==void 0&&t.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:y,children:[t.jsx(v.X,{className:"size-3"}),"Clear filter"]})]})}function qt(e){return(e.columnDef.meta?.paramType??"").replace("!","")}function Ba(e){return qt(e)==="String"}function Ga(e){const n=qt(e);return n==="Int"||n==="Float"}function Ka(e){return qt(e)==="DateTime"}function Wa(e){return qt(e)==="Boolean"}function Ja(e){const n=e.columnDef.meta;return n?.joinTable?{joinTable:n.joinTable,joinLabelColumn:n.joinLabelColumn??"id",joinFkColumn:n.joinFkColumn??"id",isSelfReference:n.isSelfReference===!0}:null}function Ha(e){return e.columnDef.meta?.column}function Qa(e){const n=e.paramType.replace("!","");if(e.dbType){const r=e.dbType.toUpperCase();return e.maxLength&&(r.includes("VARCHAR")||r.includes("CHAR"))?`${r}(${e.maxLength})`:(r.includes("DECIMAL")||r.includes("NUMERIC"),r)}return n}function Ra(e){const n=e.paramType.replace("!","");return e.isPrimaryKey?t.jsx(v.Key,{className:"size-3.5"}):n==="Int"||n==="Float"?t.jsx(v.Hash,{className:"size-3.5"}):n==="DateTime"?t.jsx(v.Calendar,{className:"size-3.5"}):n==="Boolean"?t.jsx(v.ToggleLeft,{className:"size-3.5"}):t.jsx(v.Type,{className:"size-3.5"})}function Ya({column:e,fkMeta:n}){const r=Qa(e),s=e.isNullable,o=e.isPrimaryKey,i=e.isIdentity,a=e.defaultValue;return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[Ra(e),t.jsx("span",{className:"font-semibold text-foreground",children:e.label})]}),t.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:[t.jsx("dt",{className:"text-muted-foreground",children:"Type"}),t.jsx("dd",{className:"text-foreground font-medium",children:r}),t.jsx("dt",{className:"text-muted-foreground",children:"Nullable"}),t.jsx("dd",{className:"text-foreground",children:s?"Yes":"No"}),o&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Primary Key"}),t.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[t.jsx(v.Key,{className:"size-3"}),"Yes"]})]}),i&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Auto Increment"}),t.jsx("dd",{className:"text-foreground",children:"Yes"})]}),n&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Foreign Key"}),t.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[t.jsx(v.Link2,{className:"size-3"}),n.joinTable,n.isSelfReference&&t.jsx("span",{className:"ml-1 px-1 rounded bg-primary/10 text-[10px] font-medium",children:"self-ref"})]})]}),a!=null&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Default"}),t.jsx("dd",{className:"text-foreground font-mono text-xs truncate max-w-[150px]",children:String(a)})]}),e.maxLength!==void 0&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Max Length"}),t.jsx("dd",{className:"text-foreground",children:e.maxLength})]}),e.min!==void 0&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Min"}),t.jsx("dd",{className:"text-foreground",children:e.min})]}),e.max!==void 0&&t.jsxs(t.Fragment,{children:[t.jsx("dt",{className:"text-muted-foreground",children:"Max"}),t.jsx("dd",{className:"text-foreground",children:e.max})]})]})]})}function Ze({column:e,table:n,title:r}){const s=n.options.meta?.onResetColumnWidths;if(!e.getCanSort())return t.jsx("span",{children:r});const o=e.getIsSorted(),i=e.getFilterValue()!==void 0,a=Ja(e),l=!a&&Ba(e),c=!a&&Ga(e),m=!a&&Ka(e),p=!a&&Wa(e),d=Ha(e),h=t.jsxs(q,{variant:"ghost",size:"sm",className:K("-ml-2 h-7 text-xs data-[state=open]:bg-accent",o&&"text-foreground"),children:[t.jsx("span",{children:r}),i&&t.jsx(v.Filter,{className:"size-3 text-primary"}),o==="desc"?t.jsx(v.ArrowDown,{className:"size-4"}):o==="asc"?t.jsx(v.ArrowUp,{className:"size-4"}):t.jsx(v.ArrowUpDown,{className:"size-4"})]});return t.jsxs(bt,{openDelay:400,closeDelay:200,children:[t.jsxs(zr,{children:[t.jsx(Pr,{asChild:!0,children:t.jsx(yt,{asChild:!0,children:h})}),t.jsxs(Er,{align:"start",children:[t.jsxs(pt,{onClick:()=>e.toggleSorting(!1),children:[t.jsx(v.ArrowUp,{className:"size-3.5 text-muted-foreground"}),"Asc"]}),t.jsxs(pt,{onClick:()=>e.toggleSorting(!0),children:[t.jsx(v.ArrowDown,{className:"size-3.5 text-muted-foreground"}),"Desc"]}),o&&t.jsxs(pt,{onClick:()=>e.clearSorting(),children:[t.jsx(v.ArrowUpDown,{className:"size-3.5 text-muted-foreground"}),"Clear"]}),l&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(ht,{children:[t.jsxs(xt,{children:[t.jsx(v.Filter,{className:K("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(gt,{children:t.jsx(Da,{column:e})})]})]}),c&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(ht,{children:[t.jsxs(xt,{children:[t.jsx(v.Filter,{className:K("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(gt,{children:t.jsx(Ma,{column:e})})]})]}),m&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(ht,{children:[t.jsxs(xt,{children:[t.jsx(v.Filter,{className:K("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(gt,{children:t.jsx(La,{column:e})})]})]}),p&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(ht,{children:[t.jsxs(xt,{children:[t.jsx(v.Filter,{className:K("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(gt,{children:t.jsx(qa,{column:e})})]})]}),a&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(ht,{children:[t.jsxs(xt,{children:[t.jsx(v.Filter,{className:K("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),t.jsx(gt,{children:t.jsx(Va,{column:e,joinTable:a.joinTable,joinLabelColumn:a.joinLabelColumn,joinFkColumn:a.joinFkColumn})})]})]}),e.getCanHide()&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(pt,{onClick:()=>e.toggleVisibility(!1),children:[t.jsx(v.EyeOff,{className:"size-3.5 text-muted-foreground"}),"Hide"]})]}),s&&t.jsxs(t.Fragment,{children:[t.jsx(Ke,{}),t.jsxs(pt,{onClick:s,children:[t.jsx(v.RotateCcw,{className:"size-3.5 text-muted-foreground"}),"Reset column widths"]})]})]})]}),d&&t.jsx(vt,{align:"start",className:"w-64",children:t.jsx(Ya,{column:d,fkMeta:a})})]})}function Xa(e,n){if(e==null)return null;switch(n){case"Int":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function Ua(e){return e?.paramType?.replace("!","")??"String"}function et(e){return(e.sourceColumnNames?.length??0)>1}function Za(e,n,r,s="fk"){if(!e)return null;const o=n.sourceColumnNames??[],i=n.destinationColumnNames??[];if(o.length===0||o.length!==i.length)return null;const a=new Map((r?.columns??[]).map(d=>[d.name,d])),l=[],c={},m=[];for(let d=0;d<o.length;d++){const h=o[d],y=i[d];if(!(h in e))return null;const g=Ua(a.get(y)),b=`${s}_${y}`;c[b]=Xa(e[h],g),m.push(`$${b}: ${g}`),l.push(`{${y}: {_eq: $${b}}}`)}return{filterText:l.length===1?l[0]:`{and: [${l.join(", ")}]}`,variables:c,params:m}}function tt({kind:e}){return t.jsx("span",{className:"text-muted-foreground/60 italic select-none",children:e==="null"?"NULL":"empty"})}const ei="display-format",ti="display-format-preview",ni=new Set(["date","datetime","time","relative","number","percent","raw"]);function ri(e){return{param:(e.paramType??"").replace("!","").toLowerCase(),db:(e.dbType??"").toLowerCase()}}function si({param:e,db:n}){return e==="date"||n==="date"}function oi({param:e,db:n}){return e==="datetime"||e==="datetimeoffset"||n.includes("datetime")||n==="timestamp"||n==="smalldatetime"}function ai(e,n){const s=(n?e.metadata?.[n]:void 0)??e.metadata?.[ei];if(typeof s=="string"&&ni.has(s.toLowerCase()))return s.toLowerCase();const o=ri(e);return oi(o)?"datetime":si(o)?"date":null}function ii(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){const n=new Date(e);return isNaN(n.getTime())?null:n}if(typeof e=="string"){const n=new Date(e);return isNaN(n.getTime())?null:n}return null}const li=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}),ci=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),di=new Intl.DateTimeFormat(void 0,{timeStyle:"short"}),ui=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"medium"}),Or=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),mi=[["year",31536e3],["month",2592e3],["week",604800],["day",86400],["hour",3600],["minute",60],["second",1]];function fi(e,n=new Date){const r=Math.round((e.getTime()-n.getTime())/1e3),s=Math.abs(r);for(const[o,i]of mi)if(s>=i||o==="second")return Or.format(Math.round(r/i),o);return Or.format(0,"second")}function Vt(e,n,r){if(e==null)return t.jsx(tt,{kind:"null"});if(e==="")return t.jsx(tt,{kind:"empty"});const s=ai(n,r?.formatKey);if(s===null||s==="raw")return String(e);if(s==="date"||s==="datetime"||s==="time"||s==="relative"){const o=ii(e);if(!o)return String(e);const i=ui.format(o);if(s==="relative")return t.jsx("span",{title:i,className:"cursor-help underline decoration-dotted decoration-muted-foreground/40 underline-offset-2",children:fi(o)});const a=(s==="date"?li:s==="time"?di:ci).format(o);return t.jsx("span",{title:i,children:a})}if(s==="number"||s==="percent"){const o=typeof e=="number"?e:Number(e);if(isNaN(o))return String(e);const i=s==="percent"?new Intl.NumberFormat(void 0,{style:"percent",maximumFractionDigits:2}).format(o):new Intl.NumberFormat(void 0).format(o);return t.jsx("span",{title:String(e),children:i})}return String(e)}const pi=5,hi=400,xi=200;function gi(e){return e.filter(n=>!n.isPrimaryKey).slice(0,pi)}function bi(e,n,r,s){const o=n.map(a=>a.name).join(" ");return`query FkPreview($id: ${s==="Int"||s==="Int!"?"Int":"String"}) { ${e}(filter: { ${r}: { _eq: $id } } limit: 1) { data { ${o} } } }`}function yi(e,n,r,s){const o=n.map(i=>i.name).join(" ");return`query FkPreview(${r}) { ${e}(filter: ${s} limit: 1) { data { ${o} } } }`}function vi(e,n,r,s,o,i,a){if(r.length===0)return null;if(s&&et(s)&&o){const p=Za(o,s,n);if(!p)return null;const d=p.params.join(", ");return{query:yi(e,r,d,p.filterText),variables:p.variables,cacheKey:p.variables}}const l=n.columns.find(p=>p.name===a)?.paramType??"Int",m={id:["Int","Int!","Float","Float!"].includes(l)?Number(i):i};return{query:bi(e,r,a,l),variables:m,cacheKey:i}}function ji({tableName:e,recordId:n,filterColumn:r,join:s,sourceRow:o,children:i}){const[a,l]=f.useState(!1),c=je(),m=ve(),p=c.findTable(e),d=p?gi(p.columns):[],h=p?vi(e,p,d,s,o,n,r):null,{data:y,isLoading:g}=le.useQuery({queryKey:["fkPreview",e,h?.cacheKey],queryFn:()=>m.query(h.query,h.variables),enabled:a&&!!h,staleTime:300*1e3}),b=y?.[e]?.data?.[0];return t.jsxs(bt,{openDelay:hi,closeDelay:xi,open:a,onOpenChange:l,children:[t.jsx(yt,{asChild:!0,children:i}),t.jsx(vt,{align:"start",className:"w-72",children:t.jsxs("div",{className:"space-y-2",children:[t.jsx("p",{className:"text-sm font-semibold text-foreground",children:p?.label??e}),g&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}),b&&t.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:d.map(N=>t.jsxs("div",{className:"contents",children:[t.jsx("dt",{className:"text-muted-foreground truncate",children:N.label}),t.jsx("dd",{className:"text-foreground truncate",children:Vt(b[N.name],N,{formatKey:ti})})]},N.name))}),!g&&!b&&a&&t.jsx("p",{className:"text-xs text-muted-foreground",children:"Record not found"})]})})]})}const Ni=new Set(["binary","varbinary","image","blob","tinyblob","mediumblob","longblob","bytea"]),Ci=new Set(["text","ntext","xml"]),wi=new Set(["json","jsonb"]);function jt(e){return Ni.has(e.toLowerCase().replace(/\(.*\)/,""))}function Ar(e){return wi.has(e.toLowerCase().replace(/\(.*\)/,""))}function Bt(e){const n=e.toLowerCase(),r=n.replace(/\(.*\)/,"");return!!(Ci.has(r)||n.includes("(max)"))}function hn(e,n){if(!e)return"text";if(n&&jt(n))return"binary";if(n&&Ar(n))return"json";const r=e.trimStart();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r),"json"}catch{}return r.startsWith("<?xml")||r.startsWith("<")&&r.includes("</")&&r.endsWith(">")?"xml":/^[aOsidb]:\d+[:{;]/.test(r)?"php-serialized":e.length>200||e.includes(`
|
|
78
|
-
`)?"longtext":"text"}const qr=80;function ki(e){return e.length<=qr?e:e.slice(0,qr)+"..."}function Ti(e){const n=Math.ceil(e.length*3/4);return n<1024?`${n} bytes`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}const Si={json:v.Braces,xml:v.Code,"php-serialized":v.Database,binary:v.Binary,longtext:v.FileText,text:v.FileText},Fi={json:"JSON",xml:"XML","php-serialized":"PHP",binary:"Binary",longtext:"Text",text:"Text"};function $i(e,n){if(n==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function _i({value:e,dbType:n,onExpand:r}){if(e==null)return t.jsx(tt,{kind:"null"});const s=typeof e=="object"?JSON.stringify(e):String(e);if(s==="")return t.jsx(tt,{kind:"empty"});const o=hn(s,n);if(o==="text")return t.jsx("span",{children:s});if(o==="binary")return t.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[t.jsx(v.Binary,{className:"size-3.5"}),t.jsx("span",{className:"text-xs font-mono",children:Ti(s)}),r&&t.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:c=>{c.stopPropagation(),r()},"aria-label":"Expand content",children:t.jsx(v.Expand,{className:"size-3"})})]});const i=Si[o],a=ki(s);return s.length>80||o==="json"||o==="xml"||o==="php-serialized"?t.jsxs(bt,{openDelay:300,closeDelay:200,children:[t.jsx(yt,{asChild:!0,children:t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 text-left hover:text-primary transition-colors max-w-full",children:[t.jsx(i,{className:"size-3 text-muted-foreground shrink-0"}),t.jsx("span",{className:"font-mono text-xs truncate",children:a}),r&&t.jsx("span",{role:"button",tabIndex:0,className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:c=>{c.stopPropagation(),c.preventDefault(),r()},onKeyDown:c=>{c.key==="Enter"&&(c.stopPropagation(),r())},"aria-label":"Expand content",children:t.jsx(v.Expand,{className:"size-3"})})]})}),t.jsxs(vt,{side:"bottom",align:"start",className:"w-[420px] max-h-[320px] p-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-border bg-muted/30",children:[t.jsx(i,{className:"size-3.5 text-muted-foreground"}),t.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Fi[o]}),t.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[s.length," chars"]})]}),t.jsx("pre",{className:"p-3 text-xs font-mono overflow-auto max-h-[280px] whitespace-pre-wrap break-all",children:$i(s,o)})]})]}):t.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t.jsx(i,{className:"size-3 text-muted-foreground shrink-0"}),t.jsx("span",{className:"font-mono text-xs",children:s}),r&&t.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:c=>{c.stopPropagation(),r()},"aria-label":"Expand content",children:t.jsx(v.Expand,{className:"size-3"})})]})}const Vr="::";function zi(e){return e==null?"":encodeURIComponent(String(e))}function Br(e){if(e==="")return null;try{return decodeURIComponent(e)}catch{return e}}function Nt(e){return e.map(zi).join(Vr)}function Ct(e,n,r){const s=n.primaryKeys??[];return s.length===0?`row-${r}`:Nt(s.map(o=>e?.[o]))}function Gt(e,n){const r=n.primaryKeys??[];if(r.length===0||e==null)return null;const s={};for(const o of r){if(!(o in e))return null;s[o]=e[o]}return s}function Pi(e,n){if(e==null)return null;switch(n){case"Int":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function Ei(e){return e?.paramType?.replace("!","")??"String"}function Gr(e,n){const r=Gt(e,n);if(!r)return null;const s=new Map((n.columns??[]).map(c=>[c.name,c])),o=[],i={},a=[];for(const c of n.primaryKeys??[]){const m=Ei(s.get(c)),p=`pk_${c}`;i[p]=Pi(r[c],m),a.push(`$${p}: ${m}`),o.push(`{${c}: {_eq: $${p}}}`)}return{filterText:o.length===1?o[0]:`{and: [${o.join(", ")}]}`,variables:i,params:a}}function Di(e,n){const r=n.primaryKeys??[];return r.length===0?"":Nt(r.map(s=>e[s]))}function xn(e,n){const r=n.primaryKeys??[];if(r.length===0)return null;if(r.length===1)return{[r[0]]:Br(e)};const s=e.split(Vr);if(s.length!==r.length)return null;const o={};for(let i=0;i<r.length;i++)o[r[i]]=Br(s[i]);return o}function Ii(e,n,r){if(!e)return;const s=e.filter(o=>o.destinationTable===n);if(s.length!==0){if(s.length===1)return s[0];if(r){const o=s.find(i=>i.destinationColumnNames?.[0]===r);if(o)return o}return s[0]}}function Mi(e){return e.fieldName??e.destinationTable}const Kr={String:["_eq","_neq","_contains","_starts_with","_ends_with","_null"],Int:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],Float:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],Boolean:["_eq","_null"],DateTime:["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"]},Li=/^[_A-Za-z][_0-9A-Za-z]*$/,Oi=/^[_A-Za-z][_0-9A-Za-z]*!?$/;function Wr(e){return typeof e=="string"&&Li.test(e)}function Ai(e){return typeof e=="string"&&Oi.test(e)}function Jr(e,n){return typeof e=="string"&&Hr(n).includes(e)}function Hr(e){const n=e.replace("!","");return Kr[n]??Kr.String}function Qr(e){try{if(!e)return{variables:{},param:"",filterText:""};const[n,r,s,o]=JSON.parse(e);return!Wr(n)||!Ai(o)||!Jr(r,o)?{variables:{},param:"",filterText:""}:{variables:{filter:s},param:`, $filter: ${o}`,filterText:`{${n}: {${r}: $filter} }`}}catch{return{variables:{},param:"",filterText:""}}}function Rr(e){if(!e)return"";const n=new Date(e);return n.toString()==="Invalid Date"||n<new Date("1973-01-01")?"":n.toLocaleString()}function qi(e,n){const r=n.primaryKeys??[];return r.length===0?Nt([e?.id]):r.length===1?Nt([e?.[r[0]]]):Ct(e,n,0)}function Vi(e){switch(e.replace("!","")){case"Int":return"Int";case"Float":return"Float";case"Boolean":return"Boolean";case"DateTime":return"String";default:return"String"}}function Yr(e,n){const r={},s=[],o=[];for(let i=0;i<e.length;i++){const a=e[i],l=a.value;if(l.value===void 0||l.value===null||l.value==="")continue;const c=n.columns.find(d=>d.name===a.id);if(!c||!Wr(a.id)||!Jr(l.operator,c.paramType))continue;const m=`cf_${a.id}_${i}`,p=Vi(c.paramType);if(l.operator==="_null"){o.push(`{${a.id}: {_null: ${l.value?"true":"false"}}}`);continue}if(l.operator==="_between"){const d=l.value;if(!Array.isArray(d)||d.length!==2)continue;const h=`${m}_lo`,y=`${m}_hi`;r[h]=d[0],r[y]=d[1],s.push(`$${h}: ${p}`,`$${y}: ${p}`),o.push(`{${a.id}: {_between: [$${h}, $${y}]}}`);continue}r[m]=l.value,s.push(`$${m}: ${p}`),o.push(`{${a.id}: {${l.operator}: $${m}}}`)}return{variables:r,params:s,filterTexts:o}}function Bi(e){return e.length===0?"":JSON.stringify(e.map(n=>[n.id,n.value.operator,n.value.value]))}function Gi(e){try{return e?JSON.parse(e).map(([r,s,o])=>({id:r,value:{operator:s,value:o}})):[]}catch{return[]}}function Xr(e){return wt(e)[0]?.gqlType??"Int"}function wt(e){const n=e.primaryKeys??[];if(n.length===0)return[];const r=new Map(e.columns.map(s=>[s.name,s]));return n.map(s=>({name:s,gqlType:r.get(s)?.paramType?.replace("!","")??"String"}))}function Ki(e,n){if(e==null)return null;switch(n){case"Int":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1;default:return String(e)}}function gn(e,n){if(wt(n).length<=1)return{id:Ki(e,Xr(n))};const s=xn(e,n);return s?Gr(s,n)?.variables??{}:{}}function Wi(e,n){return n.map(r=>{const s=e.findTable(r.destinationTable),o=s?.labelColumn??"id",a=[...s?.primaryKeys?.length?s.primaryKeys:["id"]];return o&&!a.includes(o)&&a.push(o),`${r.fieldName??r.destinationTable} { data { ${a.join(" ")} } }`}).join(" ")}function Ji(e,n,r,s,o,i,a){if(!e||!n?.data)return null;const l=n.findTable(e.graphQlName);if(!l)return null;const c=Xr(l),m=wt(l),p=m[0]?.name??"id";let{param:d,filterText:h}=Qr(r);const{params:y,filterTexts:g}=Yr(s,e);y.length>0&&(d+=y.map(S=>`, ${S}`).join(""));const b=[];h&&b.push(h),b.push(...g),b.length>1?h=`{and: [${b.join(", ")}]}`:b.length===1?h=b[0]:h="";const N=new Set,T=e.columns.filter(S=>S?.joinTable===void 0).map(S=>{const D=l.singleJoins.find(x=>x.sourceColumnNames?.[0]===S.name);if(!D)return S;const L=n.findTable(D.destinationTable)?.labelColumn??"id";return{...S,joinTable:D,joinLabelColumn:L}}).map(S=>{if(S?.joinTable){N.add(S.name);const D=n.findTable(S.joinTable.destinationTable),w=D?.primaryKeys?.length?D.primaryKeys:S.joinTable.destinationColumnNames,L=S.joinLabelColumn??"id",x=L&&!w.includes(L)?` label: ${L}`:"";return w.length===1?`${S.name} ${S.joinTable.destinationTable} { id: ${w[0]}${x} }`:`${S.name} ${S.joinTable.destinationTable} { ${w.join(" ")}${x} }`}return S.name}).join(" "),j=Wi(n,l.multiJoins),$=j?`${T} ${j}`:T;if(o&&(a||i)){const S=bn(e,n,i,a);if(S){const D=`${S.childField}(limit: $limit offset: $offset sort: $sort) { total offset limit data {${$}} }`,w=wt(S.parentTable);if(w.length<=1){const V=w[0]?.name??"id";d=`, $id: ${w[0]?.gqlType??"Int"}`;const A=`{ ${V}: { _eq: $id}}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${d}) { ${S.parentTable.name}(filter: ${A}) { data { ${D} } } }`}d=`, ${w.map(V=>`$pk_${V.name}: ${V.gqlType}`).join(", ")}`;const k=`{and: [${w.map(V=>`{${V.name}: {_eq: $pk_${V.name}}}`).join(", ")}]}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${d}) { ${S.parentTable.name}(filter: ${k}) { data { ${D} } } }`}}return o&&!i&&!a&&(m.length<=1?(d=`, $id: ${c}`,h=`{ ${p}: { _eq: $id}}`):(d=`, ${m.map(D=>`$pk_${D.name}: ${D.gqlType}`).join(", ")}`,h=`{and: [${m.map(D=>`{${D.name}: {_eq: $pk_${D.name}}}`).join(", ")}]}`)),h&&(h=`filter: ${h}`),`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${d}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${h}) { total offset limit data {${$}}}}`}const Hi={data:[],total:0,offset:0,limit:0};function Qi(e,n,r){const i=e?.[n]?.data?.[0]?.[r];return!i||!Array.isArray(i.data)?Hi:i}function bn(e,n,r,s){const o=r??n.findTable(e.graphQlName)?.singleJoins.find(l=>l.destinationTable===s)?.destinationTable;if(!o)return null;const i=n.findTable(o);if(!i)return null;const a=Ii(i.multiJoins,e.graphQlName,s);return a?{parentTable:i,childField:Mi(a)}:null}function Ur(e,n){return e?!n||(n.primaryKeys?.length??0)<=1?String(e?.id??""):Ct(e,n,0):""}function Ri(e,n){const r=Math.max(0,n-1);return e<0?0:e>r?r:e}function Yi(e,n){const r=n.fieldName??n.destinationTable;return e[r]?.data??[]}const Xi=(e,n,r,s)=>{if(!e||!n)return[];const o=e.columns.map(a=>{const l=e.singleJoins.find(d=>d.sourceColumnNames?.[0]===a.name),c=l?void 0:e.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(a.name)),m=Hr(a.paramType);if(l){const d=l.destinationTable,h=n.findTable(l.destinationTable),y=h?.labelColumn??"id",g=et(l),b=l.destinationTable===e.name,N=b?`Parent ${a.label}`:a.label;return{id:a.name,accessorKey:a.name,header:({column:T,table:j})=>t.jsx(Ze,{column:T,table:j,title:N}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,filterOperators:m,joinTable:l.destinationTable,joinLabelColumn:y,joinFkColumn:l.destinationColumnNames[0],column:a,isSelfReference:b,isCompositeFk:g},cell:({row:T})=>{const j=T.original[d];if(!j)return t.jsx(tt,{kind:"null"});const $=Ur(j,h);return t.jsxs("span",{className:"group/fk inline-flex items-center gap-0.5",children:[t.jsx(ji,{tableName:l.destinationTable,recordId:$,filterColumn:l.destinationColumnNames[0],join:l,sourceRow:T.original,children:t.jsx(dt,{to:"/"+h?.name+"/"+$,className:"text-primary hover:text-primary/80 hover:underline",children:j?.label})}),s&&t.jsx(q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/fk:opacity-100 size-5 shrink-0",onClick:S=>{S.stopPropagation(),s({tableName:l.destinationTable,filterId:$})},"aria-label":"Open in side column",title:"Open in side column",children:t.jsx(v.PanelRight,{className:"size-3"})})]})}}}if(c){const h=n.findTable(c.destinationTable)?.labelColumn??"id",y=c.destinationTable===e.name;return{id:a.name,accessorFn:g=>a.name?String(g?.[a.name]??""):"",cell:({row:g})=>Vt(g.original[a.name],a),header:({column:g,table:b})=>t.jsx(Ze,{column:g,table:b,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:m,joinTable:c.destinationTable,joinLabelColumn:h,joinFkColumn:c.destinationColumnNames[(c.sourceColumnNames??[]).indexOf(a.name)]??c.destinationColumnNames[0],column:a,isSelfReference:y,isCompositeFk:!0,isCompositeFkMember:!0}}}return a?.joinTable?{id:a.name,accessorKey:a.name,header:({column:d,table:h})=>t.jsx(Ze,{column:d,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,filterOperators:m,column:a},cell:({row:d})=>{const h=d.original[a.name];return h?t.jsx(dt,{to:"/"+a.name+"/"+Ur(h,void 0),className:"text-primary hover:text-primary/80 hover:underline",children:a.name}):null}}:a?.paramType==="DateTime"?{id:a.name,accessorFn:d=>Rr(d?.[a.name]),cell:({row:d})=>{const h=d.original[a.name];return h==null||h===""?t.jsx(tt,{kind:h===""?"empty":"null"}):Rr(h)},header:({column:d,table:h})=>t.jsx(Ze,{column:d,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:m,column:a}}:Bt(a.dbType)||jt(a.dbType)||Ar(a.dbType)||a.paramType==="JSON"?{id:a.name,accessorFn:d=>a.name?String(d?.[a.name]??""):"",header:({column:d,table:h})=>t.jsx(Ze,{column:d,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:m,column:a},cell:({row:d})=>t.jsx(_i,{value:d.original[a.name],dbType:a.dbType,onExpand:r?()=>r(d.index,a.name):void 0})}:{id:a.name,accessorFn:d=>a.name?String(d?.[a.name]??""):"",cell:({row:d})=>Vt(d.original[a.name],a),header:({column:d,table:h})=>t.jsx(Ze,{column:d,table:h,title:a.label}),enableSorting:!0,meta:{sortField:a.name,paramType:a.paramType,dbType:a.dbType,filterOperators:m,column:a}}}),i=e.multiJoins.map(a=>{const l=n.findTable(a.destinationTable),c=l?.labelColumn??"id",p=a.destinationTable===e.name?`Child ${l?.label??a.destinationTable}`:l?.label??a.destinationTable;return{id:`join_${a.fieldName??a.destinationTable}`,header:p,enableSorting:!1,enableHiding:!0,cell:({row:d})=>{const h=qi(d.original,e),y=Yi(d.original,a),g=y.length;if(g===0)return t.jsx("span",{className:"text-muted-foreground",children:"—"});const b=y.slice(0,10).map(T=>String(T[c]??"")).filter(Boolean),N=l?.label??a.destinationTable;return t.jsxs("span",{className:"group/fk inline-flex items-center gap-1",children:[t.jsxs(bt,{openDelay:300,closeDelay:100,children:[t.jsx(yt,{asChild:!0,children:t.jsxs(dt,{to:"/"+l?.name+"/from/"+e.name+"/"+h,className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs font-medium text-primary hover:bg-muted hover:border-primary/40 transition-colors",children:[t.jsx(v.List,{className:"size-3"}),g]})}),t.jsxs(vt,{align:"start",sideOffset:6,className:"w-auto max-w-xs p-3",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b pb-2 mb-2",children:[t.jsx(v.List,{className:"size-3.5 text-primary"}),t.jsxs("span",{className:"text-xs font-semibold text-foreground",children:[g," ",N]})]}),t.jsxs("ul",{className:"space-y-0.5 text-xs text-foreground",children:[b.map((T,j)=>t.jsx("li",{className:"truncate",children:T},j)),g>10&&t.jsxs("li",{className:"text-muted-foreground italic",children:["… and ",g-10," more"]})]})]})]}),s&&t.jsx(q,{variant:"ghost",size:"icon-sm",className:"opacity-40 group-hover/fk:opacity-100 size-5 shrink-0 transition-opacity",onClick:T=>{T.stopPropagation(),s({tableName:a.destinationTable,filterTable:e.name,filterId:h,...et(a)?{}:{filterColumn:a.destinationColumnNames[0]}})},"aria-label":"Open in side column",title:"Open in side column",children:t.jsx(v.PanelRight,{className:"size-3"})})]})}}});return[...o,...i]};function Ui(e,n,r,s,o){if(!s&&!o)return gn(e,n);const i=bn(n,r,s,o);return i?gn(e,i.parentTable):gn(e,n)}function Zi(e,n,r,s,o,i){const{search:a}=Yn(),l=Dt(),c=a.get("filter")??"",m=a.get("cf")??"",{variables:p}=Qr(c),d=je(),h=ve(),[y,g]=f.useState([]),[b,N]=f.useState(()=>Gi(m)),[T,j]=f.useState(0),[$,S]=f.useState(50),D=f.useRef(e);e&&e!==D.current&&(D.current=e,y.length>0&&g([]),b.length>0&&N([]),T!==0&&j(0));const w=f.useMemo(()=>{if(y.length>0&&e){const O=y[0];if(e.columns.some(oe=>oe.name===O.id))return[`${O.id}_${O.desc?"desc":"asc"}`]}return e?[`${e.columns.at(0)?.name??"id"}_asc`]:[]},[y,e]),L=f.useMemo(()=>Ji(e,d,c,b,n,r,s),[e,d,c,b,n,r,s]),x=f.useMemo(()=>e?Yr(b,e).variables:{},[b,e]),k=T*$,V=f.useMemo(()=>({sort:w,limit:$,offset:k,...n&&e?Ui(n,e,d,r,s):{},...p,...x}),[w,$,k,n,e,d,r,s,p,x]),{isLoading:I,error:A,data:W}=le.useQuery({queryKey:["tableData",e?.name,L,V],queryFn:()=>h.query(L,V),enabled:!!L&&!!e&&w.length>0}),H=f.useMemo(()=>e?Xi(e,d,o,i):[],[e,d,o,i]),U=f.useMemo(()=>n&&(r||s)&&e?bn(e,d,r,s):null,[n,r,s,e,d]);let E,Y;if(U){const O=Qi(W,U.parentTable.name,U.childField);E=O.data,Y=O.total}else{const O=W?.[e?.name??""];E=O?.data??[],Y=O?.total??0}const se=Math.max(1,Math.ceil(Y/$));f.useEffect(()=>{const O=Ri(T,se);O!==T&&j(O)},[T,se]);const ue=f.useCallback(O=>{const Q=new URLSearchParams(a),oe=Bi(O);oe?Q.set("cf",oe):Q.delete("cf");const ge=Q.toString();l(ge?`?${ge}`:"?")},[a,l]),M=f.useCallback(O=>{g(O),j(0)},[]),we=f.useCallback(O=>{N(O),j(0),ue(O)},[ue]),ke=f.useCallback(O=>{j(O)},[]),ye=f.useCallback(O=>{S(O),j(0)},[]),me=e?.primaryKeys??[];return{columns:H,sorting:y,columnFilters:b,primaryKeys:me,pageIndex:T,pageSize:$,pageCount:se,rows:E,loading:I,error:A,onSortingChange:M,onColumnFiltersChange:we,onPageIndexChange:ke,onPageSizeChange:ye}}function el(e){return typeof e=="object"&&e!==null}function Zr(e,n){if(e==null)return null;if(!n)return e;const r=n.replace("!","");if(r==="Int"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.trunc(s):e}if(r==="Float"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?s:e}return r==="Boolean"?typeof e=="boolean"?e:e==="true"||e===1:String(e)}function es(e){const n=ve(),r=le.useQueryClient(),s=f.useMemo(()=>{const y=new Map;for(const g of e.columns)y.set(g.name,g.paramType);return y},[e]),o=f.useMemo(()=>{const y=e.primaryKeys??[];return y.length>0?y:["id"]},[e]),i=y=>{const g={};if(el(y)){for(const N of o)g[N]=Zr(y[N],s.get(N));return g}const b=o[0];return g[b]=Zr(y,s.get(b)),g},a=f.useMemo(()=>`mutation deleteSingle($detail: Delete_${e.name}){
|
|
87
|
+
}`;class bs extends Error{constructor(t,r){super(t.map(s=>s.message).join("; ")),this.errors=t,this.data=r,this.name="GraphQLRequestError"}errors;data}class ys{constructor(t){this.uri=t}uri;async query(t,r,s){const o=await fetch(this.uri,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,variables:r}),signal:s?.signal});if(!o.ok)throw new Error(`GraphQL request failed: ${o.status} ${o.statusText}`);const i=await o.json();if(i.errors?.length)throw new bs(i.errors,i.data);return i.data}}const vs=u.createContext(null),js=vs.Provider;function $e(){const e=u.useContext(vs);if(!e)throw new Error("useFetcher must be used within a FetcherProvider");return e}function Ba(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function Ga(e){return Ba(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[_\-\s]+/).filter(Boolean)}function Ka(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function zn(e){return e&&Ga(e).map(Ka).join(" ")}const Wa={showStats:!1},ws=u.createContext(Wa);function Ja({config:e,children:t}){return n.jsx(ws.Provider,{value:e,children:t})}function cr(){return u.useContext(ws)}const Cs=u.createContext({loading:!0,error:null,data:[],findTable:()=>{}}),Ns=({children:e})=>{const t=Ha();return n.jsx(Cs.Provider,{value:t,children:e})};function Je(){return u.useContext(Cs)}function Qa(e,t){if(!t||t.length===0)return e;const r=new Set(t.map(s=>s.toLowerCase()));return e.filter(s=>r.has(s.graphQlName.toLowerCase())||r.has(s.dbName.toLowerCase()))}function Ha(){const e=$e(),{tables:t}=cr(),{isLoading:r,error:s,data:o}=de.useQuery({queryKey:["dbSchema"],queryFn:()=>e.query(Va),staleTime:1/0});return u.useMemo(()=>{if(r)return{loading:!0,error:null,data:[],findTable:()=>{}};if(s)return{loading:!1,error:{message:s.message},data:[],findTable:()=>{}};if(!o)return{loading:!1,error:null,data:[],findTable:()=>{}};const i=o._dbSchema.map(c=>({...c,name:c.graphQlName,label:zn(c.dbName),metadata:ks(c.metadata),columns:c.columns.map(m=>({...m,name:m.graphQlName,label:zn(m.dbName),metadata:ks(m.metadata),inputType:Xa(m.inputType)}))})),a=Qa(i,t);return{loading:!1,error:null,data:a,findTable:c=>a.find(m=>m.graphQlName===c)}},[r,s,o,t])}function ks(e){return e.reduce((t,r)=>({...t,[r.key]:Ua(r)}),{})}function Ua({key:e,value:t}){return e==="type"?Ya(t):t}function Ya(e){const t=e.match(/lookup\s*\(\s*(?<id>\w+)\s*,\s*(?<label>\w+)\s*\)/m);if(t?.groups?.id&&t?.groups?.label)return{type:"lookup",id:t.groups.id,label:t.groups.label}}const Ra=["text","email","url","tel","date","datetime-local","number","password","search"];function Xa(e){if(e&&Ra.includes(e))return e}function Ss(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=Ss(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Ts(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Ss(e))&&(s&&(s+=" "),s+=t);return s}const $s=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Es=Ts,Fs=(e,t)=>r=>{var s;if(t?.variants==null)return Es(e,r?.class,r?.className);const{variants:o,defaultVariants:i}=t,a=Object.keys(o).map(m=>{const d=r?.[m],f=i?.[m];if(d===null)return null;const p=$s(d)||$s(f);return o[m][p]}),l=r&&Object.entries(r).reduce((m,d)=>{let[f,p]=d;return p===void 0||(m[f]=p),m},{}),c=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((m,d)=>{let{class:f,className:p,...x}=d;return Object.entries(x).every(h=>{let[y,N]=h;return Array.isArray(N)?N.includes({...i,...l}[y]):{...i,...l}[y]===N})?[...m,f,p]:m},[]);return Es(e,a,c,r?.class,r?.className)},Za=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},ei=(e,t)=>({classGroupId:e,validator:t}),_s=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),Dn="-",Ps=[],ti="arbitrary..",ni=e=>{const t=si(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return ri(a);const l=a.split(Dn),c=l[0]===""&&l.length>1?1:0;return zs(l,c,t)},getConflictingClassGroupIds:(a,l)=>{if(l){const c=s[a],m=r[a];return c?m?Za(m,c):c:m||Ps}return r[a]||Ps}}},zs=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],i=r.nextPart.get(o);if(i){const m=zs(e,t+1,i);if(m)return m}const a=r.validators;if(a===null)return;const l=t===0?e.join(Dn):e.slice(t).join(Dn),c=a.length;for(let m=0;m<c;m++){const d=a[m];if(d.validator(l))return d.classGroupId}},ri=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?ti+s:void 0})(),si=e=>{const{theme:t,classGroups:r}=e;return oi(r,t)},oi=(e,t)=>{const r=_s();for(const s in e){const o=e[s];ur(o,r,s,t)}return r},ur=(e,t,r,s)=>{const o=e.length;for(let i=0;i<o;i++){const a=e[i];ai(a,t,r,s)}},ai=(e,t,r,s)=>{if(typeof e=="string"){ii(e,t,r);return}if(typeof e=="function"){li(e,t,r,s);return}ci(e,t,r,s)},ii=(e,t,r)=>{const s=e===""?t:Ds(t,e);s.classGroupId=r},li=(e,t,r,s)=>{if(ui(e)){ur(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(ei(r,e))},ci=(e,t,r,s)=>{const o=Object.entries(e),i=o.length;for(let a=0;a<i;a++){const[l,c]=o[a];ur(c,Ds(t,l),r,s)}},Ds=(e,t)=>{let r=e;const s=t.split(Dn),o=s.length;for(let i=0;i<o;i++){const a=s[i];let l=r.nextPart.get(a);l||(l=_s(),r.nextPart.set(a,l)),r=l}return r},ui=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,di=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(i,a)=>{r[i]=a,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=s[i])!==void 0)return o(i,a),a},set(i,a){i in r?r[i]=a:o(i,a)}}},dr="!",Ms=":",mi=[],Is=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),fi=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const i=[];let a=0,l=0,c=0,m;const d=o.length;for(let y=0;y<d;y++){const N=o[y];if(a===0&&l===0){if(N===Ms){i.push(o.slice(c,y)),c=y+1;continue}if(N==="/"){m=y;continue}}N==="["?a++:N==="]"?a--:N==="("?l++:N===")"&&l--}const f=i.length===0?o:o.slice(c);let p=f,x=!1;f.endsWith(dr)?(p=f.slice(0,-1),x=!0):f.startsWith(dr)&&(p=f.slice(1),x=!0);const h=m&&m>c?m-c:void 0;return Is(i,x,p,h)};if(t){const o=t+Ms,i=s;s=a=>a.startsWith(o)?i(a.slice(o.length)):Is(mi,!1,a,void 0,!0)}if(r){const o=s;s=i=>r({className:i,parseClassName:o})}return s},pi=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",c=t.has(a);l||c?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(a)):o.push(a)}return o.length>0&&(o.sort(),s.push(...o)),s}},hi=e=>({cache:di(e.cacheSize),parseClassName:fi(e),sortModifiers:pi(e),postfixLookupClassGroupIds:gi(e),...ni(e)}),gi=e=>{const t=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let s=0;s<r.length;s++)t[r[s]]=!0;return t},xi=/\s+/,bi=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:i,postfixLookupClassGroupIds:a}=t,l=[],c=e.trim().split(xi);let m="";for(let d=c.length-1;d>=0;d-=1){const f=c[d],{isExternal:p,modifiers:x,hasImportantModifier:h,baseClassName:y,maybePostfixModifierPosition:N}=r(f);if(p){m=f+(m.length>0?" "+m:m);continue}let T=!!N,k;if(T){const F=y.substring(0,N);k=s(F);const j=k&&a[k]?s(y):void 0;j&&j!==k&&(k=j,T=!1)}else k=s(y);if(!k){if(!T){m=f+(m.length>0?" "+m:m);continue}if(k=s(y),!k){m=f+(m.length>0?" "+m:m);continue}T=!1}const $=x.length===0?"":x.length===1?x[0]:i(x).join(":"),b=h?$+dr:$,v=b+k;if(l.indexOf(v)>-1)continue;l.push(v);const w=o(k,T);for(let F=0;F<w.length;++F){const j=w[F];l.push(b+j)}m=f+(m.length>0?" "+m:m)}return m},yi=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Ls(r))&&(o&&(o+=" "),o+=s);return o},Ls=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Ls(e[s]))&&(r&&(r+=" "),r+=t);return r},vi=(e,...t)=>{let r,s,o,i;const a=c=>{const m=t.reduce((d,f)=>f(d),e());return r=hi(m),s=r.cache.get,o=r.cache.set,i=l,l(c)},l=c=>{const m=s(c);if(m)return m;const d=bi(c,r);return o(c,d),d};return i=a,(...c)=>i(yi(...c))},ji=[],_e=e=>{const t=r=>r[e]||ji;return t.isThemeGetter=!0,t},Os=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,As=/^\((?:(\w[\w-]*):)?(.+)\)$/i,wi=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ci=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ni=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ki=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Si=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ti=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,St=e=>wi.test(e),oe=e=>!!e&&!Number.isNaN(Number(e)),ct=e=>!!e&&Number.isInteger(Number(e)),mr=e=>e.endsWith("%")&&oe(e.slice(0,-1)),xt=e=>Ci.test(e),qs=()=>!0,$i=e=>Ni.test(e)&&!ki.test(e),fr=()=>!1,Ei=e=>Si.test(e),Fi=e=>Ti.test(e),_i=e=>!K(e)&&!J(e),Pi=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),zi=e=>Tt(e,Js,fr),K=e=>Os.test(e),Ot=e=>Tt(e,Qs,$i),Vs=e=>Tt(e,Vi,oe),Di=e=>Tt(e,Us,qs),Mi=e=>Tt(e,Hs,fr),Bs=e=>Tt(e,Ks,fr),Ii=e=>Tt(e,Ws,Fi),Mn=e=>Tt(e,Ys,Ei),J=e=>As.test(e),ln=e=>At(e,Qs),Li=e=>At(e,Hs),Gs=e=>At(e,Ks),Oi=e=>At(e,Js),Ai=e=>At(e,Ws),In=e=>At(e,Ys,!0),qi=e=>At(e,Us,!0),Tt=(e,t,r)=>{const s=Os.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},At=(e,t,r=!1)=>{const s=As.exec(e);return s?s[1]?t(s[1]):r:!1},Ks=e=>e==="position"||e==="percentage",Ws=e=>e==="image"||e==="url",Js=e=>e==="length"||e==="size"||e==="bg-size",Qs=e=>e==="length",Vi=e=>e==="number",Hs=e=>e==="family-name",Us=e=>e==="number"||e==="weight",Ys=e=>e==="shadow",Bi=vi(()=>{const e=_e("color"),t=_e("font"),r=_e("text"),s=_e("font-weight"),o=_e("tracking"),i=_e("leading"),a=_e("breakpoint"),l=_e("container"),c=_e("spacing"),m=_e("radius"),d=_e("shadow"),f=_e("inset-shadow"),p=_e("text-shadow"),x=_e("drop-shadow"),h=_e("blur"),y=_e("perspective"),N=_e("aspect"),T=_e("ease"),k=_e("animate"),$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...b(),J,K],w=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto","contain","none"],j=()=>[J,K,c],V=()=>[St,"full","auto",...j()],S=()=>[ct,"none","subgrid",J,K],L=()=>["auto",{span:["full",ct,J,K]},ct,J,K],A=()=>[ct,"auto",J,K],D=()=>["auto","min","max","fr",J,K],B=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],X=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...j()],P=()=>[St,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...j()],q=()=>[St,"screen","full","dvw","lvw","svw","min","max","fit",...j()],U=()=>[St,"screen","full","lh","dvh","lvh","svh","min","max","fit",...j()],_=()=>[e,J,K],ce=()=>[...b(),Gs,Bs,{position:[J,K]}],he=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Ue=()=>["auto","cover","contain",Oi,zi,{size:[J,K]}],Pe=()=>[mr,ln,Ot],ie=()=>["","none","full",m,J,K],se=()=>["",oe,ln,Ot],ke=()=>["solid","dashed","dotted","double"],Ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[oe,mr,Gs,Bs],Ee=()=>["","none",h,J,K],Ie=()=>["none",oe,J,K],Le=()=>["none",oe,J,K],Ge=()=>[oe,J,K],Oe=()=>[St,"full",...j()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[xt],breakpoint:[xt],color:[qs],container:[xt],"drop-shadow":[xt],ease:["in","out","in-out"],font:[_i],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[xt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[xt],shadow:[xt],spacing:["px",oe],text:[xt],"text-shadow":[xt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",St,K,J,N]}],container:["container"],"container-type":[{"@container":["","normal","size",J,K]}],"container-named":[Pi],columns:[{columns:[oe,K,J,l]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:V()}],"inset-x":[{"inset-x":V()}],"inset-y":[{"inset-y":V()}],start:[{"inset-s":V(),start:V()}],end:[{"inset-e":V(),end:V()}],"inset-bs":[{"inset-bs":V()}],"inset-be":[{"inset-be":V()}],top:[{top:V()}],right:[{right:V()}],bottom:[{bottom:V()}],left:[{left:V()}],visibility:["visible","invisible","collapse"],z:[{z:[ct,"auto",J,K]}],basis:[{basis:[St,"full","auto",l,...j()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[oe,St,"auto","initial","none",K]}],grow:[{grow:["",oe,J,K]}],shrink:[{shrink:["",oe,J,K]}],order:[{order:[ct,"first","last","none",J,K]}],"grid-cols":[{"grid-cols":S()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":S()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":D()}],"auto-rows":[{"auto-rows":D()}],gap:[{gap:j()}],"gap-x":[{"gap-x":j()}],"gap-y":[{"gap-y":j()}],"justify-content":[{justify:[...B(),"normal"]}],"justify-items":[{"justify-items":[...X(),"normal"]}],"justify-self":[{"justify-self":["auto",...X()]}],"align-content":[{content:["normal",...B()]}],"align-items":[{items:[...X(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...X(),{baseline:["","last"]}]}],"place-content":[{"place-content":B()}],"place-items":[{"place-items":[...X(),"baseline"]}],"place-self":[{"place-self":["auto",...X()]}],p:[{p:j()}],px:[{px:j()}],py:[{py:j()}],ps:[{ps:j()}],pe:[{pe:j()}],pbs:[{pbs:j()}],pbe:[{pbe:j()}],pt:[{pt:j()}],pr:[{pr:j()}],pb:[{pb:j()}],pl:[{pl:j()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":j()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":j()}],"space-y-reverse":["space-y-reverse"],size:[{size:P()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...U()]}],"min-block-size":[{"min-block":["auto",...U()]}],"max-block-size":[{"max-block":["none",...U()]}],w:[{w:[l,"screen",...P()]}],"min-w":[{"min-w":[l,"screen","none",...P()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...P()]}],h:[{h:["screen","lh",...P()]}],"min-h":[{"min-h":["screen","lh","none",...P()]}],"max-h":[{"max-h":["screen","lh",...P()]}],"font-size":[{text:["base",r,ln,Ot]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,qi,Di]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",mr,K]}],"font-family":[{font:[Li,Mi,t]}],"font-features":[{"font-features":[K]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,J,K]}],"line-clamp":[{"line-clamp":[oe,"none",J,Vs]}],leading:[{leading:[i,...j()]}],"list-image":[{"list-image":["none",J,K]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",J,K]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:_()}],"text-color":[{text:_()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ke(),"wavy"]}],"text-decoration-thickness":[{decoration:[oe,"from-font","auto",J,Ot]}],"text-decoration-color":[{decoration:_()}],"underline-offset":[{"underline-offset":[oe,"auto",J,K]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:j()}],"tab-size":[{tab:[ct,J,K]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",J,K]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",J,K]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ce()}],"bg-repeat":[{bg:he()}],"bg-size":[{bg:Ue()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ct,J,K],radial:["",J,K],conic:[ct,J,K]},Ai,Ii]}],"bg-color":[{bg:_()}],"gradient-from-pos":[{from:Pe()}],"gradient-via-pos":[{via:Pe()}],"gradient-to-pos":[{to:Pe()}],"gradient-from":[{from:_()}],"gradient-via":[{via:_()}],"gradient-to":[{to:_()}],rounded:[{rounded:ie()}],"rounded-s":[{"rounded-s":ie()}],"rounded-e":[{"rounded-e":ie()}],"rounded-t":[{"rounded-t":ie()}],"rounded-r":[{"rounded-r":ie()}],"rounded-b":[{"rounded-b":ie()}],"rounded-l":[{"rounded-l":ie()}],"rounded-ss":[{"rounded-ss":ie()}],"rounded-se":[{"rounded-se":ie()}],"rounded-ee":[{"rounded-ee":ie()}],"rounded-es":[{"rounded-es":ie()}],"rounded-tl":[{"rounded-tl":ie()}],"rounded-tr":[{"rounded-tr":ie()}],"rounded-br":[{"rounded-br":ie()}],"rounded-bl":[{"rounded-bl":ie()}],"border-w":[{border:se()}],"border-w-x":[{"border-x":se()}],"border-w-y":[{"border-y":se()}],"border-w-s":[{"border-s":se()}],"border-w-e":[{"border-e":se()}],"border-w-bs":[{"border-bs":se()}],"border-w-be":[{"border-be":se()}],"border-w-t":[{"border-t":se()}],"border-w-r":[{"border-r":se()}],"border-w-b":[{"border-b":se()}],"border-w-l":[{"border-l":se()}],"divide-x":[{"divide-x":se()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":se()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ke(),"hidden","none"]}],"divide-style":[{divide:[...ke(),"hidden","none"]}],"border-color":[{border:_()}],"border-color-x":[{"border-x":_()}],"border-color-y":[{"border-y":_()}],"border-color-s":[{"border-s":_()}],"border-color-e":[{"border-e":_()}],"border-color-bs":[{"border-bs":_()}],"border-color-be":[{"border-be":_()}],"border-color-t":[{"border-t":_()}],"border-color-r":[{"border-r":_()}],"border-color-b":[{"border-b":_()}],"border-color-l":[{"border-l":_()}],"divide-color":[{divide:_()}],"outline-style":[{outline:[...ke(),"none","hidden"]}],"outline-offset":[{"outline-offset":[oe,J,K]}],"outline-w":[{outline:["",oe,ln,Ot]}],"outline-color":[{outline:_()}],shadow:[{shadow:["","none",d,In,Mn]}],"shadow-color":[{shadow:_()}],"inset-shadow":[{"inset-shadow":["none",f,In,Mn]}],"inset-shadow-color":[{"inset-shadow":_()}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:_()}],"ring-offset-w":[{"ring-offset":[oe,Ot]}],"ring-offset-color":[{"ring-offset":_()}],"inset-ring-w":[{"inset-ring":se()}],"inset-ring-color":[{"inset-ring":_()}],"text-shadow":[{"text-shadow":["none",p,In,Mn]}],"text-shadow-color":[{"text-shadow":_()}],opacity:[{opacity:[oe,J,K]}],"mix-blend":[{"mix-blend":[...Ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ae()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[oe]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":_()}],"mask-image-linear-to-color":[{"mask-linear-to":_()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":_()}],"mask-image-t-to-color":[{"mask-t-to":_()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":_()}],"mask-image-r-to-color":[{"mask-r-to":_()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":_()}],"mask-image-b-to-color":[{"mask-b-to":_()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":_()}],"mask-image-l-to-color":[{"mask-l-to":_()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":_()}],"mask-image-x-to-color":[{"mask-x-to":_()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":_()}],"mask-image-y-to-color":[{"mask-y-to":_()}],"mask-image-radial":[{"mask-radial":[J,K]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":_()}],"mask-image-radial-to-color":[{"mask-radial-to":_()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[oe]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":_()}],"mask-image-conic-to-color":[{"mask-conic-to":_()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ce()}],"mask-repeat":[{mask:he()}],"mask-size":[{mask:Ue()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",J,K]}],filter:[{filter:["","none",J,K]}],blur:[{blur:Ee()}],brightness:[{brightness:[oe,J,K]}],contrast:[{contrast:[oe,J,K]}],"drop-shadow":[{"drop-shadow":["","none",x,In,Mn]}],"drop-shadow-color":[{"drop-shadow":_()}],grayscale:[{grayscale:["",oe,J,K]}],"hue-rotate":[{"hue-rotate":[oe,J,K]}],invert:[{invert:["",oe,J,K]}],saturate:[{saturate:[oe,J,K]}],sepia:[{sepia:["",oe,J,K]}],"backdrop-filter":[{"backdrop-filter":["","none",J,K]}],"backdrop-blur":[{"backdrop-blur":Ee()}],"backdrop-brightness":[{"backdrop-brightness":[oe,J,K]}],"backdrop-contrast":[{"backdrop-contrast":[oe,J,K]}],"backdrop-grayscale":[{"backdrop-grayscale":["",oe,J,K]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[oe,J,K]}],"backdrop-invert":[{"backdrop-invert":["",oe,J,K]}],"backdrop-opacity":[{"backdrop-opacity":[oe,J,K]}],"backdrop-saturate":[{"backdrop-saturate":[oe,J,K]}],"backdrop-sepia":[{"backdrop-sepia":["",oe,J,K]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":j()}],"border-spacing-x":[{"border-spacing-x":j()}],"border-spacing-y":[{"border-spacing-y":j()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",J,K]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[oe,"initial",J,K]}],ease:[{ease:["linear","initial",T,J,K]}],delay:[{delay:[oe,J,K]}],animate:[{animate:["none",k,J,K]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,J,K]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Le()}],"scale-x":[{"scale-x":Le()}],"scale-y":[{"scale-y":Le()}],"scale-z":[{"scale-z":Le()}],"scale-3d":["scale-3d"],skew:[{skew:Ge()}],"skew-x":[{"skew-x":Ge()}],"skew-y":[{"skew-y":Ge()}],transform:[{transform:[J,K,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"translate-none":["translate-none"],zoom:[{zoom:[ct,J,K]}],accent:[{accent:_()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:_()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",J,K]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":_()}],"scrollbar-track-color":[{"scrollbar-track":_()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":j()}],"scroll-mx":[{"scroll-mx":j()}],"scroll-my":[{"scroll-my":j()}],"scroll-ms":[{"scroll-ms":j()}],"scroll-me":[{"scroll-me":j()}],"scroll-mbs":[{"scroll-mbs":j()}],"scroll-mbe":[{"scroll-mbe":j()}],"scroll-mt":[{"scroll-mt":j()}],"scroll-mr":[{"scroll-mr":j()}],"scroll-mb":[{"scroll-mb":j()}],"scroll-ml":[{"scroll-ml":j()}],"scroll-p":[{"scroll-p":j()}],"scroll-px":[{"scroll-px":j()}],"scroll-py":[{"scroll-py":j()}],"scroll-ps":[{"scroll-ps":j()}],"scroll-pe":[{"scroll-pe":j()}],"scroll-pbs":[{"scroll-pbs":j()}],"scroll-pbe":[{"scroll-pbe":j()}],"scroll-pt":[{"scroll-pt":j()}],"scroll-pr":[{"scroll-pr":j()}],"scroll-pb":[{"scroll-pb":j()}],"scroll-pl":[{"scroll-pl":j()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",J,K]}],fill:[{fill:["none",..._()]}],"stroke-w":[{stroke:[oe,ln,Ot,Vs]}],stroke:[{stroke:["none",..._()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Y(...e){return Bi(Ts(e))}const Gi=Fs("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function Rt({className:e,variant:t,...r}){return n.jsx("div",{"data-slot":"alert",role:"alert",className:Y(Gi({variant:t}),e),...r})}function Rs({className:e,...t}){return n.jsx("div",{"data-slot":"alert-title",className:Y("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Xt({className:e,...t}){return n.jsx("div",{"data-slot":"alert-description",className:Y("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",e),...t})}const Qe=Ve.forwardRef(({className:e,type:t,...r},s)=>n.jsx("input",{type:t,ref:s,"data-slot":"input",className:Y("h-9 w-full min-w-0 rounded-md border border-input bg-transparent text-foreground px-3 py-0 text-sm shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...r}));Qe.displayName="Input";function Ln({...e}){return n.jsx(R.DropdownMenu.Root,{"data-slot":"dropdown-menu",...e})}function On({...e}){return n.jsx(R.DropdownMenu.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function An({className:e,sideOffset:t=4,...r}){return n.jsx(R.DropdownMenu.Portal,{children:n.jsx(R.DropdownMenu.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Y("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...r})})}function bt({className:e,inset:t,variant:r="default",...s}){return n.jsx(R.DropdownMenu.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:Y("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...s})}function Ki({className:e,children:t,checked:r,...s}){return n.jsxs(R.DropdownMenu.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:Y("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:r,...s,children:[n.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:n.jsx(R.DropdownMenu.ItemIndicator,{children:n.jsx(C.CheckIcon,{className:"size-4"})})}),t]})}function Wi({className:e,inset:t,...r}){return n.jsx(R.DropdownMenu.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:Y("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...r})}function yt({className:e,...t}){return n.jsx(R.DropdownMenu.Separator,{"data-slot":"dropdown-menu-separator",className:Y("-mx-1 my-1 h-px bg-border",e),...t})}function cn({...e}){return n.jsx(R.DropdownMenu.Sub,{"data-slot":"dropdown-menu-sub",...e})}function un({className:e,inset:t,children:r,...s}){return n.jsxs(R.DropdownMenu.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:Y("flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(C.ChevronRightIcon,{className:"ml-auto size-4"})]})}function dn({className:e,...t}){return n.jsx(R.DropdownMenu.SubContent,{"data-slot":"dropdown-menu-sub-content",className:Y("z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})}function ut(e){return(e??"").replace("!","")}const Xs=new Set(["Int","Short","Byte","BigInt"]),Ji=new Set(["Float","Decimal"]),Qi=new Set(["DateTime","DateTimeOffset"]),Hi=new Set(["BigInt","Decimal"]);function qt(e){return Xs.has(ut(e))}function Vt(e){const t=ut(e);return Xs.has(t)||Ji.has(t)}function Bt(e){return Hi.has(ut(e))}function Zs(e){return Qi.has(ut(e))}function Ui(e){return ut(e)==="String"}function eo(e,t){const r=e.trim();if(r===""||r==="-"||r==="+"||!(qt(t)?/^[+-]?\d+$/.test(r):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(r)))return null;if(Bt(t))return r;const o=Number(r);return Number.isFinite(o)?o:null}function dt(e,t){if(e==null)return null;if(Bt(t))return String(e);if(qt(t)){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}switch(ut(t)){case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function mn(e){return e?.paramType?.replace("!","")??"String"}function Gt(e){return(e.sourceColumnNames?.length??0)>1}function Yi(e,t){const r=(e.sourceColumnNames??[]).indexOf(t);return r<0?null:(e.destinationColumnNames??[])[r]??null}function Ri(e,t,r,s="fk"){if(!e)return null;const o=t.sourceColumnNames??[],i=t.destinationColumnNames??[];if(o.length===0||o.length!==i.length)return null;const a=new Map((r?.columns??[]).map(f=>[f.name,f])),l=[],c={},m=[];for(let f=0;f<o.length;f++){const p=o[f],x=i[f];if(!(p in e))return null;const h=mn(a.get(x)),y=`${s}_${x}`;c[y]=dt(e[p],h),m.push(`$${y}: ${h}`),l.push(`{${x}: {_eq: $${y}}}`)}return{filterText:l.length===1?l[0]:`{and: [${l.join(", ")}]}`,variables:c,params:m}}const pr="::";function Xi(e){return e==null?"":encodeURIComponent(String(e))}function hr(e){if(e==="")return null;try{return decodeURIComponent(e)}catch{return e}}function $t(e){return e.map(Xi).join(pr)}function to(e,t){const r=t<=1?[e]:e.split(pr);if(r.length!==t)throw new Error(`Route id '${e}' has ${r.length} part(s) but ${t} were expected.`);return r.map(s=>s===""?"":hr(s)??"")}function He(e,t,r){const s=t.primaryKeys??[];return s.length===0?`row-${r}`:$t(s.map(o=>e?.[o]))}function mt(e,t){const r=t.primaryKeys??[];if(r.length===0||e==null)return null;const s={};for(const o of r){if(!(o in e))return null;s[o]=e[o]}return s}function qn(e,t){const r=mt(e,t);if(!r)return null;const s=new Map((t.columns??[]).map(c=>[c.name,c])),o=[],i={},a=[];for(const c of t.primaryKeys??[]){const m=mn(s.get(c)),d=`pk_${c}`;i[d]=dt(r[c],m),a.push(`$${d}: ${m}`),o.push(`{${c}: {_eq: $${d}}}`)}return{filterText:o.length===1?o[0]:`{and: [${o.join(", ")}]}`,variables:i,params:a}}function Vn(e,t){const r=t.primaryKeys??[];return r.length===0?"":$t(r.map(s=>e[s]))}function fn(e,t){const r=t.primaryKeys??[];if(r.length===0)return null;const s=r.length===1?[e]:e.split(pr);if(s.length!==r.length)return null;const o={};for(let i=0;i<r.length;i++){const a=hr(s[i]);if(a===null)return null;o[r[i]]=a}return o}function Zi(e,t,r){if(!e)return;const s=e.filter(o=>o.destinationTable===t);if(s.length!==0){if(s.length===1)return s[0];if(r)return s.find(o=>o.destinationColumnNames?.[0]===r)}}function el(e){return e.fieldName??e.destinationTable}const tl=new Set(["binary","varbinary","image","blob","tinyblob","mediumblob","longblob","bytea"]),nl=new Set(["text","ntext","xml"]),rl=new Set(["json","jsonb"]);function Et(e){return tl.has(e.toLowerCase().replace(/\(.*\)/,""))}function no(e){return rl.has(e.toLowerCase().replace(/\(.*\)/,""))}function Ft(e){return no(e.dbType)||e.paramType==="JSON"}function gr(e){const t=e.toLowerCase(),r=t.replace(/\(.*\)/,"");return!!(nl.has(r)||t.includes("(max)"))}function _t(e){return typeof e.isLargeValue=="boolean"?e.isLargeValue:Et(e.dbType)||gr(e.dbType)}function Bn(e,t){if(!e)return"text";if(t&&Et(t))return"binary";if(t&&no(t))return"json";const r=e.trimStart();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r),"json"}catch{}return r.startsWith("<?xml")||r.startsWith("<")&&r.includes("</")&&r.endsWith(">")?"xml":/^[aOsidb]:\d+[:{;]/.test(r)?"php-serialized":e.length>200||e.includes(`
|
|
88
|
+
`)?"longtext":"text"}const ro=80;function sl(e){return e.length<=ro?e:e.slice(0,ro)+"..."}function xr(e){const t=Math.ceil(e.length*3/4);return t<1024?`${t} bytes`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function so(e){const t={kind:"unknown",mime:"application/octet-stream",extension:".bin"};let r;try{r=atob(e.slice(0,24))}catch{return t}const s=o=>r.charCodeAt(o);return r.length>=4&&s(0)===137&&r.slice(1,4)==="PNG"?{kind:"image",mime:"image/png",extension:".png"}:r.length>=3&&s(0)===255&&s(1)===216&&s(2)===255?{kind:"image",mime:"image/jpeg",extension:".jpg"}:r.slice(0,4)==="GIF8"?{kind:"image",mime:"image/gif",extension:".gif"}:r.slice(0,4)==="RIFF"&&r.slice(8,12)==="WEBP"?{kind:"image",mime:"image/webp",extension:".webp"}:r.slice(0,4)==="%PDF"?{kind:"pdf",mime:"application/pdf",extension:".pdf"}:t}function oo(e,t){return`data:${t};base64,${e}`}const Pt=["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],br={String:["_eq","_neq","_contains","_starts_with","_ends_with","_null"],Int:Pt,Float:Pt,Short:Pt,Byte:Pt,BigInt:Pt,Decimal:Pt,Boolean:["_eq","_null"],DateTime:Pt,DateTimeOffset:Pt},ol=new Set(["DateTime","DateTimeOffset"]),al=/^[_A-Za-z][_0-9A-Za-z]*$/,il=/^[_A-Za-z][_0-9A-Za-z]*!?$/,ll=new Set(Object.values(br).flat());function it(e){return typeof e=="string"&&al.test(e)}function je(e,t){if(!it(e))throw new Error(`Invalid GraphQL ${t}: ${String(e)}`)}function cl(e){return typeof e=="string"&&il.test(e)}function ao(e,t){return typeof e=="string"&&pn(t).includes(e)}function pn(e){const t=e.replace("!","");return br[t]??br.String}function ul(){return{variables:{},param:"",filterText:"",error:null}}function hn(e){return{variables:{},param:"",filterText:"",error:e}}function yr(e){if(!e)return ul();let t;try{t=JSON.parse(e)}catch{return hn("The filter in the URL is not valid JSON.")}if(!Array.isArray(t)||t.length<4)return hn("The filter in the URL is malformed.");const[r,s,o,i]=t;return it(r)?cl(i)?ao(s,i)?{variables:{filter:o},param:`, $filter: ${i}`,filterText:`{${r}: {${s}: $filter} }`,error:null}:hn(`Filter operator '${String(s)}' is not supported for ${String(i)} column '${String(r)}'.`):hn(`Filter type '${String(i)}' is not a valid type name.`):hn(`Filter column '${String(r)}' is not a valid column name.`)}function dl(e,t,r=0){return He(e,t,r)}function io(e){const t=e.replace("!","");switch(t){case"Int":case"Float":case"Short":case"Byte":case"Boolean":case"BigInt":case"Decimal":case"DateTime":case"DateTimeOffset":return t;default:return"String"}}const ml=/^\d{4}-\d{2}-\d{2}$/;function fl(e){const t=e<=0?"+":"-",r=Math.abs(e),s=String(Math.floor(r/60)).padStart(2,"0"),o=String(r%60).padStart(2,"0");return`${t}${s}:${o}`}function lo(e,t,r,s){const i=`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}`;if(r!=="DateTimeOffset")return i;const a=new Date(`${e}T00:00:00`).getTimezoneOffset();return`${i}${fl(a)}`}function pl(e,t,r,s){if(!ol.has(r))return{operator:e,value:t};const o=l=>lo(String(l),"start",r),i=l=>lo(String(l),"end",r),a=l=>typeof l=="string"&&ml.test(l);if(e==="_between"){const l=Array.isArray(t)?t:null;return!l||l.length!==2?{operator:e,value:t}:{operator:e,value:[a(l[0])?o(l[0]):l[0],a(l[1])?i(l[1]):l[1]]}}if(!a(t))return{operator:e,value:t};switch(e){case"_eq":return{operator:"_between",value:[o(t),i(t)]};case"_neq":return{operator:"_nbetween",value:[o(t),i(t)]};case"_gt":case"_lte":return{operator:e,value:i(t)};default:return{operator:e,value:o(t)}}}function Gn(e,t){const r={},s=[],o=[],i=[];for(let a=0;a<e.length;a++){const l=e[a],c=l.value;if(c.value===void 0||c.value===null||c.value==="")continue;const m=t.columns.find(x=>x.name===l.id);if(!m){i.push(`Column '${String(l.id)}' is not on this table.`);continue}if(!it(l.id)){i.push(`Column '${String(l.id)}' is not a valid column name.`);continue}if(!ao(c.operator,m.paramType)){i.push(`Operator '${String(c.operator)}' is not supported for column '${l.id}'.`);continue}const d=`cf_${l.id}_${a}`,f=io(m.paramType);if(c.operator==="_null"){o.push(`{${l.id}: {_null: ${c.value?"true":"false"}}}`);continue}const p=pl(c.operator,c.value,f);if(p.operator==="_between"||p.operator==="_nbetween"){const x=p.value;if(!Array.isArray(x)||x.length!==2){i.push(`The range filter on column '${l.id}' needs exactly two bounds.`);continue}const h=`${d}_lo`,y=`${d}_hi`;r[h]=x[0],r[y]=x[1],s.push(`$${h}: ${f}`,`$${y}: ${f}`),o.push(`{${l.id}: {${p.operator}: [$${h}, $${y}]}}`);continue}r[d]=p.value,s.push(`$${d}: ${f}`),o.push(`{${l.id}: {${p.operator}: $${d}}}`)}return{variables:r,params:s,filterTexts:o,errors:i}}function co(e,t,r){const s=yr(t),o=Gn(r,e);return s.error?[s.error,...o.errors]:o.errors}function vr(e){return e.length===0?"":JSON.stringify(e.map(t=>[t.id,t.value.operator,t.value.value]))}function jr(e){try{if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(hl).map(([r,s,o])=>({id:r,value:{operator:s,value:o}})):[]}catch{return[]}}function hl(e){if(!Array.isArray(e)||e.length!==3)return!1;const[t,r]=e;return it(t)&&typeof r=="string"&&ll.has(r)}function uo(e){return zt(e)[0]?.gqlType??"Int"}function zt(e){const t=e.primaryKeys??[];if(t.length===0)return[];const r=new Map(e.columns.map(s=>[s.name,s]));return t.map(s=>({name:s,gqlType:r.get(s)?.paramType?.replace("!","")??"String"}))}function gl(e,t=()=>!0){const r=e.indexes??[];if(r.length===0)return null;const s=new Map(e.columns.map(i=>[i.name,i])),o=i=>{const a=i.columns[0],l=a?s.get(a):void 0;return l&&t(l)?l.name:null};for(const i of[a=>a.isClustered,a=>a.isUnique,()=>!0])for(const a of r){if(!i(a))continue;const l=o(a);if(l)return l}return null}function wr(e,t){if(zt(t).length<=1)return{id:dt(hr(e),uo(t))};const s=fn(e,t);return s?qn(s,t)?.variables??{}:{}}function Cr(e,t,r){je(e.name,"single-row table name");for(const o of r)je(o,"single-row selection field");const s=t.params.length>0?`(${t.params.join(", ")})`:"";return`query GetSingleRow_${e.name}${s} { value: ${e.name}(filter: ${t.filterText}) { data { ${r.join(" ")} } } }`}function mo(e,t,r){je(e.name,"rows-by-pk table name");for(const d of r)je(d,"rows-by-pk selection field");const s=e.primaryKeys??[];if(s.length===0||t.length===0||r.length===0)return null;for(const d of s)je(d,"rows-by-pk key column");const o=new Map((e.columns??[]).map(d=>[d.name,d])),i=[],a={},l=[];t.forEach((d,f)=>{const p=[];for(const x of s){const h=mn(o.get(x)),y=`pk${f}_${x}`;a[y]=dt(d[x],h),i.push(`$${y}: ${h}`),p.push(`{${x}: {_eq: $${y}}}`)}l.push(p.length===1?p[0]:`{and: [${p.join(", ")}]}`)});const c=l.length===1?l[0]:`{or: [${l.join(", ")}]}`;return{query:`query GetRowsByPk_${e.name}(${i.join(", ")}) { value: ${e.name}(filter: ${c} limit: ${t.length}) { data { ${r.join(" ")} } } }`,variables:a}}const xl=11;function fo(e,t){return t.map(r=>{const s=e.findTable(r.destinationTable),o=s?.labelColumn??"id",a=[...s?.primaryKeys?.length?s.primaryKeys:["id"]];return o&&!a.includes(o)&&a.push(o),`${r.fieldName??r.destinationTable}(limit: ${xl}) { total data { ${a.join(" ")} } }`}).join(" ")}function Nr(e,t,r,s){return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${t}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${r}) { total offset limit data {${s}}}}`}function bl(e,t,r){const s=new Set;return e.columns.filter(o=>o?.joinTable===void 0).filter(o=>o.isPrimaryKey||!_t(o)).map(o=>{const i=r.singleJoins.find(c=>c.sourceColumnNames?.[0]===o.name);if(!i)return o;const l=t.findTable(i.destinationTable)?.labelColumn??"id";return{...o,joinTable:i,joinLabelColumn:l}}).map(o=>{if(o?.joinTable){s.add(o.name);const i=t.findTable(o.joinTable.destinationTable),a=i?.primaryKeys?.length?i.primaryKeys:o.joinTable.destinationColumnNames,l=o.joinLabelColumn??"id",c=l&&!a.includes(l)?` label: ${l}`:"",m=o.joinTable.fieldName??o.joinTable.destinationTable;return a.length===1?`${o.name} ${m} { id: ${a[0]}${c} }`:`${o.name} ${m} { ${a.join(" ")}${c} }`}return o.name}).join(" ")}function yl(e,t,r,s,o,i,a,l=!1){const c=$r(e,t,i,a);if(c&&Tr(c.childJoin)){const m=c.childJoin.destinationColumnNames[0],f=`, $id: ${zt(c.parentTable)[0]?.gqlType??"Int"}`,p=`filter: { ${m}: { _eq: $id } }`,x=l?"":fo(t,r.multiJoins.filter(y=>!wl(y,c.childJoin))),h=x?`${s} ${x}`:s;return Nr(e,f,p,h)}if(c){const m=`${c.childField}(limit: $limit offset: $offset sort: $sort) { total offset limit data {${o}} }`,d=zt(c.parentTable);if(d.length===0)return null;let f,p;if(d.length===1){const x=d[0].name;f=`, $id: ${d[0].gqlType}`,p=`{ ${x}: { _eq: $id}}`}else f=`, ${d.map(y=>`$pk_${y.name}: ${y.gqlType}`).join(", ")}`,p=`{and: [${d.map(y=>`{${y.name}: {_eq: $pk_${y.name}}}`).join(", ")}]}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${f}) { ${c.parentTable.name}(filter: ${p}) { data { ${m} } } }`}return null}function vl(e,t,r){const s=zt(t);if(s.length===0)return null;let o,i;if(s.length===1){const a=uo(t),l=s[0].name;o=`, $id: ${a}`,i=`{ ${l}: { _eq: $id}}`}else o=`, ${s.map(l=>`$pk_${l.name}: ${l.gqlType}`).join(", ")}`,i=`{and: [${s.map(l=>`{${l.name}: {_eq: $pk_${l.name}}}`).join(", ")}]}`;return Nr(e,o,`filter: ${i}`,r)}function jl(e,t,r,s){let{param:o,filterText:i}=yr(t);const{params:a,filterTexts:l}=Gn(r,e);a.length>0&&(o+=a.map(m=>`, ${m}`).join(""));const c=[];return i&&c.push(i),c.push(...l),c.length>1?i=`{and: [${c.join(", ")}]}`:c.length===1?i=c[0]:i="",Nr(e,o,i?`filter: ${i}`:"",s)}function kr(e){return e.columns.filter(t=>t.isPrimaryKey||!Et(t.dbType))}function Sr(e,t,r,s,o,i,a,l){if(!e||!t?.data)return null;const c=t.findTable(e.graphQlName);if(!c)return null;const m=l?.fields==="export",d=m?kr(e).map(x=>x.name).join(" "):bl(e,t,c),f=m?"":fo(t,c.multiJoins),p=f?`${d} ${f}`:d;return o&&(a||i)?yl(e,t,c,d,p,i,a,m):o&&!i&&!a?vl(e,c,p):co(e,r,s).length>0?null:jl(e,r,s,p)}function Tr(e){return!Gt(e)&&e.isPolymorphic!==!0&&(e.destinationColumnNames?.length??0)===1}function wl(e,t){return(e.fieldName??e.destinationTable)===(t.fieldName??t.destinationTable)&&e.destinationTable===t.destinationTable&&(e.destinationColumnNames??[]).join("\0")===(t.destinationColumnNames??[]).join("\0")&&(e.sourceColumnNames??[]).join("\0")===(t.sourceColumnNames??[]).join("\0")}const Cl={data:[],total:0,offset:0,limit:0};function po(e,t,r){const i=e?.[t]?.data?.[0]?.[r];return!i||!Array.isArray(i.data)?Cl:i}function $r(e,t,r,s){const o=r??t.findTable(e.graphQlName)?.singleJoins.find(l=>l.destinationTable===s)?.destinationTable;if(!o)return null;const i=t.findTable(o);if(!i)return null;const a=Zi(i.multiJoins,e.graphQlName,s);return a?{parentTable:i,childField:el(a),childJoin:a}:null}function Nl(e){const t=e.filter(it);return t.length===0?null:`query GetTableRowCounts { ${t.map(s=>`${s}: ${s}(limit: 1) { total }`).join(" ")} }`}function kl(e=!0){const{data:t,loading:r,error:s}=Je(),o=$e(),i=u.useMemo(()=>t.map(f=>f.name),[t]),a=u.useMemo(()=>Nl(i),[i]),{data:l,isLoading:c,error:m}=de.useQuery({queryKey:["tableRowCounts",i],queryFn:()=>o.query(a),enabled:e&&!!a&&i.length>0,staleTime:300*1e3});return{stats:u.useMemo(()=>{const f={};for(const p of t){const h=l?.[p.name]?.total??null;f[p.name]={columnCount:p.columns.length,rowCount:h,fkCount:p.singleJoins.length,isLoading:c,error:m?m.message:null}}return f},[t,l,c,m]),isLoading:r||c,error:s}}function Zt({kind:e}){return n.jsx("span",{className:"text-muted-foreground/60 italic select-none",children:e==="null"?"NULL":"empty"})}const Sl="display-format",Tl="display-format-preview",$l=new Set(["date","datetime","time","relative","number","percent","raw"]);function El(e){return{param:(e.paramType??"").replace("!","").toLowerCase(),db:(e.dbType??"").toLowerCase()}}function Fl({param:e,db:t}){return e==="date"||t==="date"}function _l({param:e,db:t}){return e==="datetime"||e==="datetimeoffset"||t.includes("datetime")||t==="timestamp"||t==="smalldatetime"}function ho(e,t){const s=(t?e.metadata?.[t]:void 0)??e.metadata?.[Sl];if(typeof s=="string"&&$l.has(s.toLowerCase()))return s.toLowerCase();const o=El(e);return _l(o)?"datetime":Fl(o)?"date":null}function Pl(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){const t=new Date(e);return isNaN(t.getTime())?null:t}if(typeof e=="string"){const t=new Date(e);return isNaN(t.getTime())?null:t}return null}const zl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}),Dl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),Ml=new Intl.DateTimeFormat(void 0,{timeStyle:"short"}),Il=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"medium"}),go=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ll=[["year",31536e3],["month",2592e3],["week",604800],["day",86400],["hour",3600],["minute",60],["second",1]];function Ol(e,t=new Date){const r=Math.round((e.getTime()-t.getTime())/1e3),s=Math.abs(r);for(const[o,i]of Ll)if(s>=i||o==="second")return go.format(Math.round(r/i),o);return go.format(0,"second")}function Kn(e,t,r){if(e==null)return n.jsx(Zt,{kind:"null"});if(e==="")return n.jsx(Zt,{kind:"empty"});const s=ho(t,r?.formatKey);if(s===null||s==="raw")return String(e);if(s==="date"||s==="datetime"||s==="time"||s==="relative"){const o=Pl(e);if(!o)return String(e);const i=Il.format(o);if(s==="relative")return n.jsx("span",{title:i,className:"cursor-help underline decoration-dotted decoration-muted-foreground/40 underline-offset-2",children:Ol(o)});const a=(s==="date"?zl:s==="time"?Ml:Dl).format(o);return n.jsx("span",{title:i,children:a})}if(s==="number"||s==="percent"){const o=typeof e=="number"?e:Number(e);if(isNaN(o))return String(e);const i=s==="percent"?new Intl.NumberFormat(void 0,{style:"percent",maximumFractionDigits:2}).format(o):new Intl.NumberFormat(void 0).format(o);return n.jsx("span",{title:String(e),children:i})}return String(e)}function xo(e){if(!e)return"";const t=new Date(e);return t.toString()==="Invalid Date"||t.getTime()===0||t.getUTCFullYear()<=1?"":t.toLocaleString()}function Al(e){if(e===null)return"—";if(e===0)return"0";if(e<1e3)return e.toString();if(e<1e6){const r=e/1e3;return r%1===0?`${r.toFixed(0)}k`:`${r.toFixed(1)}k`}const t=e/1e6;return t%1===0?`${t.toFixed(0)}M`:`${t.toFixed(1)}M`}const bo="\uFEFF",ql=/["\n\r,]/;function Er(e){if(e==null)return"";const t=Vl(e);return t===""?'""':ql.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Vl(e){switch(typeof e){case"string":return e;case"bigint":return e.toString();case"number":case"boolean":return String(e);case"object":return e instanceof Date?e.toISOString():JSON.stringify(e);default:return String(e)}}function yo(e,t,r={}){const s=e.map(Er).join(","),o=t.map(a=>a.map(Er).join(",")),i=[s,...o].join(`\r
|
|
89
|
+
`);return r.bom?bo+i:i}function vo(e,t){return typeof t=="bigint"?t.toString():t}function jo(e,t){const r={};for(let s=0;s<e.length;s++)r[e[s]]=t[s];return r}function wo(e,t,r={}){if(r.mode==="lines")return t.map(o=>JSON.stringify(jo(e,o),vo)).join(`
|
|
90
|
+
`);const s=t.map(o=>jo(e,o));return JSON.stringify(s,vo,2)}const Bl=500;function Fr(e){if(e?.aborted)throw new DOMException("Export cancelled","AbortError")}async function _r(e){const t=e.pageSize??Bl,{rowCap:r,signal:s}=e,o=[];let i=0,a=!1;Fr(s);let l=0,c=Number.POSITIVE_INFINITY;for(;l<c;){Fr(s);const d=await e.fetchPage(l,t);i=d.total,c=d.total;for(const f of d.rows){if(r!==void 0&&o.length>=r){a=!0;break}o.push(f)}if(e.onProgress?.(o.length,i),a||d.rows.length===0)break;l+=d.rows.length}return Fr(s),{content:e.format==="csv"?yo(e.headers,o,e.csv):wo(e.headers,o,e.json),rowCount:o.length,total:i,truncated:a}}const Pr=1e5;function zr(e){return e==="csv"?"text/csv;charset=utf-8;":"application/json;charset=utf-8;"}function Dr(e,t){return`${e}-export.${t}`}function Mr(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=new Blob([e],{type:r}),o=URL.createObjectURL(s),i=document.createElement("a");i.href=o,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function Gl(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=Uint8Array.from(atob(e),l=>l.charCodeAt(0)),o=new Blob([s],{type:r}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}function Kl(){const e=Je(),t=$e();return u.useCallback(async(r,s)=>{const o=Sr(r,e,"",[],void 0,void 0,void 0,{fields:"export"});if(!o)throw new Error(`Cannot export '${r.label??r.name}': no export query could be built.`);const i=kr(r),a=await _r({format:s,headers:i.map(l=>l.label??l.name),csv:{bom:!0},rowCap:Pr,fetchPage:async(l,c)=>{const d=(await t.query(o,{limit:c,offset:l}))?.[r.name],f=d?.data??[];return{rows:f.map(p=>i.map(x=>p[x.name])),total:d?.total??f.length}}});return Mr(a.content,Dr(r.name,s),zr(s)),a},[e,t])}const Co=u.createContext({toast:()=>{}}),Wl=4e3;function No({children:e}){const[t,r]=u.useState([]),s=u.useRef(0),o=u.useRef(new Set),i=u.useCallback(c=>{r(m=>m.filter(d=>d.id!==c))},[]),a=u.useCallback((c,m="success")=>{const d=s.current++;r(p=>[...p,{id:d,message:c,variant:m}]);const f=setTimeout(()=>{i(d),o.current.delete(f)},Wl);o.current.add(f)},[i]);u.useEffect(()=>{const c=o.current;return()=>{c.forEach(clearTimeout)}},[]);const l=u.useMemo(()=>({toast:a}),[a]);return n.jsxs(Co.Provider,{value:l,children:[e,n.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 max-w-sm",role:"region","aria-label":"Notifications",children:t.map(c=>n.jsxs("div",{role:"status",className:Y("flex items-start gap-2 rounded-md border px-3 py-2 text-sm shadow-md bg-popover",c.variant==="error"?"border-destructive/40 text-destructive":"border-border text-foreground"),children:[c.variant==="error"?n.jsx(C.AlertCircle,{className:"size-4 shrink-0 mt-0.5"}):n.jsx(C.CheckCircle2,{className:"size-4 shrink-0 mt-0.5 text-green-600"}),n.jsx("span",{className:"flex-1 break-words",children:c.message}),n.jsx("button",{type:"button",onClick:()=>i(c.id),"aria-label":"Dismiss notification",className:"shrink-0 opacity-60 hover:opacity-100",children:n.jsx(C.X,{className:"size-3.5"})})]},c.id))})]})}function vt(){return u.useContext(Co)}const Wn=50;function Jl(e,t){return e===null||t<=0?0:Math.max(2,Math.min(100,Math.round(e/t*100)))}function Ql({percent:e,label:t}){return n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",role:"img","aria-label":t,title:t,children:n.jsx("span",{className:"block h-full rounded-full bg-emerald-500/70 dark:bg-emerald-400/70",style:{width:`${e}%`}})})}function Ir({count:e}){return e<=0?null:n.jsxs("span",{className:"shrink-0 rounded px-1 py-px text-[0.85em] tabular-nums bg-blue-100 text-blue-700 dark:bg-blue-900/60 dark:text-blue-300",children:[e," FK"]})}function Hl(e){try{return decodeURIComponent(e)}catch{return e}}function Ul({stats:e,maxRowCount:t}){const r=Jl(e.rowCount,t),s="flex items-center gap-1.5 text-xs leading-none min-w-0";return e.isLoading?n.jsxs("div",{className:`${s} text-muted-foreground`,children:[n.jsxs("span",{className:"tabular-nums shrink-0",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",children:n.jsx("span",{className:"block h-full w-1/3 rounded-full bg-muted-foreground/30 animate-pulse"})}),n.jsx(C.Loader2,{className:"size-[1em] shrink-0 animate-spin"}),n.jsx(Ir,{count:e.fkCount})]}):e.error?n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 text-destructive truncate",title:e.error,children:"err"}),n.jsx(Ir,{count:e.fkCount})]}):n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground/70",children:[e.columnCount,"c"]}),n.jsx(Ql,{percent:r,label:`${e.rowCount?.toLocaleString()??"unknown"} rows`}),n.jsx("span",{className:"tabular-nums shrink-0 text-right text-muted-foreground",children:Al(e.rowCount)}),n.jsx(Ir,{count:e.fkCount})]})}function Yl({table:e,stats:t,maxRowCount:r,showStats:s,active:o,actions:i}){const a=(i??[]).filter(l=>l.enabled?.(e)??!0);return n.jsxs("div",{className:`group/tablerow flex items-stretch border-l-2 ${o?"bg-accent text-accent-foreground border-primary":"text-foreground border-transparent hover:bg-muted/50"}`,children:[n.jsx(Pn,{to:`/${e.name}`,"aria-current":o?"page":void 0,className:`plain-link flex-1 min-w-0 no-underline py-1.5 px-2 text-sm font-medium ${o?"":"hover:text-primary"}`,children:n.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[n.jsx("span",{className:"truncate",title:e.label,children:e.label}),s&&n.jsx(Ul,{stats:t,maxRowCount:r})]})}),a.length>0&&n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":`Actions for ${e.label}`,className:"shrink-0 px-1 opacity-0 group-hover/tablerow:opacity-100 focus:opacity-100 data-[state=open]:opacity-100 text-muted-foreground hover:text-foreground",children:n.jsx(C.MoreVertical,{className:"size-3.5"})})}),n.jsx(An,{align:"start",children:a.map(l=>{const c=l.icon;return n.jsxs(bt,{onSelect:()=>{l.onSelect(e)},children:[c&&n.jsx(c,{className:"size-3.5"}),l.label]},l.id)})})]})]})}function Lr(e){const t=e.dbName.lastIndexOf(".");return t>0?e.dbName.slice(0,t):null}function ko({schema:e,count:t,collapsed:r,context:s,onToggle:o}){const i=r?C.ChevronRight:C.ChevronDown,a=n.jsxs(n.Fragment,{children:[n.jsx(i,{className:"size-3.5 shrink-0 text-muted-foreground"}),n.jsx("span",{className:"truncate font-semibold",title:e,children:e}),n.jsx("span",{className:"ml-auto shrink-0 tabular-nums text-[0.85em] text-muted-foreground",children:t})]}),l="flex items-center gap-1.5 w-full px-2 py-1 text-xs uppercase tracking-wide text-muted-foreground bg-muted/40 border-y border-border sticky top-0 z-10";return s?n.jsx("div",{className:l,"aria-hidden":"true",children:a}):n.jsx("button",{type:"button",onClick:o,"aria-expanded":!r,className:`${l} hover:bg-muted/70 text-left`,children:a})}function Rl(){const{showStats:e,tableActions:t}=cr(),{loading:r,error:s,data:o}=Je(),i=Kl(),{toast:a}=vt(),l=u.useCallback(async(E,P)=>{try{const q=await i(E,P);a(q.truncated?`${E.label} exported (truncated to ${q.rowCount.toLocaleString()} of ${q.total.toLocaleString()} rows)`:`${E.label} exported (${q.rowCount.toLocaleString()} rows)`)}catch(q){a(`Export failed: ${q.message}`,"error")}},[i,a]),c=u.useMemo(()=>[{id:"download-csv",label:"Download CSV",icon:C.Download,onSelect:E=>l(E,"csv")},{id:"download-json",label:"Download JSON",icon:C.Download,onSelect:E=>l(E,"json")},...t??[]],[l,t]),{stats:m,isLoading:d}=kl(e),[f,p]=u.useState(""),[x,h]=u.useState(new Set),[y,N]=u.useState(0),T=ps(),k=Hl(T.split("/")[1]??""),$=u.useMemo(()=>{const E=Object.values(m).map(P=>P.rowCount).filter(P=>P!==null);return E.length>0?Math.max(...E):0},[m]),b=f.trim().length>0,v=u.useMemo(()=>{const E=f.trim().toLowerCase();return E?o.filter(P=>{const q=Lr(P);return P.label.toLowerCase().includes(E)||P.dbName.toLowerCase().includes(E)||(q?.toLowerCase().includes(E)??!1)}):o},[o,f]),{schemas:w,grouped:F,multiSchema:j}=u.useMemo(()=>{const E=new Map;for(const q of v){const U=Lr(q),_=E.get(U)??[];_.push(q),E.set(U,_)}const P=[...E.keys()].filter(q=>q!==null).sort((q,U)=>q.localeCompare(U));return{schemas:P,grouped:E,multiSchema:P.length>1}},[v]),V=u.useMemo(()=>{const E=[];if(j){const P=[...w,...F.has(null)?[null]:[]];for(const q of P){const U=F.get(q===void 0?null:q)??[],_=!b&&x.has(q);if(E.push({kind:"group",schema:q??"(no schema)",count:U.length,collapsed:_}),!_)for(const ce of U)E.push({kind:"table",schema:q,table:ce})}}else for(const P of v)E.push({kind:"table",schema:Lr(P),table:P});return E},[j,w,F,v,x,b]);u.useEffect(()=>{N(0)},[f]);const S=Math.max(1,Math.ceil(V.length/Wn)),L=Math.min(y,S-1),A=L*Wn,D=V.slice(A,A+Wn),B=j&&D[0]?.kind==="table"&&D[0].schema?D[0].schema:null,X=E=>h(P=>{const q=new Set(P);return q.has(E)?q.delete(E):q.add(E),q});return r?n.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):s?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",s.message]})}):o.length===0?n.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{className:"font-medium",children:"No tables found"}),n.jsx("p",{className:"mt-1",children:"The database may be empty or the connection may have failed."})]}):n.jsxs("div",{className:"@container min-w-0 flex flex-col h-full",children:[n.jsxs("div",{className:"sticky top-0 z-20 bg-background p-2 border-b border-border",children:[n.jsxs("div",{className:"relative",children:[n.jsx(C.Search,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:f,onChange:E=>p(E.target.value),placeholder:"Search tables...","aria-label":"Search tables",className:"pl-8 pr-8 h-8 text-sm"}),b&&n.jsx("button",{type:"button",onClick:()=>p(""),"aria-label":"Clear search",className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted",children:n.jsx(C.X,{className:"size-4"})})]}),b&&n.jsxs("p",{className:"mt-1 px-0.5 text-xs text-muted-foreground",children:[v.length," match",v.length!==1?"es":""]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:V.length===0?n.jsxs("p",{className:"p-4 text-center text-sm text-muted-foreground",children:["No tables match “",f,"”."]}):n.jsxs(n.Fragment,{children:[B&&n.jsx(ko,{schema:B,count:F.get(B)?.length??0,collapsed:!1,context:!0}),D.map(E=>E.kind==="group"?n.jsx(ko,{schema:E.schema,count:E.count,collapsed:E.collapsed,onToggle:()=>X(E.schema)},`g:${E.schema}`):n.jsx(Yl,{table:E.table,stats:m[E.table.name]??{columnCount:E.table.columns.length,rowCount:null,fkCount:E.table.singleJoins.length,isLoading:d,error:null},maxRowCount:$,showStats:e,active:E.table.name===k,actions:c},`t:${E.table.name}`))]})}),S>1&&n.jsxs("div",{className:"sticky bottom-0 z-20 bg-background border-t border-border flex items-center justify-between gap-2 px-2 py-1.5",children:[n.jsx("button",{type:"button",onClick:()=>N(E=>Math.max(0,E-1)),disabled:L===0,"aria-label":"Previous page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),n.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[A+1,"–",Math.min(A+Wn,V.length)," of ",V.length]}),n.jsx("button",{type:"button",onClick:()=>N(E=>Math.min(S-1,E+1)),disabled:L>=S-1,"aria-label":"Next page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(C.ChevronRight,{className:"size-4"})})]})]})}const Xl=Fs("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),Q=Ve.forwardRef(({className:e,variant:t,size:r,asChild:s=!1,...o},i)=>{const a=s?ka.Slot:"button";return n.jsx(a,{className:Y(Xl({variant:t,size:r,className:e})),ref:i,...o})});Q.displayName="Button";const gn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Root,{"data-slot":"hover-card",...e}));gn.displayName="HoverCard";const xn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Trigger,{"data-slot":"hover-card-trigger",...e}));xn.displayName="HoverCardTrigger";const bn=Ve.forwardRef(({className:e,align:t="center",sideOffset:r=4,...s},o)=>n.jsx(R.HoverCard.Portal,{children:n.jsx(R.HoverCard.Content,{ref:o,"data-slot":"hover-card-content",align:t,sideOffset:r,className:Y("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));bn.displayName="HoverCardContent";function Ze({...e}){return n.jsx(R.Select.Root,{"data-slot":"select",...e})}function et({...e}){return n.jsx(R.Select.Value,{"data-slot":"select-value",...e})}function tt({className:e,size:t="default",children:r,...s}){return n.jsxs(R.Select.Trigger,{"data-slot":"select-trigger","data-size":t,className:Y("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(R.Select.Icon,{asChild:!0,children:n.jsx(C.ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function nt({className:e,children:t,position:r="item-aligned",align:s="center",...o}){return n.jsx(R.Select.Portal,{children:n.jsxs(R.Select.Content,{"data-slot":"select-content",className:Y("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,align:s,...o,children:[n.jsx(Zl,{}),n.jsx(R.Select.Viewport,{className:Y("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),n.jsx(ec,{})]})})}function we({className:e,children:t,...r}){return n.jsxs(R.Select.Item,{"data-slot":"select-item",className:Y("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[n.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:n.jsx(R.Select.ItemIndicator,{children:n.jsx(C.CheckIcon,{className:"size-4"})})}),n.jsx(R.Select.ItemText,{children:t})]})}function Zl({className:e,...t}){return n.jsx(R.Select.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(C.ChevronUpIcon,{className:"size-4"})})}function ec({className:e,...t}){return n.jsx(R.Select.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(C.ChevronDownIcon,{className:"size-4"})})}function So(e){const t=u.useRef(null),r=u.useRef(null),s=u.useRef(e);s.current=e;const o=u.useMemo(()=>{const i=()=>{t.current&&(clearTimeout(t.current),t.current=null)},a=()=>{i();const l=r.current;r.current=null,l?.()};return{schedule:l=>{i(),r.current=l,t.current=setTimeout(a,s.current)},cancel:()=>{i(),r.current=null},flush:a}},[]);return u.useEffect(()=>()=>o.flush(),[o]),o}const To={_contains:"Contains",_starts_with:"Starts with",_ends_with:"Ends with",_eq:"Equals",_neq:"Not equals",_null:"Is null"},tc=300;function nc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(y=>y in To),s=e.getFilterValue(),[o,i]=u.useState(s?.operator??"_contains"),[a,l]=u.useState(s?.operator==="_null"?"":String(s?.value??"")),{schedule:c,cancel:m}=So(tc),d=o==="_null",f=(y,N)=>{if(y==="_null"){m(),e.setFilterValue({operator:"_null",value:!0});return}if(!N){m(),e.setFilterValue(void 0);return}c(()=>e.setFilterValue({operator:y,value:N}))},p=y=>{i(y),y==="_null"?(l(""),f("_null","")):a?f(y,a):(m(),e.setFilterValue(void 0))},x=y=>{l(y),f(o,y)},h=()=>{m(),i("_contains"),l(""),e.setFilterValue(void 0)};return r.length===0?null:n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:p,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(y=>n.jsx(we,{value:y,children:To[y]},y))})]}),!d&&n.jsx(Qe,{placeholder:"Filter value...",value:a,onChange:y=>x(y.target.value),className:"h-8 text-xs",autoFocus:!0}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const $o={_eq:"Equals",_neq:"Not equals",_gt:"Greater than",_gte:"Greater or equal",_lt:"Less than",_lte:"Less or equal",_between:"Between",_null:"Is null"},rc=300;function sc(e){return e.columnDef.meta?.paramType??""}function Or(e,t){return eo(e,t)}function oc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(D=>D in $o),s=sc(e),o=qt(s),i=Bt(s),a=e.getFilterValue(),l=a?.operator??"_eq",[c,m]=u.useState(l),[d,f]=u.useState(()=>!a||a.operator==="_null"||a.operator==="_between"?"":String(a.value??"")),[p,x]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[0]??""):""),[h,y]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[1]??""):""),{schedule:N,cancel:T}=So(rc),k=(D,B)=>{if(D==="_null"){T(),e.setFilterValue({operator:"_null",value:!0});return}const X=Or(B,s);if(X===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:D,value:X}))},$=(D,B)=>{const X=Or(D,s),E=Or(B,s);if(X===null||E===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:"_between",value:[X,E]}))},b=D=>{m(D),D==="_null"?(f(""),x(""),y(""),k("_null","")):D==="_between"?(f(""),p&&h?$(p,h):(T(),e.setFilterValue(void 0))):(x(""),y(""),d?k(D,d):(T(),e.setFilterValue(void 0)))},v=D=>{f(D),k(c,D)},w=D=>{x(D),$(D,h)},F=D=>{y(D),$(p,D)},j=()=>{T(),m("_eq"),f(""),x(""),y(""),e.setFilterValue(void 0)};if(r.length===0)return null;const V=c==="_between",S=c==="_null",L=i?"text":"number",A=i?o?"numeric":"decimal":void 0;return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:c,onValueChange:b,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(D=>n.jsx(we,{value:D,children:$o[D]},D))})]}),!S&&!V&&n.jsx(Qe,{type:L,inputMode:A,placeholder:"Filter value...",value:d,onChange:D=>v(D.target.value),className:"h-8 text-xs",autoFocus:!0}),V&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:L,inputMode:A,placeholder:"Min",value:p,onChange:D=>w(D.target.value),className:"h-8 text-xs",autoFocus:!0}),n.jsx(Qe,{type:L,inputMode:A,placeholder:"Max",value:h,onChange:D=>F(D.target.value),className:"h-8 text-xs"})]}),a!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:j,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const Eo={_eq:"On",_neq:"Not on",_gt:"After",_gte:"On or after",_lt:"Before",_lte:"On or before",_between:"Between",_null:"Is null"};function ac({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(w=>w in Eo),s=e.getFilterValue(),o=s?.operator??"_eq",[i,a]=u.useState(o),[l,c]=u.useState(()=>!s||s.operator==="_null"||s.operator==="_between"?"":String(s.value??"")),[m,d]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[0]??""):""),[f,p]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[1]??""):""),x=(w,F)=>{if(w==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!F){e.setFilterValue(void 0);return}e.setFilterValue({operator:w,value:F})},h=(w,F)=>{if(!w||!F){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_between",value:[w,F]})},y=w=>{a(w),w==="_null"?(c(""),d(""),p(""),e.setFilterValue({operator:"_null",value:!0})):w==="_between"?(c(""),m&&f?h(m,f):e.setFilterValue(void 0)):(d(""),p(""),l?x(w,l):e.setFilterValue(void 0))},N=w=>{c(w),x(i,w)},T=w=>{d(w),h(w,f)},k=w=>{p(w),h(m,w)},$=()=>{a("_eq"),c(""),d(""),p(""),e.setFilterValue(void 0)};if(r.length===0)return null;const b=i==="_between",v=i==="_null";return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:i,onValueChange:y,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(w=>n.jsx(we,{value:w,children:Eo[w]},w))})]}),!v&&!b&&n.jsx(Qe,{type:"date",value:l,onChange:w=>N(w.target.value),className:"h-8 text-xs"}),b&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:"date",value:m,onChange:w=>T(w.target.value),className:"h-8 text-xs"}),n.jsx(Qe,{type:"date",value:f,onChange:w=>k(w.target.value),className:"h-8 text-xs"})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:$,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const ic={all:"All",true:"True",false:"False",_null:"Is null"};function lc(e){return e?e.operator==="_null"?"_null":e.operator==="_eq"&&e.value===!0?"true":e.operator==="_eq"&&e.value===!1?"false":"all":"all"}function cc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).includes("_null"),s=e.getFilterValue(),o=lc(s),i=r?["all","true","false","_null"]:["all","true","false"],a=c=>{switch(c){case"true":e.setFilterValue({operator:"_eq",value:!0});break;case"false":e.setFilterValue({operator:"_eq",value:!1});break;case"_null":e.setFilterValue({operator:"_null",value:!0});break;default:e.setFilterValue(void 0)}},l=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:a,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:i.map(c=>n.jsx(we,{value:c,children:ic[c]},c))})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:l,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}function uc(e,t,r,s){return!it(e)||!it(t)||!it(r)||s&&(!s.some(o=>o.name===t)||!s.some(o=>o.name===r))?null:`query Lookup${e} { ${e}(sort: [${t}_asc], limit: 100) { data { id: ${r} label: ${t} } } }`}function dc({column:e,joinTable:t,joinLabelColumn:r,joinFkColumn:s}){const o=$e(),a=Je().findTable(t),l=uc(t,r,s,a?.columns),c=mn(a?.columns.find(y=>y.name===s)),{data:m}=de.useQuery({queryKey:["fkLookup",t,r,s],queryFn:()=>o.query(l),staleTime:300*1e3,enabled:!!a&&!!l}),d=m?.[t]?.data??[],f=e.getFilterValue(),p=f?.operator==="_eq"&&f.value!=null?String(f.value):"all",x=y=>{if(y==="all"){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_eq",value:dt(y,c)})},h=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:p,onValueChange:x,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:"all",children:"All"}),d.map(y=>n.jsx(we,{value:String(y.id),children:String(y.label)},String(y.id)))]})]}),f!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}function Jn(e){return(e.columnDef.meta?.paramType??"").replace("!","")}function mc(e){return Jn(e)==="String"}function fc(e){return Vt(Jn(e))}function pc(e){return Zs(Jn(e))}function hc(e){return Jn(e)==="Boolean"}function gc(e){const t=e.columnDef.meta;return t?.joinTable?{joinTable:t.joinTable,joinLabelColumn:t.joinLabelColumn??"id",joinFkColumn:t.joinFkColumn??null,isSelfReference:t.isSelfReference===!0}:null}function xc(e){return e.columnDef.meta?.column}function Fo(e){const t=e.paramType.replace("!","");if(e.dbType){const r=e.dbType.toUpperCase();return e.maxLength&&(r.includes("VARCHAR")||r.includes("CHAR"))?`${r}(${e.maxLength})`:(r.includes("DECIMAL")||r.includes("NUMERIC"),r)}return t}function bc(e){const t=e.paramType.replace("!","");return e.isPrimaryKey?n.jsx(C.Key,{className:"size-3.5"}):Vt(t)?n.jsx(C.Hash,{className:"size-3.5"}):Zs(t)?n.jsx(C.Calendar,{className:"size-3.5"}):t==="Boolean"?n.jsx(C.ToggleLeft,{className:"size-3.5"}):n.jsx(C.Type,{className:"size-3.5"})}function yc({column:e,fkMeta:t}){const r=Fo(e),s=e.isNullable,o=e.isPrimaryKey,i=e.isIdentity,a=e.defaultValue;return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[bc(e),n.jsx("span",{className:"font-semibold text-foreground",children:e.label})]}),n.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-muted-foreground",children:"Type"}),n.jsx("dd",{className:"text-foreground font-medium",children:r}),n.jsx("dt",{className:"text-muted-foreground",children:"Nullable"}),n.jsx("dd",{className:"text-foreground",children:s?"Yes":"No"}),o&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Primary Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(C.Key,{className:"size-3"}),"Yes"]})]}),i&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Auto Increment"}),n.jsx("dd",{className:"text-foreground",children:"Yes"})]}),t&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Foreign Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(C.Link2,{className:"size-3"}),t.joinTable,t.isSelfReference&&n.jsx("span",{className:"ml-1 px-1 rounded bg-primary/10 text-[10px] font-medium",children:"self-ref"})]})]}),a!=null&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Default"}),n.jsx("dd",{className:"text-foreground font-mono text-xs truncate max-w-[150px]",children:String(a)})]}),e.maxLength!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max Length"}),n.jsx("dd",{className:"text-foreground",children:e.maxLength})]}),e.min!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Min"}),n.jsx("dd",{className:"text-foreground",children:e.min})]}),e.max!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max"}),n.jsx("dd",{className:"text-foreground",children:e.max})]})]})]})}function yn({column:e,table:t,title:r}){const s=t.options.meta?.onResetColumnWidths;if(!e.getCanSort())return n.jsx("span",{children:r});const o=e.getIsSorted(),i=e.getFilterValue()!==void 0,a=gc(e),l=a?.joinFkColumn??null,c=!l&&mc(e),m=!l&&fc(e),d=!l&&pc(e),f=!l&&hc(e),p=xc(e),x=n.jsxs(Q,{variant:"ghost",size:"sm",className:Y("-ml-2 h-7 text-xs data-[state=open]:bg-accent",o&&"text-foreground"),children:[n.jsx("span",{children:r}),i&&n.jsx(C.Filter,{className:"size-3 text-primary"}),o==="desc"?n.jsx(C.ArrowDown,{className:"size-4"}):o==="asc"?n.jsx(C.ArrowUp,{className:"size-4"}):n.jsx(C.ArrowUpDown,{className:"size-4"})]});return n.jsxs(gn,{openDelay:400,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsx("span",{className:"inline-flex",children:n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:x}),n.jsxs(An,{align:"start",children:[p&&n.jsxs(n.Fragment,{children:[n.jsxs(Wi,{className:"text-xs font-normal text-muted-foreground",children:[Fo(p),p.isNullable?" · nullable":" · required",p.isPrimaryKey?" · PK":"",a?` · FK → ${a.joinTable}`:""]}),n.jsx(yt,{})]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!1),children:[n.jsx(C.ArrowUp,{className:"size-3.5 text-muted-foreground"}),"Asc"]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!0),children:[n.jsx(C.ArrowDown,{className:"size-3.5 text-muted-foreground"}),"Desc"]}),o&&n.jsxs(bt,{onClick:()=>e.clearSorting(),children:[n.jsx(C.ArrowUpDown,{className:"size-3.5 text-muted-foreground"}),"Clear"]}),c&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(nc,{column:e})})]})]}),m&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(oc,{column:e})})]})]}),d&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(ac,{column:e})})]})]}),f&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(cc,{column:e})})]})]}),a&&l&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(dc,{column:e,joinTable:a.joinTable,joinLabelColumn:a.joinLabelColumn,joinFkColumn:l})})]})]}),e.getCanHide()&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:()=>e.toggleVisibility(!1),children:[n.jsx(C.EyeOff,{className:"size-3.5 text-muted-foreground"}),"Hide"]})]}),s&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:s,children:[n.jsx(C.RotateCcw,{className:"size-3.5 text-muted-foreground"}),"Reset column widths"]})]})]})]})})}),p&&n.jsx(bn,{align:"start",className:"w-64",children:n.jsx(yc,{column:p,fkMeta:a})})]})}const vc=5,jc=400,wc=200;function Cc(e){return e.filter(t=>!t.isPrimaryKey&&!_t(t)).slice(0,vc)}function Nc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview($id: ${s}) { ${e}(filter: { ${r}: { _eq: $id } } limit: 1) { data { ${o} } } }`}function kc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview(${r}) { ${e}(filter: ${s} limit: 1) { data { ${o} } } }`}function Sc(e,t,r,s,o,i,a){if(r.length===0)return null;if(s&&Gt(s)&&o){const d=Ri(o,s,t);if(!d)return null;const f=d.params.join(", ");return{query:kc(e,r,f,d.filterText),variables:d.variables,cacheKey:d.variables}}const l=t.columns.find(d=>d.name===a)?.paramType??"Int",c=io(l),m={id:dt(i,c)};return{query:Nc(e,r,a,c),variables:m,cacheKey:`${a}:${i}`}}function Tc({tableName:e,fkValue:t,filterColumn:r,join:s,sourceRow:o,children:i}){const[a,l]=u.useState(!1),c=Je(),m=$e(),d=c.findTable(e),f=d?Cc(d.columns):[],p=d?Sc(e,d,f,s,o,t,r):null,{data:x,isLoading:h}=de.useQuery({queryKey:["fkPreview",e,p?.cacheKey],queryFn:()=>m.query(p.query,p.variables),enabled:a&&!!p,staleTime:300*1e3}),y=x?.[e]?.data?.[0];return n.jsxs(gn,{openDelay:jc,closeDelay:wc,open:a,onOpenChange:l,children:[n.jsx(xn,{asChild:!0,children:i}),n.jsx(bn,{align:"start",className:"w-72",children:n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:d?.label??e}),h&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}),y&&n.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:f.map(N=>n.jsxs("div",{className:"contents",children:[n.jsx("dt",{className:"text-muted-foreground truncate",children:N.label}),n.jsx("dd",{className:"text-foreground truncate",children:Kn(y[N.name],N,{formatKey:Tl})})]},N.name))}),!h&&!y&&a&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Record not found"})]})})]})}const $c={json:C.Braces,xml:C.Code,"php-serialized":C.Database,binary:C.Binary,longtext:C.FileText,text:C.FileText},Ec={json:"JSON",xml:"XML","php-serialized":"PHP",binary:"Binary",longtext:"Text",text:"Text"};function Fc(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function _o({value:e,dbType:t,onExpand:r,deferred:s}){if(e===void 0&&s)return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(C.FileText,{className:"size-3.5"}),n.jsx("span",{className:"text-xs italic",children:"content"}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]});if(e==null)return n.jsx(Zt,{kind:"null"});const o=typeof e=="object"?JSON.stringify(e):String(e);if(o==="")return n.jsx(Zt,{kind:"empty"});const i=Bn(o,t);if(i==="text")return n.jsx("span",{children:o});if(i==="binary")return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(C.Binary,{className:"size-3.5"}),n.jsx("span",{className:"text-xs font-mono",children:xr(o)}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]});const a=$c[i],l=sl(o);return o.length>80||i==="json"||i==="xml"||i==="php-serialized"?n.jsxs("span",{className:"inline-flex items-center gap-1.5 max-w-full",children:[n.jsxs(gn,{openDelay:300,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 text-left hover:text-primary transition-colors min-w-0",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs truncate",children:l})]})}),n.jsxs(bn,{side:"bottom",align:"start",className:"w-[420px] max-h-[320px] p-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-border bg-muted/30",children:[n.jsx(a,{className:"size-3.5 text-muted-foreground"}),n.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ec[i]}),n.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[o.length," chars"]})]}),n.jsx("pre",{className:"p-3 text-xs font-mono overflow-auto max-h-[280px] whitespace-pre-wrap break-all",children:Fc(o,i)})]})]}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]}):n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs",children:o}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]})}const Po="gb",Ar="gs",zo=/^[_A-Za-z][_0-9A-Za-z]*$/;function Do(e,t){return!e||!t?null:t.columns.find(r=>r.name===e||r.graphQlName===e)??null}const en={field:"key",desc:!1};function _c(e,t){if(!e||!t)return null;const r=Do(e,t);return r&&/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(r.paramType.replace(/[!\[\]]/g,""))?r:null}function Mo(e,t,r){const s=new URLSearchParams(e);return r?s.set(t,r):s.delete(t),s}function Pc(e){const t=new URLSearchParams(e);return t.delete(Po),t.delete(Ar),t}function Io(e,t,r){const s=[];try{const o=JSON.parse(r);if(Array.isArray(o)&&o.length===4){const[i,a,l,c]=o,m=typeof i=="string"?t.columns.find(d=>d.name===i):void 0;m&&c===m.paramType&&typeof a=="string"&&pn(m.paramType).includes(a)&&s.push({[m.graphQlName]:{[a]:a==="_null"?!!l:l}})}}catch{}for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.operator!=="_null"&&(i.value===void 0||i.value===null||i.value==="")||s.push({[a.graphQlName]:{[i.operator]:i.operator==="_null"?!!i.value:i.value}})}return s.length===0?void 0:s.length===1?s[0]:{and:s}}function zc(e,t,r,s,o=null,i=en){for(const m of[e.name,e.graphQlName,t.graphQlName,...o?[o.graphQlName]:[]])if(!zo.test(m))throw new Error("Invalid schema-derived grouping name.");const a=Io(r,e,s),l=a?`($filter: ${e.graphQlName}Filter)`:"",c=[a?"filter: $filter":"",`groupBy: [${t.graphQlName}]`].filter(Boolean).join(", ");return{query:`query GridGrouping${l} { ${e.name}Aggregate(${c}) { ${t.graphQlName} _count${o?` _sum { ${o.graphQlName} }`:""} } }`,variables:a?{filter:a}:{},groupBy:t,sumBy:o,sort:i}}function Lo(e,t){return e.value===t.value?0:e.value===null||e.value===void 0?-1:t.value===null||t.value===void 0?1:typeof e.value=="number"&&typeof t.value=="number"?e.value-t.value:String(e.value).localeCompare(String(t.value))}function Dc(e,t,r=en){if(r.field==="count"){const o=e.count-t.count;return o!==0?r.desc?-o:o:Lo(e,t)}const s=Lo(e,t);return r.desc?-s:s}function Mc(e,t,r,s,o=en){const i=e?.[`${t.name}Aggregate`];return Array.isArray(i)?i.map(a=>{const l=a;return{value:l[r.graphQlName],count:Number(l._count??0),sum:s?l._sum?.[s.graphQlName]:void 0}}).sort((a,l)=>Dc(a,l,o)):[]}function Ic(e,t,r,s,o,i=[]){for(const d of[e.name,e.graphQlName,t.graphQlName,...e.columns.map(f=>f.graphQlName)])if(!zo.test(d))throw new Error("Invalid schema-derived grouping name.");const a=Io(s,e,o),l={[t.graphQlName]:r==null?{_null:!0}:{_eq:r}},c=a?{and:[a,l]}:l,m=e.columns.map(d=>d.graphQlName).join(" ");return{query:`query GridGroupMembers($filter: ${e.graphQlName}Filter, $sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int) { ${e.name}(filter: $filter sort: $sort limit: $limit offset: $offset) { total offset limit data { ${m} } } }`,variables:{filter:c,sort:[...i],limit:50,offset:0},responseKey:e.name}}function Lc(e,t){return!e||!t?"":(t.primaryKeys?.length??0)<=1?$t([e?.id]):He(e,t,0)}function Oc(e,t){const r=Math.max(0,t-1);return e<0?0:e>r?r:e}function Oo(e,t){return vr(e)===t?e:jr(t)}function Ac(e,t){const r=t.fieldName??t.destinationTable;return e[r]?.data??[]}function qc(e,t){const r=t.fieldName??t.destinationTable;return e[r]}function Vc(e,t){const r=t.fieldName??t.destinationTable,s=e[r];return s?.total??s?.data?.length??0}function vn(e,t,r={}){return{sortField:e.name,paramType:e.paramType,filterOperators:t,column:e,...r}}function Bc(e,t,r,s,o,i){const a=s.findTable(t.destinationTable),l=a?.labelColumn??"id",c=Gt(t),m=t.destinationTable===r.name,d=m?`Parent ${e.label}`:e.label;return{id:e.name,accessorKey:e.name,header:({column:f,table:p})=>n.jsx(yn,{column:f,table:p,title:d}),enableSorting:!0,meta:vn(e,o,{joinTable:t.destinationTable,joinLabelColumn:l,joinFkColumn:t.destinationColumnNames[0],isSelfReference:m,isCompositeFk:c}),cell:({row:f})=>{const p=qc(f.original,t);if(!p)return n.jsx(Zt,{kind:"null"});const x=Lc(p,a);return x?n.jsxs("span",{className:"group/fk inline-flex items-center gap-0.5",children:[n.jsx(Tc,{tableName:t.destinationTable,fkValue:x,filterColumn:t.destinationColumnNames[0],join:t,sourceRow:f.original,children:n.jsx(Pn,{to:"/"+a?.name+"/"+x,className:"text-primary hover:text-primary/80 hover:underline",children:p?.label})}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/fk:opacity-100 size-5 shrink-0",onClick:h=>{h.stopPropagation(),i({tableName:t.destinationTable,filterId:x})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]}):n.jsx(n.Fragment,{children:p?.label})}}}function Gc(e,t,r,s,o,i){if(t){const c=s.findTable(t.destinationTable)?.labelColumn??"id",m=t.destinationTable===r.name;return{id:e.name,accessorFn:d=>e.name?String(d?.[e.name]??""):"",cell:({row:d})=>Kn(d.original[e.name],e),header:({column:d,table:f})=>n.jsx(yn,{column:d,table:f,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType,joinTable:t.destinationTable,joinLabelColumn:c,joinFkColumn:Yi(t,e.name),isSelfReference:m,isCompositeFk:!0,isCompositeFkMember:!0})}}return e?.paramType==="DateTime"?{id:e.name,accessorFn:l=>xo(l?.[e.name]),cell:({row:l})=>{const c=l.original[e.name];return c==null||c===""?n.jsx(Zt,{kind:c===""?"empty":"null"}):xo(c)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}:_t(e)||Ft(e)?{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType}),cell:({row:l})=>n.jsx(_o,{value:l.original[e.name],dbType:e.dbType,deferred:_t(e),onExpand:i?()=>i(l.index,e.name):void 0})}:{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",cell:({row:l})=>{const c=l.original[e.name];if(typeof c=="string"&&c.length>1){const m=Bn(c);if(m==="json"||m==="xml"||m==="php-serialized")return n.jsx(_o,{value:c,dbType:e.dbType,onExpand:i?()=>i(l.index,e.name):void 0})}return Kn(c,e)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}}const Kc=(e,t,r,s)=>{if(!e||!t)return[];const o=e.columns.map(a=>{const l=e.singleJoins.find(d=>d.sourceColumnNames?.[0]===a.name),c=l?void 0:e.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(a.name)),m=pn(a.paramType);return l?Bc(a,l,e,t,m,s):Gc(a,c,e,t,m,r)}),i=e.multiJoins.map(a=>{const l=t.findTable(a.destinationTable),c=l?.labelColumn??"id",d=a.destinationTable===e.name?`Child ${l?.label??a.destinationTable}`:l?.label??a.destinationTable;return{id:`join_${a.fieldName??a.destinationTable}`,header:d,enableSorting:!1,enableHiding:!0,cell:({row:f})=>{const p=dl(f.original,e,f.index),x=Ac(f.original,a),h=Vc(f.original,a);if(h===0)return n.jsx("span",{className:"text-muted-foreground",children:"—"});const y=x.slice(0,10).map(T=>String(T[c]??"")).filter(Boolean),N=l?.label??a.destinationTable;return n.jsxs("span",{className:"group/fk inline-flex items-center gap-1",children:[n.jsxs(gn,{openDelay:300,closeDelay:100,children:[n.jsx(xn,{asChild:!0,children:n.jsxs(Pn,{to:"/"+l?.name+"/from/"+e.name+"/"+p,className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs font-medium text-primary hover:bg-muted hover:border-primary/40 transition-colors",children:[n.jsx(C.List,{className:"size-3"}),h]})}),n.jsxs(bn,{align:"start",sideOffset:6,className:"w-auto max-w-xs p-3",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2 mb-2",children:[n.jsx(C.List,{className:"size-3.5 text-primary"}),n.jsxs("span",{className:"text-xs font-semibold text-foreground",children:[h," ",N]})]}),n.jsxs("ul",{className:"space-y-0.5 text-xs text-foreground",children:[y.map((T,k)=>n.jsx("li",{className:"truncate",children:T},k)),h>10&&n.jsxs("li",{className:"text-muted-foreground italic",children:["… and ",h-10," more"]})]})]})]}),s&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-40 group-hover/fk:opacity-100 size-5 shrink-0 transition-opacity",onClick:T=>{T.stopPropagation(),s({tableName:a.destinationTable,filterTable:e.name,filterId:p,...Gt(a)?{}:{filterColumn:a.destinationColumnNames[0]}})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]})}}});return[...o,...i]};function Wc(e,t,r,s,o){if(!s&&!o)return wr(e,t);const i=$r(t,r,s,o);return i?wr(e,i.parentTable):wr(e,t)}function Jc(e,t,r,s,o,i){const{search:a}=hs(),l=_n(),c=a.get("filter")??"",m=a.get("cf")??"",d=a.get("gb"),f=a.get("gs"),p=u.useMemo(()=>yr(c).variables,[c]),x=Je(),h=$e(),[y,N]=u.useState([]),[T,k]=u.useState(en),[$,b]=u.useState(()=>jr(m)),[v,w]=u.useState(0),[F,j]=u.useState(50),V=u.useRef(e);e&&e!==V.current&&(V.current=e,y.length>0&&N([]),T!==en&&k(en),v!==0&&w(0)),u.useEffect(()=>{b(W=>Oo(W,m))},[m]);const S=u.useMemo(()=>Oo($,m),[$,m]),L=u.useRef(e?.name),A=L.current!==e?.name;A&&(L.current=e?.name);const D=u.useMemo(()=>A?null:Do(d,e),[A,d,e]),B=u.useMemo(()=>A?null:_c(f,e),[A,f,e]);u.useEffect(()=>{if(!A||!d)return;const me=Pc(a).toString();l(me?`?${me}`:"?")},[A,d,a,l]);const X=u.useMemo(()=>{if(!e)return"id";const W=zt(e)[0]?.name;if(W&&e.columns.some(ve=>ve.name===W))return W;const me=gl(e,ve=>!_t(ve)&&!Ft(ve));return me||(e.columns.find(ve=>!_t(ve)&&!Ft(ve))?.name??e.columns.at(0)?.name??"id")},[e]),E=u.useMemo(()=>{if(y.length>0&&e){const W=y[0];if(e.columns.some(Ne=>Ne.name===W.id))return[`${W.id}_${W.desc?"desc":"asc"}`]}return e?[`${X}_asc`]:[]},[y,e,X]),P=u.useMemo(()=>Sr(e,x,c,S,t,r,s),[e,x,c,S,t,r,s]),q=u.useMemo(()=>e?Gn(S,e).variables:{},[S,e]),U=u.useMemo(()=>{if(!e)return null;const W=co(e,c,S);return W.length===0?null:new Error(`These rows can't be shown because the filter can't be applied: ${W.join(" ")}`)},[e,c,S]),_=v*F,ce=u.useMemo(()=>({sort:E,limit:F,offset:_,...t&&e?Wc(t,e,x,r,s):{},...p,...q}),[E,F,_,t,e,x,r,s,p,q]),{isLoading:he,isFetching:Ue,error:Pe,data:ie}=de.useQuery({queryKey:["tableData",e?.name,P,ce],queryFn:({signal:W})=>h.query(P,ce,{signal:W}),enabled:!!P&&!!e&&E.length>0,placeholderData:(W,me)=>me?.queryKey?.[1]===e?.name?W:void 0}),se=u.useMemo(()=>e&&D?zc(e,D,S,c,B,T):null,[e,D,B,S,c,T]),ke=de.useQuery({queryKey:["tableGrouping",e?.name,se?.query,se?.variables],queryFn:({signal:W})=>h.query(se.query,se.variables,{signal:W}),enabled:se!==null,placeholderData:void 0}),Ae=u.useMemo(()=>e?Kc(e,x,o,i):[],[e,x,o,i]),re=u.useMemo(()=>t&&(r||s)&&e?$r(e,x,r,s):null,[t,r,s,e,x]);let Ee,Ie;if(re&&!Tr(re.childJoin)){const W=po(ie,re.parentTable.name,re.childField);Ee=W.data,Ie=W.total}else{const W=ie?.[e?.name??""];Ee=W?.data??[],Ie=W?.total??0}const Le=Math.max(1,Math.ceil(Ie/F));u.useEffect(()=>{const W=Oc(v,Le);W!==v&&w(W)},[v,Le]);const Ge=u.useCallback(W=>{const me=new URLSearchParams(a),Ne=vr(W);Ne?me.set("cf",Ne):me.delete("cf");const ve=me.toString();l(ve?`?${ve}`:"?")},[a,l]),Oe=u.useCallback(W=>{N(W),w(0)},[]),ye=u.useCallback(W=>{b(W),w(0),Ge(W)},[Ge]),ze=u.useCallback(W=>{w(W)},[]),O=u.useCallback(W=>{j(W),w(0)},[]),Z=u.useCallback(W=>{const me=Mo(a,Po,W);W||me.delete(Ar);const Ne=me.toString();l(Ne?`?${Ne}`:"?")},[a,l]),ee=u.useCallback(W=>{const Ne=Mo(a,Ar,W).toString();l(Ne?`?${Ne}`:"?")},[a,l]),Ce=e?.primaryKeys??[],xe=u.useMemo(()=>e?Sr(e,x,c,S,t,r,s,{fields:"export"}):null,[e,x,c,S,t,r,s]),qe=u.useCallback(async W=>{if(!xe||!e)return null;const me=kr(e),Ne=me.map(rt=>rt.label),ve=me.map(rt=>rt.name);return _r({headers:Ne,format:W.format,signal:W.signal,onProgress:W.onProgress,rowCap:W.rowCap,csv:{bom:!0},fetchPage:async(rt,Mt)=>{const be={...ce,limit:Mt,offset:rt},ft=await h.query(xe,be,{signal:W.signal});let Nt,Ye;if(re&&!Tr(re.childJoin)){const Xe=po(ft,re.parentTable.name,re.childField);Nt=Xe.data,Ye=Xe.total}else{const Xe=ft?.[e.name];Nt=Xe?.data??[],Ye=Xe?.total??0}return{rows:Nt.map(Xe=>ve.map(Qt=>Xe[Qt])),total:Ye}}})},[xe,e,ce,h,re]);return{columns:Ae,sorting:y,columnFilters:$,primaryKeys:Ce,pageIndex:v,pageSize:F,pageCount:Le,rows:Ee,totalRows:Ie,grouping:se?{column:se.groupBy,sumColumn:se.sumBy,rows:Mc(ke.data,e,se.groupBy,se.sumBy,se.sort),loading:ke.isLoading,error:ke.error,sort:se.sort,onSortChange:k,memberRequest:W=>Ic(e,se.groupBy,W,S,c,E)}:null,exportRows:qe,loading:he,fetching:Ue&&!he,error:U??Pe,onSortingChange:Oe,onColumnFiltersChange:ye,onPageIndexChange:ze,onPageSizeChange:O,onGroupingChange:Z,onGroupingSumChange:ee}}const Qc=new Set(["tableData","editRecord","tableRowCounts","m2mRows","fkPreview"]),Hc=new Set(["tableRef","tableRefValue","compositeTableRef","m2mTargets"]);function jn(e,t){return e.invalidateQueries({predicate:r=>{const[s,o]=r.queryKey;return typeof s!="string"?!1:Qc.has(s)?!0:Hc.has(s)?o===t:!1}})}function Uc(e){return typeof e=="object"&&e!==null}function Ao(e,t){if(e==null)return null;if(!t)return e;const r=ut(t);if(Bt(t))return String(e);if(qt(t)){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.trunc(s):e}if(r==="Float"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?s:e}return r==="Boolean"?typeof e=="boolean"?e:e==="true"||e===1:String(e)}function Qn(e){je(e.name,"delete mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>{const h=new Map;for(const y of e.columns)h.set(y.name,y.paramType);return h},[e]),i=u.useMemo(()=>e.primaryKeys??[],[e]),a=h=>{if(i.length===0)throw new Error(`Cannot delete from '${e.name}': the table has no primary key.`);const y={};if(Uc(h)){for(const T of i){const k=h[T];if(k==null)throw new Error(`Cannot delete row: missing value for primary-key column '${T}'.`);y[T]=Ao(k,o.get(T))}return y}if(i.length!==1)throw new Error(`Cannot delete from '${e.name}': composite primary key requires an object key, not a scalar.`);if(h==null)throw new Error(`Cannot delete row: missing value for primary-key column '${i[0]}'.`);const N=i[0];return y[N]=Ao(h,o.get(N)),y},l=u.useMemo(()=>`mutation deleteSingle($detail: Delete_${e.name}){
|
|
79
91
|
${e.name}(delete: $detail)
|
|
80
|
-
}`,[e]),
|
|
81
|
-
${e.name}
|
|
82
|
-
}`,[e]),
|
|
83
|
-
|
|
92
|
+
}`,[e]),c=u.useMemo(()=>`mutation deleteMany($delta: ${e.name}_delta){
|
|
93
|
+
${e.name}(delta: $delta)
|
|
94
|
+
}`,[e]),m=de.useMutation({mutationFn:h=>t.query(l,{detail:h}),onSuccess:()=>{jn(r,e.name),s("Row deleted")}}),d=de.useMutation({mutationFn:h=>t.query(c,{delta:{deleted:h}}),onSuccess:(h,y)=>{jn(r,e.name);const N=y.length;s(`${N} ${N===1?"row":"rows"} deleted`)}}),f=h=>{let y;try{y=a(h)}catch(N){return Promise.reject(N)}return m.mutateAsync(y)},p=h=>{let y;try{y=h.map(N=>a(N))}catch(N){return Promise.reject(N)}return d.mutateAsync(y)},x=m.error??d.error;return{deleteRow:f,deleteRows:p,isPending:m.isPending||d.isPending,error:x}}function Yc(e){return(e.inserted?.length??0)+(e.updated?.length??0)+(e.deleted?.length??0)}function qo(e){je(e.name,"delta mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>`mutation saveDelta($delta: ${e.name}_delta){
|
|
95
|
+
${e.name}(delta: $delta)
|
|
96
|
+
}`,[e]),i=de.useMutation({mutationFn:a=>t.query(o,{delta:a}),onSuccess:(a,l)=>{jn(r,e.name);const c=Yc(l);s(`${c} ${c===1?"change":"changes"} saved`)}});return{saveDelta:a=>i.mutateAsync(a),isPending:i.isPending,error:i.error}}function Rc(e){return Vt(e.paramType)}function Xc(e){return qt(e.paramType)}const Zc={Int:{min:-2147483648,max:2147483647},Short:{min:-32768,max:32767},Byte:{min:0,max:255}},eu=-(2n**63n),tu=2n**63n-1n;function nu(e){const t=(e.dbType??"").toLowerCase().trim(),r=t.includes("(")?t.slice(0,t.indexOf("(")).trimEnd():t;if(r==="datetimeoffset"||r==="datetime"||r==="datetime2"||r==="smalldatetime"||r.startsWith("timestamp"))return"datetime";if(r==="date")return"date";if(r.startsWith("time"))return"time"}function ru(e){const t=/^[+-]?(\d*)(?:\.\d*)?$/.exec(e.trim());return t?t[1].replace(/^0+/,"").length:void 0}function su(e){return e.startsWith("^")?e:`^(?:${e})$`}function ou(e){if(e!==e.trim()||/\s/.test(e))return!1;const t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return!1;const r=e.slice(t+1);return r.includes(".")&&!r.startsWith(".")&&!r.endsWith(".")}function au(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function qr(e,t,r){const s=e.label;if(r&&(t==null||t===""))return`${s} is required`;if(t==null||t==="")return;if(typeof t=="string"){if(e.pattern){let i;try{i=new RegExp(su(e.pattern))}catch{return`${s} has an invalid validation pattern`}if(!i.test(t))return e.patternMessage||`${s} format is invalid`}if(e.minLength&&t.length<e.minLength)return`${s} must be at least ${e.minLength} characters`;if(e.maxLength&&t.length>e.maxLength)return`${s} must be at most ${e.maxLength} characters`;if(e.inputType==="email"&&!ou(t))return"Invalid email address";if(e.inputType==="url"&&!au(t))return"Invalid URL"}const o=nu(e);if(o&&typeof t=="string"){if(!(o==="time"?/^\d{1,2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(t.trim()):!Number.isNaN(new Date(t).getTime())))return`${s} must be a valid ${o==="datetime"?"date/time":o}`;if(o!=="time"){const a=new Date(t).getTime(),l=typeof e.min=="string"?new Date(e.min).getTime():NaN,c=typeof e.max=="string"?new Date(e.max).getTime():NaN;if(!Number.isNaN(l)&&a<l)return`${s} must be on or after ${e.min}`;if(!Number.isNaN(c)&&a>c)return`${s} must be on or before ${e.max}`}return}if(ut(e.paramType)==="BigInt"&&typeof t=="string"&&t.trim()!==""){const i=t.trim();if(!/^[+-]?\d+$/.test(i))return`${s} must be a whole number`;const a=BigInt(i);return a<eu||a>tu?`${s} is out of range for a 64-bit integer`:void 0}if(e.precision!=null&&(typeof t=="string"||typeof t=="number")){const i=Math.max(e.precision-(e.scale??0),0),a=ru(String(t));if(a!==void 0&&a>i)return`${s} must have at most ${i} digits before the decimal point`}if(Rc(e)){const i=Number(t);if(!Number.isFinite(i))return`${s} must be a number`;if(Xc(e)&&!Number.isInteger(i))return`${s} must be a whole number`;const a=Zc[ut(e.paramType)];if(a&&(i<a.min||i>a.max))return`${s} must be between ${a.min} and ${a.max}`;const l=e.min==null?NaN:Number(e.min),c=e.max==null?NaN:Number(e.max);if(!Number.isNaN(l)&&i<l)return`${s} must be at least ${e.min}`;if(!Number.isNaN(c)&&i>c)return`${s} must be at most ${e.max}`}}function Hn(e,t){const r=[];for(const s of e){const o=t[s.name];if(o==null||o==="")continue;const i=qr(s,o,!1);i&&r.push(i)}return r}const Vo=e=>Vt(e)&&!Bt(e),iu=["Boolean","Boolean!"];function Bo(e,t,r){const s=ut(t),o=qt(t);if(typeof e=="number"){if(Number.isFinite(e)&&(!o||Number.isInteger(e)))return e;throw new Error(`Invalid ${s} value for column '${r}'.`)}const i=String(e).trim();if(!(o?/^[+-]?\d+$/.test(i):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(i)))throw new Error(`Invalid ${s} value for column '${r}'.`);const l=Number(i);if(!Number.isFinite(l))throw new Error(`Invalid ${s} value for column '${r}'.`);return l}function Un(e,t,r,s,o){const i={...e};for(const{column:a}of t){if(i[a.name]===null){i[a.name]=o?void 0:null;continue}if(Vo(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:Bo(l,a.paramType,a.name)}if(Bt(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:String(l)}if(iu.some(l=>l===a.paramType)){const l=i[a.name];a.isNullable&&l==null?i[a.name]=o?void 0:null:i[a.name]=!!l}if(Ft(a)){const l=i[a.name];if(typeof l=="string"&&l.trim()!=="")try{i[a.name]=JSON.parse(l)}catch{}}}if(!o&&s)for(const a of r){const l=s[a.name];Vo(a.paramType)?i[a.name]=l==null?null:Bo(l,a.paramType,a.name):i[a.name]=l}return i}function lu(e,t,r,s,o){const i=t.map(a=>({column:a}));return s.map(a=>{const l=mt(a,e);if(!l)throw new Error("Cannot bulk edit: a selected row has no resolvable primary key.");const c={};for(const d of t)c[d.name]=a[d.name]??null;Object.assign(c,o);const m=Hn(t,c);if(m.length>0)throw new Error(m.join(" "));return Un(c,i,r,l,!1)})}function cu(e,t,r,s,o){return s.map(i=>{const a=o(i);if(!a||Object.keys(a).length===0)throw new Error("Cannot save: a fetched row carries no staged changes.");const l=mt(i,e);if(!l)throw new Error("Cannot save: an edited row has no resolvable primary key.");const c=t.filter(f=>!f.isNullable||f.name in a),m={};for(const f of c)m[f.name]=i[f.name]??null;Object.assign(m,a);const d=Hn(c,m);if(d.length>0)throw new Error(d.join(" "));return Un(m,c.map(f=>({column:f})),r,l,!1)})}function wn(e,t,r,s){je(e.name,"table mutation table name");const o=$e(),i=de.useQueryClient(),{toast:a}=vt(),l=s===void 0||s==="",c=u.useMemo(()=>`mutation updateSingle($detail: Update_${e.name}){
|
|
97
|
+
${e.name}(update: $detail)
|
|
98
|
+
}`,[e]),m=u.useMemo(()=>`mutation insertSingle($detail: Insert_${e.name}){
|
|
99
|
+
${e.name}(insert: $detail)
|
|
100
|
+
}`,[e]),d=de.useMutation({mutationFn:$=>o.query(c,{detail:$}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} saved`)}}),f=de.useMutation({mutationFn:$=>o.query(m,{detail:$}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} created`)}}),p=u.useMemo(()=>l||!s?null:fn(s,e),[l,s,e]),[x,h]=u.useState(null),y=$=>{const b=$ instanceof Error?$:new Error(String($));return h(b),Promise.reject(b)},N=$=>{if(h(null),!p||r.length===0)return y(new Error(`Cannot update ${e.label??e.name}: the record has no resolvable primary key.`));const b=Hn(t.map(w=>w.column),$);if(b.length>0)return y(new Error(b.join(" ")));let v;try{v=Un($,t,r,p,!1)}catch(w){return y(w)}return d.mutateAsync(v)},T=$=>{h(null);const b=Hn(t.map(w=>w.column),$);if(b.length>0)return y(new Error(b.join(" ")));let v;try{v=Un($,t,r,null,!0)}catch(w){return y(w)}return f.mutateAsync(v)},k=x??d.error??f.error;return{update:N,insert:T,isPending:d.isPending||f.isPending,error:k}}const uu=1e3,du=50;function Go(e){const t=e.labelColumn||zt(e)[0]?.name||e.columns[0]?.name;if(!t)throw new Error(`Table '${e.name}' has no usable label column for a reference dropdown.`);return t}function mu(e,t,r){je(e.name,"reference table name"),je(t,"reference key column");const s=Go(e);if(je(s,"reference label column"),!e.columns.some(d=>d.name===t))throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const i=e.columns.find(d=>d.name===s)?.paramType?.replace("!","")==="String",a=!!r&&r.trim()!==""&&i,l=a?"$limit: Int, $search: String":"$limit: Int",c=a?`filter: {${s}: {_contains: $search}} `:"";return{query:`query Get_${e.name}_Ref(${l}) {
|
|
101
|
+
values: ${e.name}(${c}limit: $limit sort: [${s}_asc]) {
|
|
84
102
|
data {
|
|
85
|
-
key: ${
|
|
86
|
-
label: ${
|
|
103
|
+
key: ${t}
|
|
104
|
+
label: ${s}
|
|
87
105
|
}
|
|
88
106
|
}
|
|
89
|
-
}`,
|
|
90
|
-
${e.name}(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
107
|
+
}`,labelColumn:s,serverSearch:i}}function fu(e,t){je(e.name,"reference table name"),je(t,"reference key column");const r=Go(e);je(r,"reference label column");const s=e.columns.find(a=>a.name===t);if(!s)throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const o=s.paramType.replace("!","");return{query:`query Get_${e.name}_RefValue($key: ${o}) {
|
|
108
|
+
values: ${e.name}(filter: {${t}: {_eq: $key}} limit: 1) {
|
|
109
|
+
data {
|
|
110
|
+
key: ${t}
|
|
111
|
+
label: ${r}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}`,keyType:o}}function pu(e,t){return dt(t,e)}function Ko(e,t){return e?.data?.find(r=>r.graphQlName===t)}function hu(e,t,r,s="",o=!0){const i=$e(),a=u.useMemo(()=>Ko(e,t),[e,t]),l=s.trim(),c=u.useMemo(()=>e.loading||e.error||!a?null:mu(a,r,l),[r,a,e.loading,e.error,l]),m=c?.serverSearch?l:"",{isLoading:d,error:f,data:p}=de.useQuery({queryKey:["tableRef",t,r,m],queryFn:({signal:x})=>i.query(c.query,m?{limit:du,search:m}:{limit:uu},{signal:x}),enabled:!!c&&o});return{loading:d||e.loading,error:f||e.error,data:p?.values?.data??[],serverSearch:c?.serverSearch??!1}}function gu(e,t,r,s){const o=$e(),i=u.useMemo(()=>Ko(e,t),[e,t]),a=!e.loading&&!e.error&&!!i&&s!=null&&s!=="",l=u.useMemo(()=>a?fu(i,r):null,[a,i,r]),{isLoading:c,error:m,data:d}=de.useQuery({queryKey:["tableRefValue",t,r,String(s??"")],queryFn:({signal:f})=>o.query(l.query,{key:pu(l.keyType,s)},{signal:f}),enabled:!!l});return{loading:c,error:m||e.error,value:d?.values?.data?.at(0)??null}}const xu=500,bu=50;function yu(e,t,r,s={}){const o=$e(),{search:i="",enabled:a=!0,currentValues:l=null}=s,c=i.trim(),m=u.useMemo(()=>e?.data?.find(S=>S.graphQlName===t),[e,t]),d=u.useMemo(()=>m?.labelColumn||r[0],[m,r]),f=u.useMemo(()=>m?.columns.find(L=>L.name===d)?.paramType?.replace("!","")==="String",[m,d]),p=u.useMemo(()=>{if(!m||r.length===0||!it(t)||!it(d))return!1;const S=new Set(m.columns.map(L=>L.name));return S.has(d)?r.every(L=>it(L)&&S.has(L)):!1},[m,t,r,d]),x=u.useMemo(()=>{if(!m||!p)return"";const S=new Set(r);return S.add(d),Array.from(S).join(" ")},[m,p,r,d]),h=!!c&&f,y=u.useMemo(()=>{if(e.loading||e.error||!m||r.length===0||!p)return null;const S=h?"($limit: Int, $search: String)":"($limit: Int)",L=h?`filter: {${d}: {_contains: $search}} `:"";return`query Get_${t}_CompositeRef${S} { values: ${t}(${L}limit: $limit sort: [${d}_asc]) { data { ${x} } } }`},[m,t,x,d,h,e.loading,e.error,r.length,p]),N=f?c:"",{isLoading:T,error:k,data:$}=de.useQuery({queryKey:["compositeTableRef",t,r.join("|"),N],queryFn:()=>o.query(y,N?{limit:bu,search:N}:{limit:xu}),enabled:!!y&&a}),b=u.useMemo(()=>{if(!m||!$)return[];const S={primaryKeys:r};return($.values?.data??[]).map((L,A)=>{const D={};for(const X of r)D[X]=L[X];const B=He(L,S,A);return{route:B,values:D,label:String(L[d]??B)}})},[m,r,d,$]),v=u.useMemo(()=>{if(!l)return"";const S=[];for(const L of r){const A=l[L];if(A==null||A==="")return"";S.push(A)}return $t(S)},[l,r]),w=v===""||b.some(S=>S.route===v),F=u.useMemo(()=>{if(!m||!p||w||v===""||!l)return null;const S=new Map(m.columns.map(E=>[E.name,E])),L=[],A=[],D={};for(let E=0;E<r.length;E++){const P=r[E],q=mn(S.get(P)),U=`k${E}`;A.push(`$${U}: ${q}`),L.push(`{${P}: {_eq: $${U}}}`),D[U]=dt(l[P],q)}const B=L.length===1?L[0]:`{and: [${L.join(", ")}]}`;return{query:`query Get_${t}_CompositeRefValue(${A.join(", ")}) { values: ${t}(filter: ${B} limit: 1) { data { ${x} } } }`,variables:D}},[m,t,x,r,w,v,l,p]),{data:j}=de.useQuery({queryKey:["compositeTableRefValue",t,v],queryFn:()=>o.query(F.query,F.variables),enabled:!!F}),V=u.useMemo(()=>{const S=j?.values?.data?.[0];if(!S)return b;const L={};for(const D of r)L[D]=S[D];const A=$t(r.map(D=>S[D]));return b.some(D=>D.route===A)?b:[{route:A,values:L,label:String(S[d]??A)},...b]},[b,j,r,d]);return{loading:T||e.loading,error:k||e.error,data:V,serverSearch:f}}const vu=new Set(["DateTime","DateTime!"]);function Yn(e){return vu.has(e.paramType)}function Vr(e){return ho(e)==="datetime"}function Br(e,t){if(!e)return"";const r=e.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2})?))?/);if(!r||r[1]==="0001-01-01")return"";if(!t||!r[2])return r[1];const s=r[2].length===5?`${r[2]}:00`:r[2];return`${r[1]}T${s}`}function ju(e,t,r){const s={...e};for(const o of r){if(!Yn(o))continue;const i=t[o.name];typeof i!="string"||i===""||Br(i,Vr(o))===s[o.name]&&(s[o.name]=i)}return s}function Wo(e,t,r){const s=e;return String(s.label??s[t]??"").toLowerCase().includes(r.toLowerCase())}const jt=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Root,{"data-slot":"dialog",...e}));jt.displayName="Dialog";const wu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Trigger,{"data-slot":"dialog-trigger",...e}));wu.displayName="DialogTrigger";const Jo=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Portal,{"data-slot":"dialog-portal",...e}));Jo.displayName="DialogPortal";const Cu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Close,{"data-slot":"dialog-close",...e}));Cu.displayName="DialogClose";const Qo=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Overlay,{ref:r,"data-slot":"dialog-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t}));Qo.displayName="DialogOverlay";const wt=Ve.forwardRef(({className:e,children:t,showCloseButton:r=!0,...s},o)=>n.jsxs(Jo,{"data-slot":"dialog-portal",children:[n.jsx(Qo,{}),n.jsxs(R.Dialog.Content,{ref:o,"data-slot":"dialog-content",className:Y("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...s,children:[t,r&&n.jsxs(R.Dialog.Close,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(C.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));wt.displayName="DialogContent";const tn=Ve.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,"data-slot":"dialog-header",className:Y("flex flex-col gap-2 text-center sm:text-left",e),...t}));tn.displayName="DialogHeader";const Gr=Ve.forwardRef(({className:e,showCloseButton:t=!1,children:r,...s},o)=>n.jsxs("div",{ref:o,"data-slot":"dialog-footer",className:Y("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...s,children:[r,t&&n.jsx(R.Dialog.Close,{asChild:!0,children:n.jsx(Q,{variant:"outline",children:"Close"})})]}));Gr.displayName="DialogFooter";const Ct=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Title,{ref:r,"data-slot":"dialog-title",className:Y("text-lg leading-none font-semibold",e),...t}));Ct.displayName="DialogTitle";const Kt=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Description,{ref:r,"data-slot":"dialog-description",className:Y("text-sm text-muted-foreground",e),...t}));Kt.displayName="DialogDescription";function Cn({className:e,...t}){return n.jsx(R.Checkbox.Root,{"data-slot":"checkbox",className:Y("peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",e),...t,children:n.jsx(R.Checkbox.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:n.jsx(C.CheckIcon,{className:"size-3.5"})})})}function Wt({className:e,...t}){return n.jsx(R.Label.Root,{"data-slot":"label",className:Y("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Kr({open:e,onOpenChange:t,title:r,description:s,confirmLabel:o="Confirm",cancelLabel:i="Cancel",variant:a="default",isPending:l=!1,onConfirm:c}){return n.jsx(jt,{open:e,onOpenChange:t,children:n.jsxs(wt,{showCloseButton:!1,children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:r}),n.jsx(Kt,{asChild:!0,children:n.jsx("div",{children:s})})]}),n.jsxs(Gr,{children:[n.jsx(Q,{variant:"outline",onClick:()=>t(!1),disabled:l,children:i}),n.jsx(Q,{variant:a==="destructive"?"destructive":"default",onClick:c,disabled:l,children:l?`${o}…`:o})]})]})})}function Nu({name:e,label:t,value:r,dbType:s,onChange:o,onBlur:i,required:a,invalid:l}){const c=Et(s),m=gr(s),d=Bn(r,s),[f,p]=u.useState(null),x=u.useRef(null),h=u.useCallback(()=>{const k=x.current;k&&(k.style.height="auto",k.style.height=Math.min(k.scrollHeight,400)+"px")},[]);if(u.useEffect(h,[r,h]),c)return n.jsx(ku,{name:e,label:t,value:r});if(!m&&d==="text")return null;const y=()=>{if(p(null),d==="json")try{o(JSON.stringify(JSON.parse(r),null,2))}catch{p("Invalid JSON")}else if(d==="xml")try{const k=r.replace(/>\s*</g,`>
|
|
94
115
|
<`).replace(/(<[^/][^>]*[^/]>)\n/g,`$1
|
|
95
|
-
`).trim();o(
|
|
96
|
-
value: ${
|
|
97
|
-
data { ${
|
|
116
|
+
`).trim();o(k)}catch{p("Could not format XML")}},N=()=>{if(p(null),d==="json")try{o(JSON.stringify(JSON.parse(r)))}catch{p("Invalid JSON")}else d==="xml"&&o(r.replace(/\n\s*/g,"").trim())},T=d==="json"||d==="xml";return n.jsxs("div",{className:"grid gap-1",children:[T&&n.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:y,children:[n.jsx(C.WrapText,{className:"size-3"}),"Format"]}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:N,children:"Minify"})]}),n.jsx("textarea",{ref:x,id:e,value:r,onChange:k=>{o(k.target.value),p(null)},onBlur:i,required:a,"aria-invalid":l,className:Y("flex w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","resize-none min-h-[80px] max-h-[400px]",l&&"border-destructive")}),f&&n.jsx("p",{className:"text-xs text-destructive",children:f})]})}function ku({name:e,label:t,value:r}){const s=r?Math.ceil(r.length*3/4):0,o=s<1024?`${s} bytes`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`,i=r?r.slice(0,256)+(r.length>256?"...":""):"(empty)",a=r?so(r):null;return n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(Wt,{htmlFor:e,className:"flex items-center gap-1.5",children:[n.jsx(C.Binary,{className:"size-3.5 text-muted-foreground"}),t,n.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(binary, ",o,")"]})]}),a?.kind==="image"?n.jsx("img",{src:oo(r,a.mime),alt:t,className:"max-h-[160px] w-fit rounded-md border border-input"}):n.jsx("div",{className:"rounded-md border border-input bg-muted/30 p-3 max-h-[160px] overflow-auto",children:n.jsx("pre",{className:"text-xs font-mono text-muted-foreground break-all whitespace-pre-wrap",children:i})}),n.jsx("p",{className:"text-xs text-muted-foreground",children:"Binary fields are read-only in this editor."})]})}const Wr=["Boolean","Boolean!"],Dt="__none__";function Ho(e,t){return e==null||e===""?t?Dt:"":String(e)}function Jr(e){return t=>{t!==""&&e(t)}}function Nn(e,t){const r=({value:s})=>qr(e,s,t);return{onSubmit:r,onBlur:r}}function Rn(e,t){const r=e.state.meta.errors.length>0;return{hasError:r,ariaProps:{"aria-invalid":r,"aria-describedby":r?t:void 0}}}function Uo(e){return Et(e.dbType)||gr(e.dbType)||Ft(e)}const Yo={filterText:"",variables:{},params:[]};function Su(e,t){return t!=="none"||(e.enumValues?.length??0)>0}function Tu(e,t){return u.useMemo(()=>{const r=e?.data?.find(l=>l.graphQlName===t),o=r.columns.filter(l=>!l.isReadOnly&&!l.isIdentity).map(l=>{const c=r.singleJoins.find(d=>d.sourceColumnNames[0]===l.graphQlName);if(c)return{column:l,join:c,fkRole:Gt(c)?"anchor-composite":"anchor-single"};const m=r.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(l.graphQlName));return m?{column:l,join:m,fkRole:"member-composite"}:{column:l,fkRole:"none"}}),i=new Map(r.columns.map(l=>[l.name,l])),a=(r.primaryKeys??[]).map(l=>i.get(l)).filter(l=>!!l);return[r,o,a]},[e,t])}function $u(e,t,r){const s=$e(),o=r===void 0||r==="",i=u.useMemo(()=>o?null:fn(r,e),[o,r,e]),a=u.useMemo(()=>o||!i?Yo:qn(i,e)??Yo,[o,i,e]),l=!o&&a.filterText==="",c=u.useMemo(()=>{const N=a.params.length>0?a.params.join(", "):"";return`query GetSingleEdit_${e.name}(${N}){
|
|
117
|
+
value: ${e.name}(filter: ${a.filterText||"{}"}) {
|
|
118
|
+
data { ${t.map(({column:T})=>T.name).join(" ")} }
|
|
98
119
|
}
|
|
99
|
-
}`},[a,l,h]),{isLoading:g,error:b,data:N}=le.useQuery({queryKey:["editRecord",a.name,r],queryFn:()=>o.query(y,h.variables),enabled:!!a&&!i&&h.filterText!==""}),T=f.useMemo(()=>N?.value?.data?.at(0)??{},[N]),j=f.useMemo(()=>{const x={};for(const{column:k}of l)if(as.some(V=>V===k.paramType)){const V=T[k.name]?.split("T")?.[0];x[k.name]=V==="0001-01-01"?"":V??""}else jn.some(V=>V===k.paramType)?x[k.name]=!!T[k.name]:x[k.name]=T[k.name]??"";return x},[T,l]),$=Pn.useForm({defaultValues:j,onSubmit:async({value:x})=>{await(i?d.insert:d.update)({...x}),s()}});if(g&&!i)return null;if(b)return t.jsxs("div",{children:["Error: ",b.message]});const S=T?.[m]??r,D=l.filter(({column:x})=>jn.some(k=>k===x.paramType)),w=l.filter(({column:x})=>jt(x.dbType)||Bt(x.dbType)),L=l.filter(({column:x})=>!jn.some(k=>k===x.paramType)&&!jt(x.dbType)&&!Bt(x.dbType));return t.jsx(kt,{open:!0,onOpenChange:x=>{x||s()},children:t.jsxs(Tt,{showCloseButton:!1,className:"sm:max-w-2xl max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border bg-muted/30 shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx(St,{className:"text-sm font-semibold truncate",children:i?`New ${p}`:`${p} : ${S}`}),t.jsxs(Wt,{className:"sr-only",children:[i?"Create":"Edit"," ",p," record"]})]}),t.jsx(q,{variant:"ghost",size:"icon-sm",onClick:s,"aria-label":"Close",className:"shrink-0 -mr-1",children:t.jsx(v.X,{className:"size-4"})})]}),d.error&&t.jsxs("div",{className:"flex items-center gap-2 px-5 py-2 bg-destructive/10 border-b border-destructive/20 text-destructive text-sm shrink-0",children:[t.jsx(v.AlertCircle,{className:"size-3.5 shrink-0"}),t.jsx("span",{className:"truncate",children:d.error.message})]}),t.jsxs("form",{onSubmit:x=>{x.preventDefault(),x.stopPropagation(),$.handleSubmit()},className:"flex flex-col flex-1 min-h-0",children:[t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[L.length>0&&t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:L.map(({column:x,join:k,fkRole:V})=>t.jsx(vl,{column:x,join:k,fkRole:V,form:$,schema:n},x.name))}),D.length>0&&t.jsx("div",{className:L.length>0?"mt-4 pt-4 border-t border-border":"",children:t.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2",children:D.map(({column:x})=>t.jsx(Nl,{column:x,form:$},x.name))})}),w.length>0&&t.jsx("div",{className:L.length>0||D.length>0?"mt-4 pt-4 border-t border-border":"",children:t.jsx("div",{className:"grid gap-3",children:w.map(({column:x})=>t.jsx(Cl,{column:x,form:$},x.name))})})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border bg-muted/30 shrink-0",children:[t.jsx(q,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsxs(q,{type:"submit",size:"sm",disabled:d.isPending,children:[d.isPending?t.jsx(v.LoaderCircle,{className:"size-3.5 animate-spin"}):t.jsx(v.Save,{className:"size-3.5"}),i?"Create":"Save"]})]})]})]})})}function Jt(){const{table:e,editid:n}=on(),r=Dt();return e?t.jsx(is,{table:e,editid:n??"",onClose:()=>r("../..")}):t.jsx("div",{children:"Table missing"})}function is({table:e,editid:n,onClose:r}){const s=je();return e?s.loading?t.jsx("div",{children:"Loading..."}):s.error?t.jsxs("div",{children:["Error: ",s.error.message]}):t.jsx(gl,{table:e,schema:s,editid:n,onClose:r}):t.jsx("div",{children:"Table missing"})}function bl({current:e,max:n}){const r=n-e,s=r<=10&&r>0,o=r<=0;return t.jsx("div",{className:"text-xs text-right mt-0.5","aria-live":"polite",children:t.jsxs("span",{className:o?"text-destructive font-medium":s?"text-amber-500":"text-muted-foreground",children:[e,"/",n]})})}function yl({min:e,max:n,step:r}){if(e===void 0&&n===void 0)return null;let s="";return e!=null&&n!==void 0&&n!==null?s=`Range: ${e} to ${n}`:e!=null?s=`Min: ${e}`:n!=null&&(s=`Max: ${n}`),r!=null&&r!==1&&(s+=` (step: ${r})`),t.jsx("div",{className:"text-xs text-muted-foreground mt-0.5","aria-live":"polite",children:s})}function vl({column:e,join:n,fkRole:r,form:s,schema:o}){const i=e.name,a=!e.isNullable;if(r==="member-composite")return null;const l=as.some(h=>h===e.paramType),c=hl.some(h=>h===e.paramType),m=e.maxLength&&e.maxLength>0&&!l&&!c;if(e.enumValues&&e.enumValues.length>0)return t.jsx(jl,{column:e,form:s,isRequired:a});if(n&&o)return r==="anchor-composite"?t.jsx(kl,{column:e,join:n,form:s,schema:o,isRequired:a}):t.jsx(wl,{column:e,join:n,form:s,schema:o,isRequired:a});const p=e.inputType||(l?"date":c?"number":"text"),d={onSubmit:({value:h})=>dl(e,h,a)};return t.jsx(s.Field,{name:i,validators:d,children:h=>t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(nt,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,a&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsx(Ne,{id:i,type:p,value:h.state.value??"",onChange:y=>h.handleChange(y.target.value),onBlur:h.handleBlur,required:a,maxLength:e.maxLength,minLength:e.minLength,min:e.min,max:e.max,step:e.step,pattern:e.pattern,title:e.patternMessage,"aria-invalid":h.state.meta.errors.length>0,className:"h-8 text-sm"}),m&&t.jsx(bl,{current:String(h.state.value??"").length,max:e.maxLength}),c&&(e.min!==void 0||e.max!==void 0)&&t.jsx(yl,{min:e.min,max:e.max,step:e.step}),t.jsx(Ht,{errors:h.state.meta.errors})]})})}function jl({column:e,form:n,isRequired:r}){const s=e.name,o=e.enumValues||[],i=e.enumLabels&&e.enumLabels.length===o.length?e.enumLabels:o;return t.jsx(n.Field,{name:s,validators:r?{onSubmit:({value:a})=>{if(a==null||a==="")return`${e.label} is required`}}:void 0,children:a=>t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(nt,{htmlFor:s,className:"text-xs text-muted-foreground",children:[e.label,r&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsxs(_e,{value:String(a.state.value??""),onValueChange:l=>a.handleChange(l),children:[t.jsx(Pe,{id:s,className:"w-full h-8 text-sm","aria-invalid":a.state.meta.errors.length>0,children:t.jsx(ze,{placeholder:`Select ${e.label}`})}),t.jsx(Ee,{children:o.map((l,c)=>t.jsx(Ce,{value:l,children:i[c]||l},l))})]}),t.jsx(Ht,{errors:a.state.meta.errors})]})})}function Nl({column:e,form:n}){const r=e.name;return t.jsx(n.Field,{name:r,children:s=>t.jsxs("label",{htmlFor:r,className:"flex items-center gap-2 cursor-pointer select-none",children:[t.jsx(vn,{id:r,checked:!!s.state.value,onCheckedChange:o=>s.handleChange(!!o),onBlur:s.handleBlur}),t.jsx("span",{className:"text-sm",children:e.label})]})})}function Cl({column:e,form:n}){const r=e.name,s=!e.isNullable;return t.jsx(n.Field,{name:r,validators:s?{onSubmit:({value:o})=>{if(o==null||o==="")return`${e.label} is required`}}:void 0,children:o=>t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(nt,{htmlFor:r,className:"text-xs text-muted-foreground",children:[e.label,s&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsx(fl,{name:r,label:e.label,value:String(o.state.value??""),dbType:e.dbType,onChange:i=>o.handleChange(i),onBlur:o.handleBlur,required:s,invalid:o.state.meta.errors.length>0}),t.jsx(Ht,{errors:o.state.meta.errors})]})})}function wl({column:e,join:n,form:r,schema:s,isRequired:o}){const i=e.name,a=tl(s,n.destinationTable,n.destinationColumnNames[0]);return t.jsx(r.Field,{name:i,validators:o?{onSubmit:({value:l})=>{if(l==null||l==="")return`${e.label} is required`}}:void 0,children:l=>t.jsxs("div",{className:"grid gap-1",children:[t.jsxs(nt,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,o&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),t.jsxs(_e,{value:String(l.state.value??""),onValueChange:c=>l.handleChange(c),children:[t.jsx(Pe,{id:i,className:"w-full h-8 text-sm","aria-invalid":l.state.meta.errors.length>0,children:t.jsx(ze,{placeholder:`Select ${e.label}`})}),t.jsx(Ee,{children:a.data.map(c=>t.jsx(Ce,{value:String(c.key),children:c.label},c.key))})]}),t.jsx(Ht,{errors:l.state.meta.errors})]})})}function kl({column:e,join:n,form:r,schema:s,isRequired:o}){const i=n.sourceColumnNames??[],a=n.destinationColumnNames??[],l=rl(s,n.destinationTable,a),c=Pn.useStore(r.store,p=>{const d=[];for(const h of i){const y=p.values?.[h];if(y==null||y==="")return"";d.push(y)}return Nt(d)}),m=p=>{const d=l.data.find(h=>h.route===p);if(d)for(let h=0;h<i.length;h++){const y=a[h],g=i[h];r.setFieldValue(g,d.values[y])}};return t.jsxs("div",{className:"grid gap-1 sm:col-span-2",children:[t.jsxs(nt,{htmlFor:e.name,className:"text-xs text-muted-foreground",children:[e.label,o&&t.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),t.jsxs("span",{className:"ml-2 px-1 rounded bg-primary/10 text-[10px] font-medium text-primary",children:["composite FK (",i.length," cols)"]})]}),t.jsxs(_e,{value:c,onValueChange:m,children:[t.jsx(Pe,{id:e.name,className:"w-full h-8 text-sm",children:t.jsx(ze,{placeholder:`Select ${e.label}`})}),t.jsx(Ee,{children:l.data.map(p=>t.jsx(Ce,{value:p.route,children:p.label},p.route))})]})]})}function Ht({errors:e}){return e.length===0?null:t.jsx(t.Fragment,{children:e.map((n,r)=>t.jsx("p",{className:"text-xs text-destructive",children:String(n)},r))})}const ls=40,cs=32;function Tl({className:e,...n}){return t.jsx("div",{"data-slot":"table-container",className:"relative w-full h-full overflow-x-auto",children:t.jsx("table",{"data-slot":"table",className:K("min-w-full caption-bottom text-sm border-separate border-spacing-0",e),...n})})}function Sl({className:e,...n}){return t.jsx("thead",{"data-slot":"table-header",className:K("[&_tr]:border-b",e),...n})}function Fl({className:e,...n}){return t.jsx("tbody",{"data-slot":"table-body",className:K("[&_tr:last-child]:border-0 [&_tr:nth-child(even)]:bg-muted/25",e),...n})}function Qt({className:e,style:n,...r}){return t.jsx("tr",{"data-slot":"table-row",className:K("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),style:{height:ls,...n},...r})}function $l({className:e,style:n,...r}){return t.jsx("th",{"data-slot":"table-head",className:K("px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground text-xs border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),style:{height:cs,...n},...r})}function Cn({className:e,...n}){return t.jsx("td",{"data-slot":"table-cell",className:K("px-2 py-1 align-middle whitespace-nowrap text-[13px] overflow-hidden text-ellipsis border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...n})}function _l({anchorEl:e,onEdit:n,onDelete:r,onMouseEnter:s,onDismiss:o}){const i=f.useRef(null);return f.useEffect(()=>{const a=i.current;return a?((()=>{const c=e.getBoundingClientRect(),m=a.offsetHeight,p=a.offsetWidth;a.style.top=`${c.top+(c.height-m)/2}px`;const d=Math.min(c.right-p-8,window.innerWidth-p-8);a.style.left=`${Math.max(8,d)}px`})(),a.showPopover(),()=>{try{a.hidePopover()}catch{}}):void 0},[e]),f.useEffect(()=>{const a=l=>{const c=i.current;c&&!c.contains(l.target)&&o()};return document.addEventListener("pointerdown",a),()=>document.removeEventListener("pointerdown",a)},[o]),t.jsxs("div",{ref:i,popover:"manual",className:"flex items-center gap-0.5 rounded-md border border-border bg-popover px-1 py-0.5 shadow-md m-0",style:{position:"fixed"},onClick:a=>a.stopPropagation(),onMouseEnter:s,onMouseLeave:o,children:[n&&t.jsx(q,{variant:"ghost",size:"icon-sm",onClick:n,"aria-label":"Edit row",title:"Edit",className:"size-6",children:t.jsx(v.Pencil,{className:"size-3.5"})}),r&&t.jsx(q,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete row",title:"Delete",className:"size-6 text-destructive hover:text-destructive",children:t.jsx(v.Trash2,{className:"size-3.5"})})]})}const ds=60,zl=450,Pl=150,wn="bifrost-col-sizes:";function us(e){try{const n=localStorage.getItem(wn+e);return n?JSON.parse(n):{}}catch{return{}}}function El(e,n){try{Object.keys(n).length===0?localStorage.removeItem(wn+e):localStorage.setItem(wn+e,JSON.stringify(n))}catch{}}const Dl=[10,20,30,50,100],kn=-1;function Il({columns:e,data:n,tableName:r,pageCount:s,pageIndex:o,pageSize:i,sorting:a,columnFilters:l,loading:c,selectable:m=!1,primaryKeys:p=[],selectedRowId:d,onRowSelect:h,onSortingChange:y,onColumnFiltersChange:g,onPageIndexChange:b,onPageSizeChange:N,onEditRow:T,onDeleteRow:j,onDeleteSelected:$,stackingEnabled:S,onToggleStacking:D}){const[w,L]=f.useState(null),x=f.useRef(null),k=f.useCallback((F,B)=>{x.current&&(clearTimeout(x.current),x.current=null),L({rowId:F,el:B})},[]),V=f.useCallback(()=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>L(null),150)},[]),I=f.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null)},[]),A=f.useRef(null),W=f.useRef(!1),H=f.useRef(!1),U=500,E=f.useCallback(()=>{A.current&&(clearTimeout(A.current),A.current=null)},[]),Y=f.useCallback((F,B,ee)=>{ee.pointerType==="touch"&&(W.current=!1,E(),A.current=setTimeout(()=>{W.current||(H.current=!0,k(F,B))},U))},[E,k]),se=f.useCallback(()=>{W.current=!0,E()},[E]),[ue,M]=f.useState({}),[we,ke]=f.useState({}),[ye,me]=f.useState(()=>r?us(r):{}),[O,Q]=f.useState(!0),oe=f.useRef(null);f.useEffect(()=>{r&&El(r,ye)},[r,ye]);const ge=f.useRef(r);if(r&&r!==ge.current){ge.current=r;const F=us(r);me(F)}const re=f.useCallback(F=>{const B=oe.current;if(!B)return;const ee=B.querySelectorAll(`[data-col-id="${F}"]`);let Ae=ds;ee.forEach(st=>{const Ft=st.scrollWidth+4;Ft>Ae&&(Ae=Ft)});const Re=Math.min(Ae,zl);me(st=>({...st,[F]:Re}))},[]),Ie=f.useCallback(()=>{me({})},[]),Me=f.useRef(0),Se=f.useCallback(()=>{const F=oe.current;return F?Math.max(5,Math.floor((F.clientHeight-cs)/ls)):10},[]);f.useEffect(()=>{if(!O)return;const F=oe.current;if(!F)return;const B=()=>{const Re=Se();Re!==Me.current&&(Me.current=Re,N(Re))},ee=requestAnimationFrame(B),Ae=new ResizeObserver(()=>requestAnimationFrame(B));return Ae.observe(F),()=>{cancelAnimationFrame(ee),Ae.disconnect()}},[O,Se,N]),f.useEffect(()=>{ke({})},[n,o]);const Fe=[];m&&Fe.push({id:"_select",header:({table:F})=>t.jsx(vn,{checked:F.getIsAllPageRowsSelected()||F.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:B=>F.toggleAllPageRowsSelected(!!B),"aria-label":"Select all"}),cell:({row:F})=>t.jsx(vn,{checked:F.getIsSelected(),onCheckedChange:B=>F.toggleSelected(!!B),onClick:B=>B.stopPropagation(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1,enableResizing:!1,size:32}),Fe.push(...e);const de=$t.useReactTable({data:n,columns:Fe,pageCount:s,getRowId:(F,B)=>Ct(F,{primaryKeys:p},B),state:{sorting:a,columnFilters:l,pagination:{pageIndex:o,pageSize:i},columnVisibility:ue,rowSelection:we,columnSizing:ye},defaultColumn:{minSize:ds,size:Pl},columnResizeMode:"onChange",enableColumnResizing:!0,onColumnSizingChange:me,meta:{onResetColumnWidths:Ie},onSortingChange:F=>{const B=typeof F=="function"?F(a):F;y(B)},onPaginationChange:F=>{const ee=typeof F=="function"?F({pageIndex:o,pageSize:i}):F;ee.pageSize!==i?(N(ee.pageSize),b(0)):b(ee.pageIndex)},onColumnFiltersChange:F=>{const B=typeof F=="function"?F(l):F;g(B)},onColumnVisibilityChange:M,onRowSelectionChange:ke,enableRowSelection:m,getCoreRowModel:$t.getCoreRowModel(),manualSorting:!0,manualFiltering:!0,manualPagination:!0}),Je=Object.keys(we).length,He=f.useCallback(()=>{if(!$)return;const F=[];for(const B of de.getSelectedRowModel().rows){const ee=Gt(B.original,{primaryKeys:p});ee&&F.push(ee)}F.length>0&&$(F)},[de,$,p]),Qe=f.useCallback(F=>{const B=de.getRow(F);return B?Gt(B.original,{primaryKeys:p}):null},[de,p]),Xt=f.useCallback(()=>{if(!w||!T)return;const F=Qe(w.rowId);F&&T(F)},[w,T,Qe]),rt=f.useCallback(()=>{if(!w||!j)return;const F=Qe(w.rowId);F&&j(F)},[w,j,Qe]);return t.jsxs("div",{className:"flex flex-col w-full min-h-0 flex-1",children:[t.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&t.jsxs(q,{variant:"outline",size:"sm",onClick:()=>de.resetColumnFilters(),title:"Clear all column filters",children:[t.jsx(v.FilterX,{className:"size-3.5"}),"Clear filters"]}),Je>0&&$&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"text-xs text-muted-foreground",children:[Je," selected"]}),t.jsxs(q,{variant:"outline",size:"sm",onClick:He,className:"text-destructive hover:text-destructive",children:[t.jsx(v.Trash2,{className:"size-3.5"}),"Delete"]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[D&&t.jsxs(q,{variant:S?"secondary":"outline",size:"sm",role:"switch","aria-checked":!!S,onClick:()=>D(!S),title:S?"Stacked drill-down active — click for flat grid":"Flat grid active — click for stacked drill-down",children:[S?t.jsx(v.PanelRight,{className:"size-3.5"}):t.jsx(v.Rows3,{className:"size-3.5"}),S?"Stacked":"Grid"]}),t.jsxs(zr,{children:[t.jsx(Pr,{asChild:!0,children:t.jsxs(q,{variant:"outline",size:"sm",children:[t.jsx(v.Columns3,{className:"size-3.5"}),"Columns",t.jsx(v.ChevronDown,{className:"size-3.5"})]})}),t.jsx(Er,{align:"end",children:de.getAllColumns().filter(F=>F.getCanHide()).map(F=>t.jsx(_a,{checked:F.getIsVisible(),onCheckedChange:B=>F.toggleVisibility(!!B),children:F.id},F.id))})]})]})]}),t.jsxs("div",{ref:oe,className:"flex-1 overflow-auto min-h-0",children:[t.jsxs(Tl,{style:{width:de.getTotalSize()},children:[t.jsx(Sl,{children:de.getHeaderGroups().map(F=>t.jsx(Qt,{children:F.headers.map(B=>t.jsxs($l,{"data-col-id":B.column.id,className:"relative",style:{width:B.getSize()},children:[B.isPlaceholder?null:$t.flexRender(B.column.columnDef.header,B.getContext()),B.column.getCanResize()&&t.jsx("div",{onMouseDown:B.getResizeHandler(),onTouchStart:B.getResizeHandler(),onDoubleClick:()=>re(B.column.id),className:`absolute top-0 right-0 w-1 h-full cursor-col-resize select-none touch-none opacity-0 hover:opacity-100 transition-opacity ${B.column.getIsResizing()?"bg-primary opacity-100":"bg-border hover:bg-muted-foreground"}`})]},B.id))},F.id))}),t.jsx(Fl,{children:c?t.jsx(Qt,{children:t.jsx(Cn,{colSpan:Fe.length,className:"h-24 text-center",children:"Loading..."})}):de.getRowModel().rows.length===0?t.jsx(Qt,{children:t.jsx(Cn,{colSpan:Fe.length,className:"h-24 text-center",children:"No results."})}):de.getRowModel().rows.map(F=>{const B=d!=null&&F.id===d;return t.jsx(Qt,{"data-state":B||F.getIsSelected()?"selected":void 0,className:h?"cursor-pointer group/row":"group/row",onClick:h?()=>{if(H.current){H.current=!1;return}window.getSelection()?.toString()||h(B?null:F.id)}:void 0,onPointerEnter:ee=>{ee.pointerType==="mouse"&&k(F.id,ee.currentTarget)},onPointerLeave:ee=>{ee.pointerType==="mouse"&&V()},onPointerDown:ee=>Y(F.id,ee.currentTarget,ee),onPointerMove:se,onPointerUp:E,onPointerCancel:E,children:F.getVisibleCells().map(ee=>t.jsx(Cn,{"data-col-id":ee.column.id,style:{width:ee.column.getSize()},children:$t.flexRender(ee.column.columnDef.cell,ee.getContext())},ee.id))},F.id)})})]}),w&&(T||j)&&t.jsx(_l,{anchorEl:w.el,onEdit:T?Xt:void 0,onDelete:j?rt:void 0,onMouseEnter:I,onDismiss:V})]}),t.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 border-t border-border mt-auto shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[t.jsx("span",{children:"Rows per page"}),t.jsxs(_e,{value:String(O?kn:i),onValueChange:F=>{const B=Number(F);B===kn?(Q(!0),N(Se())):(Q(!1),N(B))},children:[t.jsx(Pe,{size:"sm",className:"w-auto h-7 text-xs","aria-label":"Rows per page",children:t.jsx(ze,{children:O?"Fit":i})}),t.jsxs(Ee,{children:[t.jsx(Ce,{value:String(kn),children:"Fit"}),Dl.map(F=>t.jsx(Ce,{value:String(F),children:F},F))]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("span",{className:"text-xs text-muted-foreground mr-2",children:["Page ",o+1," of ",s||1]}),t.jsx(q,{variant:"outline",size:"icon-sm",onClick:()=>b(0),disabled:o===0,"aria-label":"First page",title:"First page",children:t.jsx(v.ChevronsLeft,{className:"size-4"})}),t.jsx(q,{variant:"outline",size:"icon-sm",onClick:()=>b(o-1),disabled:!de.getCanPreviousPage(),"aria-label":"Previous page",title:"Previous page",children:t.jsx(v.ChevronLeft,{className:"size-4"})}),t.jsx(q,{variant:"outline",size:"icon-sm",onClick:()=>b(o+1),disabled:!de.getCanNextPage(),"aria-label":"Next page",title:"Next page",children:t.jsx(v.ChevronRight,{className:"size-4"})}),t.jsx(q,{variant:"outline",size:"icon-sm",onClick:()=>b(s-1),disabled:o>=s-1,"aria-label":"Last page",title:"Last page",children:t.jsx(v.ChevronsRight,{className:"size-4"})})]})]})]})}function Ml({open:e,onOpenChange:n,title:r,description:s,confirmLabel:o="Confirm",cancelLabel:i="Cancel",variant:a="default",isPending:l=!1,onConfirm:c}){return t.jsx(kt,{open:e,onOpenChange:n,children:t.jsxs(Tt,{showCloseButton:!1,children:[t.jsxs(Kt,{children:[t.jsx(St,{children:r}),t.jsx(Wt,{asChild:!0,children:t.jsx("div",{children:s})})]}),t.jsxs(os,{children:[t.jsx(q,{variant:"outline",onClick:()=>n(!1),disabled:l,children:i}),t.jsx(q,{variant:a==="destructive"?"destructive":"default",onClick:c,disabled:l,children:l?"Deleting...":o})]})]})})}function Ll({...e}){return t.jsx(G.Dialog.Root,{"data-slot":"sheet",...e})}function Ol({...e}){return t.jsx(G.Dialog.Portal,{"data-slot":"sheet-portal",...e})}function Al({className:e,...n}){return t.jsx(G.Dialog.Overlay,{"data-slot":"sheet-overlay",className:K("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...n})}function ql({className:e,children:n,side:r="right",...s}){return t.jsxs(Ol,{children:[t.jsx(Al,{}),t.jsxs(G.Dialog.Content,{"data-slot":"sheet-content",className:K("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out duration-200 outline-none","data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-200 data-[state=open]:duration-200",r==="right"&&"inset-y-0 right-0 h-full w-3/4 max-w-md border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",r==="left"&&"inset-y-0 left-0 h-full w-3/4 max-w-md border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),...s,children:[n,t.jsxs(G.Dialog.Close,{"data-slot":"sheet-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[t.jsx(v.XIcon,{}),t.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Vl({className:e,...n}){return t.jsx("div",{"data-slot":"sheet-header",className:K("flex flex-col gap-2 p-4 pb-0",e),...n})}function Bl({className:e,...n}){return t.jsx(G.Dialog.Title,{"data-slot":"sheet-title",className:K("text-lg leading-none font-semibold",e),...n})}function Gl({className:e,...n}){return t.jsx(G.Dialog.Description,{"data-slot":"sheet-description",className:K("text-sm text-muted-foreground",e),...n})}const Kl={json:v.Braces,xml:v.Code,"php-serialized":v.Database,binary:v.Binary,longtext:v.FileText,text:v.FileText},Wl={json:"JSON",xml:"XML","php-serialized":"PHP Serialized",binary:"Binary",longtext:"Text",text:"Text"};function Jl(e,n){if(n==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return n==="xml"?e.replace(/>\s*</g,`>
|
|
100
|
-
<`).trim():e}function
|
|
101
|
-
<`).trim())},[p,N]),x=N==="json"||N==="xml",k=!e?.isReadOnly&&N!=="binary",V=t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx(T,{className:"size-4 text-muted-foreground shrink-0"}),t.jsx("span",{className:"truncate font-semibold text-sm",children:e?.columnLabel}),t.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:Wl[N]}),t.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[b.length," chars"]})]}),I=t.jsxs("div",{className:"flex items-center gap-1 px-4 pb-2",children:[t.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:$,children:[h?t.jsx(v.Check,{className:"size-3"}):t.jsx(v.Copy,{className:"size-3"}),h?"Copied":"Copy"]}),k&&!c&&t.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:S,children:[t.jsx(v.Pencil,{className:"size-3"}),"Edit"]}),c&&x&&t.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:L,children:[t.jsx(v.WrapText,{className:"size-3"}),"Format"]}),t.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[t.jsx(q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("prev"),disabled:!o,"aria-label":"Previous row",title:"Previous row",children:t.jsx(v.ChevronUp,{className:"size-4"})}),t.jsx(q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("next"),disabled:!i,"aria-label":"Next row",title:"Next row",children:t.jsx(v.ChevronDown,{className:"size-4"})}),t.jsx(q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>l(H=>!H),"aria-label":a?"Exit full screen":"Full screen",title:a?"Exit full screen":"Full screen",children:a?t.jsx(v.Minimize2,{className:"size-4"}):t.jsx(v.Maximize2,{className:"size-4"})})]})]}),A=t.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-4 pb-4",children:c?t.jsxs("div",{className:"flex flex-col gap-2 h-full",children:[t.jsx("textarea",{ref:g,value:p,onChange:H=>d(H.target.value),className:K("flex-1 w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none min-h-[200px]")}),t.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[t.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:D,children:"Cancel"}),t.jsx(q,{type:"button",size:"sm",onClick:w,children:"Save"})]})]}):t.jsx("pre",{className:"text-xs font-mono leading-relaxed whitespace-pre-wrap break-all",children:j})}),W=!!e;return t.jsxs(t.Fragment,{children:[t.jsx(Ll,{open:W&&!a,onOpenChange:H=>{H||n()},children:t.jsxs(ql,{side:"right",className:"w-[480px] max-w-[90vw]",children:[t.jsxs(Vl,{children:[t.jsx(Bl,{children:V}),t.jsx(Gl,{className:"sr-only",children:"Content viewer panel"})]}),I,A]})}),t.jsx(kt,{open:W&&a,onOpenChange:H=>{H||l(!1)},children:t.jsxs(Tt,{className:"max-w-[90vw] max-h-[90vh] w-full h-full flex flex-col",children:[t.jsxs(Kt,{children:[t.jsx(St,{children:V}),t.jsx(Wt,{className:"sr-only",children:"Content viewer full screen"})]}),I,A]})})]})}function Tn({table:e,id:n,tableFilter:r,filterColumn:s,selectedRowId:o,onRowSelect:i,onOpenColumn:a,stackingEnabled:l,onToggleStacking:c}){const m=es(e),[p,d]=f.useState(null),[h,y]=f.useState(null),[g,b]=f.useState(null),[N,T]=f.useState(0),j=f.useCallback(O=>{y(Di(O,e))},[e]),$=f.useCallback(O=>{d({type:"single",pk:O})},[]),S=f.useCallback(O=>{O.length!==0&&d({type:"batch",pks:O})},[]),D=f.useCallback((O,Q)=>{T(O),b(Q)},[]),{columns:w,sorting:L,columnFilters:x,pageIndex:k,pageSize:V,pageCount:I,rows:A,loading:W,error:H,onSortingChange:U,onColumnFiltersChange:E,onPageIndexChange:Y,onPageSizeChange:se}=Zi(e,n,r,s,D,a),ue=f.useCallback(async()=>{if(p)try{p.type==="single"?await m.deleteRow(p.pk):await m.deleteRows(p.pks),d(null)}catch{}},[p,m]),M=p?.type==="batch"?p.pks.length:1,we=(()=>{if(g===null||!A[N])return null;const O=A[N],Q=e.columns.find(re=>re.name===g);if(!Q)return null;const oe=O[g];return{value:typeof oe=="object"&&oe!==null?JSON.stringify(oe,null,2):String(oe??""),columnName:Q.name,columnLabel:Q.label,dbType:Q.dbType,rowIndex:N,isReadOnly:Q.isReadOnly||Q.isPrimaryKey||Q.isIdentity}})(),ke=f.useCallback(()=>{b(null)},[]),ye=f.useCallback(O=>{T(Q=>O==="prev"?Math.max(0,Q-1):Math.min(A.length-1,Q+1))},[A.length]);if(H)return t.jsxs("div",{children:["Error: ",H.message]});const me=e.isEditable!==!1;return t.jsxs(t.Fragment,{children:[t.jsx(Il,{columns:w,data:A,tableName:e.name,pageCount:I,pageIndex:k,pageSize:V,sorting:L,columnFilters:x,loading:W,primaryKeys:e.primaryKeys??[],selectable:me,selectedRowId:o,onRowSelect:i,onSortingChange:U,onColumnFiltersChange:E,onPageIndexChange:Y,onPageSizeChange:se,onEditRow:me?j:void 0,onDeleteRow:me?$:void 0,onDeleteSelected:me?S:void 0,stackingEnabled:l,onToggleStacking:c}),t.jsx(Ml,{open:p!==null,onOpenChange:O=>{O||d(null)},title:`Delete ${M} ${M===1?"row":"rows"}?`,description:t.jsxs(t.Fragment,{children:[t.jsx("p",{children:"This action cannot be undone."}),m.error&&t.jsx("p",{className:"mt-2 text-sm text-destructive",children:m.error.message})]}),confirmLabel:`Delete ${M===1?"row":`${M} rows`}`,variant:"destructive",isPending:m.isPending,onConfirm:ue}),t.jsx(Hl,{target:we,onClose:ke,onNavigate:ye,canNavigatePrev:N>0,canNavigateNext:N<A.length-1}),h!==null&&t.jsx(is,{table:e.graphQlName,editid:h,onClose:()=>y(null)})]})}const Ql=new Set(["Int","Int!","Float","Float!"]);function Rl(e){return new Set((e.manyToManyJoins??[]).map(n=>n.junctionTable))}function ms(e){const n=Rl(e),r=e.multiJoins.filter(o=>!n.has(o.destinationTable)).map(o=>({kind:"child",key:`child:${o.fieldName??o.destinationTable}`,join:o})),s=(e.manyToManyJoins??[]).map(o=>({kind:"m2m",key:`m2m:${o.junctionTable}:${o.targetTable}`,m2m:o}));return[...r,...s]}function fs(e,n){const r=new Set([...n.junctionSourceColumnNames,...n.junctionTargetColumnNames]);return e.columns.filter(s=>!s.isPrimaryKey&&!r.has(s.name))}function Yl(e,n){return n&&Ql.has(n)?Number(e):e}function Xl(e,n,r,s){const o=r.junctionSourceColumnNames[0],i=e.columns.find(b=>b.name===o),a=i?i.paramType.replace("!",""):"Int",l=e.primaryKeys??[],c=fs(e,r).map(b=>b.name),m=n.primaryKeys?.length?n.primaryKeys:r.targetColumnNames,p=n.labelColumn,d=[...m];p&&!m.includes(p)&&d.push(`label: ${p}`);const h=`${r.junctionTargetField} { ${d.join(" ")} }`,y=[...l,...c,h].join(" ");return{query:`query GetLinks_${e.name}($id: ${a}, $limit: Int, $offset: Int) { ${e.name}(filter: { ${o}: { _eq: $id } } limit: $limit offset: $offset) { total offset limit data { ${y} } } }`,variables:{id:Yl(s,a)}}}function Ul(e,n){const r=wt(e)[0]?.name??n.targetColumnNames[0],s=e.labelColumn||r,o=s!==r?`${r} label: ${s}`:r;return{query:`query PickTarget($limit: Int) { ${e.name}(limit: $limit sort: [${s}_asc]) { data { ${o} } } }`,idColumn:r}}function Zl(e,n,r){const s=e[n.junctionTargetField];if(!s)return null;const o=Ct(s,r,0),i=s.label!=null?String(s.label):o;return{id:o,label:i}}function ec(e,n,r){if(e.junctionSourceColumnNames.length!==1||e.junctionTargetColumnNames.length!==1)throw new Error("attachJunctionDetail supports single-column junction FKs only; this relationship uses a composite key which is not yet supported.");return{[e.junctionSourceColumnNames[0]]:n,[e.junctionTargetColumnNames[0]]:r}}function tc({parentTable:e,m2m:n,parentRowId:r,onOpenColumn:s}){const o=je(),i=ve(),a=le.useQueryClient(),[l,c]=f.useState(!1),m=o.findTable(n.junctionTable),p=o.findTable(n.targetTable),d=es(m??e),{query:h,variables:y}=m&&p?Xl(m,p,n,r):{query:null,variables:{}},g=["m2mRows",n.junctionTable,n.targetTable,r],{data:b,isLoading:N,error:T}=le.useQuery({queryKey:g,queryFn:()=>i.query(h,{...y,limit:200,offset:0}),enabled:!!h}),j=f.useCallback(()=>a.invalidateQueries({queryKey:g}),[a,g]),$=f.useCallback(async L=>{if(!m)return;const x=Gt(L,m);x&&(await d.deleteRow(x),await j())},[m,d,j]);if(!m||!p)return t.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Relationship schema unavailable."});const S=b?.[m.name]?.data??[],D=fs(m,n),w=m.isEditable!==!1;return t.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 bg-muted/20 border-b border-border shrink-0",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground",title:`Linked through ${m.label}`,children:[t.jsx(v.Link2,{className:"size-3"}),"via ",m.label]}),w&&t.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs ml-auto",onClick:()=>c(!0),children:[t.jsx(v.Plus,{className:"size-3 mr-1"})," Add link"]})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[T&&t.jsxs("div",{className:"p-3 text-sm text-destructive",children:["Error: ",T.message]}),N&&t.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[t.jsx(v.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!N&&S.length===0&&t.jsxs("div",{className:"p-3 text-sm text-muted-foreground",children:["No linked ",p.label,"."]}),S.length>0&&t.jsxs("table",{className:"w-full text-sm",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[t.jsx("th",{className:"px-2 py-1 font-medium",children:p.label}),D.map(L=>t.jsx("th",{className:"px-2 py-1 font-medium",children:L.label},L.name)),w&&t.jsx("th",{className:"px-2 py-1 w-8","aria-label":"actions"})]})}),t.jsx("tbody",{children:S.map((L,x)=>{const k=Zl(L,n,p);return t.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30",children:[t.jsx("td",{className:"px-2 py-1",children:k?t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(dt,{to:`/${p.name}/${k.id}`,className:"text-primary hover:underline",children:k.label}),s&&t.jsx(q,{variant:"ghost",size:"icon-sm",className:"size-5",onClick:()=>s({tableName:p.name,filterId:k.id}),"aria-label":`Open ${k.label} in side column`,title:"Open in side column",children:t.jsx(v.Search,{className:"size-3"})})]}):t.jsx("span",{className:"text-muted-foreground",children:"—"})}),D.map(V=>t.jsx("td",{className:"px-2 py-1",children:Vt(L[V.name],V)},V.name)),w&&t.jsx("td",{className:"px-2 py-1",children:t.jsx(q,{variant:"ghost",size:"icon-sm",className:"size-6 text-muted-foreground hover:text-destructive",onClick:()=>$(L),disabled:d.isPending,"aria-label":`Detach ${k?.label??"link"}`,title:"Detach",children:t.jsx(v.Unlink,{className:"size-3.5"})})})]},x)})})]})]}),l&&t.jsx(nc,{target:p,junction:m,m2m:n,parentRowId:r,onClose:()=>c(!1),onLinked:j})]})}function nc({target:e,junction:n,m2m:r,parentRowId:s,onClose:o,onLinked:i}){const a=ve(),l=n.columns.filter($=>r.junctionSourceColumnNames.includes($.name)||r.junctionTargetColumnNames.includes($.name)).map($=>({column:$})),c=yn(n,l,[]),[m,p]=f.useState(""),{query:d,idColumn:h}=Ul(e,r),{data:y,isLoading:g}=le.useQuery({queryKey:["m2mTargets",e.name],queryFn:()=>a.query(d,{limit:500})}),b=y?.[e.name]?.data??[],N=m.trim().toLowerCase(),T=N?b.filter($=>String($.label??$[h]??"").toLowerCase().includes(N)):b,j=f.useCallback(async $=>{await c.insert(ec(r,s,$)),await i(),o()},[c,r,s,i,o]);return t.jsx(kt,{open:!0,onOpenChange:$=>{$||o()},children:t.jsxs(Tt,{className:"max-w-md",children:[t.jsx(Kt,{children:t.jsxs(St,{children:["Add ",e.label," link"]})}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(v.Search,{className:"size-4 text-muted-foreground"}),t.jsx(Ne,{autoFocus:!0,placeholder:`Search ${e.label}…`,value:m,onChange:$=>p($.target.value)})]}),c.error&&t.jsx("p",{className:"text-sm text-destructive",children:c.error.message}),t.jsxs("div",{className:"max-h-72 overflow-auto border border-border rounded-md",children:[g&&t.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[t.jsx(v.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!g&&T.length===0&&t.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No matches."}),T.map(($,S)=>{const D=String($[h]??""),w=$.label!=null?String($.label):D;return t.jsx("button",{type:"button",className:"block w-full text-left px-3 py-1.5 text-sm hover:bg-muted/50 disabled:opacity-50",disabled:c.isPending,onClick:()=>j(D),children:w},S)})]})]})})}function ps(e){return e.kind==="child"?e.join.destinationTable:e.m2m.targetTable}function hs({parentTable:e,selectedRowId:n,onClose:r,onOpenColumn:s}){const o=je(),i=ms(e),[a,l]=f.useState(i[0]?.key??""),[c,m]=f.useState(!1),[p,d]=f.useState(null),h=i.find(b=>b.key===a)??i[0];if(f.useEffect(()=>{d(null)},[a,n]),i.length===0||!o.data)return null;const y=h.kind==="child"?o.findTable(h.join.destinationTable):void 0,g=(y?.multiJoins?.length??0)>0;return t.jsxs("div",{className:"border-t-2 border-primary/20 flex flex-col min-h-0 flex-1 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[t.jsx(q,{variant:"ghost",size:"icon-sm",onClick:()=>m(!c),"aria-label":c?"Expand detail panel":"Collapse detail panel",title:c?"Expand detail panel":"Collapse detail panel",children:c?t.jsx(v.ChevronUp,{className:"size-3.5"}):t.jsx(v.ChevronDown,{className:"size-3.5"})}),t.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Detail:"}),t.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto",children:i.map(b=>{const T=o.findTable(ps(b))?.label??ps(b),j=b.key===h.key;return t.jsxs("span",{className:"group/tab inline-flex items-center",children:[t.jsx(q,{variant:j?"secondary":"ghost",size:"sm",className:K("text-xs h-7 px-2.5",j&&"font-semibold"),onClick:()=>l(b.key),children:T}),s&&b.kind==="child"&&t.jsx(q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/tab:opacity-100 size-5 shrink-0",onClick:()=>s({tableName:b.join.destinationTable,filterTable:e.name,filterId:n,...et(b.join)?{}:{filterColumn:b.join.destinationColumnNames[0]}}),"aria-label":"Open in side column",title:"Open in side column",children:t.jsx(v.PanelRight,{className:"size-3"})})]},b.key)})}),r&&t.jsx(q,{variant:"ghost",size:"icon-sm",onClick:r,className:"ml-auto shrink-0","aria-label":"Close detail panel",title:"Close detail panel",children:t.jsx(v.X,{className:"size-3.5"})})]}),!c&&t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:h.kind==="child"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:g&&p?"flex-1 min-h-0 max-h-[50%] overflow-hidden flex flex-col":"flex-1 min-h-0 overflow-hidden flex flex-col",children:t.jsx(Tn,{table:y,id:n,tableFilter:e.name,...et(h.join)?{}:{filterColumn:h.join.destinationColumnNames[0]},selectedRowId:g?p:void 0,onRowSelect:g?d:void 0,onOpenColumn:s},`${h.key}-${n}`)}),g&&p&&t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:t.jsx(hs,{parentTable:y,selectedRowId:p,onClose:()=>d(null),onOpenColumn:s})})]}):t.jsx(tc,{parentTable:e,m2m:h.m2m,parentRowId:n,onOpenColumn:s},`${h.key}-${n}`)})]})}const rc={mainTable:null,columns:[],focusedIndex:0,focusColumn:()=>{},closeColumn:()=>{}},xs=f.createContext(rc),gs=f.createContext({register:()=>{},unregister:()=>{}});function sc({children:e}){const[n,r]=f.useState(null),[s,o]=f.useState(0),i=f.useCallback(d=>{r(d)},[]),a=f.useCallback(()=>{r(null),o(0)},[]),l=f.useCallback(d=>{if(o(d),!n)return;const h=n.columnRefs.get(d);h&&h.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[n]),c=f.useCallback(d=>{n&&d>0&&n.onClose(d-1)},[n]),m=n?n.columns.map((d,h)=>({panel:d,element:n.columnRefs.get(h+1)??null})):[],p={mainTable:n?.mainTable??null,columns:m,focusedIndex:s,focusColumn:l,closeColumn:c};return t.jsx(gs.Provider,{value:{register:i,unregister:a},children:t.jsx(xs.Provider,{value:p,children:e})})}function oc(){return f.useContext(xs)}function ac(){return f.useContext(gs)}function bs(e,n){return e.tableName===n.tableName&&e.filterTable===n.filterTable&&e.filterId===n.filterId&&e.filterColumn===n.filterColumn}function ic(e,n){const r=e[e.length-1];if(r&&bs(r,n))return e;const s=e.findIndex(o=>bs(o,n));return s>=0?e.slice(0,s+1):[...e,n]}function lc(e,n){return n<0?[]:n>=e.length?e:e.slice(0,n)}function cc(e,n,r){const s=i=>r(i)??i,o=[{index:-1,label:s(e)}];for(let i=0;i<n.length;i++){const a=n[i],l=a.filterTable?s(a.filterTable):s(i===0?e:n[i-1].tableName),c=a.filterId?`from ${l} #${a.filterId}`:void 0;o.push({index:i,label:s(a.tableName),detail:c,frame:a})}return o}function Rt(e,n){return e.find(r=>r.name===n)}function We(){const e=on(),{table:n,id:r,filterTable:s}=e,{loading:o,error:i,data:a}=je(),[l,c]=f.useState(null),[m,p]=f.useState([]),[d,h]=f.useState(!0),[y,g]=f.useState(new Set),b=f.useRef(n);n!==b.current&&(b.current=n,m.length>0&&p([]),y.size>0&&g(new Set));const N=f.useCallback(E=>{g(Y=>{const se=new Set(Y);return se.has(E)?se.delete(E):se.add(E),se})},[]),{register:T,unregister:j}=ac(),$=f.useRef(null),S=f.useRef(new Map),D=f.useMemo(()=>a?Rt(a,n):void 0,[a,n]),w=D?ms(D).length>0:!1,L=f.useCallback(E=>{p(Y=>ic(Y,E))},[]),x=f.useCallback(E=>{h(E),E||p([])},[]),k=d?L:void 0,V=f.useCallback(E=>{p(Y=>Y.filter((se,ue)=>ue!==E))},[]),I=f.useCallback(E=>{p(Y=>lc(Y,E+1))},[]),A=f.useMemo(()=>cc(n??"",m,E=>{if(a)return Rt(a,E)?.label}),[n,m,a]);if(f.useEffect(()=>{const E=S.current;E.set(0,$.current);for(const Y of E.keys())Y>m.length&&E.delete(Y);return T({mainTable:n,columns:m,columnRefs:E,onClose:V}),()=>j()},[n,m,T,j,V]),!n)return t.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table missing"});if(o)return t.jsxs("div",{className:"flex items-center justify-center gap-2 p-5",children:[t.jsx(v.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});if(i)return t.jsx(mt,{variant:"destructive",className:"m-2",children:t.jsxs(ft,{children:["Error: ",i.message]})});if(!D)return t.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table not found"});const W=t.jsx(Tn,{table:D,id:r,tableFilter:s,selectedRowId:w?l:void 0,onRowSelect:w?c:void 0,onOpenColumn:k,stackingEnabled:d,onToggleStacking:x});if(m.length===0)return t.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:t.jsxs("div",{ref:$,className:"flex flex-col flex-1 min-h-0 min-w-0",children:[t.jsx("div",{className:w&&l?"flex-1 min-h-0 max-h-[50%] overflow-hidden flex flex-col":"flex-1 min-h-0 overflow-hidden flex flex-col",children:W}),w&&l&&t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:t.jsx(hs,{parentTable:D,selectedRowId:l,onClose:()=>c(null),onOpenColumn:k})})]})});const H=m.length-1,U=(E,Y)=>Y||y.has(E);return t.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[t.jsx(dc,{crumbs:A,onCrumbClick:I,activeIndex:m.length-1}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto flex flex-col gap-0.5 p-0.5",children:[t.jsx(ys,{title:D.label,selectedRowId:m[0]?.filterId,expanded:U(-1,!1),active:!1,onToggle:()=>N(-1),onRef:E=>{$.current=E,S.current.set(0,E)},children:W}),m.map((E,Y)=>{const se=Y===H;return t.jsx(ys,{title:Rt(a,E.tableName)?.label??E.tableName,selectedRowId:m[Y+1]?.filterId,expanded:U(Y,se),active:se,onToggle:()=>N(Y),onClose:()=>V(Y),onRef:ue=>{S.current.set(Y+1,ue)},children:t.jsx(Tn,{table:Rt(a,E.tableName),id:E.filterId,tableFilter:E.filterTable,filterColumn:E.filterColumn,onOpenColumn:L})},`${E.tableName}-${E.filterId??""}-${E.filterColumn??""}-${Y}`)})]})]})}function dc({crumbs:e,onCrumbClick:n,activeIndex:r}){return t.jsx("nav",{"aria-label":"Drill-down breadcrumb",className:"flex items-center gap-1 px-2 py-1 bg-muted/20 border-b border-border shrink-0 overflow-x-auto",children:e.map((s,o)=>{const i=s.index===r,a=o===0;return t.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[!a&&t.jsx(v.ChevronRight,{className:"size-3 text-muted-foreground shrink-0"}),t.jsxs(q,{variant:i?"secondary":"ghost",size:"sm",className:K("h-6 px-2 text-xs gap-1",i&&"font-semibold"),onClick:()=>n(s.index),"aria-current":i?"page":void 0,title:s.detail?`${s.label} (${s.detail})`:s.label,children:[a&&t.jsx(v.Home,{className:"size-3"}),t.jsx("span",{className:"truncate max-w-[12rem]",children:s.label}),s.detail&&t.jsx("span",{className:"text-muted-foreground font-normal truncate max-w-[10rem]",children:s.detail})]})]},`${s.index}-${s.label}`)})})}function ys({title:e,selectedRowId:n,expanded:r,active:s,onToggle:o,onClose:i,onRef:a,children:l}){return t.jsxs("div",{ref:a,className:"shrink-0 flex flex-col border border-border rounded-sm overflow-hidden",children:[t.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[t.jsx("button",{type:"button",onClick:o,className:"inline-flex items-center justify-center size-5 shrink-0 text-muted-foreground hover:text-foreground","aria-expanded":r,"aria-label":r?"Collapse table":"Expand table",title:r?"Collapse":"Expand",children:r?t.jsx(v.ChevronDown,{className:"size-3.5"}):t.jsx(v.ChevronRight,{className:"size-3.5"})}),t.jsx("span",{className:"text-xs font-medium truncate",children:e}),s&&t.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary/70 shrink-0",children:"active"}),!r&&n&&t.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["#",n]}),t.jsx("div",{className:"flex-1"}),i&&t.jsx(q,{variant:"ghost",size:"icon-sm",className:"shrink-0",onClick:i,"aria-label":"Close column",title:"Close column",children:t.jsx(v.X,{className:"size-3.5"})})]}),r&&t.jsx("div",{className:"flex flex-col min-h-[18rem] max-h-[34rem]",children:l})]})}function Sn(){const e=on(),{loading:n,error:r,data:s}=je(),{mainTable:o,columns:i,focusedIndex:a,focusColumn:l,closeColumn:c}=oc(),[m,p]=f.useState(""),d=Dt(),{search:h}=Yn(),y=!!h.get("filter"),{back:g,hasBack:b}=io(),N=e?.table,T=i.length>0,j=f.useMemo(()=>s?.find(x=>x.graphQlName===N),[s,N]),$=f.useMemo(()=>j?.columns?.map(x=>({key:x.name,value:`${x.name},${x.paramType}`,label:x.label})),[j]),[S,D]=f.useState($?.at(0)?.value??"");f.useEffect(()=>{p(""),D($?.at(0)?.value??"")},[$]);const w=()=>{if(!m)return;const[x,k]=S.split(",");(k==="Int"||k==="Int!"||k==="Float"||k==="Float!")&&d(`?filter=["${x}", "_eq", ${m}, "${k}"]`),(k==="String"||k==="String!")&&d(`?filter=["${x}", "_contains", "${m}", "${k}"]`)},L=()=>{p("");const x=new URLSearchParams(h.toString());x.delete("filter");const k=x.toString();d(k?`?${k}`:"?")};return n?t.jsxs("div",{className:"flex items-center gap-2 p-2.5",children:[t.jsx(v.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?t.jsx(mt,{variant:"destructive",className:"m-2",children:t.jsxs(ft,{children:["Error: ",r.message]})}):t.jsxs("header",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 min-h-[2.5rem]",children:[t.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto min-w-0 flex-1",children:[t.jsx(q,{variant:"ghost",size:"icon-sm",onClick:()=>b&&g(),disabled:!b,"aria-label":"Go back",title:"Go back",className:"shrink-0",children:t.jsx(v.ChevronLeft,{className:"size-4"})}),T?t.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto",children:[t.jsx("button",{type:"button",onClick:()=>l(0),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===0?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:j?.label??It(e?.table??"")}),i.map((x,k)=>{const I=s?.find(A=>A.graphQlName===x.panel.tableName)?.label??It(x.panel.tableName);return t.jsxs("button",{type:"button",onClick:()=>l(k+1),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===k+1?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:[I,t.jsx("span",{role:"button",tabIndex:0,onClick:A=>{A.stopPropagation(),c(k+1)},onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.stopPropagation(),c(k+1))},className:"ml-0.5 rounded-sm hover:bg-background/50 p-px","aria-label":`Close ${I}`,children:t.jsx(v.X,{className:"size-3"})})]},`${x.panel.tableName}-${x.panel.filterId??k}`)})]}):t.jsx("h2",{className:"text-sm font-semibold whitespace-nowrap",children:j?.dbName??e?.table??"(Select)"})]}),$?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden flex-[2_2_16rem] min-w-[12rem]",children:[t.jsxs(_e,{value:S,onValueChange:D,children:[t.jsx(Pe,{size:"sm",className:"w-auto min-w-[120px] shrink-0 border-0 rounded-none border-r border-border h-8 text-xs",children:t.jsx(ze,{})}),t.jsx(Ee,{children:$.map(x=>t.jsx(Ce,{value:x.value,children:x.label},x.key))})]}),t.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[t.jsx(v.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),t.jsx(Ne,{type:"search",value:m,onChange:x=>p(x.target.value),onKeyDown:x=>x.key==="Enter"&&w(),className:"h-8 border-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0",style:{paddingLeft:"2.25rem"},placeholder:"Search..."})]}),t.jsxs(q,{variant:"ghost",size:"sm",onClick:w,className:"shrink-0 rounded-none border-l border-border h-8 px-3 text-xs",children:[t.jsx(v.Filter,{className:"size-3.5"}),"Filter"]}),y&&t.jsx(q,{variant:"ghost",size:"sm",onClick:L,title:"Clear filter","aria-label":"Clear filter",className:"shrink-0 rounded-none border-l border-border h-8 px-2 text-xs text-muted-foreground",children:t.jsx(v.X,{className:"size-3.5"})})]}),t.jsxs("div",{className:"flex items-center gap-px border border-border rounded-md overflow-hidden shrink-0",children:[t.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>d("/"),className:"text-muted-foreground text-xs h-8 px-3 rounded-none",children:[t.jsx(v.X,{className:"size-3.5"}),"Clear"]}),j?.isEditable&&t.jsxs(q,{variant:"default",size:"sm",onClick:()=>d("edit/"),className:"h-8 text-xs px-4 rounded-none",children:[t.jsx(v.Plus,{className:"size-3.5"}),"Add"]})]})]}):null]})}class Yt extends f.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){const{onError:s,section:o}=this.props;console.error(`Error in ${o??"component"}:`,n,r),s?.(n,r)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){const{hasError:n,error:r}=this.state,{children:s,fallback:o,section:i}=this.props;return n?o||t.jsx("div",{className:"flex items-center justify-center p-5 min-h-[100px]",children:t.jsxs(mt,{variant:"destructive",className:"max-w-[400px]",children:[t.jsx(v.AlertCircle,{className:"size-4"}),t.jsxs(Fr,{children:["Something went wrong",i?` in ${i}`:""]}),t.jsxs(ft,{className:"mt-2",children:[t.jsx("p",{children:r?.message??"An unexpected error occurred"}),t.jsx(q,{variant:"destructive",size:"sm",className:"mt-3",onClick:this.handleRetry,children:"Try Again"})]})]})}):s}}function uc(){const{loading:e,error:n,data:r}=je();return e?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[t.jsx(v.Database,{className:"size-10 animate-pulse"}),t.jsx("p",{className:"text-sm",children:"Loading schema..."})]}):n?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[t.jsx(v.Database,{className:"size-12 text-destructive"}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Connection Error"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n.message})]})]}):r.length===0?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[t.jsx(v.Database,{className:"size-12 text-muted-foreground/50"}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"No Tables Found"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"This database doesn't contain any tables. It may be a new or empty database."}),t.jsx("p",{className:"mt-3 text-xs text-muted-foreground/70",children:"Create tables in your database and reconnect, or try a different connection."})]})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-6 max-w-lg mx-auto text-center",children:[t.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground/50",children:[t.jsx(v.Table2,{className:"size-10"}),t.jsx(v.MousePointerClick,{className:"size-6"})]}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Select a Table"}),t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Choose a table from the sidebar to browse and edit its data."})]}),t.jsxs("div",{className:"text-xs text-muted-foreground/60 border border-border rounded-md px-4 py-3 bg-muted/30",children:[t.jsxs("p",{className:"font-medium text-muted-foreground mb-1",children:[r.length," table",r.length!==1?"s":""," available"]}),t.jsxs("p",{className:"leading-relaxed",children:[r.slice(0,8).map(s=>s.label).join(", "),r.length>8?`, and ${r.length-8} more`:""]})]})]})}function mc({children:e}){const{loading:n,error:r}=je();return n?t.jsxs("div",{className:"flex items-center justify-center flex-1 gap-3 text-muted-foreground",children:[t.jsx(v.Loader2,{className:"size-6 animate-spin"}),t.jsx("span",{className:"text-sm",children:"Connecting to database..."})]}):r?t.jsx("div",{className:"flex items-center justify-center flex-1",children:t.jsxs(mt,{variant:"destructive",className:"max-w-lg",children:[t.jsx(v.AlertCircle,{className:"size-4"}),t.jsx(Fr,{children:"Database Connection Error"}),t.jsxs(ft,{className:"mt-2",children:[t.jsx("p",{className:"text-sm",children:r.message}),t.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Check your connection string and ensure the database server is running."})]})]})}):t.jsx(t.Fragment,{children:e})}const vs=()=>t.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[t.jsx(v.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});function fc(){const[e,n]=f.useState(!0);return t.jsx(mc,{children:t.jsx(sc,{children:t.jsxs("div",{className:`grid h-full flex-1 min-h-0 grid-rows-[auto_1fr] ${e?"grid-cols-[minmax(150px,min-content)_1fr]":"grid-cols-[0px_1fr]"} md:grid-cols-[minmax(150px,min-content)_1fr] transition-[grid-template-columns] duration-200`,children:[t.jsxs("div",{className:"col-span-full sticky top-0 z-50 bg-background border-b border-border flex items-center",children:[t.jsx(q,{variant:"ghost",size:"icon",className:"md:hidden ml-1 shrink-0",onClick:()=>n(!e),"aria-label":"Toggle sidebar",title:"Toggle sidebar",children:t.jsx(v.PanelLeft,{className:"size-5"})}),t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx(Yt,{section:"Header",children:t.jsxs(an,{children:[t.jsx(he,{path:"/:table/*",element:t.jsx(Sn,{})}),t.jsx(he,{path:"/:table",element:t.jsx(Sn,{})}),t.jsx(he,{path:"/",element:t.jsx(Sn,{})})]})})})]}),t.jsx("nav",{"aria-label":"Tables",className:`border-r border-border overflow-hidden min-h-0 ${e?"":"hidden"} md:block`,children:t.jsx(Yt,{section:"Table List",children:t.jsx(Fa,{})})}),t.jsxs("main",{className:"flex flex-col overflow-hidden min-h-0 px-1 py-0.5",children:[t.jsx(Yt,{section:"Data Panel",children:t.jsx(f.Suspense,{fallback:t.jsx(vs,{}),children:t.jsxs(an,{children:[t.jsx(he,{path:"/:table/from/:filterTable/:id/edit/:editid",element:t.jsx(We,{})}),t.jsx(he,{path:"/:table/from/:filterTable/:id",element:t.jsx(We,{})}),t.jsx(he,{path:"/:table/:id/edit/:editid",element:t.jsx(We,{})}),t.jsx(he,{path:"/:table/:id",element:t.jsx(We,{})}),t.jsx(he,{path:"/:table/edit/:editid",element:t.jsx(We,{})}),t.jsx(he,{path:"/:table/edit",element:t.jsx(We,{})}),t.jsx(he,{path:"/:table",element:t.jsx(We,{})}),t.jsx(he,{path:"/",element:t.jsx(uc,{})})]})})}),t.jsx(Yt,{section:"Data Edit",children:t.jsx(f.Suspense,{fallback:t.jsx(vs,{}),children:t.jsxs(an,{children:[t.jsx(he,{path:"/:table/from/:filterTable/:id/edit/:editid",element:t.jsx(Jt,{})}),t.jsx(he,{path:"/:table/:id/edit/:editid",element:t.jsx(Jt,{})}),t.jsx(he,{path:"/:table/edit/:editid",element:t.jsx(Jt,{})}),t.jsx(he,{path:"/:table/edit",element:t.jsx(Jt,{})})]})})})]})]})})})}function pc({onLocate:e}){const n=Rn();return f.useEffect(()=>{e?.(n)},[n,e]),t.jsx(fc,{})}function js({uri:e,fetcher:n,uiPath:r,onLocate:s,showStats:o=!1}){const i=f.useMemo(()=>n||(e?new Zn(e):null),[e,n]),a=f.useMemo(()=>new le.QueryClient({defaultOptions:{queries:{staleTime:300*1e3,retry:1}}}),[]);return i?t.jsx(le.QueryClientProvider,{client:a,children:t.jsx(go,{value:i,children:t.jsx(Na,{config:{showStats:o},children:t.jsx(lo,{path:r||"/",children:t.jsx(jo,{children:t.jsx(pc,{onLocate:s})})})})})}):t.jsx("section",{children:"CONFIG MISSING..."})}fe.Editor=js,fe.HttpGraphQLFetcher=Zn,fe.default=js,fe.useTableMutation=yn,Object.defineProperties(fe,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
120
|
+
}`},[e,t,a]),{isLoading:m,error:d,data:f}=de.useQuery({queryKey:["editRecord",e.name,r],queryFn:()=>s.query(c,a.variables),enabled:!!e&&!o&&a.filterText!==""}),p=f?.value?.data?.at(0),x=!o&&f!==void 0&&p===void 0,h=u.useMemo(()=>p??{},[p]),y=u.useMemo(()=>{const N={};for(const{column:T,fkRole:k}of t){const $=Su(T,k);if(Yn(T))N[T.name]=Br(h[T.name],Vr(T));else if(Wr.some(b=>b===T.paramType)){const b=h[T.name];N[T.name]=T.isNullable&&b==null?null:!!b}else if(Ft(T)){const b=h[T.name];N[T.name]=b==null?"":JSON.stringify(b,null,2)}else if($){const b=h[T.name];N[T.name]=b??null}else N[T.name]=h[T.name]??""}return N},[h,t]);return{isLoading:m,error:d,value:h,defaultValues:y,pkResolveFailed:l,recordNotFound:x}}function Eu({table:e,schema:t,editId:r,onClose:s}){const o=r===void 0||r==="",[i,a,l]=Tu(t,e),c=i.labelColumn,m=i.label,d=wn(i,a,l,r),{isLoading:f,error:p,value:x,defaultValues:h,pkResolveFailed:y,recordNotFound:N}=$u(i,a,r),T=Tn.useForm({defaultValues:h,onSubmit:async({value:S})=>{const L=ju(S,x,a.map(({column:D})=>D));await(o?d.insert:d.update)(L),s()}}),k=Tn.useStore(T.store,S=>S.isDirty),[$,b]=u.useState(!1),v=()=>{k?b(!0):s()};if(f&&!o)return n.jsx(jt,{open:!0,onOpenChange:S=>{S||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl",children:[n.jsx(Ct,{className:"sr-only",children:"Loading record"}),n.jsx(Kt,{className:"sr-only",children:"Loading record for editing"}),n.jsxs("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground",children:[n.jsx(C.LoaderCircle,{className:"size-4 animate-spin"}),"Loading…"]})]})});if(p)return n.jsxs("div",{children:["Error: ",p.message]});if(y||N)return n.jsx(jt,{open:!0,onOpenChange:S=>{S||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-md",children:[n.jsx(Ct,{className:"text-sm font-semibold",children:"Cannot edit record"}),n.jsxs(Kt,{className:"text-sm text-muted-foreground",children:[y?`This record can't be opened for editing: its key (${r||"empty"}) is missing or malformed for the ${m} table.`:`No ${m} record matches the key ${r}. It may have been deleted or is no longer visible to you.`," ","Return to the grid and try again."]}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Q,{type:"button",size:"sm",onClick:s,children:"Close"})})]})});const w=x?.[c]??r,F=a.filter(({column:S})=>Wr.some(L=>L===S.paramType)),j=a.filter(({column:S})=>Uo(S)),V=a.filter(({column:S})=>!Wr.some(L=>L===S.paramType)&&!Uo(S));return n.jsxs(jt,{open:!0,onOpenChange:S=>{S||v()},children:[n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border bg-muted/30 shrink-0",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx(Ct,{className:"text-sm font-semibold truncate",children:o?`New ${m}`:`${m} : ${w}`}),n.jsxs(Kt,{className:"sr-only",children:[o?"Create":"Edit"," ",m," record"]})]}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:v,"aria-label":"Close",className:"shrink-0 -mr-1",children:n.jsx(C.X,{className:"size-4"})})]}),d.error&&n.jsxs("div",{className:"flex items-center gap-2 px-5 py-2 bg-destructive/10 border-b border-destructive/20 text-destructive text-sm shrink-0",children:[n.jsx(C.AlertCircle,{className:"size-3.5 shrink-0"}),n.jsx("span",{className:"truncate",children:d.error.message})]}),n.jsxs("form",{onSubmit:S=>{S.preventDefault(),S.stopPropagation(),T.handleSubmit().catch(()=>{})},className:"flex flex-col flex-1 min-h-0",children:[n.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[V.length>0&&n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:V.map(({column:S,join:L,fkRole:A})=>n.jsx(Pu,{column:S,join:L,fkRole:A,form:T,schema:t},S.name))}),F.length>0&&n.jsx("div",{className:V.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2",children:F.map(({column:S})=>n.jsx(Du,{column:S,form:T},S.name))})}),j.length>0&&n.jsx("div",{className:V.length>0||F.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"grid gap-3",children:j.map(({column:S})=>n.jsx(Mu,{column:S,form:T},S.name))})})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border bg-muted/30 shrink-0",children:[n.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:v,children:"Cancel"}),n.jsxs(Q,{type:"submit",size:"sm",disabled:d.isPending,children:[d.isPending?n.jsx(C.LoaderCircle,{className:"size-3.5 animate-spin"}):n.jsx(C.Save,{className:"size-3.5"}),o?"Create":"Save"]})]})]})]}),n.jsx(Kr,{open:$,onOpenChange:b,title:"Discard unsaved changes?",description:n.jsx("p",{children:"You have unsaved changes. Closing now will discard them."}),confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"destructive",onConfirm:()=>{b(!1),s()}})]})}function Xn(){const{table:e,editId:t}=ir(),r=_n();if(!e)return n.jsx("div",{children:"Table missing"});const s=t?"../..":"..";return n.jsx(Ro,{table:e,editId:t??"",onClose:()=>r(s)})}function Ro({table:e,editId:t,onClose:r}){const s=Je();return e?s.loading?n.jsx("div",{children:"Loading..."}):s.error?n.jsxs("div",{children:["Error: ",s.error.message]}):s.findTable(e)?n.jsx(Eu,{table:e,schema:s,editId:t,onClose:r}):n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Table not found: ",e]}):n.jsx("div",{children:"Table missing"})}function Fu({current:e,max:t}){const r=t-e,s=r<=10&&r>0,o=r<=0;return n.jsx("div",{className:"text-xs text-right mt-0.5","aria-live":"polite",children:n.jsxs("span",{className:o?"text-destructive font-medium":s?"text-amber-500":"text-muted-foreground",children:[e,"/",t]})})}function _u({min:e,max:t,step:r}){if(e===void 0&&t===void 0)return null;let s="";return e!=null&&t!==void 0&&t!==null?s=`Range: ${e} to ${t}`:e!=null?s=`Min: ${e}`:t!=null&&(s=`Max: ${t}`),r!=null&&r!==1&&(s+=` (step: ${r})`),n.jsx("div",{className:"text-xs text-muted-foreground mt-0.5","aria-live":"polite",children:s})}function Pu({column:e,join:t,fkRole:r,form:s,schema:o}){const i=e.name,a=!e.isNullable;if(r==="member-composite")return null;const l=Yn(e),c=Vt(e.paramType),m=e.maxLength&&e.maxLength>0&&!l&&!c;if(e.enumValues&&e.enumValues.length>0)return n.jsx(zu,{column:e,form:s,isRequired:a});if(t&&o)return r==="anchor-composite"?n.jsx(Lu,{column:e,join:t,form:s,schema:o,isRequired:a}):n.jsx(Iu,{column:e,join:t,form:s,schema:o,isRequired:a});const d=Bt(e.paramType),f=e.inputType||(l?Vr(e)?"datetime-local":"date":d?"text":c?"number":"text"),p=d?qt(e.paramType)?"numeric":"decimal":void 0,x=`${i}-error`;return n.jsx(s.Field,{name:i,validators:Nn(e,a),children:h=>{const{ariaProps:y}=Rn(h,x);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,a&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Qe,{id:i,type:f,inputMode:p,value:h.state.value??"",onChange:N=>h.handleChange(N.target.value),onBlur:h.handleBlur,required:a,maxLength:e.maxLength,minLength:e.minLength,min:e.min,max:e.max,step:e.step,pattern:e.pattern,title:e.patternMessage,...y,className:"h-8 text-sm"}),m&&n.jsx(Fu,{current:String(h.state.value??"").length,max:e.maxLength}),c&&(e.min!==void 0||e.max!==void 0)&&n.jsx(_u,{min:e.min,max:e.max,step:e.step}),n.jsx(Zn,{errors:h.state.meta.errors,id:x})]})}})}function zu({column:e,form:t,isRequired:r}){const s=e.name,o=e.enumValues||[],i=e.enumLabels&&e.enumLabels.length===o.length?e.enumLabels:o,a=`${s}-error`;return n.jsx(t.Field,{name:s,validators:Nn(e,r),children:l=>{const{ariaProps:c}=Rn(l,a);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:s,className:"text-xs text-muted-foreground",children:[e.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsxs(Ze,{value:Ho(l.state.value,!r),onValueChange:Jr(m=>l.handleChange(m===Dt?null:m)),children:[n.jsx(tt,{id:s,className:"w-full h-8 text-sm",...c,children:n.jsx(et,{placeholder:`Select ${e.label}`})}),n.jsxs(nt,{children:[!r&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),o.map((m,d)=>n.jsx(we,{value:m,children:i[d]||m},m))]})]}),n.jsx(Zn,{errors:l.state.meta.errors,id:a})]})}})}const Qr="true",Xo="false";function Du({column:e,form:t}){const r=e.name;return e.isNullable?n.jsx(t.Field,{name:r,children:s=>{const o=s.state.value,i=o==null?Dt:o?Qr:Xo;return n.jsxs("div",{className:"grid gap-1 min-w-[10rem]",children:[n.jsx(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:e.label}),n.jsxs(Ze,{value:i,onValueChange:Jr(a=>s.handleChange(a===Dt?null:a===Qr)),children:[n.jsx(tt,{id:r,className:"w-full h-8 text-sm",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(unset)"}),n.jsx(we,{value:Qr,children:"Yes"}),n.jsx(we,{value:Xo,children:"No"})]})]})]})}}):n.jsx(t.Field,{name:r,children:s=>n.jsxs("label",{htmlFor:r,className:"flex items-center gap-2 cursor-pointer select-none",children:[n.jsx(Cn,{id:r,checked:!!s.state.value,onCheckedChange:o=>s.handleChange(!!o),onBlur:s.handleBlur}),n.jsx("span",{className:"text-sm",children:e.label})]})})}function Mu({column:e,form:t}){const r=e.name,s=!e.isNullable,o=`${r}-error`;return n.jsx(t.Field,{name:r,validators:Nn(e,s),children:i=>{const{hasError:a}=Rn(i,o);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:[e.label,s&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Nu,{name:r,label:e.label,value:String(i.state.value??""),dbType:e.dbType,onChange:l=>i.handleChange(l),onBlur:i.handleBlur,required:s,invalid:a}),n.jsx(Zn,{errors:i.state.meta.errors,id:o})]})}})}function Zo(){const[e,t]=u.useState(""),[r,s]=u.useState(""),[o,i]=u.useState(!1);return u.useEffect(()=>{const l=setTimeout(()=>s(e),300);return()=>clearTimeout(l)},[e]),{search:e,setSearch:t,debounced:r,open:o,onOpenChange:l=>{i(l),l||(t(""),s(""))}}}function ea({field:e,column:t,isRequired:r,errorId:s,value:o,onValueChange:i,search:a,setSearch:l,onOpenChange:c,loadError:m,composite:d,children:f}){const{ariaProps:p}=Rn(e,s);return n.jsxs("div",{className:d?"grid gap-1 sm:col-span-2":"grid gap-1",children:[n.jsxs(Wt,{htmlFor:t.name,className:"text-xs text-muted-foreground",children:[t.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),d&&n.jsxs("span",{className:"ml-2 px-1 rounded bg-primary/10 text-[10px] font-medium text-primary",children:["composite FK (",d.cols," cols)"]})]}),n.jsxs(Ze,{value:o,onValueChange:Jr(i),onOpenChange:c,children:[n.jsx(tt,{id:t.name,className:"w-full h-8 text-sm",...p,children:n.jsx(et,{placeholder:`Select ${t.label}`})}),n.jsxs(nt,{children:[n.jsx("div",{className:"px-1 pb-1 sticky top-0 bg-popover z-10",children:n.jsx(Qe,{value:a,onChange:x=>l(x.target.value),onKeyDown:x=>{(x.key.length===1||x.key==="Backspace"||x.key==="Delete")&&x.stopPropagation()},placeholder:"Search…",className:"h-7 text-xs"})}),f]})]}),m!=null&&n.jsxs("p",{className:"text-xs text-destructive",role:"alert",children:["Failed to load ",t.label," options: ",String(m?.message??m)]}),n.jsx(Zn,{errors:e.state.meta.errors,id:s})]})}function Iu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=e.name,a=t.destinationColumnNames[0],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:f}=Zo(),p=hu(s,t.destinationTable,a,m,d),x=Tn.useStore(r.store,b=>b.values?.[i]),h=x==null||x===""||p.data.some(b=>String(b.key)===String(x)),y=gu(s,t.destinationTable,a,!p.loading&&!h?x:null),N=`${i}-error`,T=m.trim(),k=p.serverSearch||!T?p.data:p.data.filter(b=>Wo(b,"key",T)),$=x==null||x===""?null:p.data.find(b=>String(b.key)===String(x))??y.value??{key:String(x),label:String(x)};return n.jsx(r.Field,{name:i,validators:Nn(e,o),children:b=>n.jsxs(ea,{field:b,column:e,isRequired:o,errorId:N,value:Ho(b.state.value,!o),onValueChange:v=>b.handleChange(v===Dt?null:v),search:l,setSearch:c,onOpenChange:f,loadError:p.error,children:[!o&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),$&&!k.some(v=>String(v.key)===String($.key))&&n.jsx(we,{value:String($.key),children:$.label}),k.map(v=>n.jsx(we,{value:String(v.key),children:v.label},v.key)),k.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Lu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=t.sourceColumnNames??[],a=t.destinationColumnNames??[],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:f}=Zo(),p=Tn.useStore(r.store,$=>{const b={};for(let v=0;v<i.length;v++)b[a[v]]=$.values?.[i[v]];return b}),x=yu(s,t.destinationTable,a,{search:m,enabled:d,currentValues:p}),h=u.useMemo(()=>{const $=[];for(let b=0;b<i.length;b++){const v=p[a[b]];if(v==null||v==="")return"";$.push(v)}return $t($)},[p,i,a]),y=m.trim(),N=x.serverSearch||!y?x.data:x.data.filter($=>$.label.toLowerCase().includes(y.toLowerCase())),T=$=>{const b=x.data.find(v=>v.route===$);if(b)for(let v=0;v<i.length;v++){const w=a[v],F=i[v];r.setFieldValue(F,b.values[w])}},k=`${e.name}-error`;return n.jsx(r.Field,{name:e.name,validators:Nn(e,o),children:$=>n.jsxs(ea,{field:$,column:e,isRequired:o,errorId:k,value:h,onValueChange:T,search:l,setSearch:c,onOpenChange:f,loadError:x.error,composite:{cols:i.length},children:[N.map(b=>n.jsx(we,{value:b.route,children:b.label},b.route)),N.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Zn({errors:e,id:t}){return e.length===0?null:n.jsx("div",{id:t,role:"alert",children:e.map((r,s)=>n.jsx("p",{className:"text-xs text-destructive",children:String(r)},s))})}const ta=40,na=32;function Ou({className:e,...t}){return n.jsx("div",{"data-slot":"table-container",className:"relative w-full h-full overflow-x-auto",children:n.jsx("table",{"data-slot":"table",className:Y("min-w-full caption-bottom text-sm border-separate border-spacing-0",e),...t})})}function Au({className:e,...t}){return n.jsx("thead",{"data-slot":"table-header",className:Y("[&_tr]:border-b",e),...t})}function qu({className:e,...t}){return n.jsx("tbody",{"data-slot":"table-body",className:Y("[&_tr:last-child]:border-0 [&_tr:nth-child(even)]:bg-muted/25",e),...t})}function er({className:e,style:t,...r}){return n.jsx("tr",{"data-slot":"table-row",className:Y("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),style:{height:ta,...t},...r})}function Vu({className:e,style:t,...r}){return n.jsx("th",{"data-slot":"table-head",className:Y("px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground text-xs border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),style:{height:na,...t},...r})}function Hr({className:e,...t}){return n.jsx("td",{"data-slot":"table-cell",className:Y("px-2 py-1 align-middle whitespace-nowrap text-[13px] overflow-hidden text-ellipsis border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function Bu({anchorEl:e,onEdit:t,onDelete:r,onMouseEnter:s,onDismiss:o}){const i=u.useRef(null);return u.useEffect(()=>{const a=i.current;return a?((()=>{const c=e.getBoundingClientRect(),m=a.offsetHeight,d=a.offsetWidth;a.style.top=`${c.top+(c.height-m)/2}px`;const f=Math.min(c.right-d-8,window.innerWidth-d-8);a.style.left=`${Math.max(8,f)}px`})(),a.showPopover(),()=>{try{a.hidePopover()}catch{}}):void 0},[e]),u.useEffect(()=>{const a=l=>{const c=i.current;c&&!c.contains(l.target)&&o()};return document.addEventListener("pointerdown",a),()=>document.removeEventListener("pointerdown",a)},[o]),n.jsxs("div",{ref:i,popover:"manual",className:"flex items-center gap-0.5 rounded-md border border-border bg-popover px-1 py-0.5 shadow-md m-0",style:{position:"fixed"},onClick:a=>a.stopPropagation(),onMouseEnter:s,onMouseLeave:o,onFocusCapture:s,onBlur:a=>{a.currentTarget.contains(a.relatedTarget)||o()},children:[t&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:t,"aria-label":"Edit row",title:"Edit",className:"size-6",children:n.jsx(C.Pencil,{className:"size-3.5"})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete row",title:"Delete",className:"size-6 text-destructive hover:text-destructive",children:n.jsx(C.Trash2,{className:"size-3.5"})})]})}function Gu({exportRows:e,total:t,tableName:r,rowCap:s=Pr}){const{toast:o}=vt(),[i,a]=u.useState(!1),[l,c]=u.useState(0),m=u.useRef(null);u.useEffect(()=>()=>m.current?.abort(),[]);const d=u.useCallback(async p=>{if(i||t>s&&typeof window<"u"&&!window.confirm(`This export has ${t.toLocaleString()} rows, over the ${s.toLocaleString()} row limit. Only the first ${s.toLocaleString()} rows will be exported. Continue?`))return;const x=new AbortController;m.current=x,a(!0),c(0);try{const h=await e({format:p,signal:x.signal,rowCap:s,onProgress:y=>c(y)});if(!h)return;Mr(h.content,Dr(r,p),zr(p)),h.truncated&&o(`Export truncated at ${h.rowCount.toLocaleString()} rows.`,"error")}catch(h){if(x.signal.aborted)return;o(`Export failed: ${h instanceof Error?h.message:String(h)}`,"error")}finally{a(!1),m.current=null}},[i,t,s,e,r,o]),f=u.useCallback(()=>m.current?.abort(),[]);return i?n.jsxs(Q,{variant:"outline",size:"sm",onClick:f,title:"Cancel export",children:[n.jsx(C.X,{className:"size-3.5"}),"Cancel (",l.toLocaleString(),")"]}):n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(C.Download,{className:"size-3.5"}),"Export",n.jsx(C.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(An,{align:"end",children:[n.jsx(bt,{onClick:()=>{d("csv")},children:"CSV"}),n.jsx(bt,{onClick:()=>{d("json")},children:"JSON"})]})]})}const Ur=60,ra=450,Ku=150,Yr="bifrost-col-sizes:";function sa(e){try{const t=localStorage.getItem(Yr+e);return t?Wu(JSON.parse(t)):{}}catch{return{}}}function Wu(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={};for(const[r,s]of Object.entries(e))typeof s!="number"||!Number.isFinite(s)||(t[r]=Math.min(Math.max(s,Ur),ra));return t}function Rr(e,t){try{Object.keys(t).length===0?localStorage.removeItem(Yr+e):localStorage.setItem(Yr+e,JSON.stringify(t))}catch{}}function Ju(e){const[t,r]=u.useState(()=>e?sa(e):{}),s=u.useRef(null),o=u.useRef(!0);u.useEffect(()=>{const a=s.current;if(a&&a.tableName!==e&&(s.current=null,Rr(a.tableName,a.sizing)),!e)return;if(o.current){o.current=!1;return}s.current={tableName:e,sizing:t};const l=setTimeout(()=>{s.current=null,Rr(e,t)},300);return()=>clearTimeout(l)},[e,t]),u.useEffect(()=>()=>{const a=s.current;a&&Rr(a.tableName,a.sizing)},[]);const i=u.useRef(e);if(e&&e!==i.current){i.current=e,o.current=!0;const a=sa(e);r(a)}return{columnSizing:t,setColumnSizing:r}}const Qu="bifrost-col-visibility:";function Xr(e){return Qu+e}function Zr(e){try{const t=localStorage.getItem(Xr(e));return t?Hu(JSON.parse(t)):null}catch{return null}}function Hu(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;const t={};for(const[r,s]of Object.entries(e))typeof s=="boolean"&&(t[r]=s);return t}function Uu(e,t){try{localStorage.setItem(Xr(e),JSON.stringify(t))}catch{}}function Yu(e){try{localStorage.removeItem(Xr(e))}catch{}}function Ru(e,t){if(!t||t.length===0)return{};const r=new Set(t),s={};for(const o of e)s[o]=r.has(o);return s}function Xu(e,t){const[r,s]=u.useState(()=>(e?Zr(e):null)??t),o=u.useRef(r),i=u.useCallback(d=>{o.current=d,s(d)},[]),a=u.useCallback(d=>{const f=typeof d=="function"?d(o.current):d;i(f),e&&Uu(e,f)},[i,e]),l=u.useCallback(()=>{e&&Yu(e),i(t)},[i,t,e]),c=u.useRef(e);e&&e!==c.current&&(c.current=e,i(Zr(e)??t));const m=u.useRef(t);return e&&m.current!==t&&(m.current=t,Zr(e)===null&&i(t)),{columnVisibility:r,setColumnVisibility:a,resetColumnVisibility:l}}const Zu=500;function ed(){const[e,t]=u.useState(null),r=u.useRef(null),s=u.useCallback((p,x)=>{r.current&&(clearTimeout(r.current),r.current=null),t({rowId:p,el:x})},[]),o=u.useCallback(()=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>t(null),150)},[]),i=u.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),a=u.useRef(null),l=u.useRef(!1),c=u.useRef(!1),m=u.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]),d=u.useCallback((p,x,h)=>{h.pointerType==="touch"&&(l.current=!1,m(),a.current=setTimeout(()=>{l.current||(c.current=!0,s(p,x))},Zu))},[m,s]),f=u.useCallback(()=>{l.current=!0,m()},[m]);return{hoveredRow:e,hoverRow:s,scheduleDismiss:o,cancelDismiss:i,suppressClick:c,startPress:d,onPressMove:f,cancelPress:m}}const es=-1;function td(e){return Math.max(5,Math.floor((e-na)/ta))}function nd(e,t){const[r,s]=u.useState(!0),o=u.useRef(0),i=u.useCallback(()=>{const a=e.current;return a?td(a.clientHeight):10},[e]);return u.useEffect(()=>{if(!r)return;const a=e.current;if(!a)return;const l=()=>{const f=i();f!==o.current&&(o.current=f,t(f))},c=requestAnimationFrame(l);let m=null;const d=new ResizeObserver(()=>{m&&clearTimeout(m),m=setTimeout(()=>requestAnimationFrame(l),200)});return d.observe(a),()=>{cancelAnimationFrame(c),m&&clearTimeout(m),d.disconnect()}},[r,i,t,e]),{fitMode:r,setFitMode:s,computeFitSize:i}}function rd(e){return e.id??("accessorKey"in e?String(e.accessorKey):void 0)}function oa(e,t){return t.map(r=>e.find(s=>rd(s)===r)).filter(r=>r!==void 0)}function sd(e,{leading:t,trailing:r}){const s=t?oa(e,t):[],o=r?oa(e,r):[];if(s.length===0&&o.length===0)return e;const i=new Set([...s,...o]),a=e.filter(l=>!i.has(l));return[...s,...a,...o]}function od({label:e,rows:t,loading:r,error:s,sumLabel:o,pageSize:i,sort:a,onSortChange:l,memberRequest:c}){const m=$e(),[d,f]=u.useState(0),[p,x]=u.useState(null),h=p===null?null:c(p.value),y=de.useQuery({queryKey:["groupMembers",h?.query,h?.variables],queryFn:({signal:v})=>m.query(h.query,h.variables,{signal:v}),enabled:h!==null}),N=t.map(v=>`${String(v.value)}:${v.count}:${String(v.sum)}`).join("|");if(u.useEffect(()=>{f(0),x(null)},[e,N,i]),s)return n.jsxs("p",{role:"alert",className:"px-2 py-1 text-sm text-destructive",children:["Grouping failed: ",s.message]});if(r)return n.jsx("p",{className:"px-2 py-1 text-sm text-muted-foreground",children:"Loading grouped results…"});const T=Math.max(1,i),k=Math.max(1,Math.ceil(t.length/T)),$=t.slice(Math.min(d,k-1)*T,(Math.min(d,k-1)+1)*T),b=h?y.data?.[h.responseKey]:void 0;return n.jsxs("div",{className:"border-b px-2 py-2","aria-label":`Grouped by ${e}`,children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-sm font-medium",children:[n.jsxs("span",{children:["Grouped by ",e]}),n.jsxs("label",{className:"text-xs font-normal text-muted-foreground",children:["Group order",n.jsxs("select",{"aria-label":"Group order",className:"ml-1 rounded border bg-background px-1 py-0.5 text-foreground",value:`${a.field}:${a.desc?"desc":"asc"}`,onChange:v=>{const[w,F]=v.target.value.split(":");l({field:w==="count"?"count":"key",desc:F==="desc"})},children:[n.jsxs("option",{value:"key:asc",children:[e," ascending"]}),n.jsxs("option",{value:"key:desc",children:[e," descending"]}),n.jsx("option",{value:"count:desc",children:"Count high to low"}),n.jsx("option",{value:"count:asc",children:"Count low to high"})]})]}),n.jsxs("span",{className:"text-muted-foreground",children:[t.length," groups"]})]}),n.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1 text-sm",children:[$.map((v,w)=>n.jsxs("div",{className:"contents",children:[n.jsx("button",{type:"button",className:"text-left underline-offset-2 hover:underline","aria-expanded":p===v,onClick:()=>x(p===v?null:v),children:v.value===null||v.value===void 0?"(null)":String(v.value)}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:v.count}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:o?String(v.sum??"—"):""})]},`${String(v.value)}-${w}`)),t.length===0&&n.jsx("span",{className:"text-muted-foreground",children:"No grouped results."})]}),t.length>T&&n.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs",children:[n.jsx("button",{type:"button",disabled:d===0,onClick:()=>f(v=>v-1),children:"Previous groups"}),n.jsxs("span",{children:["Group page ",Math.min(d,k-1)+1," of ",k]}),n.jsx("button",{type:"button",disabled:d>=k-1,onClick:()=>f(v=>v+1),children:"Next groups"})]}),h&&n.jsx("div",{className:"mt-2 rounded bg-muted/40 p-2 text-xs","aria-live":"polite",children:y.isLoading?"Loading group members…":y.error?"Group member query failed.":n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[b?.total??0," matching members"]}),n.jsx("pre",{className:"max-h-32 overflow-auto",children:JSON.stringify(b?.data??[],null,2)})]})})]})}const ad=[10,20,30,50,100];function id({columns:e,data:t,tableName:r,pageCount:s,pageIndex:o,pageSize:i,sorting:a,columnFilters:l,loading:c,fetching:m=!1,selectable:d=!1,primaryKeys:f=[],selectedRowId:p,onRowSelect:x,onSortingChange:h,onColumnFiltersChange:y,onPageIndexChange:N,onPageSizeChange:T,onEditRow:k,onDeleteRow:$,onDeleteSelected:b,onBulkEditSelected:v,inlineEditableColumns:w,inlineBooleanColumns:F,pendingEdits:j,onCellCommit:V,onSaveAllEdits:S,onDiscardAllEdits:L,savingEdits:A=!1,stackingEnabled:D,onToggleStacking:B,exportRows:X,totalRows:E,onVisualize:P,groupableColumns:q,grouping:U,onGroupingChange:_,onGroupingSumChange:ce}){const{hoveredRow:he,hoverRow:Ue,scheduleDismiss:Pe,cancelDismiss:ie,suppressClick:se,startPress:ke,onPressMove:Ae,cancelPress:re}=ed(),{defaultColumns:Ee,trailingColumns:Ie}=cr(),[Le,Ge]=u.useState({}),[Oe,ye]=u.useState(null),{columnSizing:ze,setColumnSizing:O}=Ju(r),Z=u.useRef(null),{fitMode:ee,setFitMode:Ce,computeFitSize:xe}=nd(Z,T),qe=u.useCallback(z=>{const H=Z.current;if(!H)return;const I=H.querySelectorAll(`[data-col-id="${z}"]`);let ne=Ur;I.forEach(De=>{const ot=De.scrollWidth+4;ot>ne&&(ne=ot)});const Se=Math.min(ne,ra);O(De=>({...De,[z]:Se}))},[O]),W=u.useCallback(()=>{O({})},[O]);u.useEffect(()=>{Ge({})},[t,o]);const me=u.useMemo(()=>{const z=[];return d&&z.push({id:"_select",header:({table:H})=>n.jsx(Cn,{checked:H.getIsAllPageRowsSelected()||H.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:I=>H.toggleAllPageRowsSelected(!!I),"aria-label":"Select all"}),cell:({row:H})=>n.jsx(Cn,{checked:H.getIsSelected(),onCheckedChange:I=>H.toggleSelected(!!I),onClick:I=>I.stopPropagation(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1,enableResizing:!1,size:32}),z.push(...sd(e,{leading:r?Ee?.[r]:void 0,trailing:Ie})),z},[e,d,Ee,r,Ie]),Ne=u.useMemo(()=>Ru(me.filter(z=>z.enableHiding!==!1).map(z=>z.id).filter(z=>z!==void 0),r?Ee?.[r]:void 0),[me,Ee,r]),{columnVisibility:ve,setColumnVisibility:rt,resetColumnVisibility:Mt}=Xu(r,Ne),be=$n.useReactTable({data:t,columns:me,pageCount:s,getRowId:(z,H)=>He(z,{primaryKeys:f},H),state:{sorting:a,columnFilters:l,pagination:{pageIndex:o,pageSize:i},columnVisibility:ve,rowSelection:Le,columnSizing:ze},defaultColumn:{minSize:Ur,size:Ku},columnResizeMode:"onChange",enableColumnResizing:!0,onColumnSizingChange:O,meta:{onResetColumnWidths:W},onSortingChange:z=>{const H=typeof z=="function"?z(a):z;h(H)},onPaginationChange:z=>{const I=typeof z=="function"?z({pageIndex:o,pageSize:i}):z;I.pageSize!==i?(T(I.pageSize),N(0)):N(I.pageIndex)},onColumnFiltersChange:z=>{const H=typeof z=="function"?z(l):z;y(H)},onColumnVisibilityChange:rt,onRowSelectionChange:Ge,enableRowSelection:d,getCoreRowModel:$n.getCoreRowModel(),manualSorting:!0,manualFiltering:!0,manualPagination:!0}),ft=Object.keys(Le).length,Nt=be.getVisibleLeafColumns().map(z=>z.id).join("|"),Ye=u.useCallback(()=>{const z=[];for(const H of be.getSelectedRowModel().rows){const I=mt(H.original,{primaryKeys:f});I&&z.push(I)}return z},[be,f]),Xe=u.useCallback(()=>{if(!b)return;const z=Ye();z.length>0&&b(z)},[Ye,b]),Qt=u.useCallback(()=>{if(!v)return;const z=Ye();z.length>0&&v(z)},[Ye,v]),kn=u.useCallback((z,H)=>{ye({rowId:z,columnId:H})},[]),Sn=u.useCallback((z,H,I)=>{ye(null),V?.(z,H,I)},[V]),Ht=u.useCallback(()=>ye(null),[]),pt=u.useCallback(z=>{const H=be.getRow(z);return H?mt(H.original,{primaryKeys:f}):null},[be,f]),It=u.useCallback(z=>{if(!k)return;const H=pt(z);H&&k(H)},[k,pt]),st=u.useCallback(z=>{if(!$)return;const H=pt(z);H&&$(H)},[$,pt]),Ut=u.useCallback(()=>{he&&It(he.rowId)},[he,It]),Lt=u.useCallback(()=>{he&&st(he.rowId)},[he,st]);return n.jsxs("div",{className:"flex flex-col w-full min-h-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>be.resetColumnFilters(),title:"Clear all column filters",children:[n.jsx(C.FilterX,{className:"size-3.5"}),"Clear filters"]}),ft>0&&(b||v)&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-muted-foreground",children:[ft," selected"]}),v&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Qt,title:"Apply one set of field changes to every selected row in one transaction",children:[n.jsx(C.Pencil,{className:"size-3.5"}),"Edit"]}),b&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Xe,className:"text-destructive hover:text-destructive",children:[n.jsx(C.Trash2,{className:"size-3.5"}),"Delete"]})]}),(j?.size??0)>0&&S&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-amber-600 dark:text-amber-400",children:[j.size," unsaved ",j.size===1?"row":"rows"]}),n.jsx(Q,{size:"sm",onClick:S,disabled:A,children:A?"Saving…":"Save all"}),L&&n.jsx(Q,{variant:"outline",size:"sm",onClick:L,disabled:A,children:"Discard"})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[P&&n.jsx(Q,{variant:"outline",size:"sm",onClick:P,title:"Open a chart using this table and its active filters",children:"Visualize"}),X&&n.jsx(Gu,{exportRows:X,total:E??0,tableName:r??"export"}),B&&n.jsxs(Q,{variant:D?"secondary":"outline",size:"sm",role:"switch","aria-checked":!!D,onClick:()=>B(!D),title:D?"Stacked drill-down active — click for flat grid":"Flat grid active — click for stacked drill-down",children:[D?n.jsx(C.PanelRight,{className:"size-3.5"}):n.jsx(C.Rows3,{className:"size-3.5"}),D?"Stacked":"Grid"]}),_&&q&&n.jsxs(Ze,{value:U?.column.name??"__none",onValueChange:z=>_(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group grid by column",children:n.jsx(et,{placeholder:"Group by"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"No grouping"}),q.map(z=>n.jsx(we,{value:z.name,children:z.label},z.name))]})]}),U&&ce&&q&&n.jsxs(Ze,{value:U.sumColumn?.name??"__none",onValueChange:z=>ce(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group sum column",children:n.jsx(et,{placeholder:"Sum column"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"Count only"}),q.filter(z=>/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(z.paramType.replace(/[!\[\]]/g,""))).map(z=>n.jsxs(we,{value:z.name,children:["Sum ",z.label]},z.name))]})]}),n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(C.Columns3,{className:"size-3.5"}),"Columns",n.jsx(C.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(An,{align:"end",children:[be.getAllColumns().filter(z=>z.getCanHide()).map(z=>{const I=z.columnDef.meta?.column?.label??(typeof z.columnDef.header=="string"?z.columnDef.header:z.id);return n.jsx(Ki,{checked:z.getIsVisible(),onCheckedChange:ne=>z.toggleVisibility(!!ne),children:I},z.id)}),n.jsx(yt,{}),n.jsx(bt,{onClick:Mt,children:"Reset to default columns"})]})]})]})]}),U?n.jsxs(n.Fragment,{children:[n.jsx(od,{label:U.column.label,rows:U.rows,loading:U.loading,error:U.error,sumLabel:U.sumColumn?.label,pageSize:i,sort:U.sort,onSortChange:U.onSortChange,memberRequest:U.memberRequest}),n.jsx("p",{className:"border-b px-2 py-1 text-xs text-muted-foreground",role:"note",children:"Inline editing is disabled while grouping is active; expand a group to inspect its server-filtered members."})]}):n.jsxs(n.Fragment,{children:[m&&n.jsx("div",{className:"relative h-0 z-20",children:n.jsxs("div",{"data-testid":"fetch-indicator",role:"progressbar","aria-label":"Loading page",className:"absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-primary/20",children:[n.jsx("div",{className:"h-full w-1/3 bg-primary",style:{animation:"edit-db-indeterminate 1.2s ease-in-out infinite"}}),n.jsx("style",{children:"@keyframes edit-db-indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } }"})]})}),n.jsxs("div",{ref:Z,className:"relative flex-1 overflow-auto min-h-0","aria-busy":m||c,children:[n.jsxs(Ou,{style:{tableLayout:"fixed",width:be.getTotalSize()},children:[n.jsx("colgroup",{children:be.getVisibleLeafColumns().map(z=>n.jsx("col",{style:{width:z.getSize()}},z.id))}),n.jsx(Au,{children:be.getHeaderGroups().map(z=>n.jsx(er,{children:z.headers.map(H=>n.jsxs(Vu,{"data-col-id":H.column.id,className:"relative","aria-sort":H.column.getIsSorted()==="asc"?"ascending":H.column.getIsSorted()==="desc"?"descending":H.column.getCanSort()?"none":void 0,children:[H.isPlaceholder?null:$n.flexRender(H.column.columnDef.header,H.getContext()),H.column.getCanResize()&&n.jsx("div",{onMouseDown:H.getResizeHandler(),onTouchStart:H.getResizeHandler(),onDoubleClick:()=>qe(H.column.id),className:`absolute top-0 right-0 w-1 h-full cursor-col-resize select-none touch-none opacity-0 hover:opacity-100 transition-opacity ${H.column.getIsResizing()?"bg-primary opacity-100":"bg-border hover:bg-muted-foreground"}`})]},H.id))},z.id))}),n.jsx(qu,{children:c?n.jsx(er,{children:n.jsx(Hr,{colSpan:me.length,className:"h-24 text-center",children:"Loading..."})}):be.getRowModel().rows.length===0?n.jsx(er,{children:n.jsx(Hr,{colSpan:me.length,className:"h-24 text-center",children:"No results."})}):be.getRowModel().rows.map(z=>n.jsx(cd,{row:z,isSelected:p!=null&&z.id===p,checked:z.getIsSelected(),visibleKey:Nt,pending:j?.get(z.id),editingColumnId:Oe?.rowId===z.id?Oe.columnId:null,inlineEditableColumns:V?w:void 0,inlineBooleanColumns:F,onStartEditCell:V?kn:void 0,onCommitCell:Sn,onCancelEditCell:Ht,onRowSelect:x,onEditRow:k?It:void 0,onDeleteRow:$?st:void 0,suppressClick:se,hoverRow:Ue,scheduleDismiss:Pe,startPress:ke,onPressMove:Ae,cancelPress:re},z.id))})]}),he&&(k||$)&&n.jsx(Bu,{anchorEl:he.el,onEdit:k?Ut:void 0,onDelete:$?Lt:void 0,onMouseEnter:ie,onDismiss:Pe})]}),n.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 border-t border-border mt-auto shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[n.jsx("span",{children:"Rows per page"}),n.jsxs(Ze,{value:String(ee?es:i),onValueChange:z=>{const H=Number(z);H===es?(Ce(!0),T(xe())):(Ce(!1),T(H))},children:[n.jsx(tt,{size:"sm",className:"w-auto h-7 text-xs","aria-label":"Rows per page",children:n.jsx(et,{children:ee?"Fit":i})}),n.jsxs(nt,{children:[n.jsx(we,{value:String(es),children:"Fit"}),ad.map(z=>n.jsx(we,{value:String(z),children:z},z))]})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("span",{className:"text-xs text-muted-foreground mr-2",children:["Page ",o+1," of ",s||1]}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(0),disabled:o===0,"aria-label":"First page",title:"First page",children:n.jsx(C.ChevronsLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o-1),disabled:!be.getCanPreviousPage(),"aria-label":"Previous page",title:"Previous page",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o+1),disabled:!be.getCanNextPage(),"aria-label":"Next page",title:"Next page",children:n.jsx(C.ChevronRight,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(s-1),disabled:o>=s-1,"aria-label":"Last page",title:"Last page",children:n.jsx(C.ChevronsRight,{className:"size-4"})})]})]})]})]})}function ld({row:e,isSelected:t,checked:r,pending:s,editingColumnId:o,inlineEditableColumns:i,inlineBooleanColumns:a,onStartEditCell:l,onCommitCell:c,onCancelEditCell:m,onRowSelect:d,onEditRow:f,onDeleteRow:p,suppressClick:x,hoverRow:h,scheduleDismiss:y,startPress:N,onPressMove:T,cancelPress:k}){const $=!!(d||f||p);return n.jsx(er,{"data-state":t||r?"selected":void 0,className:d?"cursor-pointer group/row focus-visible:outline-2 focus-visible:outline-primary":"group/row focus-visible:outline-2 focus-visible:outline-primary",tabIndex:$?0:void 0,onClick:d?()=>{if(x.current){x.current=!1;return}window.getSelection()?.toString()||d(t?null:e.id)}:void 0,onKeyDown:$?b=>{b.target===b.currentTarget&&((b.key==="Enter"||b.key===" ")&&d?(b.preventDefault(),d(t?null:e.id)):(b.key==="e"||b.key==="E")&&f?(b.preventDefault(),f(e.id)):(b.key==="Delete"||b.key==="Backspace")&&p&&(b.preventDefault(),p(e.id)))}:void 0,onFocus:b=>{b.target===b.currentTarget&&h(e.id,b.currentTarget)},onBlur:b=>{b.currentTarget.contains(b.relatedTarget)||y()},onPointerEnter:b=>{b.pointerType==="mouse"&&h(e.id,b.currentTarget)},onPointerLeave:b=>{b.pointerType==="mouse"&&y()},onPointerDown:b=>N(e.id,b.currentTarget,b),onPointerMove:T,onPointerUp:k,onPointerCancel:k,children:e.getVisibleCells().map(b=>{const v=b.column.id,w=!!l&&!!i?.has(v),F=o===v,j=!!s&&v in s;return n.jsx(Hr,{"data-col-id":v,"data-dirty":j?"true":void 0,className:j?"bg-amber-500/10 border-l-2 border-l-amber-500":void 0,title:w&&!F?"Double-click to edit":void 0,onDoubleClick:w&&!F?()=>l(e.id,v):void 0,children:F&&c&&m?n.jsx(ud,{initialValue:j?s[v]:e.original[v],boolean:!!a?.has(v),onCommit:V=>c(e.id,v,V),onCancel:m}):j?n.jsx("span",{title:"Unsaved change",children:s[v]==null?"":String(s[v])}):$n.flexRender(b.column.columnDef.cell,b.getContext())},b.id)})})}const cd=u.memo(ld);function ud({initialValue:e,boolean:t,onCommit:r,onCancel:s}){const[o,i]=u.useState(e==null?"":String(e));return t?n.jsx("input",{type:"checkbox",autoFocus:!0,defaultChecked:e===!0||e==="true",onChange:a=>r(a.target.checked),onKeyDown:a=>{a.key==="Escape"&&s()},onBlur:s,"aria-label":"Edit cell value"}):n.jsx("input",{autoFocus:!0,className:"w-full bg-background border border-primary rounded px-1 py-0.5 text-sm outline-none",value:o,onChange:a=>i(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),r(o)):a.key==="Escape"&&(a.preventDefault(),s()),a.stopPropagation()},onBlur:()=>r(o),onClick:a=>a.stopPropagation(),onDoubleClick:a=>a.stopPropagation(),"aria-label":"Edit cell value"})}function dd({table:e,pks:t,onClose:r}){const s=$e(),{toast:o}=vt(),i=qo(e),[a,l]=u.useState({}),[c,m]=u.useState(null),[d,f]=u.useState(!1),p=u.useMemo(()=>e.columns.filter(b=>!b.isReadOnly&&!b.isIdentity&&!b.isPrimaryKey&&!Et(b.dbType)),[e]),x=u.useMemo(()=>e.columns.some(b=>!b.isReadOnly&&!b.isIdentity&&!b.isPrimaryKey&&!b.isNullable&&Et(b.dbType)),[e]),h=u.useMemo(()=>{const b=new Map(e.columns.map(v=>[v.name,v]));return(e.primaryKeys??[]).map(v=>b.get(v)).filter(v=>!!v)},[e]),y=p.filter(b=>a[b.name]?.enabled),N=d||i.isPending,T=(b,v)=>l(w=>{const F=w[b]??{enabled:!1,value:"",setNull:!1};return{...w,[b]:{...F,...v}}}),k=b=>{const v=a[b.name];return v.setNull?null:b.paramType.startsWith("Boolean")?v.value==="true":v.value},$=async()=>{if(m(null),y.length===0){m("Choose at least one field to change.");return}f(!0);try{const b={};for(const L of y)b[L.name]=k(L);const v=p.filter(L=>!L.isNullable||b[L.name]!==void 0),w=[...new Set([...e.primaryKeys??[],...v.map(L=>L.name)])],F=mo(e,t,w);if(!F)throw new Error("The selected rows have no resolvable primary keys.");const V=(await s.query(F.query,F.variables))?.value?.data??[];if(V.length!==t.length)throw new Error(`Only ${V.length} of ${t.length} selected rows still exist. Refresh and retry.`);const S=lu(e,v,h,V,b);await i.saveDelta({updated:S}),r()}catch(b){const v=b.message??String(b);m(v),o(`Bulk edit failed: ${v}`,"error")}finally{f(!1)}};return n.jsx(jt,{open:!0,onOpenChange:b=>{!b&&!N&&r()},children:n.jsxs(wt,{showCloseButton:!1,className:"max-w-lg",children:[n.jsxs(tn,{children:[n.jsxs(Ct,{children:["Edit ",t.length," ",t.length===1?"row":"rows"]}),n.jsx(Kt,{children:"Chosen fields are applied to every selected row and saved in one transaction — if any row fails, nothing changes."})]}),x?n.jsx("p",{className:"text-sm text-destructive",children:"This table has a required binary column, which bulk edit cannot echo. Edit rows individually."}):n.jsx("div",{className:"flex flex-col gap-2 max-h-80 overflow-y-auto py-1",children:p.map(b=>{const v=a[b.name]??{enabled:!1,value:"",setNull:!1},w=b.paramType.startsWith("Boolean");return n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Cn,{id:`bulk-${b.name}`,checked:v.enabled,onCheckedChange:F=>T(b.name,{enabled:F===!0})}),n.jsx(Wt,{htmlFor:`bulk-${b.name}`,className:"w-40 truncate",title:b.label??b.name,children:b.label??b.name}),w?n.jsxs("select",{className:"h-8 rounded-md border bg-transparent px-2 text-sm flex-1",disabled:!v.enabled||v.setNull,value:v.value==="true"?"true":"false",onChange:F=>T(b.name,{value:F.target.value}),children:[n.jsx("option",{value:"true",children:"true"}),n.jsx("option",{value:"false",children:"false"})]}):n.jsx(Qe,{className:"h-8 flex-1",disabled:!v.enabled||v.setNull,value:v.value,onChange:F=>T(b.name,{value:F.target.value})}),b.isNullable&&n.jsxs("label",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(Cn,{checked:v.setNull,disabled:!v.enabled,onCheckedChange:F=>T(b.name,{setNull:F===!0})}),"null"]})]},b.name)})}),c&&n.jsx("p",{className:"text-sm text-destructive",children:c}),n.jsxs(Gr,{children:[n.jsx(Q,{variant:"outline",onClick:r,disabled:N,children:"Cancel"}),n.jsx(Q,{onClick:$,disabled:N||x,children:N?"Saving…":`Apply to ${t.length} ${t.length===1?"row":"rows"}`})]})]})})}function md({...e}){return n.jsx(R.Dialog.Root,{"data-slot":"sheet",...e})}function fd({...e}){return n.jsx(R.Dialog.Portal,{"data-slot":"sheet-portal",...e})}function pd({className:e,...t}){return n.jsx(R.Dialog.Overlay,{"data-slot":"sheet-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function hd({className:e,children:t,side:r="right",...s}){return n.jsxs(fd,{children:[n.jsx(pd,{}),n.jsxs(R.Dialog.Content,{"data-slot":"sheet-content",className:Y("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out duration-200 outline-none","data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-200 data-[state=open]:duration-200",r==="right"&&"inset-y-0 right-0 h-full w-3/4 max-w-md border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",r==="left"&&"inset-y-0 left-0 h-full w-3/4 max-w-md border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),...s,children:[t,n.jsxs(R.Dialog.Close,{"data-slot":"sheet-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(C.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gd({className:e,...t}){return n.jsx("div",{"data-slot":"sheet-header",className:Y("flex flex-col gap-2 p-4 pb-0",e),...t})}function xd({className:e,...t}){return n.jsx(R.Dialog.Title,{"data-slot":"sheet-title",className:Y("text-lg leading-none font-semibold",e),...t})}function bd({className:e,...t}){return n.jsx(R.Dialog.Description,{"data-slot":"sheet-description",className:Y("text-sm text-muted-foreground",e),...t})}const yd={json:C.Braces,xml:C.Code,"php-serialized":C.Database,binary:C.Binary,longtext:C.FileText,text:C.FileText},aa={json:"JSON",xml:"XML","php-serialized":"PHP Serialized",binary:"Binary",longtext:"Text",text:"Text"};function vd(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return t==="xml"?e.replace(/>\s*</g,`>
|
|
121
|
+
<`).trim():e}function jd({target:e,onClose:t,onNavigate:r,onSave:s,canNavigatePrev:o,canNavigateNext:i}){const{toast:a}=vt(),[l,c]=u.useState(!1),[m,d]=u.useState(!1),[f,p]=u.useState(""),[x,h]=u.useState(!1),[y,N]=u.useState(!1),T=u.useRef(null),k=e?.value??"",$=Bn(k,e?.dbType),b=yd[$],v=vd(k,$),w=$==="binary"&&k?so(k):null,F=u.useCallback(()=>{!e||!w||Gl(k,`${e.columnName}${w.extension}`,w.mime)},[e,w,k]);u.useEffect(()=>{d(!1),p(""),h(!1),N(!1)},[e?.rowKey,e?.columnName]),u.useEffect(()=>{if(!e)return;const _=ce=>{m||(ce.key==="ArrowUp"&&o?(ce.preventDefault(),r("prev")):ce.key==="ArrowDown"&&i&&(ce.preventDefault(),r("next")))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[e,m,o,i,r]);const j=u.useRef(null);u.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]);const V=u.useCallback(async()=>{try{await navigator.clipboard.writeText(k)}catch(_){a(`Copy failed: ${_ instanceof Error?_.message:String(_)}`,"error");return}h(!0),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>h(!1),1500)},[k,a]),S=u.useCallback(()=>{p(v),d(!0),requestAnimationFrame(()=>T.current?.focus())},[v]),L=u.useCallback(()=>{d(!1),p("")},[]),A=u.useCallback(async()=>{if(f===v){d(!1);return}if(!(!s||y)){N(!0);try{await s(f),d(!1)}catch{}finally{N(!1)}}},[s,f,v,y]),D=u.useCallback(()=>{if($==="json")try{p(JSON.stringify(JSON.parse(f),null,2))}catch{}else $==="xml"&&p(f.replace(/>\s*</g,`>
|
|
122
|
+
<`).trim())},[f,$]),B=$==="json"||$==="xml",X=!!s&&!e?.isReadOnly&&$!=="binary",E=n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(b,{className:"size-4 text-muted-foreground shrink-0"}),n.jsx("span",{className:"truncate font-semibold text-sm",children:e?.columnLabel}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:w?w.kind==="image"?w.mime.replace("image/","").toUpperCase()+" image":w.kind==="pdf"?"PDF document":aa[$]:aa[$]}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:w?xr(k):`${k.length} chars`})]}),P=n.jsxs("div",{className:"flex items-center gap-1 px-4 pb-2",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:V,children:[x?n.jsx(C.Check,{className:"size-3"}):n.jsx(C.Copy,{className:"size-3"}),x?"Copied":"Copy"]}),w&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:F,children:[n.jsx(C.Download,{className:"size-3"}),"Download"]}),X&&!m&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:S,children:[n.jsx(C.Pencil,{className:"size-3"}),"Edit"]}),m&&B&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:D,children:[n.jsx(C.WrapText,{className:"size-3"}),"Format"]}),n.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("prev"),disabled:!o,"aria-label":"Previous row",title:"Previous row",children:n.jsx(C.ChevronUp,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("next"),disabled:!i,"aria-label":"Next row",title:"Next row",children:n.jsx(C.ChevronDown,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>c(_=>!_),"aria-label":l?"Exit full screen":"Full screen",title:l?"Exit full screen":"Full screen",children:l?n.jsx(C.Minimize2,{className:"size-4"}):n.jsx(C.Maximize2,{className:"size-4"})})]})]}),q=n.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-4 pb-4",children:m?n.jsxs("div",{className:"flex flex-col gap-2 h-full",children:[n.jsx("textarea",{ref:T,value:f,onChange:_=>p(_.target.value),className:Y("flex-1 w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none min-h-[200px]")}),n.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:L,disabled:y,children:"Cancel"}),n.jsx(Q,{type:"button",size:"sm",onClick:A,disabled:y,children:y?"Saving…":"Save"})]})]}):w?.kind==="image"?n.jsx("img",{src:oo(k,w.mime),alt:e?.columnLabel??"Image content",className:"max-w-full rounded-md border border-input"}):w?n.jsxs("div",{className:"rounded-md border border-input bg-muted/30 p-4 text-sm text-muted-foreground",children:[n.jsxs("p",{children:[w.kind==="pdf"?"PDF document":"Binary content"," · ",xr(k)]}),n.jsx("p",{className:"mt-1 text-xs",children:"Use Download to save and open the file."})]}):n.jsx("pre",{className:"text-xs font-mono leading-relaxed whitespace-pre-wrap break-all",children:v})}),U=!!e;return n.jsxs(n.Fragment,{children:[n.jsx(md,{open:U&&!l,onOpenChange:_=>{_||t()},children:n.jsxs(hd,{side:"right",className:"w-[480px] max-w-[90vw]",children:[n.jsxs(gd,{children:[n.jsx(xd,{children:E}),n.jsx(bd,{className:"sr-only",children:"Content viewer panel"})]}),P,q]})}),n.jsx(jt,{open:U&&l,onOpenChange:_=>{_||c(!1)},children:n.jsxs(wt,{className:"max-w-[90vw] max-h-[90vh] w-full h-full flex flex-col",children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:E}),n.jsx(Kt,{className:"sr-only",children:"Content viewer full screen"})]}),P,q]})})]})}function wd(e,t){if(Gn(e,t).filterTexts.length===0)return;const s=[];for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.value===void 0||i.value===""&&i.operator!=="_null"||s.push({[a.graphQlName]:{[i.operator]:i.value}})}return s.length===1?s[0]:s.length>1?{and:s}:void 0}function ts({table:e,id:t,filterTable:r,filterColumn:s,selectedRowId:o,onRowSelect:i,onOpenColumn:a,stackingEnabled:l,onToggleStacking:c}){const m=Qn(e),[d,f]=u.useState(null),[p,x]=u.useState(null),[h,y]=u.useState(null),N=u.useRef([]),T=u.useCallback(I=>{x(Vn(I,e))},[e]),k=u.useCallback(I=>{f({type:"single",pk:I})},[]),$=u.useCallback(I=>{I.length!==0&&f({type:"batch",pks:I})},[]),[b,v]=u.useState(null),w=u.useCallback(I=>{I.length!==0&&v(I)},[]),[F,j]=u.useState(new Map),V=u.useRef(F);V.current=F;const[S,L]=u.useState(!1),A=qo(e),D=u.useCallback((I,ne)=>{const Se=N.current[I];y({columnName:ne,pk:Se?mt(Se,e):null,rowIndex:I,tableName:e.name})},[e]),{columns:B,sorting:X,columnFilters:E,pageIndex:P,pageSize:q,pageCount:U,rows:_,totalRows:ce,grouping:he,exportRows:Ue,loading:Pe,fetching:ie,error:se,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onGroupingChange:Ie,onGroupingSumChange:Le}=Jc(e,t,r,s,D,a),Ge=u.useCallback(async()=>{if(d)try{d.type==="single"?await m.deleteRow(d.pk):await m.deleteRows(d.pks),f(null)}catch{}},[d,m]),Oe=d?.type==="batch"?d.pks.length:1;N.current=_;const{toast:ye}=vt(),ze=$e(),O=e.isEditable!==!1,Z=u.useMemo(()=>h?.pk?Vn(h.pk,e):null,[h,e]),ee=u.useMemo(()=>!h||h.tableName!==e.name?-1:Z===null?h.rowIndex<_.length?h.rowIndex:-1:_.findIndex(I=>{const ne=mt(I,e);return ne!==null&&Vn(ne,e)===Z}),[h,Z,_,e]),Ce=ee>=0?_[ee]:void 0,xe=u.useMemo(()=>h?.pk?qn(h.pk,e):null,[h,e]),qe=h?e.columns.find(I=>I.name===h.columnName):void 0,W=!!h&&!!qe&&!!xe&&_t(qe)&&Ce!==void 0&&!(qe.name in Ce),{data:me,isLoading:Ne,error:ve}=de.useQuery({queryKey:["contentPanelValue",e.name,h?.columnName,Z],queryFn:async()=>{const I=Cr(e,xe,[qe.name]),Se=(await ze.query(I,xe.variables))?.value?.data?.at(0);if(!Se)throw new Error("Row no longer exists.");return Se[qe.name]??null},enabled:W});u.useEffect(()=>{h!==null&&W&&ve&&(y(null),ye(`Could not load content: ${ve.message}`,"error"))},[h,W,ve,ye]),u.useEffect(()=>{h!==null&&h.tableName!==e.name&&y(null)},[h,e.name]),u.useEffect(()=>{h!==null&&h.tableName===e.name&&!Pe&&ee===-1&&(y(null),ye("Row is no longer in the current view; panel closed.","error"))},[h,e.name,Pe,ee,ye]);const rt=u.useMemo(()=>{if(!h||!Ce)return null;const I=e.columns.find(ot=>ot.name===h.columnName);if(!I||W&&(Ne||ve))return null;const ne=W?me:Ce[h.columnName],Se=Ft(I);return{value:ne==null?"":Se||typeof ne=="object"?JSON.stringify(ne,null,2):String(ne),columnName:I.name,columnLabel:I.label,dbType:I.dbType,rowKey:Z??`row-${h.rowIndex}`,isReadOnly:I.isReadOnly||I.isPrimaryKey||I.isIdentity}},[h,Ce,Z,e,W,me,Ne,ve]),Mt=u.useMemo(()=>e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity),[e]),be=u.useMemo(()=>Mt.filter(I=>!I.isNullable||I.name===h?.columnName),[Mt,h?.columnName]),ft=u.useMemo(()=>be.map(I=>({column:I})),[be]),Nt=u.useMemo(()=>{const I=new Map(e.columns.map(ne=>[ne.name,ne]));return(e.primaryKeys??[]).map(ne=>I.get(ne)).filter(ne=>!!ne)},[e]),Ye=wn(e,ft,Nt,Z??""),Xe=O&&xe!==null&&!Ye.isPending,Qt=u.useCallback(async I=>{if(!h||!xe)return;const ne=e.columns.find(De=>De.name===h.columnName);let Se=I;if(ne&&Ft(ne))try{Se=JSON.parse(I)}catch{}try{const De=Cr(e,xe,be.map(kt=>kt.name)),ht=(await ze.query(De,xe.variables))?.value?.data?.[0];if(!ht)throw new Error("Row no longer exists.");const Ke={};for(const kt of be)Ke[kt.name]=ht[kt.name]??null;Ke[h.columnName]=Se,await Ye.update(Ke)}catch(De){throw ye(`Save failed: ${De.message}`,"error"),De}},[h,xe,e,be,Ye,ze,ye]),kn=u.useCallback(()=>{y(null)},[]),Sn=u.useCallback(I=>{if(!h||ee<0)return;const ne=I==="prev"?Math.max(0,ee-1):Math.min(_.length-1,ee+1);D(ne,h.columnName)},[h,ee,_.length,D]),Ht=u.useMemo(()=>new Set(e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity&&!I.isPrimaryKey&&!Et(I.dbType)&&!_t(I)).map(I=>I.name)),[e]),pt=u.useMemo(()=>new Set(e.columns.filter(I=>I.paramType.startsWith("Boolean")).map(I=>I.name)),[e]),It=u.useCallback((I,ne,Se)=>{const De=fn(I,e);if(!De)return;const ot=N.current.find(ht=>He(ht,e,-1)===I);j(ht=>{const Ke=new Map(ht),gt={...Ke.get(I)?.changes??{}},nn=ot?.[ne];return ot!==void 0&&nn==null==(Se==null)&&String(nn??"")===String(Se??"")?delete gt[ne]:gt[ne]=Se,Object.keys(gt).length===0?Ke.delete(I):Ke.set(I,{pk:De,changes:gt}),Ke})},[e]),st=u.useCallback(()=>j(new Map),[]),Ut=u.useCallback(async()=>{const I=[...V.current.entries()];if(I.length!==0){L(!0);try{const ne=e.columns.filter(Me=>Ht.has(Me.name)),Se=(e.primaryKeys??[]).map(Me=>e.columns.find(as=>as.name===Me)).filter(Me=>!!Me),De=new Set(I.flatMap(([,Me])=>Object.keys(Me.changes))),ot=ne.filter(Me=>!Me.isNullable||De.has(Me.name)),ht=[...new Set([...e.primaryKeys??[],...ot.map(Me=>Me.name)])],Ke=mo(e,I.map(([,Me])=>Me.pk),ht);if(!Ke)throw new Error("The edited rows have no resolvable primary keys.");const gt=(await ze.query(Ke.query,Ke.variables))?.value?.data??[];if(gt.length!==I.length)throw new Error(`Only ${gt.length} of ${I.length} edited rows still exist. Refresh and retry.`);const nn=cu(e,ne,Se,gt,Me=>V.current.get(He(Me,e,-1))?.changes);await A.saveDelta({updated:nn}),j(new Map)}catch(ne){ye(`Save failed: ${ne.message}`,"error")}finally{L(!1)}}},[e,Ht,A,ze,ye]),Lt=u.useRef(e.name);u.useEffect(()=>{Lt.current!==e.name&&(Lt.current=e.name,V.current.size>0&&(j(new Map),ye("Unsaved cell edits were discarded on table switch","error")))},[e.name,ye]);const z=u.useMemo(()=>new Map([...F].map(([I,ne])=>[I,ne.changes])),[F]),H=u.useCallback(()=>{const I=wd(E,e);window.dispatchEvent(new CustomEvent("bifrostql:visualize",{detail:{table:e.graphQlName,filter:I,filterType:`TableFilter${e.graphQlName}Input`}}))},[E,e]);return se?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",se.message]})}):n.jsxs(n.Fragment,{children:[n.jsx(id,{columns:B,data:_,tableName:e.name,pageCount:U,pageIndex:P,pageSize:q,sorting:X,columnFilters:E,loading:Pe,fetching:ie,primaryKeys:e.primaryKeys??[],selectable:O&&!he,selectedRowId:o,onRowSelect:i,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onEditRow:O&&!he?T:void 0,onDeleteRow:O&&!he?k:void 0,onDeleteSelected:O&&!he?$:void 0,onBulkEditSelected:O&&!he?w:void 0,inlineEditableColumns:Ht,inlineBooleanColumns:pt,pendingEdits:z,onCellCommit:O&&!he?It:void 0,onSaveAllEdits:Ut,onDiscardAllEdits:st,savingEdits:S,stackingEnabled:l,onToggleStacking:c,exportRows:Ue,totalRows:ce,groupableColumns:e.columns,grouping:he,onGroupingChange:Ie,onGroupingSumChange:Le,onVisualize:H}),n.jsx(Kr,{open:d!==null,onOpenChange:I=>{I||f(null)},title:`Delete ${Oe} ${Oe===1?"row":"rows"}?`,description:n.jsxs(n.Fragment,{children:[n.jsx("p",{children:"This action cannot be undone."}),m.error&&n.jsx("p",{className:"mt-2 text-sm text-destructive",children:m.error.message})]}),confirmLabel:`Delete ${Oe===1?"row":`${Oe} rows`}`,variant:"destructive",isPending:m.isPending,onConfirm:Ge}),n.jsx(jd,{target:rt,onClose:kn,onNavigate:Sn,onSave:Xe?Qt:void 0,canNavigatePrev:ee>0,canNavigateNext:ee>=0&&ee<_.length-1}),b!==null&&n.jsx(dd,{table:e,pks:b,onClose:()=>v(null)}),p!==null&&n.jsx(Ro,{table:e.graphQlName,editId:p,onClose:()=>x(null)})]})}function Cd(e){return new Set((e.manyToManyJoins??[]).map(t=>t.junctionTable))}function ia(e){const t=Cd(e),r=e.multiJoins.filter(o=>!t.has(o.destinationTable)).map(o=>({kind:"child",key:`child:${o.fieldName??o.destinationTable}`,join:o})),s=(e.manyToManyJoins??[]).map(o=>({kind:"m2m",key:`m2m:${o.junctionTable}:${o.targetTable}`,m2m:o}));return[...r,...s]}function la(e,t){const r=new Set([...t.junctionSourceColumnNames,...t.junctionTargetColumnNames]);return e.columns.filter(s=>!s.isPrimaryKey&&!r.has(s.name))}function Nd(e,t,r,s){const o=r.junctionSourceColumnNames;if(o.length===0)throw new Error(`Many-to-many relationship '${r.name}' has no junction source columns.`);const i=to(s,o.length),a=new Map(e.columns.map($=>[$.name,$])),l=[],c=[],m={};o.forEach(($,b)=>{const v=a.get($);if(!v)throw new Error(`Junction table '${e.name}' has no column '${$}' (junction source column of many-to-many relationship '${r.name}').`);const w=v.paramType.replace("!",""),F=`src${b}`;l.push(`$${F}: ${w}`),c.push(`{ ${$}: { _eq: $${F} } }`),m[F]=dt(i[b],w)});const d=c.length===1?c[0]:`{ and: [${c.join(", ")}] }`,f=e.primaryKeys??[],p=la(e,r).map($=>$.name),x=t.primaryKeys?.length?t.primaryKeys:r.targetColumnNames,h=t.labelColumn,y=[...x];h&&!x.includes(h)&&y.push(`label: ${h}`);const N=`${r.junctionTargetField} { ${y.join(" ")} }`,T=[...f,...p,N].join(" ");return{query:`query GetLinks_${e.name}(${l.join(", ")}, $limit: Int, $offset: Int) { ${e.name}(filter: ${d} limit: $limit offset: $offset) { total offset limit data { ${T} } } }`,variables:m}}function ca(e,t){const r=zt(e).map(s=>s.name);return r.length>0?r:[...t.targetColumnNames]}function kd(e,t,r){je(e.name,"many-to-many target table name");const s=ca(e,t),o=t.targetColumnNames[0],i=e.labelColumn||s[0];for(const h of s)je(h,"many-to-many target identity column");je(o,"many-to-many junction target column"),je(i,"many-to-many target label column");const l=`${[...new Set([...s,o])].join(" ")} label: ${i}`,c=e.columns.find(h=>h.name===i);if(!c)throw new Error(`Target table '${e.name}' has no column '${i}' (label column for the '${t.name}' many-to-many picker).`);const m=c.paramType.replace("!","")==="String",d=!!r&&r.trim()!==""&&m,f=d?"$limit: Int, $search: String":"$limit: Int",p=d?`filter: {${i}: {_contains: $search}} `:"";return{query:`query PickTarget(${f}) { ${e.name}(${p}limit: $limit sort: [${i}_asc]) { data { ${l} } } }`,identityColumns:s,linkColumn:o,serverSearch:m}}function Sd(e,t,r){const s=e[t.junctionTargetField];if(!s)return null;const o=He(s,r,0),i=s.label!=null?String(s.label):o;return{id:o,label:i}}function Td(e,t,r){if(e.junctionSourceColumnNames.length!==1||e.junctionTargetColumnNames.length!==1)throw new Error("attachJunctionDetail supports single-column junction FKs only; this relationship uses a composite key which is not yet supported.");const[s]=to(t,1);return{[e.junctionSourceColumnNames[0]]:s,[e.junctionTargetColumnNames[0]]:r}}const ns=200,$d=50,Ed=500;function Fd({m2m:e,parentRowId:t,onOpenColumn:r}){const s=Je(),o=s.findTable(e.junctionTable),i=s.findTable(e.targetTable);return!o||!i?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Relationship schema unavailable."}):n.jsx(_d,{m2m:e,parentRowId:t,onOpenColumn:r,junction:o,target:i})}function _d({m2m:e,parentRowId:t,onOpenColumn:r,junction:s,target:o}){const i=$e(),a=de.useQueryClient(),{toast:l}=vt(),[c,m]=u.useState(!1),[d,f]=u.useState(null),p=Qn(s);let x={query:null,variables:{}},h=null;try{x=Nd(s,o,e,t)}catch(A){h=A}const{query:y,variables:N}=x,T=u.useMemo(()=>["m2mRows",e.junctionTable,e.targetTable,t],[e.junctionTable,e.targetTable,t]),{data:k,isLoading:$,error:b}=de.useQuery({queryKey:T,queryFn:()=>i.query(y,{...N,limit:ns,offset:0}),enabled:!!y}),v=u.useCallback(()=>a.invalidateQueries({queryKey:T}),[a,T]),w=u.useCallback(async A=>{const D=mt(A,s);if(!D)throw new Error(`This link cannot be removed: its ${s.label} row is missing one or more key columns (${(s.primaryKeys??[]).join(", ")||"none declared"}).`);await p.deleteRow(D),await v()},[s,p,v]);if(h)return n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Relationship misconfigured: ",h.message]});const F=k?.[s.name]?.data??[],j=la(s,e),V=s.isEditable!==!1,S=ca(o,e),L=new Set;for(const A of F){const D=A[e.junctionTargetField];D&&(S.some(B=>D[B]==null)||L.add($t(S.map(B=>D[B]))))}return n.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 bg-muted/20 border-b border-border shrink-0",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground",title:`Linked through ${s.label}`,children:[n.jsx(C.Link2,{className:"size-3"}),"via ",s.label]}),V&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs ml-auto",onClick:()=>m(!0),children:[n.jsx(C.Plus,{className:"size-3 mr-1"})," Add link"]})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[b&&n.jsxs("div",{className:"p-3 text-sm text-destructive",children:["Error: ",b.message]}),$&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!$&&F.length===0&&n.jsxs("div",{className:"p-3 text-sm text-muted-foreground",children:["No linked ",o.label,"."]}),F.length>0&&n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[n.jsx("th",{className:"px-2 py-1 font-medium",children:o.label}),j.map(A=>n.jsx("th",{className:"px-2 py-1 font-medium",children:A.label},A.name)),V&&n.jsx("th",{className:"px-2 py-1 w-8","aria-label":"actions"})]})}),n.jsx("tbody",{children:F.map((A,D)=>{const B=Sd(A,e,o);return n.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30",children:[n.jsx("td",{className:"px-2 py-1",children:B?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Pn,{to:`/${o.name}/${B.id}`,className:"text-primary hover:underline",children:B.label}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-5",onClick:()=>r({tableName:o.name,filterId:B.id}),"aria-label":`Open ${B.label} in side column`,title:"Open in side column",children:n.jsx(C.Search,{className:"size-3"})})]}):n.jsx("span",{className:"text-muted-foreground",children:"—"})}),j.map(X=>n.jsx("td",{className:"px-2 py-1",children:Kn(A[X.name],X)},X.name)),V&&n.jsx("td",{className:"px-2 py-1",children:n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-6 text-muted-foreground hover:text-destructive",onClick:()=>f(A),disabled:p.isPending,"aria-label":`Detach ${B?.label??"link"}`,title:"Detach",children:n.jsx(C.Unlink,{className:"size-3.5"})})})]},D)})})]}),F.length>=ns&&n.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground italic border-t border-border",children:["Showing the first ",ns," links. Detach some or narrow the parent selection to see more."]})]}),c&&n.jsx(Pd,{target:o,junction:s,m2m:e,parentRowId:t,linkedIds:L,onClose:()=>m(!1),onLinked:v}),n.jsx(Kr,{open:d!==null,onOpenChange:A=>{A||f(null)},title:"Detach this link?",description:n.jsxs("p",{children:["This removes the link row. The ",o.label," record itself is not deleted."]}),confirmLabel:"Detach",variant:"destructive",isPending:p.isPending,onConfirm:async()=>{try{d&&await w(d)}catch(A){l(`Detach failed: ${A.message}`,"error")}finally{f(null)}}})]})}function Pd({target:e,junction:t,m2m:r,parentRowId:s,linkedIds:o,onClose:i,onLinked:a}){const l=$e(),c=t.columns.filter(B=>r.junctionSourceColumnNames.includes(B.name)||r.junctionTargetColumnNames.includes(B.name)).map(B=>({column:B})),m=wn(t,c,[]),[d,f]=u.useState(""),[p,x]=u.useState("");u.useEffect(()=>{const B=setTimeout(()=>x(d),300);return()=>clearTimeout(B)},[d]);const h=p.trim();let y=null,N=null;try{y=kd(e,r,h)}catch(B){N=B}const{query:T,identityColumns:k,linkColumn:$,serverSearch:b}=y??{query:"",identityColumns:[],linkColumn:"",serverSearch:!1},v=b?$d:Ed,{data:w,isLoading:F}=de.useQuery({queryKey:["m2mTargets",e.name,b?h:""],queryFn:({signal:B})=>l.query(T,b&&h?{limit:v,search:h}:{limit:v},{signal:B}),enabled:y!==null}),j=w?.[e.name]?.data??[],V=b||!h?j:j.filter(B=>Wo(B,"label",h)),S=j.length>=v,[L,A]=u.useState(null),D=u.useCallback(async(B,X)=>{if(o.has(B))return;let E;try{E=Td(r,s,X)}catch(P){A(P);return}A(null);try{await m.insert(E)}catch{return}await a(),i()},[m,r,s,o,a,i]);return N?n.jsx(jt,{open:!0,onOpenChange:B=>{B||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("p",{className:"text-sm text-destructive",children:["Relationship misconfigured: ",N.message]})]})}):n.jsx(jt,{open:!0,onOpenChange:B=>{B||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(C.Search,{className:"size-4 text-muted-foreground"}),n.jsx(Qe,{autoFocus:!0,placeholder:`Search ${e.label}…`,value:d,onChange:B=>f(B.target.value)})]}),L&&n.jsx("p",{className:"text-sm text-destructive",children:L.message}),m.error&&n.jsx("p",{className:"text-sm text-destructive",children:m.error.message}),n.jsxs("div",{className:"max-h-72 overflow-auto border border-border rounded-md",children:[F&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!F&&V.length===0&&n.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No matches."}),V.map((B,X)=>{const E=$t(k.map(_=>B[_])),P=String(B[$]??""),q=B.label!=null?String(B.label):E,U=o.has(E);return n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 text-left px-3 py-1.5 text-sm hover:bg-muted/50 disabled:opacity-50 disabled:hover:bg-transparent",disabled:m.isPending||U,onClick:()=>D(E,P),children:[n.jsx("span",{className:"truncate",children:q}),U&&n.jsx("span",{className:"shrink-0 text-xs text-muted-foreground italic",children:"Already linked"})]},X)}),!F&&S&&n.jsx("div",{className:"px-3 py-1.5 text-xs text-muted-foreground italic border-t border-border",children:b?`Showing the first ${v} matches — type to narrow.`:`Showing the first ${v} rows; some may not be listed.`})]})]})})}function ua(e){return e.kind==="child"?e.join.destinationTable:e.m2m.targetTable}function da({parentTable:e,selectedRowId:t,onClose:r,onOpenColumn:s}){const o=Je(),i=ia(e),[a,l]=u.useState(i[0]?.key??""),[c,m]=u.useState(!1),[d,f]=u.useState(null),p=i.find(y=>y.key===a)??i[0];if(u.useEffect(()=>{f(null)},[a,t]),i.length===0||!o.data)return null;const x=p.kind==="child"?o.findTable(p.join.destinationTable):void 0,h=(x?.multiJoins?.length??0)>0;return n.jsxs("div",{className:"border-t-2 border-primary/20 flex flex-col flex-1 shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>m(!c),"aria-label":c?"Expand detail panel":"Collapse detail panel",title:c?"Expand detail panel":"Collapse detail panel",children:c?n.jsx(C.ChevronUp,{className:"size-3.5"}):n.jsx(C.ChevronDown,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Detail:"}),n.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto",children:i.map(y=>{const T=o.findTable(ua(y))?.label??ua(y),k=y.key===p.key;return n.jsxs("span",{className:"group/tab inline-flex items-center",children:[n.jsx(Q,{variant:k?"secondary":"ghost",size:"sm",className:Y("text-xs h-7 px-2.5",k&&"font-semibold"),onClick:()=>l(y.key),children:T}),s&&y.kind==="child"&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/tab:opacity-100 size-5 shrink-0",onClick:()=>s({tableName:y.join.destinationTable,filterTable:e.name,filterId:t,...Gt(y.join)?{}:{filterColumn:y.join.destinationColumnNames[0]}}),"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]},y.key)})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,className:"ml-auto shrink-0","aria-label":"Close detail panel",title:"Close detail panel",children:n.jsx(C.X,{className:"size-3.5"})})]}),!c&&n.jsx("div",{className:"flex-1 flex flex-col",children:p.kind==="child"&&!x?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"This related table is not available."}):p.kind==="child"?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex-1 min-h-[11rem] overflow-hidden flex flex-col",children:n.jsx(ts,{table:x,id:t,filterTable:e.name,...Gt(p.join)?{}:{filterColumn:p.join.destinationColumnNames[0]},selectedRowId:h?d:void 0,onRowSelect:h?f:void 0,onOpenColumn:s},`${p.key}-${t}`)}),h&&d&&n.jsx("div",{className:"flex-1 flex flex-col",children:n.jsx(da,{parentTable:x,selectedRowId:d,onClose:()=>f(null),onOpenColumn:s})})]}):n.jsx(Fd,{m2m:p.m2m,parentRowId:t,onOpenColumn:s},`${p.key}-${t}`)})]})}const zd={mainTable:null,columns:[],focusedIndex:0,focusColumn:()=>{},closeColumn:()=>{}},ma=u.createContext(zd),fa=u.createContext({register:()=>{},unregister:()=>{}});function Dd({children:e}){const[t,r]=u.useState(null),[s,o]=u.useState(0),i=u.useCallback(p=>{r(p)},[]),a=u.useCallback(()=>{r(null),o(0)},[]),l=u.useCallback(p=>{if(o(p),!t)return;const x=t.columnRefs.get(p);x&&x.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),c=u.useCallback(p=>{t&&p>0&&t.onClose(p-1)},[t]),m=u.useMemo(()=>t?t.columns.map((p,x)=>({panel:p,element:t.columnRefs.get(x+1)??null})):[],[t]),d=u.useMemo(()=>({mainTable:t?.mainTable??null,columns:m,focusedIndex:s,focusColumn:l,closeColumn:c}),[t,m,s,l,c]),f=u.useMemo(()=>({register:i,unregister:a}),[i,a]);return n.jsx(fa.Provider,{value:f,children:n.jsx(ma.Provider,{value:d,children:e})})}function Md(){return u.useContext(ma)}function Id(){return u.useContext(fa)}function pa(e,t){return e.tableName===t.tableName&&e.filterTable===t.filterTable&&e.filterId===t.filterId&&e.filterColumn===t.filterColumn}function Ld(e,t){const r=e[e.length-1];if(r&&pa(r,t))return e;const s=e.findIndex(o=>pa(o,t));return s>=0?e.slice(0,s+1):[...e,t]}function Od(e,t){return t<0?[]:t>=e.length?e:e.slice(0,t)}function Ad(e,t,r){const s=i=>r(i)??i,o=[{index:-1,label:s(e)}];for(let i=0;i<t.length;i++){const a=t[i],l=a.filterTable?s(a.filterTable):s(i===0?e:t[i-1].tableName),c=a.filterId?`from ${l} #${a.filterId}`:void 0;o.push({index:i,label:s(a.tableName),detail:c,frame:a})}return o}const ha="edit-db:panel:",qd=16;function ga(e,t,r){return Math.min(r,Math.max(t,e))}function Vd(e,t,r,s){try{const o=localStorage.getItem(ha+e),i=o===null?NaN:Number(o);return Number.isFinite(i)?ga(i,r,s):t}catch{return t}}function Bd(e,t){try{localStorage.setItem(ha+e,String(Math.round(t)))}catch{}}function xa({key:e,initial:t,min:r,max:s,axis:o,invert:i=!1}){const[a,l]=u.useState(()=>Vd(e,t,r,s)),c=u.useRef(null),m=u.useCallback(p=>{const x=ga(p,r,s);return l(x),Bd(e,x),x},[e,r,s]),d=u.useCallback(p=>{if(p.button!==0)return;p.preventDefault();const x=p.currentTarget;x.setPointerCapture(p.pointerId),c.current={start:o==="x"?p.clientX:p.clientY,startSize:a};const h=N=>{if(!c.current)return;const k=((o==="x"?N.clientX:N.clientY)-c.current.start)*(i?-1:1);m(c.current.startSize+k)},y=N=>{c.current=null;try{x.releasePointerCapture(N.pointerId)}catch{}x.removeEventListener("pointermove",h),x.removeEventListener("pointerup",y),x.removeEventListener("pointercancel",y)};x.addEventListener("pointermove",h),x.addEventListener("pointerup",y),x.addEventListener("pointercancel",y)},[m,o,i,a]),f=u.useCallback(p=>{const x=o==="x"?"ArrowRight":"ArrowDown",h=o==="x"?"ArrowLeft":"ArrowUp";if(p.key!==x&&p.key!==h)return;p.preventDefault();const y=(p.key===x?1:-1)*(i?-1:1);m(a+y*qd)},[m,o,i,a]);return{size:a,onPointerDown:d,onKeyDown:f}}function tr(e,t){return e.find(r=>r.name===t)}function Jt(){const e=ir(),{table:t,id:r,filterTable:s}=e,{loading:o,error:i,data:a}=Je(),[l,c]=u.useState(null),m=xa({key:"detail-height",initial:300,min:120,max:800,axis:"y",invert:!0}),[d,f]=u.useState([]),[p,x]=u.useState(!0),[h,y]=u.useState(new Set),N=u.useRef(t);t!==N.current&&(N.current=t,d.length>0&&f([]),h.size>0&&y(new Set));const T=u.useCallback(P=>{y(q=>{const U=new Set(q);return U.has(P)?U.delete(P):U.add(P),U})},[]),{register:k,unregister:$}=Id(),b=u.useRef(null),v=u.useRef(new Map),w=u.useMemo(()=>a?tr(a,t):void 0,[a,t]),F=w?ia(w).length>0:!1,j=u.useCallback(P=>{f(q=>Ld(q,P))},[]),V=u.useCallback(P=>{x(P),P||f([])},[]),S=p?j:void 0,L=u.useCallback(P=>{f(q=>q.filter((U,_)=>_!==P))},[]),A=u.useCallback(P=>{f(q=>Od(q,P+1))},[]),D=u.useMemo(()=>Ad(t??"",d,P=>{if(a)return tr(a,P)?.label}),[t,d,a]);if(u.useEffect(()=>{const P=v.current;P.set(0,b.current);for(const q of P.keys())q>d.length&&P.delete(q);return k({mainTable:t,columns:d,columnRefs:P,onClose:L}),()=>$()},[t,d,k,$,L]),!t)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table missing"});if(o)return n.jsxs("div",{className:"flex items-center justify-center gap-2 p-5",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});if(i)return n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",i.message]})});if(!w)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table not found"});const B=n.jsx(ts,{table:w,id:r,filterTable:s,selectedRowId:F?l:void 0,onRowSelect:F?c:void 0,onOpenColumn:S,stackingEnabled:p,onToggleStacking:V});if(d.length===0){const P=F&&l;return n.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:n.jsxs("div",{ref:b,className:"flex flex-col flex-1 min-h-0 min-w-0",children:[n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:B}),P&&n.jsxs(n.Fragment,{children:[n.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":"Resize detail panel",tabIndex:0,"data-testid":"detail-resize-handle",className:"h-1.5 shrink-0 cursor-row-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:m.onPointerDown,onKeyDown:m.onKeyDown}),n.jsx("div",{className:"min-h-0 overflow-y-auto flex flex-col",style:{flex:`0 0 ${m.size}px`},children:n.jsx(da,{parentTable:w,selectedRowId:l,onClose:()=>c(null),onOpenColumn:S})})]})]})})}const X=d.length-1,E=(P,q)=>q||h.has(P);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[n.jsx(Gd,{crumbs:D,onCrumbClick:A,activeIndex:d.length-1}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto flex flex-col gap-0.5 p-0.5",children:[n.jsx(ba,{title:w.label,selectedRowId:d[0]?.filterId,expanded:E(-1,!1),active:!1,onToggle:()=>T(-1),onRef:P=>{b.current=P,v.current.set(0,P)},children:B}),d.map((P,q)=>{const U=q===X;return n.jsx(ba,{title:tr(a,P.tableName)?.label??P.tableName,selectedRowId:d[q+1]?.filterId,expanded:E(q,U),active:U,onToggle:()=>T(q),onClose:()=>L(q),onRef:_=>{v.current.set(q+1,_)},children:n.jsx(ts,{table:tr(a,P.tableName),id:P.filterId,filterTable:P.filterTable,filterColumn:P.filterColumn,onOpenColumn:j})},`${P.tableName}|${P.filterTable??""}|${P.filterId??""}|${P.filterColumn??""}`)})]})]})}function Gd({crumbs:e,onCrumbClick:t,activeIndex:r}){return n.jsx("nav",{"aria-label":"Drill-down breadcrumb",className:"flex items-center gap-1 px-2 py-1 bg-muted/20 border-b border-border shrink-0 overflow-x-auto",children:e.map((s,o)=>{const i=s.index===r,a=o===0;return n.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[!a&&n.jsx(C.ChevronRight,{className:"size-3 text-muted-foreground shrink-0"}),n.jsxs(Q,{variant:i?"secondary":"ghost",size:"sm",className:Y("h-6 px-2 text-xs gap-1",i&&"font-semibold"),onClick:()=>t(s.index),"aria-current":i?"page":void 0,title:s.detail?`${s.label} (${s.detail})`:s.label,children:[a&&n.jsx(C.Home,{className:"size-3"}),n.jsx("span",{className:"truncate max-w-[12rem]",children:s.label}),s.detail&&n.jsx("span",{className:"text-muted-foreground font-normal truncate max-w-[10rem]",children:s.detail})]})]},`${s.index}-${s.label}`)})})}function ba({title:e,selectedRowId:t,expanded:r,active:s,onToggle:o,onClose:i,onRef:a,children:l}){return n.jsxs("div",{ref:a,className:"shrink-0 flex flex-col border border-border rounded-sm overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx("button",{type:"button",onClick:o,className:"inline-flex items-center justify-center size-5 shrink-0 text-muted-foreground hover:text-foreground","aria-expanded":r,"aria-label":r?"Collapse table":"Expand table",title:r?"Collapse":"Expand",children:r?n.jsx(C.ChevronDown,{className:"size-3.5"}):n.jsx(C.ChevronRight,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs font-medium truncate",children:e}),s&&n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary/70 shrink-0",children:"active"}),!r&&t&&n.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["#",t]}),n.jsx("div",{className:"flex-1"}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"shrink-0",onClick:i,"aria-label":"Close column",title:"Close column",children:n.jsx(C.X,{className:"size-3.5"})})]}),r&&n.jsx("div",{className:"flex flex-col min-h-[18rem] max-h-[34rem]",children:l})]})}function rs(){const e=ir(),{loading:t,error:r,data:s}=Je(),{mainTable:o,columns:i,focusedIndex:a,focusColumn:l,closeColumn:c}=Md(),[m,d]=u.useState(""),f=_n(),{search:p}=hs(),x=!!p.get("filter"),{back:h,hasBack:y}=Da(),N=e?.table,T=i.length>0,k=u.useMemo(()=>s?.find(j=>j.graphQlName===N),[s,N]),$=u.useMemo(()=>k?.columns?.filter(j=>Ui(j.paramType)||Vt(j.paramType)).map(j=>({key:j.name,value:`${j.name},${j.paramType}`,label:j.label})),[k]),[b,v]=u.useState($?.at(0)?.value??"");u.useEffect(()=>{d(""),v($?.at(0)?.value??"")},[$]);const w=()=>{if(!m)return;const[j,V]=b.split(",");if(!V)return;const S=V.replace("!","");if(Vt(S)){const L=eo(m,S);if(L===null)return;f(`?filter=["${j}", "_eq", ${JSON.stringify(L)}, "${V}"]`)}else S==="String"&&f(`?filter=["${j}", "_contains", ${JSON.stringify(m)}, "${V}"]`)},F=()=>{d("");const j=new URLSearchParams(p.toString());j.delete("filter");const V=j.toString();f(V?`?${V}`:"?")};return t?n.jsxs("div",{className:"flex items-center gap-2 p-2.5",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",r.message]})}):n.jsxs("header",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 min-h-[2.5rem]",children:[n.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto min-w-0 flex-1",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>y&&h(),disabled:!y,"aria-label":"Go back",title:"Go back",className:"shrink-0",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),T?n.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto",children:[n.jsx("button",{type:"button",onClick:()=>l(0),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===0?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:k?.label??zn(e?.table??"")}),i.map((j,V)=>{const L=s?.find(A=>A.graphQlName===j.panel.tableName)?.label??zn(j.panel.tableName);return n.jsxs("span",{className:`inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===V+1?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:[n.jsx("button",{type:"button",onClick:()=>l(V+1),className:"whitespace-nowrap",children:L}),n.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),c(V+1)},className:"rounded-sm hover:bg-background/50 p-px","aria-label":`Close ${L}`,children:n.jsx(C.X,{className:"size-3"})})]},`${j.panel.tableName}-${j.panel.filterId??V}`)})]}):n.jsx("h2",{className:"text-sm font-semibold whitespace-nowrap",children:k?.label??e?.table??"(Select)"})]}),$&&$.length>0&&n.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden flex-[2_2_16rem] min-w-[12rem]",children:[n.jsxs(Ze,{value:b,onValueChange:v,children:[n.jsx(tt,{size:"sm",className:"w-auto min-w-[120px] shrink-0 border-0 rounded-none border-r border-border h-8 text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:$.map(j=>n.jsx(we,{value:j.value,children:j.label},j.key))})]}),n.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[n.jsx(C.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:m,onChange:j=>d(j.target.value),onKeyDown:j=>j.key==="Enter"&&w(),className:"h-8 border-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0",style:{paddingLeft:"2.25rem"},placeholder:"Search..."})]}),n.jsxs(Q,{variant:"ghost",size:"sm",onClick:w,className:"shrink-0 rounded-none border-l border-border h-8 px-3 text-xs",children:[n.jsx(C.Filter,{className:"size-3.5"}),"Filter"]}),x&&n.jsx(Q,{variant:"ghost",size:"sm",onClick:F,title:"Clear filter","aria-label":"Clear filter",className:"shrink-0 rounded-none border-l border-border h-8 px-2 text-xs text-muted-foreground",children:n.jsx(C.X,{className:"size-3.5"})})]}),k&&n.jsxs("div",{className:"flex items-center gap-px border border-border rounded-md overflow-hidden shrink-0",children:[n.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>f("/"),title:"Back to table list",className:"text-muted-foreground text-xs h-8 px-3 rounded-none",children:[n.jsx(C.Home,{className:"size-3.5"}),"Home"]}),k?.isEditable&&n.jsxs(Q,{variant:"default",size:"sm",onClick:()=>f("edit/"),className:"h-8 text-xs px-4 rounded-none",children:[n.jsx(C.Plus,{className:"size-3.5"}),"Add"]})]})]})}class nr extends u.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){const{onError:s,section:o}=this.props;console.error(`Error in ${o??"component"}:`,t,r),s?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){const{hasError:t,error:r}=this.state,{children:s,fallback:o,section:i}=this.props;return t?o||n.jsx("div",{className:"flex items-center justify-center p-5 min-h-[100px]",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-[400px]",children:[n.jsx(C.AlertCircle,{className:"size-4"}),n.jsxs(Rs,{children:["Something went wrong",i?` in ${i}`:""]}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{children:r?.message??"An unexpected error occurred"}),n.jsx(Q,{variant:"destructive",size:"sm",className:"mt-3",onClick:this.handleRetry,children:"Try Again"})]})]})}):s}}function Kd(){const{loading:e,error:t,data:r}=Je();return e?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[n.jsx(C.Database,{className:"size-10 animate-pulse"}),n.jsx("p",{className:"text-sm",children:"Loading schema..."})]}):t?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(C.Database,{className:"size-12 text-destructive"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Connection Error"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:t.message})]})]}):r.length===0?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(C.Database,{className:"size-12 text-muted-foreground/50"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"No Tables Found"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"This database doesn't contain any tables. It may be a new or empty database."}),n.jsx("p",{className:"mt-3 text-xs text-muted-foreground/70",children:"Create tables in your database and reconnect, or try a different connection."})]})]}):n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-6 max-w-lg mx-auto text-center",children:[n.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground/50",children:[n.jsx(C.Table2,{className:"size-10"}),n.jsx(C.MousePointerClick,{className:"size-6"})]}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Select a Table"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Choose a table from the sidebar to browse and edit its data."})]}),n.jsxs("div",{className:"text-xs text-muted-foreground/60 border border-border rounded-md px-4 py-3 bg-muted/30",children:[n.jsxs("p",{className:"font-medium text-muted-foreground mb-1",children:[r.length," table",r.length!==1?"s":""," available"]}),n.jsxs("p",{className:"leading-relaxed",children:[r.slice(0,8).map(s=>s.label).join(", "),r.length>8?`, and ${r.length-8} more`:""]})]})]})}function Wd({children:e}){const{loading:t,error:r}=Je();return t?n.jsxs("div",{className:"flex items-center justify-center flex-1 gap-3 text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-6 animate-spin"}),n.jsx("span",{className:"text-sm",children:"Connecting to database..."})]}):r?n.jsx("div",{className:"flex items-center justify-center flex-1",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-lg",children:[n.jsx(C.AlertCircle,{className:"size-4"}),n.jsx(Rs,{children:"Database Connection Error"}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{className:"text-sm",children:r.message}),n.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Check your connection string and ensure the database server is running."})]})]})}):n.jsx(n.Fragment,{children:e})}function Jd(){const[e,t]=u.useState(!0),r=xa({key:"sidebar-width",initial:240,min:150,max:560,axis:"x"});return n.jsx(Wd,{children:n.jsx(Dd,{children:n.jsxs("div",{className:"grid h-full flex-1 min-h-0 grid-rows-[auto_1fr]",style:{gridTemplateColumns:e?`${r.size}px 1fr`:"0px 1fr"},children:[n.jsxs("div",{className:"col-span-full sticky top-0 z-50 bg-background border-b border-border flex items-center",children:[n.jsx(Q,{variant:"ghost",size:"icon",className:"md:hidden ml-1 shrink-0",onClick:()=>t(!e),"aria-label":"Toggle sidebar",title:"Toggle sidebar",children:n.jsx(C.PanelLeft,{className:"size-5"})}),n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx(nr,{section:"Header",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/*",element:n.jsx(rs,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(rs,{})}),n.jsx(Be,{path:"/",element:n.jsx(rs,{})})]})})})]}),n.jsxs("nav",{"aria-label":"Tables",className:`relative border-r border-border overflow-hidden min-h-0 ${e?"":"hidden"} md:block`,children:[n.jsx(nr,{section:"Table List",children:n.jsx(Rl,{})}),n.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize table list",tabIndex:0,"data-testid":"sidebar-resize-handle",className:"absolute inset-y-0 right-0 w-1.5 cursor-col-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:r.onPointerDown,onKeyDown:r.onKeyDown})]}),n.jsxs("main",{className:"flex flex-col overflow-hidden min-h-0 px-1 py-0.5",children:[n.jsx(nr,{section:"Data Panel",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/from/:filterTable/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/",element:n.jsx(Kd,{})})]})}),n.jsx(nr,{section:"Data Edit",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Xn,{})})]})})]})]})})})}function Qd({onLocate:e}){const t=ps();return u.useEffect(()=>{e?.(t)},[t,e]),n.jsx(Jd,{})}function ya({uri:e,fetcher:t,uiPath:r,onLocate:s,showStats:o=!1,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c}){const m=u.useMemo(()=>t||(e?new ys(e):null),[e,t]),d=u.useMemo(()=>({showStats:o,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c}),[o,i,a,l,c]),f=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:300*1e3,retry:1}}}),[]);if(!m)throw new Error("Editor requires either a `fetcher` (GraphQLFetcher) or a `uri` prop to reach the GraphQL endpoint; neither was provided.");return n.jsx(de.QueryClientProvider,{client:f,children:n.jsx(js,{value:m,children:n.jsx(Ja,{config:d,children:n.jsx(No,{children:n.jsx(Ma,{path:r||"/",children:n.jsx(Ns,{children:n.jsx(Qd,{onLocate:s})})})})})})})}const Hd=["query","form","report","dashboard"];class va extends Error{constructor(t){super(t),this.name="SavedObjectConflictError"}}const ja="/_saved-objects";function Ud(e=""){const t=`${e}${ja}`,r=encodeURIComponent;async function s(o){try{return(await o.json())?.error??`${o.status} ${o.statusText}`}catch{return`${o.status} ${o.statusText}`}}return{async list(o,i,a){const l=o?`${t}/${r(o)}`:t,c=await fetch(l,{signal:i});if(!c.ok)throw new Error(`Failed to list saved objects: ${await s(c)}`);const m=await c.json();if(!Array.isArray(m))throw new Error("Failed to list saved objects: the server did not return a list.");const d=m.map(rr),f=d.filter(p=>p!==null);return f.length!==d.length&&a?.(d.length-f.length),f},async get(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{signal:a});if(l.status===404)return null;if(!l.ok)throw new Error(`Failed to load saved object: ${await s(l)}`);return rr(await l.json())},async put(o,i){const a=await fetch(`${t}/${r(o.type)}/${r(o.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i});if(a.status===409)throw new va(await s(a));if(!a.ok)throw new Error(`Failed to save object: ${await s(a)}`);const l=rr(await a.json());if(l===null)throw new Error("Server returned a malformed saved object.");return l},async remove(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{method:"DELETE",signal:a});if(!l.ok&&l.status!==404)throw new Error(`Failed to delete saved object: ${await s(l)}`)}}}function rr(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||t.id.length===0||typeof t.type!="string"||!Hd.includes(t.type)||typeof t.name!="string"||typeof t.version!="number"||!("definition"in t)?null:{id:t.id,type:t.type,name:t.name,folder:typeof t.folder=="string"?t.folder:void 0,definition:t.definition,version:t.version}}const Yd=4,Rd=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function Xd(e){return typeof e=="string"&&Rd.has(e)?e:"text"}function Zd(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.min(Yd,Math.max(1,Math.trunc(e)))}function em(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.column!="string"||t.column===""?null:{column:t.column,label:typeof t.label=="string"?t.label:t.column,control:Xd(t.control),readOnly:t.readOnly===!0,required:t.required===!0,include:t.include!==!1}}function tm(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.relationship!="string"||typeof t.childTable!="string"||!Array.isArray(t.parentColumns)||!Array.isArray(t.childColumns)||!t.parentColumns.every(r=>typeof r=="string")||!t.childColumns.every(r=>typeof r=="string")||t.parentColumns.length===0||t.parentColumns.length!==t.childColumns.length?null:{relationship:t.relationship,childTable:t.childTable,parentColumns:t.parentColumns,childColumns:t.childColumns,label:typeof t.label=="string"?t.label:t.childTable,mode:t.mode==="stacked"?"stacked":"grid"}}function nm(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.table!="string"||t.table===""||!Array.isArray(t.fields))return null;const r=t.fields.map(em).filter(s=>s!==null);return r.length===0?null:{table:t.table,title:typeof t.title=="string"?t.title:t.table,columns:Zd(t.columns),fields:r,subforms:Array.isArray(t.subforms)?t.subforms.map(tm).filter(s=>s!==null):void 0}}function wa(e){return e.fields.filter(t=>t.include)}const rm=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function sm(e){return e!==void 0&&rm.has(e)?e:void 0}function om(e,t){return{control:sm(t?.widget)??e.control,readOnly:e.readOnly||t?.readOnly===!0,visible:e.include&&t?.visible!==!1}}function am(e){switch(e){case"textarea":return{kind:"textarea"};case"checkbox":return{kind:"checkbox"};case"select":return{kind:"select"};case"number":return{kind:"input",type:"number"};case"date":return{kind:"input",type:"date"};case"datetime":return{kind:"input",type:"datetime-local"};default:return{kind:"input",type:"text"}}}function Ca(e,t,r){const s=Math.max(0,t-1);switch(r){case"first":return 0;case"last":return s;case"prev":return Math.max(0,Math.min(s,e-1));case"next":return Math.max(0,Math.min(s,e+1))}}function sr(e,t,r){return Ca(e,t,r)!==e}function im(e,t){return t<=0?"0 of 0":`${e+1} of ${t}`}function lm(e,t,r){return r.sourceColumnNames.length>0&&r.sourceColumnNames.length===r.destinationColumnNames.length&&r.sourceColumnNames.every(s=>e.columns.some(o=>o.name===s))&&r.destinationColumnNames.every(s=>t.columns.some(o=>o.name===s))}function cm(e,t,r,s){if(!s||!lm(e,t,r))return null;const o=[],i=[],a={};for(let l=0;l<r.sourceColumnNames.length;l++){const c=r.sourceColumnNames[l],m=r.destinationColumnNames[l],d=s[c];if(d==null)return null;const f=t.columns.find(x=>x.name===m)?.paramType.replace("!","")??"String",p=`parent_${c}`;o.push(`$${p}: ${f}`),i.push(`{${m}: {_eq: $${p}}}`),a[p]=dt(d,f)}return{params:o,filter:i.length===1?i[0]:`{and: [${i.join(", ")}]}`,variables:a}}function um(e,t){return!t||e.sourceColumnNames.length!==e.destinationColumnNames.length?{}:Object.fromEntries(e.destinationColumnNames.map((r,s)=>[r,t[e.sourceColumnNames[s]]]))}function dm(e){return{table:e.name,title:e.label,columns:1,fields:e.columns.map(t=>({column:t.name,label:t.label,control:t.paramType.startsWith("Boolean")?"checkbox":t.paramType.startsWith("Int")||t.paramType.startsWith("Float")||t.paramType.startsWith("Decimal")?"number":"text",readOnly:t.isReadOnly||t.isIdentity,required:!t.isNullable,include:!0}))}}function mm({parent:e,child:t,subform:r,row:s}){const o=$e(),i=de.useQueryClient(),a=Qn(t),[l,c]=u.useState(null),m=u.useMemo(()=>({name:r.relationship,fieldName:r.relationship,sourceColumnNames:r.parentColumns,destinationTable:t.name,destinationColumnNames:r.childColumns}),[r,t.name]),d=u.useMemo(()=>cm(e,t,m,s),[e,t,m,s]),f=u.useMemo(()=>t.columns.map(w=>(je(w.name,"form subform field"),w.name)),[t]),p=u.useMemo(()=>d?(je(t.name,"form subform table"),`query FormSubform_${t.name}(${d.params.join(", ")}) { ${t.name}(filter: ${d.filter}) { data { ${f.join(" ")} } } }`):null,[t.name,f,d]),x=["formSubform",e.name,t.name,He(s,e,0)],{data:h,isLoading:y,error:N}=de.useQuery({queryKey:x,queryFn:()=>o.query(p,d.variables),enabled:!!p}),T=u.useMemo(()=>dm(t),[t]),k=u.useMemo(()=>um(m,s),[m,s]);if(!d)return n.jsx("p",{style:lt.notice,children:"Related records unavailable: this relationship is incomplete."});if(y)return n.jsxs("p",{style:lt.notice,children:["Loading ",r.label,"…"]});if(N)return n.jsxs("p",{role:"alert",style:lt.error,children:["Failed to load ",r.label,": ",N.message]});const $=h?.[t.name]?.data??[],b=async w=>{const F=mt(w,t);F&&(await a.deleteRow(F),await i.invalidateQueries({queryKey:x}))},v=async()=>{c(null),await i.invalidateQueries({queryKey:x})};return n.jsxs("section",{style:lt.root,"aria-label":r.label,children:[n.jsx("h3",{style:lt.title,children:r.label}),n.jsxs("button",{type:"button",onClick:()=>c({kind:"create"}),children:["Add ",r.label]}),l?n.jsx("div",{style:lt.childForm,children:n.jsx(os,{table:t,definition:T,hiddenFields:r.childColumns,initialValues:l.kind==="create"?k:void 0,startInNewMode:l.kind==="create",initialPkRoute:l.kind==="edit"?He(l.row,t,l.index??0):void 0,onClose:()=>{v()}},l.kind==="create"?"create":He(l.row,t,l.index??0))}):$.length===0?n.jsx("p",{style:lt.notice,children:"No related records."}):r.mode==="grid"?n.jsxs("table",{style:lt.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[t.columns.map(w=>n.jsx("th",{style:lt.cell,children:w.label},w.name)),n.jsx("th",{})]})}),n.jsx("tbody",{children:$.map((w,F)=>n.jsxs("tr",{children:[t.columns.map(j=>n.jsx("td",{style:lt.cell,children:String(w[j.name]??"")},j.name)),n.jsxs("td",{children:[n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:w,index:F}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>b(w),disabled:a.isPending,children:"Delete"})]})]},He(w,t,F)))})]}):n.jsx("div",{children:$.map((w,F)=>n.jsxs("article",{style:lt.card,children:[t.columns.map(j=>n.jsxs("div",{children:[n.jsxs("strong",{children:[j.label,": "]}),String(w[j.name]??"")]},j.name)),n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:w,index:F}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>b(w),disabled:a.isPending,children:"Delete"})]},He(w,t,F)))})]})}const lt={root:{marginTop:20,borderTop:"1px solid #d1d5db",paddingTop:12},title:{margin:"0 0 8px",fontSize:15},notice:{color:"#6b7280",fontSize:13},error:{color:"#b91c1c",fontSize:13},table:{width:"100%",borderCollapse:"collapse",fontSize:13},cell:{textAlign:"left",padding:5,borderBottom:"1px solid #e5e7eb"},card:{border:"1px solid #e5e7eb",borderRadius:6,padding:8,marginBottom:8,fontSize:13},childForm:{minHeight:420,border:"1px solid #e5e7eb",borderRadius:6,marginTop:8}},fm={};function pm(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function ss(e,t){const r=e.findTable(t);if(r)return r;const s=pm(t);return e.data.find(o=>o.graphQlName===t||o.dbName===t||o.graphQlName===s||o.dbName===s)}const hm="\0new";function gm(e,t){const r=new Set;for(const s of e)r.add(s.column.name);for(const s of t.primaryKeys??[])r.add(s);return[...r]}function xm(e,t){je(e.name,"form browse table name");for(const r of t)je(r,"form browse selection field");return`query FormBrowse_${e.name}($limit: Int, $offset: Int) { ${e.name}(limit: $limit offset: $offset) { total data { ${t.join(" ")} } } }`}function or(e,t,r){return e==="checkbox"?!!r:(e==="date"||e==="datetime")&&(r==null||typeof r=="string")?Br(r??void 0,e==="datetime"||Yn(t)&&!1):r==null?"":String(r)}function bm(e,t){const r={fields:{},form:null},s=e?.errors;if(Array.isArray(s)){const o=[];for(const i of s){const a=i.path?.[i.path.length-1];typeof a=="string"&&t.has(a)?r.fields[a]=i.message:o.push(i.message)}return r.form=o.length>0?o.join("; "):null,r}return r.form=e instanceof Error?e.message:String(e),r}function os({table:e,definition:t,fieldMetadata:r,onClose:s,schema:o,initialValues:i=fm,hiddenFields:a=[],startInNewMode:l=!1,initialPkRoute:c}){const m=$e(),d=de.useQueryClient(),f=u.useMemo(()=>new Map(e.columns.map(O=>[O.name,O])),[e]),[p,x]=u.useState(c?{kind:"pk",route:c}:{kind:"offset",index:0}),[h,y]=u.useState(l?"new":"browse"),[N,T]=u.useState(i),[k,$]=u.useState({}),[b,v]=u.useState(null),[w,F]=u.useState(""),[j,V]=u.useState(0),S=h==="new",L=u.useMemo(()=>wa(t).map(O=>{const Z=f.get(O.column);if(!Z)return null;const ee=om(O,r?.[O.column]);return ee.visible?{field:O,column:Z,control:ee.control,readOnly:ee.readOnly}:null}).filter(O=>O!==null),[t,f,r]),A=u.useCallback(O=>!(O.readOnly||O.column.isReadOnly||O.column.isIdentity||O.column.isPrimaryKey&&!S),[S]),D=u.useMemo(()=>L.filter(A).map(O=>({column:O.column})),[L,A]),B=u.useMemo(()=>(e.primaryKeys??[]).map(O=>f.get(O)).filter(O=>!!O),[e,f]),X=u.useMemo(()=>new Set(D.map(O=>O.column.name)),[D]),E=u.useMemo(()=>{const O=new Set(gm(L,e));for(const Z of t.subforms??[])for(const ee of Z.parentColumns)O.add(ee);return[...O]},[L,e,t.subforms]),P=u.useMemo(()=>{if(S||L.length===0)return null;if(p.kind==="offset")return{text:xm(e,E),variables:{limit:1,offset:p.index},kind:"offset"};const O=fn(p.route,e),Z=O?qn(O,e):null;return Z?{text:Cr(e,Z,E),variables:Z.variables,kind:"pk"}:null},[S,L.length,p,e,E]),{data:q,isLoading:U,error:_}=de.useQuery({queryKey:["formRunner",e.name,p,S],queryFn:()=>m.query(P.text,P.variables),enabled:!S&&P!==null}),ce=u.useMemo(()=>!q||!P?null:P.kind==="offset"?q[e.name]?.data?.[0]??null:q.value?.data?.[0]??null,[q,P,e.name]);u.useEffect(()=>{if(q&&P?.kind==="offset"){const O=q[e.name];O&&V(O.total)}},[q,P,e.name]);const he=S?hm:ce?He(ce,e,0):null,Ue=u.useRef(null),Pe=u.useRef(!1);u.useEffect(()=>{if(Ue.current===he&&Pe.current)return;if(Ue.current=he,Pe.current=!1,$({}),v(null),S){T(i);return}const O={};for(const Z of L)O[Z.column.name]=ce?.[Z.column.name]??null;T(O)},[he,ce,S,L,i]);const ie=p.kind==="offset"?p.index:-1,se=u.useMemo(()=>S||!ce?"":He(ce,e,ie<0?0:ie),[S,ce,e,ie]),ke=wn(e,D,B,se),Ae=Qn(e),re=u.useCallback(O=>{y("browse"),x(Z=>{const ee=Z.kind==="offset"?Z.index:0;return{kind:"offset",index:Ca(ee,j,O)}})},[j]),Ee=u.useCallback(()=>{y("new")},[]),Ie=u.useCallback(()=>{const O=w.trim();O!==""&&(y("browse"),x({kind:"pk",route:O}))},[w]),Le=u.useCallback((O,Z)=>{Pe.current=!0,T(ee=>({...ee,[O]:Z}))},[]),Ge=u.useCallback(async()=>{const O={};for(const ee of L){if(!A(ee))continue;const Ce=ee.field.required||!ee.column.isNullable,xe=qr(ee.column,N[ee.column.name],Ce);xe&&(O[ee.column.name]=xe)}if(Object.keys(O).length>0){$(O),v(null);return}$({}),v(null);const Z={};for(const ee of X)Z[ee]=N[ee];try{if(S){const Ce=(await ke.insert(Z))?.[e.name],xe={},qe=e.primaryKeys??[];for(const W of qe){const me=f.get(W);xe[W]=qe.length===1&&me?.isIdentity?Ce:N[W]}y("browse"),x({kind:"pk",route:Vn(xe,e)})}else await ke.update(Z),Pe.current=!1,await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(ee){const Ce=bm(ee,X);$(Ce.fields),v(Ce.form)}},[L,A,N,X,S,ke,e,f,d]),Oe=u.useCallback(async()=>{const O=mt(ce,e);if(O)try{await Ae.deleteRow(O),y("browse"),x({kind:"offset",index:Math.max(0,(ie<0?0:ie)-1)}),await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(Z){v(Z instanceof Error?Z.message:String(Z))}},[ce,e,Ae,ie,d]);if(L.length===0)return n.jsx("div",{style:fe.notice,children:"This form has no fields that match the current schema."});const ye=p.kind==="pk"?`key ${p.route}`:im(ie,j),ze=!S&&p.kind==="offset"&&j===0&&!U;return n.jsxs("div",{style:fe.root,children:[n.jsxs("div",{style:fe.toolbar,role:"toolbar","aria-label":"Record navigation",children:[n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("first"),disabled:S||!sr(ie,j,"first"),"aria-label":"First record",children:"⏮"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("prev"),disabled:S||!sr(ie,j,"prev"),"aria-label":"Previous record",children:"◀"}),n.jsx("span",{style:fe.position,"aria-label":"Record position",children:S?"New record":ye}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("next"),disabled:S||!sr(ie,j,"next"),"aria-label":"Next record",children:"▶"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("last"),disabled:S||!sr(ie,j,"last"),"aria-label":"Last record",children:"⏭"}),n.jsx("span",{style:fe.spacer}),n.jsx("input",{style:fe.jump,value:w,onChange:O=>F(O.target.value),placeholder:"Jump to key…","aria-label":"Jump to key"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ie,"aria-label":"Go to key",children:"Go"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ee,"aria-label":"New record",children:"New"}),s&&n.jsx("button",{type:"button",style:fe.btn,onClick:s,"aria-label":"Close form",children:"✕"})]}),n.jsxs("div",{style:fe.body,children:[n.jsx("h2",{style:fe.title,children:t.title}),b&&n.jsx("div",{role:"alert",style:fe.formError,children:b}),_&&n.jsxs("div",{role:"alert",style:fe.formError,children:["Failed to load record: ",_.message]}),ze?n.jsx("p",{style:fe.notice,children:"No records. Use “New” to create one."}):n.jsx("div",{style:{...fe.grid,gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`},children:L.filter(O=>!a.includes(O.column.name)).map(O=>{const Z=A(O),ee=N[O.column.name],Ce=k[O.column.name],xe=O.field.required||!O.column.isNullable;return n.jsxs("label",{style:fe.field,children:[n.jsxs("span",{style:fe.label,children:[O.field.label,xe&&n.jsx("span",{style:fe.req,children:" *"})]}),ym(O,ee,Z,xe,Le),Ce&&n.jsx("span",{role:"alert",style:fe.fieldError,children:Ce})]},O.column.name)})}),!S&&ce&&o&&(t.subforms??[]).map(O=>{const Z=ss(o,O.childTable);return Z?n.jsx(mm,{parent:e,child:Z,subform:O,row:ce},O.relationship):n.jsxs("p",{style:fe.notice,children:[O.label," is not available in this schema."]},O.relationship)})]}),n.jsxs("div",{style:fe.footer,children:[n.jsx("button",{type:"button",style:fe.primaryBtn,onClick:Ge,disabled:ke.isPending||ze&&!S,children:S?"Create":"Save"}),!S&&!ze&&n.jsx("button",{type:"button",style:fe.btn,onClick:Oe,disabled:Ae.isPending,children:"Delete"})]})]})}function ym(e,t,r,s,o){const i=e.column.name,a=am(e.control),l={id:i,"aria-label":e.field.label,disabled:!r,style:fe.control};if(a.kind==="checkbox")return n.jsx("input",{...l,type:"checkbox",checked:!!or("checkbox",e.column,t),onChange:c=>o(i,c.target.checked)});if(a.kind==="textarea")return n.jsx("textarea",{...l,rows:3,required:s,value:String(or("text",e.column,t)),onChange:c=>o(i,c.target.value)});if(a.kind==="select"){const c=e.column.enumValues??[],m=e.column.enumLabels&&e.column.enumLabels.length===c.length?e.column.enumLabels:c;return n.jsxs("select",{...l,value:String(or("text",e.column,t)),onChange:d=>o(i,d.target.value===""?null:d.target.value),children:[!s&&n.jsx("option",{value:"",children:"(none)"}),c.map((d,f)=>n.jsx("option",{value:d,children:m[f]??d},d))]})}return n.jsx("input",{...l,type:a.type,required:s,value:String(or(e.control,e.column,t)),onChange:c=>o(i,c.target.value)})}function Na({definition:e,fieldMetadata:t,onClose:r}){const s=Je();if(s.loading)return n.jsx("div",{style:fe.notice,children:"Loading schema…"});if(s.error)return n.jsxs("div",{style:fe.notice,children:["Could not load schema: ",s.error.message]});const o=ss(s,e.table);return o?n.jsx(os,{table:o,definition:e,fieldMetadata:t,onClose:r,schema:s}):n.jsxs("div",{style:fe.notice,children:["Table “",e.table,"” is not in the current schema."]})}const fe={root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},toolbar:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderBottom:"1px solid var(--border, #d1d5db)",flexWrap:"wrap"},position:{fontSize:13,color:"#374151",minWidth:80,textAlign:"center"},spacer:{flex:1},jump:{padding:"4px 6px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13,width:120},body:{flex:1,minHeight:0,overflow:"auto",padding:16},title:{margin:"0 0 16px",fontSize:18},grid:{display:"grid",gap:14,maxWidth:720},field:{display:"flex",flexDirection:"column",gap:4,minWidth:0},label:{fontSize:12,fontWeight:600,color:"#374151"},control:{padding:"6px 8px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13},footer:{display:"flex",gap:8,padding:"8px 12px",borderTop:"1px solid var(--border, #d1d5db)"},btn:{border:"1px solid var(--border, #d1d5db)",background:"transparent",borderRadius:6,padding:"6px 12px",cursor:"pointer",font:"inherit"},primaryBtn:{border:"1px solid #2563eb",background:"#2563eb",color:"#fff",borderRadius:6,padding:"6px 16px",cursor:"pointer",font:"inherit"},req:{color:"#dc2626"},formError:{background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:6,padding:"8px 10px",marginBottom:12,fontSize:13},fieldError:{color:"#dc2626",fontSize:12},notice:{padding:24,color:"#6b7280"}};function vm({fetcher:e,definition:t,fieldMetadata:r,onClose:s}){const o=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}}),[]);return n.jsx(de.QueryClientProvider,{client:o,children:n.jsx(js,{value:e,children:n.jsx(No,{children:n.jsx(Ns,{children:n.jsx(Na,{definition:t,fieldMetadata:r,onClose:s})})})})})}ae.DEFAULT_ROW_CAP=Pr,ae.Editor=ya,ae.FormRunner=Na,ae.FormRunnerHost=vm,ae.FormRunnerView=os,ae.GraphQLRequestError=bs,ae.HttpGraphQLFetcher=ys,ae.SAVED_OBJECTS_PATH=ja,ae.SavedObjectConflictError=va,ae.UTF8_BOM=bo,ae.buildCsv=yo,ae.buildJson=wo,ae.createSavedObjectsClient=Ud,ae.default=ya,ae.deserializeColumnFilters=jr,ae.downloadTextFile=Mr,ae.exportAllRows=_r,ae.filenameFor=Dr,ae.formatCsvCell=Er,ae.mimeFor=zr,ae.parseFormDefinition=nm,ae.parseSavedObject=rr,ae.resolveDefinitionTable=ss,ae.serializeColumnFilters=vr,ae.useTableMutation=wn,ae.visibleFields=wa,Object.defineProperties(ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|