react-semaphor 0.0.510 → 0.0.512
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/chunks/{dashboard-plus-Ca0ukwIg.js → dashboard-plus-BDcdayC4.js} +24 -24
- package/dist/chunks/{dashboard-plus-BpQ1PeXs.js → dashboard-plus-Dy8EGFPy.js} +1493 -1492
- package/dist/chunks/{index-Cr3ClsCY.js → index-Cd-WqnTH.js} +35 -35
- package/dist/chunks/{index-D7xZMlBg.js → index-DGX0ifYc.js} +1131 -1118
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var Vt=s=>{throw TypeError(s)};var Xe=(s,a,n)=>a.has(s)||Vt("Cannot "+n);var X=(s,a,n)=>(Xe(s,a,"read from private field"),n?n.call(s):a.get(s)),le=(s,a,n)=>a.has(s)?Vt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(s):a.set(s,n),te=(s,a,n,r)=>(Xe(s,a,"write to private field"),r?r.call(s,n):a.set(s,n),n),ce=(s,a,n)=>(Xe(s,a,"access private method"),n);const e=require("react/jsx-runtime"),t=require("./index-
|
|
1
|
+
"use strict";var Vt=s=>{throw TypeError(s)};var Xe=(s,a,n)=>a.has(s)||Vt("Cannot "+n);var X=(s,a,n)=>(Xe(s,a,"read from private field"),n?n.call(s):a.get(s)),le=(s,a,n)=>a.has(s)?Vt("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(s):a.set(s,n),te=(s,a,n,r)=>(Xe(s,a,"write to private field"),r?r.call(s,n):a.set(s,n),n),ce=(s,a,n)=>(Xe(s,a,"access private method"),n);const e=require("react/jsx-runtime"),t=require("./index-Cd-WqnTH.js"),L=require("react");require("react-dom");function Bs(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const ie=Bs(L);function Pt(s,a){return s.filter(n=>!a.includes(n))}function zs(s,a,n){const r=s.slice(0);return r[a]=n,r}var fe,re,Ee,Ie,oe,xe,Oe,Fe,Be,ee,it,lt,ct,dt,ut,Qt,Rs=(Qt=class extends t.Subscribable{constructor(a,n,r){super();le(this,ee);le(this,fe);le(this,re);le(this,Ee);le(this,Ie);le(this,oe);le(this,xe);le(this,Oe);le(this,Fe);le(this,Be,[]);te(this,fe,a),te(this,Ie,r),te(this,Ee,[]),te(this,oe,[]),te(this,re,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&X(this,oe).forEach(a=>{a.subscribe(n=>{ce(this,ee,dt).call(this,a,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,X(this,oe).forEach(a=>{a.destroy()})}setQueries(a,n,r){if(te(this,Ee,a),te(this,Ie,n),process.env.NODE_ENV!=="production"){const o=a.map(i=>X(this,fe).defaultQueryOptions(i).queryHash);new Set(o).size!==o.length&&console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.")}t.notifyManager.batch(()=>{const o=X(this,oe),i=ce(this,ee,ct).call(this,X(this,Ee));te(this,Be,i),i.forEach(m=>m.observer.setOptions(m.defaultedQueryOptions,r));const l=i.map(m=>m.observer),u=l.map(m=>m.getCurrentResult()),c=l.some((m,d)=>m!==o[d]);o.length===l.length&&!c||(te(this,oe,l),te(this,re,u),this.hasListeners()&&(Pt(o,l).forEach(m=>{m.destroy()}),Pt(l,o).forEach(m=>{m.subscribe(d=>{ce(this,ee,dt).call(this,m,d)})}),ce(this,ee,ut).call(this)))})}getCurrentResult(){return X(this,re)}getQueries(){return X(this,oe).map(a=>a.getCurrentQuery())}getObservers(){return X(this,oe)}getOptimisticResult(a,n){const r=ce(this,ee,ct).call(this,a),o=r.map(i=>i.observer.getOptimisticResult(i.defaultedQueryOptions));return[o,i=>ce(this,ee,lt).call(this,i??o,n),()=>ce(this,ee,it).call(this,o,r)]}},fe=new WeakMap,re=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,oe=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Fe=new WeakMap,Be=new WeakMap,ee=new WeakSet,it=function(a,n){return n.map((r,o)=>{const i=a[o];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,l=>{n.forEach(u=>{u.observer.trackProp(l)})})})},lt=function(a,n){return n?((!X(this,xe)||X(this,re)!==X(this,Fe)||n!==X(this,Oe))&&(te(this,Oe,n),te(this,Fe,X(this,re)),te(this,xe,t.replaceEqualDeep(X(this,xe),n(a)))),X(this,xe)):a},ct=function(a){const n=new Map(X(this,oe).map(o=>[o.options.queryHash,o])),r=[];return a.forEach(o=>{const i=X(this,fe).defaultQueryOptions(o),l=n.get(i.queryHash);l?r.push({defaultedQueryOptions:i,observer:l}):r.push({defaultedQueryOptions:i,observer:new t.QueryObserver(X(this,fe),i)})}),r},dt=function(a,n){const r=X(this,oe).indexOf(a);r!==-1&&(te(this,re,zs(X(this,re),r,n)),ce(this,ee,ut).call(this))},ut=function(){var a;if(this.hasListeners()){const n=X(this,xe),r=ce(this,ee,it).call(this,X(this,re),X(this,Be)),o=ce(this,ee,lt).call(this,r,(a=X(this,Ie))==null?void 0:a.combine);n!==o&&t.notifyManager.batch(()=>{this.listeners.forEach(i=>{i(X(this,re))})})}},Qt);function Vs({queries:s,...a},n){const r=t.useQueryClient(),o=t.useIsRestoring(),i=t.useQueryErrorResetBoundary(),l=ie.useMemo(()=>s.map(x=>{const g=r.defaultQueryOptions(x);return g._optimisticResults=o?"isRestoring":"optimistic",g}),[s,r,o]);l.forEach(x=>{t.ensureSuspenseTimers(x),t.ensurePreventErrorBoundaryRetry(x,i)}),t.useClearResetErrorBoundary(i);const[u]=ie.useState(()=>new Rs(r,l,a)),[c,m,d]=u.getOptimisticResult(l,a.combine),h=!o&&a.subscribed!==!1;ie.useSyncExternalStore(ie.useCallback(x=>h?u.subscribe(t.notifyManager.batchCalls(x)):t.noop,[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),ie.useEffect(()=>{u.setQueries(l,a,{listeners:!1})},[l,a,u]);const f=c.some((x,g)=>t.shouldSuspend(l[g],x))?c.flatMap((x,g)=>{const p=l[g];if(p){const C=new t.QueryObserver(r,p);if(t.shouldSuspend(p,x))return t.fetchOptimistic(p,C,i);t.willFetch(x,o)&&t.fetchOptimistic(p,C,i)}return[]}):[];if(f.length>0)throw Promise.all(f);const y=c.find((x,g)=>{const p=l[g];return p&&t.getHasError({result:x,errorResetBoundary:i,throwOnError:p.throwOnError,query:r.getQueryCache().get(p.queryHash),suspense:p.suspense})});if(y!=null&&y.error)throw y.error;return m(d())}/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const Ps=t.createLucideIcon("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
|
|
7
7
|
* @license lucide-react v0.453.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
@@ -18,17 +18,17 @@
|
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const Gs=t.createLucideIcon("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/**
|
|
22
22
|
* @license lucide-react v0.453.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const $s=t.createLucideIcon("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/**
|
|
27
27
|
* @license lucide-react v0.453.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
30
30
|
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const
|
|
31
|
+
*/const Je=t.createLucideIcon("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
|
|
32
32
|
* @license lucide-react v0.453.0 - ISC
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const Ue=t.createLucideIcon("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
|
|
62
62
|
* @license lucide-react v0.453.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const Wt=t.createLucideIcon("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
|
|
77
77
|
* @license lucide-react v0.453.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
*
|
|
99
99
|
* This source code is licensed under the ISC license.
|
|
100
100
|
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const
|
|
101
|
+
*/const Ye=t.createLucideIcon("ChartColumnIncreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
|
|
102
102
|
* @license lucide-react v0.453.0 - ISC
|
|
103
103
|
*
|
|
104
104
|
* This source code is licensed under the ISC license.
|
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
*
|
|
114
114
|
* This source code is licensed under the ISC license.
|
|
115
115
|
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const
|
|
116
|
+
*/const Ke=t.createLucideIcon("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/**
|
|
117
117
|
* @license lucide-react v0.453.0 - ISC
|
|
118
118
|
*
|
|
119
119
|
* This source code is licensed under the ISC license.
|
|
@@ -143,7 +143,7 @@
|
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the ISC license.
|
|
145
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const
|
|
146
|
+
*/const Xt=t.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
147
147
|
* @license lucide-react v0.453.0 - ISC
|
|
148
148
|
*
|
|
149
149
|
* This source code is licensed under the ISC license.
|
|
@@ -183,7 +183,7 @@
|
|
|
183
183
|
*
|
|
184
184
|
* This source code is licensed under the ISC license.
|
|
185
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
186
|
-
*/const
|
|
186
|
+
*/const Zt=t.createLucideIcon("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/**
|
|
187
187
|
* @license lucide-react v0.453.0 - ISC
|
|
188
188
|
*
|
|
189
189
|
* This source code is licensed under the ISC license.
|
|
@@ -298,12 +298,12 @@
|
|
|
298
298
|
*
|
|
299
299
|
* This source code is licensed under the ISC license.
|
|
300
300
|
* See the LICENSE file in the root directory of this source tree.
|
|
301
|
-
*/const
|
|
301
|
+
*/const qt=t.createLucideIcon("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/**
|
|
302
302
|
* @license lucide-react v0.453.0 - ISC
|
|
303
303
|
*
|
|
304
304
|
* This source code is licensed under the ISC license.
|
|
305
305
|
* See the LICENSE file in the root directory of this source tree.
|
|
306
|
-
*/const
|
|
306
|
+
*/const _t=t.createLucideIcon("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/**
|
|
307
307
|
* @license lucide-react v0.453.0 - ISC
|
|
308
308
|
*
|
|
309
309
|
* This source code is licensed under the ISC license.
|
|
@@ -323,7 +323,7 @@
|
|
|
323
323
|
*
|
|
324
324
|
* This source code is licensed under the ISC license.
|
|
325
325
|
* See the LICENSE file in the root directory of this source tree.
|
|
326
|
-
*/const
|
|
326
|
+
*/const es=t.createLucideIcon("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
327
327
|
* @license lucide-react v0.453.0 - ISC
|
|
328
328
|
*
|
|
329
329
|
* This source code is licensed under the ISC license.
|
|
@@ -348,7 +348,7 @@
|
|
|
348
348
|
*
|
|
349
349
|
* This source code is licensed under the ISC license.
|
|
350
350
|
* See the LICENSE file in the root directory of this source tree.
|
|
351
|
-
*/const
|
|
351
|
+
*/const ts=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
352
352
|
* @license lucide-react v0.453.0 - ISC
|
|
353
353
|
*
|
|
354
354
|
* This source code is licensed under the ISC license.
|
|
@@ -358,12 +358,12 @@
|
|
|
358
358
|
*
|
|
359
359
|
* This source code is licensed under the ISC license.
|
|
360
360
|
* See the LICENSE file in the root directory of this source tree.
|
|
361
|
-
*/const
|
|
361
|
+
*/const Qe=t.createLucideIcon("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/**
|
|
362
362
|
* @license lucide-react v0.453.0 - ISC
|
|
363
363
|
*
|
|
364
364
|
* This source code is licensed under the ISC license.
|
|
365
365
|
* See the LICENSE file in the root directory of this source tree.
|
|
366
|
-
*/const
|
|
366
|
+
*/const ss=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
367
367
|
* @license lucide-react v0.453.0 - ISC
|
|
368
368
|
*
|
|
369
369
|
* This source code is licensed under the ISC license.
|
|
@@ -373,7 +373,7 @@
|
|
|
373
373
|
*
|
|
374
374
|
* This source code is licensed under the ISC license.
|
|
375
375
|
* See the LICENSE file in the root directory of this source tree.
|
|
376
|
-
*/const
|
|
376
|
+
*/const ns=t.createLucideIcon("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/**
|
|
377
377
|
* @license lucide-react v0.453.0 - ISC
|
|
378
378
|
*
|
|
379
379
|
* This source code is licensed under the ISC license.
|
|
@@ -383,7 +383,7 @@
|
|
|
383
383
|
*
|
|
384
384
|
* This source code is licensed under the ISC license.
|
|
385
385
|
* See the LICENSE file in the root directory of this source tree.
|
|
386
|
-
*/const rs=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function Dt(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(l=>os(l))}})}})}}function os(s){return{...s,customCfg:Bn(s.customCfg),data:[]}}function Bn(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function zn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function mt(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:l}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:l,operation:"update"})}async function Rn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Pn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:l}=t.useDashboardActions(),[u,c]=L.useState(!1),[m,d]=L.useState(!1),h=t.useDashboardStore(x=>x.dashboard),S=t.useDashboardStore(x=>x.filterValues),{authToken:f}=t.useSemaphorContext();async function y(){c(!0);const x=Dt(h),g=await zn(s,x,S,f==null?void 0:f.accessToken);g&&(i([...o||[],g]),l(g.id),d(!1)),c(!1)}return e.jsxs(t.Dialog,{open:m,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:y,disabled:u,children:u?"Creating...":"Add"})})]})]})}function Vn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(d=>d.lenses),r=t.useDashboardStore(d=>d.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:l}=t.useSemaphorContext();async function u(d){i(d)}async function c(d){if(await Rn(d,l==null?void 0:l.accessToken)){const S=n==null?void 0:n.filter(f=>f.id!==d);o(S||[]),i("original")}}async function m(d){const h=n==null?void 0:n.map(y=>y.id===d.id?{...y,isDefault:!d.isDefault}:{...y,isDefault:!1});o(h||[]);const S={...d,isDefault:!d.isDefault};await mt(S,l==null?void 0:l.accessToken);const f=n==null?void 0:n.find(y=>y.isDefault);if(f&&f.id!==d.id){const y={...f,isDefault:!1};await mt(y,l==null?void 0:l.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(fn,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:u,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(d=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:d.id,children:[e.jsx("p",{children:d.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(yn,{onClick:h=>{h.preventDefault(),m(d)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!d.isDefault,"text-green-500":d.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:h=>{h.preventDefault(),c(d.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},d.id))]})]})]})}function is(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function ls(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=is();if(s)return;const l=new URLSearchParams;l.set("token",(a==null?void 0:a.accessToken)||""),l.set("theme",n),l.set("filterValues",JSON.stringify(r)),l.set("selectedSheetId",i||"");const u=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(l.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const d=(await(await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=d;const S=`${o}-${new Date().toISOString()}.pdf`;h.download=S,h.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function qn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await ls()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(ue,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function de({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:l,showPlaceholderLabel:u=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),u&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))]})})]})}const Gt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function cs({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:l}=_n(),[u,c]=L.useState(""),[m,d]=L.useState(Gt[0].value),[h,S]=L.useState("06:00"),[f,y]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(an,{className:"size-4"})})}),e.jsx(t.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:u,onChange:x=>c(x.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:f,onChange:x=>{y(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(de,{className:"col-span-2 h-8",label:"Select Frequency",options:Gt,value:m,onValueChange:x=>d(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:h,onChange:x=>S(x.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:u,frequency:m,time:h,subject:f}),S("00:00"),c(""),y("")},className:"h-8 p-2",disabled:o==="loading"||!u,children:[o==="loading"&&e.jsx(ue,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(Zt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[t.titleCase(x.frequency)," "]}),e.jsx(t.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(Ht,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(nn,{className:"size-3.5"})}),e.jsx(Ht,{tooltip:`${x.endUserEmail}`,children:e.jsx(wn,{className:"size-3.5"})}),l===x.id?e.jsx(ue,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const Ht=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function _n(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),l=t.useDashboardStore(T=>T.authToken),u=t.useDashboardStore(T=>T.dashboard.id),c=t.useDashboardStore(T=>T.dashboard.title),{endUserId:m}=t.getTenantAndEndUserId((l==null?void 0:l.accessToken)||""),d="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:u,endUserId:m},{data:S,isLoading:f,isError:y,isFetching:x,refetch:g}=t.useQuery({queryKey:["subscriptions",u,m],queryFn:()=>t.getRequest(d,(l==null?void 0:l.accessToken)||"",h),enabled:!!(l!=null&&l.accessToken)&&!!u&&!!m});async function p({email:T,subject:E,frequency:j,time:b}){const{authToken:v,...w}=is(),I=Intl.DateTimeFormat().resolvedOptions().timeZone,D={email:T,frequency:j,time:b,timezone:I,endUserId:m,endUserEmail:T,subject:E||c||"Scheduled Dashboard",dashboardId:u,dashboardParams:w};a("loading");const N="https://semaphor.cloud/api/v1/subscriptions/create";try{const F=await t.postRequestRegular(N,(v==null?void 0:v.accessToken)||"",{...D});a("success"),r(""),g(),setTimeout(()=>{a("idle")},2e3)}catch(F){console.error(F),a("error"),r(F.message)}}async function C(T){const E="https://semaphor.cloud/api/v1/subscriptions/delete";i(T);try{await t.postRequestRegular(E,(l==null?void 0:l.accessToken)||"",{id:T}),g(),setTimeout(()=>{i(null)},2e3)}catch(j){console.error(j),i(null),a("error"),r(j.message)}}return{data:S,isLoading:f,isFetching:x,isError:y,isDeleting:o,refetch:g,handleScheduleSubscription:p,handleDeleteSubscription:C,status:s,error:n}}function $n(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(D=>D.theme);const a=t.useDashboardStore(D=>D.lenses),n=t.useDashboardStore(D=>D.selectedLensId),r=a==null?void 0:a.find(D=>D.id===n),o=t.useDashboardStore(D=>D.dashboard);t.useDashboardStore(D=>D.selectedSheetId);const i=t.useDashboardStore(D=>D.isDashboardEditing),l=t.useEditorStore(D=>D.selectedConnectionId),[u,c]=L.useState(!1),m=t.useDashboardStore(D=>D.filterValues),d=t.useDashboardStore(D=>D.isVisualEditing),h=t.useDashboardStore(D=>D.showFilters);t.useDashboardStore(D=>D.showDashboardJSON);const S=t.useDashboardStore(D=>D.onSaveFunction),f=t.useDashboardStore(D=>D.actions.setShowFilters),{addFrame:y,setSelectedFrameId:x}=t.useDashboardStore(D=>D.actions),{getSelectedSheet:g,setIsDashboardEditing:p,setShowDashboardJSON:C}=t.useDashboardStore(D=>D.actions),T=g(),{tenantId:E,endUserId:j}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),b=L.useMemo(()=>E||j,[E,j]),v=()=>{if(!i||!T)return;const D={connectionId:l,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},N={id:t.v4(),cards:[D],activeCardId:D.id};y(T.id,N),x(N.id)},w=()=>{p(!0)};async function I(){if(c(!0),!n||!r)return;const D=Dt(o),N=JSON.stringify(D),F={...r,template:N,filterValues:m};await mt(F,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),S==null||S(D),c(!1)}return d?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!d&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!d&&e.jsx(qn,{}),!d&&e.jsx(cs,{}),i&&!d&&b&&e.jsx(Pn,{}),!d&&b&&e.jsx(Vn,{}),i&&!d&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:v,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:w,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!d&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{p(!1),C(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!d&&b&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:I,size:"sm",children:e.jsx(An,{className:"h-4 w-4"})}),!h&&!d&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>f(!0),size:"sm",children:e.jsx(Ct,{className:"h-4 w-4"})}),!d&&i&&!1,!d&&!1]})]})}function Gn({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:l,className:u,icon:c,showNone:m=!1}){const d=ie.useRef(null),[h,S]=ie.useState(!1),[f,y]=ie.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ie.useLayoutEffect(()=>{d.current&&y(d.current.offsetWidth)},[]);function g(){var C;return o?"Loading...":i?"Error":n?(C=a==null?void 0:a.find(T=>T.id===n))==null?void 0:C.name:`Select ${s}`}function p(C,T){r(T),S(!1)}return e.jsxs(t.Popover,{open:h,onOpenChange:S,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:d,variant:"outline",role:"combobox","aria-expanded":h,className:t.cn("flex h-9 w-full justify-between",u),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("div",{className:"mr-2",children:c}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:g()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:f},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:l,children:e.jsx(ts,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:x==null?void 0:x.map(C=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:C.name,onSelect:T=>p(T,C.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===C.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:C.name,children:C.name})]})},C.id))})]})]})})]})}function ke({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:l,showNone:u=!1,className:c,disabled:m=!1,type:d="combobox"}){const h=r?"Loading...":o?"Error":n;function S(){if(s==="Connection")return e.jsx(Tn,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(Dn,{className:"size-4"});if(s==="Table")return e.jsx(We,{className:"size-4"});if(s==="Model")return e.jsx(Xs,{className:"size-4"})}function f(){return e.jsxs(t.Select,{disabled:m,value:h,onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",c),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(ts,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[u&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,g)=>e.jsx(t.SelectItem,{value:x.id,children:x.name},g))]}),(r||o)&&e.jsx(t.SelectItem,{value:h,children:h})]})})]})}function y(){return e.jsx(Gn,{icon:S(),items:a,value:h,onChange:l||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:u})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:d==="select"?f():y()})})}function Hn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(x=>x.selectedTableName),o=t.useEditorStore(x=>x.selectedSchemaName),i=t.useEditorStore(x=>x.selectedDatabaseName),l=t.useEditorStore(x=>x.selectedDatamodelId),u=t.useEditorStore(x=>x.sqlGen),{modelItems:c,connectionType:m}=t.useEditorAside(),d=t.useEditorStore(x=>x.actions.setSqlGen),h=t.useEditorStore(x=>x.actions.setCardSql),S=t.useEditorStore(x=>x.actions.setRunSql);function f(x,g){var E;const p=t.createSqlGenConfig(x,u,g),C=(E=c==null?void 0:c.find(j=>j.id===l))==null?void 0:E.name;d(p);const T=t.getSql(p,t.fmt(o||""),t.fmt(r),C||"",m,i||"");T&&(h(T),S(!0)),n(!1)}function y(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:y()})]})}function Tt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(St,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(as,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Zs,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Ze({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Tt,{column:s}),e.jsx("span",{children:s.column_name})]})}function Jn({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:l}=t.useDraggable({id:s,data:{type:n}}),u=l?{translate:t.CSS.Translate.toString(l),transform:t.CSS.Transform.toString(l)}:void 0;return e.jsx("div",{ref:i,style:u,...o,...r,children:a})}function Un({onClick:s,column:a}){const n=t.useDndStore(d=>d.activeId),r=t.useEditorStore(d=>{var h;return(h=d.card.queryConfig)==null?void 0:h.groupByColumns}),o=t.useEditorStore(d=>{var h;return(h=d.card.queryConfig)==null?void 0:h.metricColumns}),i=t.useEditorStore(d=>{var h;return(h=d.card.queryConfig)==null?void 0:h.filterColumns});function l(d){return u(d)||c(d)||m(d)}function u(d){return r==null?void 0:r.some(h=>h.name===d.column_name)}function c(d){return o==null?void 0:o.some(h=>h.name===d.column_name)}function m(d){return i==null?void 0:i.some(h=>h.name===d.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":l(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Ze,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Ze,{column:a})}),e.jsx(Jn,{id:a.column_name,type:"column",children:e.jsx(Ze,{column:a})})]})}const et={id:"__placeholder__",role:"groupby",type:"string"},tt={id:"__placeholder__",role:"groupby",type:"string"},st={id:"__placeholder__",role:"metric",type:"number"},nt={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},ds={id:"__placeholder__"},ge="droppable-group-by",je="droppable-metrics",ye="droppable-pivot-by",_e="sortable-group-by",ht="sortable-metrics",$e="sortable-pivot-by",xt="droppable-filters",pt="sortable-filters",Mt="sortable-order-by";function Yn(){const s=t.useDndStore(A=>A.insertIndex),a=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.groupByColumns)||[]}),n=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.metricColumns)||[]}),r=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.filterColumns)||[]}),o=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.orderBy)||[]}),i=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.pivotColumns)||[]}),{setInsertIndex:l,setActiveId:u,setPreviewGroupByColumns:c,setPreviewMetricColumns:m,setPreviewFilterColumns:d,setPreviewPivotColumns:h}=t.useDndActions(),{setGroupByColumns:S,setMetricColumns:f,setFilterColumns:y,setOrderByColumns:x,setPivotByColumns:g}=t.useEditorActions(),{columns:p}=t.useDataColumns(),{formattedTableName:C}=t.useEditorAside(),T=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),E=A=>{var B;const{active:k,over:M}=A;if(((B=k.data.current)==null?void 0:B.type)==="column"&&M){const z=M.id,P=p.find(_=>_.column_name===k.id);if(!P)return;const R=t.isNumberDataType(P.data_type),K=t.isTextDataType(P.data_type),J=t.isDateDataType(P.data_type);if(K||J){if(a.some(U=>U.id===z)){const U=a.findIndex(V=>V.id===z);l(U);const q=a.filter(V=>V.id!==et.id);q.splice(U,0,et),c(q)}else if(M.id===ge){l(a.length);const U=[...a,et];c(U),m(n),d(r)}}if(K||J){if(i.some(U=>U.id===z)){const U=i.findIndex(V=>V.id===z);l(U);const q=i.filter(V=>V.id!==tt.id);q.splice(U,0,tt),h(q)}else if(M.id===ye){l(i.length);const U=[...i,tt];h(U),c(a),m(n),d(r)}}if(R||K){if(n.some(U=>U.id===z)){console.log("isOverMetricSortable",z);const U=n.findIndex(V=>V.id===z);l(U);const q=n.filter(V=>V.id!==st.id);q.splice(U,0,st),m(q)}else if(M.id===je){l(n.length);const U=[...n,st];m(U),d(r),c(a),h(i)}}if(b(P)){if(r.some(U=>U.id===z)){const U=r.findIndex(V=>V.id===z);l(U);const q=r.filter(V=>V.id!==nt.id);q.splice(U,0,nt),d(q)}else if(M.id===xt){l(r.length);const U=[...r,nt];d(U),m(n),c(a),h(i)}}}else c(a),m(n),d(r),h(i)};function j(A){u(A.active.id),l(null),c(a),m(n),d(r),h(i)}function b(A){return!r.some(k=>k.name===A.column_name)}function v(A,k="SUM"){const{column_name:M,data_type:B}=A,z=[...n],P=s!==null?s:n.length,R={...A,id:me(M),name:M,label:Le(M,k),type:B,role:"metric",aggregate:k};z.splice(P,0,R),f(z)}function w(A){const k=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...i],B=s!==null?s:i.length;let z;k?z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:De(A.column_name,"month"),granularity:"month"},M.splice(B,0,z),g(M)}function I(A){const k=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...a],B=s!==null?s:a.length;let z;k?z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:De(A.column_name,"month"),granularity:"month"},M.splice(B,0,z),S(M)}function D(A){const k=[...r],M=s!==null?s:r.length,B={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,sql:t.getDefaultFilterSql(A.data_type,C,t.fmt(A.column_name)),role:"filter"};k.splice(M,0,B),y(k)}function N(A){var z,P,R,K,J,_,U,q;const{active:k,over:M}=A,B=k.data.current;if((B==null?void 0:B.type)==="column"&&M){const V=p.find(Z=>Z.column_name===k.id);if(!V)return;const G=t.isNumberDataType(V.data_type),H=t.isTextDataType(V.data_type),Y=t.isDateDataType(V.data_type);(H||Y)&&(M.id===ge||((z=M.data.current)==null?void 0:z.type)===_e)&&I(V),(H||Y)&&(M.id===ye||((P=M.data.current)==null?void 0:P.type)===$e)?w(V):(G||H)&&(M.id===je||((R=M.data.current)==null?void 0:R.type)===ht)?(G&&v(V),H&&v(V,"COUNT")):b(V)&&(M.id===xt||((K=M.data.current)==null?void 0:K.type)===pt)&&D(V)}if(M&&((J=M.data.current)==null?void 0:J.type)===_e&&a.some(V=>V.id===k.id)){const V=a.findIndex(H=>H.id===k.id),G=a.findIndex(H=>H.id===M.id);if(V!==-1&&G!==-1&&V!==G){const H=[...a],[Y]=H.splice(V,1);H.splice(G,0,Y),S(H)}}if(M&&((_=M.data.current)==null?void 0:_.type)===$e&&i.some(V=>V.id===k.id)){const V=i.findIndex(H=>H.id===k.id),G=i.findIndex(H=>H.id===M.id);if(V!==-1&&G!==-1&&V!==G){const H=[...i],[Y]=H.splice(V,1);H.splice(G,0,Y),g(H)}}if(M&&((U=M.data.current)==null?void 0:U.type)===ht&&n.some(V=>V.id===k.id)){const V=n.findIndex(H=>H.id===k.id),G=n.findIndex(H=>H.id===M.id);if(V!==-1&&G!==-1&&V!==G){const H=[...n],[Y]=H.splice(V,1);H.splice(G,0,Y),f(H)}}if(M&&((q=M.data.current)==null?void 0:q.type)===pt&&r.some(V=>V.id===k.id)){const V=r.findIndex(H=>H.id===k.id),G=r.findIndex(H=>H.id===M.id);if(V!==-1&&G!==-1&&V!==G){const H=[...r],[Y]=H.splice(V,1);H.splice(G,0,Y),y(H)}}F(A),u(null),l(null),c(a),m(n),d(r),h(i)}function F(A){const{active:k,over:M}=A,B=k.data.current;if((B==null?void 0:B.type)===Mt&&M){const z=o.findIndex(R=>Ae(R.columnId)===k.id),P=o.findIndex(R=>Ae(R.columnId)===M.id);if(z!==-1&&P!==-1&&z!==P){const R=[...o],[K]=R.splice(z,1);R.splice(P,0,K),x(R)}}}function O(){u(null),l(null),c(a),m(n),d(r)}return{handleDragOver:E,handleDragEnd:N,handleDragStart:j,handleDragCancel:O,sensors:T}}function me(s){return`${s}-${t.v4()}`}function Le(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ae(s){return`${Mt}-${s}`}function De(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Kn({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(k=>k.sqlGen),i=t.useEditorStore(k=>k.isDevMode),l=t.useEditorStore(k=>k.selectedConnectionId),u=t.useEditorStore(k=>{var M,B;return(B=(M=k.card)==null?void 0:M.queryConfig)==null?void 0:B.metricColumns});t.useEditorStore(k=>{var M,B;return(B=(M=k.card)==null?void 0:M.queryConfig)==null?void 0:B.groupByColumns});const c=t.useEditorStore(k=>k.selectedDatabaseName),m=t.useEditorStore(k=>k.selectedSchemaName),d=t.useEditorStore(k=>k.selectedTableName),h=t.useEditorStore(k=>k.selectedDatamodelId),S=t.useDashboardStore(k=>k.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:y}=t.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:g,setCardSql:p,setRunSql:C,setSqlGen:T,setIsShowingVisual:E}=t.useEditorActions(),{connectionType:j,modelItems:b,selectedDatamodelName:v}=t.useEditorAside();function w(k){var M;if(i){const B=t.createSqlGenConfig(k,o);T(B);const z=(M=b==null?void 0:b.find(R=>R.id===h))==null?void 0:M.name,P=t.getSql(B,t.fmt(s),t.fmt(a),z||"",j,c||"");P&&(p(P),C(!0))}if(!i){if(t.isTextDataType(k.data_type))if(u&&u.length>0){const B={...k,role:"groupby",id:me(k.column_name),name:k.column_name,type:k.data_type};g(B)}else{const B={...k,role:"metric",id:me(k.column_name),name:k.column_name,label:Le(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};x(B)}if(t.isDateDataType(k.data_type)){const B={...k,role:"groupby",id:me(k.column_name),name:k.column_name,type:k.data_type,label:De(k.column_name,"month"),granularity:"month"};g(B)}if(t.isNumberDataType(k.data_type)){const B={...k,role:"metric",id:me(k.column_name),name:k.column_name,label:Le(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};x(B)}}}function I(k){k===!0&&(d||v)&&l?(f({connectionId:l,connectionType:j==="S3"||j==="API"?"DuckDb":j||"",databaseName:c||"",schemaName:m||"",tableName:d||"",datamodelName:t.resolveDatamodelName(v),datamodelId:h||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(y({connectionId:l||"",connectionType:j||"",tableName:d||"",datamodelName:t.resolveDatamodelName(v),datamodelId:h||"",databaseName:c||"",schemaName:m||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function D(){const k=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:v,connectionType:j,databaseName:c||""});E(!1);const M=j==="MSSQL"?`SELECT top 10 * FROM ${k}`:`SELECT * FROM ${k} LIMIT 10`;p(M),C(!0)}function N(){const k=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:v,connectionType:j,databaseName:c||""});p(`SELECT COUNT(*) as count FROM ${k}`),C(!0)}function F(){return(S==null?void 0:S.find(k=>k.connectionId===l&&(k.tableName===d||k.datamodelName===v)))!==void 0}function O(k){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(k),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Tt,{column:k}),e.jsx("span",{children:k.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(k.data_type)&&e.jsx(Hn,{column:k})})]}):e.jsx(Un,{onClick:w,column:k})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${F()?"Remove from":"Add to"} Assistant Scope`,pressed:F(),onPressedChange:I,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":F(),"text-muted-foreground":!F()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:D,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Sn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:N,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ss,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((k,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:A()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(k=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:O(k)},k.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function us({ColumnsComponent:s,type:a}){var Me;const n=t.useEditorStore(W=>W.card),r=t.useEditorStore(W=>W.selectedConnectionId),o=t.useDashboardStore(W=>W.showFilters),i=t.useEditorStore(W=>W.selectedDatamodelId),l=t.useEditorStore(W=>W.selectedDatabaseName),u=t.useEditorStore(W=>W.selectedSchemaName),c=t.useEditorStore(W=>W.selectedTableName),m=t.useEditorStore(W=>W.isDevMode),{setSelectedTableName:d,setIsDevMode:h,setCardSql:S}=t.useEditorActions(),{connectionItems:f,modelItems:y,schemaItems:x,databaseItems:g,tableItems:p,columns:C,isConnectionsLoading:T,isModelsLoading:E,isConnectionsError:j,isModelsError:b,isDatabasesLoadingOrFetching:v,isDatabaseError:w,isSchemaLoadingOrFetching:I,isSchemaError:D,isColumnsError:N,isColumnsLoadingOrFetching:F,isTableLoadingOrFetching:O,isTableError:A,connectionType:k,isNonDbConnection:M,refetchDatabases:B,refetchModels:z,refetchSchemas:P,refetchTables:R,refetchColumns:K,refetchConnections:J,handleConnectionChange:_,handleDatabaseChange:U,handleSchemaChange:q,handleDatamodelChange:V,handleTableChange:G,tableName:H,schemaName:Y}=t.useEditorAside(),{data:Z,refetch:ae}=t.useDashboardCardQuery(n);function Ne(){return s?s(Y,H,C):e.jsx(Kn,{schemaName:Y,tableName:H,columns:C,status:F?"Loading...":N?"Error":"Success"})}function pe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function Ce(W){W===!0?Z&&(S(Z.userSql),setTimeout(()=>{ae()},100)):S(""),h(W)}function Se(){if(!r||k==="S3"||k==="API")return null;if(!i||i==="none")return e.jsx(ke,{refetch:B,showNone:!0,onChange:U,isError:w,isLoading:v,items:g,value:l||"",title:"Database",type:"combobox"})}function $(){if(r&&!M&&(!l||l==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function Q(){if(!r||k==="S3"||k==="API")return null;if(!l||l==="none")return e.jsx(ke,{refetch:z,showNone:!0,onChange:V,isError:b,isLoading:E,items:y,value:i||"",title:"Model",type:"combobox"})}function he(){return!r||k==="S3"||k==="API"||!l||l==="none"?null:e.jsx(ke,{refetch:P,onChange:q,isError:D,isLoading:I,items:x,value:u||"",title:"Schema",type:"combobox"})}function we(){function W(){let se=!1;return k==="API"?(se=!1,se):((k==="S3"||r&&l&&l!=="none"&&u)&&(se=!0),se)}return W()?e.jsx(ke,{refetch:R,onChange:G,isError:A,items:p,isLoading:O,value:c||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ke,{refetch:J,items:f,title:"Connection",value:r||"",onChange:_,isLoading:T,isError:j,type:"combobox",connectionTooltip:((Me=f==null?void 0:f.find(W=>W.id===r))==null?void 0:Me.type)||""}),Se(),$(),Q(),he(),we()]}),Ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,onCheckedChange:Ce,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:pe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(En,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function ms({sql:s,error:a,onClick:n}){const r=t.useEditorStore(c=>c.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:l}=t.useEditorActions();function u(){o(!r),i(s),setTimeout(()=>{l(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&a,s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&e.jsxs(t.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(jn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function hs({sql:s,error:a,onClick:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Zt,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-full min-w-fit max-w-[700px]",children:e.jsx(ms,{sql:s,error:a,onClick:n})})]})}var xs={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Jt=L.createContext&&L.createContext(xs),Qn=["attr","size","title"];function Wn(s,a){if(s==null)return{};var n=Xn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Xn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Ge(){return Ge=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Ge.apply(this,arguments)}function Ut(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function He(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Ut(Object(n),!0).forEach(function(r){Zn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):Ut(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function Zn(s,a,n){return a=ea(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function ea(s){var a=ta(s,"string");return typeof a=="symbol"?a:a+""}function ta(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function ps(s){return s&&s.map((a,n)=>L.createElement(a.tag,He({key:n},a.attr),ps(a.child)))}function be(s){return a=>L.createElement(sa,Ge({attr:He({},s.attr)},a),ps(s.child))}function sa(s){var a=n=>{var{attr:r,size:o,title:i}=s,l=Wn(s,Qn),u=o||n.size||"1em",c;return n.className&&(c=n.className),s.className&&(c=(c?c+" ":"")+s.className),L.createElement("svg",Ge({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,l,{className:c,style:He(He({color:s.color||n.color},n.style),s.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return Jt!==void 0?L.createElement(Jt.Consumer,null,n=>a(n)):a(xs)}function na(s){return be({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}function fs(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(x=>x.theme),r=t.useEditorStore(x=>x.frame),o=t.useEditorStore(x=>x.card),i=t.useEditorStore(x=>x.activeTabCardId),l=t.Le(),{refetch:u}=t.useDashboardCardQuery(o),{updateCardTab:c,setRunSql:m}=t.useEditorActions(),d=L.useRef(),h=L.useRef({}),S=r.cards.find(x=>x.id===i),f=L.useCallback(()=>{let x="";return s==="python"&&(x=(S==null?void 0:S.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(x=(S==null?void 0:S.sql)||""),x},[s,S]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(d.current&&l){const x=d.current.getModel();x&&(h.current[o.id]=x);let g=h.current[i];if(!g){const p=f();g=l.editor.createModel(p,s),h.current[i]=g}d.current.setModel(g)}c(i,o),m(!0)}},[i,o,c,l,m,s,f]),L.useEffect(()=>{if(!l)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",g=n==="system"?x:n;l.editor.defineTheme("default",{base:g==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":g==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[a,n,l]),L.useEffect(()=>{const x=d.current;x&&l&&o&&x.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return u(),!1})},[l,u,o]);function y(x,g){if(d.current=x,!h.current[o.id]){const p=x.getModel(),C=f();h.current[o.id]=p||(g==null?void 0:g.editor.createModel(C,s))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:y}}function aa(){const s=t.useEditorStore(l=>l.card.sql),a=t.useEditorStore(l=>l.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=fs("sql");function i(l){n(l),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function ra(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=fs("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function oa({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ia(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(R=>R.frame);const i=t.useEditorStore(R=>R.card);t.useEditorStore(R=>R.isShowingVisual),t.useEditorStore(R=>R.selectedConnectionId),t.useEditorStore(R=>R.tempQueryData),t.useEditorStore(R=>R.selectedDatabaseName),t.useEditorStore(R=>R.selectedDatamodelId),t.useEditorStore(R=>R.selectedSchemaName);const l=t.useEditorStore(R=>R.showAIDialog);t.useEditorStore(R=>R.selectedTableName);const u=t.useEditorStore(R=>{var K;return(K=R==null?void 0:R.card)==null?void 0:K.sql}),c=t.useEditorStore(R=>{var K;return(K=R==null?void 0:R.card)==null?void 0:K.python}),{sheetFilterValues:m}=t.useSheetFilterValues(),{setCardCustomCfg:d,setQueryResultColumns:h,setCardSql:S,setTempQueryData:f,setPythonStdOut:y,setCardPreferences:x,setCardType:g,setCardPython:p,runAssistant:C,setShowAIDialog:T}=t.useEditorActions();t.useEditorStore(R=>R.onSave),t.useEditorStore(R=>R.onClose),t.useEditorStore(R=>R.actions.setSqlGen);const E=t.useEditorStore(R=>R.runSql),j=t.useEditorStore(R=>R.actions.setRunSql),b=t.useEditorStore(R=>R.actions.setIsSqlRunning),{data:v,isLoading:w,isFetching:I,isSuccess:D,isError:N,error:F,queryKey:O,refetch:A,errorMessage:k}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(v&&(v.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),y((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:R}=t.getKeys(v.records);h(R)}},[v,h,y]),L.useEffect(()=>{(w||I)&&b(!0),(N||D)&&b(!1),N&&(h([]),y(""))},[w,I,v,y,N,D,b,h,F]),L.useEffect(()=>{E&&(s.getQueryData(O)||A(),j(!1))},[E,A,j,O,s]);async function M(){const R=`Can you help me debug this query in the current table scope?
|
|
386
|
+
*/const as=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function Dt(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(l=>rs(l))}})}})}}function rs(s){return{...s,customCfg:Bn(s.customCfg),data:[]}}function Bn(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function zn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function mt(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:l}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:l,operation:"update"})}async function Rn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Vn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(x=>x.lenses),{setLenses:i,setSelectedLensId:l}=t.useDashboardActions(),[u,c]=L.useState(!1),[m,d]=L.useState(!1),h=t.useDashboardStore(x=>x.dashboard),S=t.useDashboardStore(x=>x.filterValues),{authToken:f}=t.useSemaphorContext();async function y(){c(!0);const x=Dt(h),g=await zn(s,x,S,f==null?void 0:f.accessToken);g&&(i([...o||[],g]),l(g.id),d(!1)),c(!1)}return e.jsxs(t.Dialog,{open:m,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,onChange:x=>{a(x.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:y,disabled:u,children:u?"Creating...":"Add"})})]})]})}function Pn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(d=>d.lenses),r=t.useDashboardStore(d=>d.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:l}=t.useSemaphorContext();async function u(d){i(d)}async function c(d){if(await Rn(d,l==null?void 0:l.accessToken)){const S=n==null?void 0:n.filter(f=>f.id!==d);o(S||[]),i("original")}}async function m(d){const h=n==null?void 0:n.map(y=>y.id===d.id?{...y,isDefault:!d.isDefault}:{...y,isDefault:!1});o(h||[]);const S={...d,isDefault:!d.isDefault};await mt(S,l==null?void 0:l.accessToken);const f=n==null?void 0:n.find(y=>y.isDefault);if(f&&f.id!==d.id){const y={...f,isDefault:!1};await mt(y,l==null?void 0:l.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(fn,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:u,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(d=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:d.id,children:[e.jsx("p",{children:d.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(yn,{onClick:h=>{h.preventDefault(),m(d)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!d.isDefault,"text-green-500":d.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:h=>{h.preventDefault(),c(d.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},d.id))]})]})]})}function os(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function is(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=os();if(s)return;const l=new URLSearchParams;l.set("token",(a==null?void 0:a.accessToken)||""),l.set("theme",n),l.set("filterValues",JSON.stringify(r)),l.set("selectedSheetId",i||"");const u=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(l.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const d=(await(await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,h=document.createElement("a");h.href=d;const S=`${o}-${new Date().toISOString()}.pdf`;h.download=S,h.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function qn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await is()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(ue,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function de({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:l,showPlaceholderLabel:u=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),u&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))]})})]})}const Gt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function ls({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:l}=_n(),[u,c]=L.useState(""),[m,d]=L.useState(Gt[0].value),[h,S]=L.useState("06:00"),[f,y]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(an,{className:"size-4"})})}),e.jsx(t.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:u,onChange:x=>c(x.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:f,onChange:x=>{y(x.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(de,{className:"col-span-2 h-8",label:"Select Frequency",options:Gt,value:m,onValueChange:x=>d(x)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:h,onChange:x=>S(x.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:u,frequency:m,time:h,subject:f}),S("00:00"),c(""),y("")},className:"h-8 p-2",disabled:o==="loading"||!u,children:[o==="loading"&&e.jsx(ue,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(Xt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(x=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[t.titleCase(x.frequency)," "]}),e.jsx(t.Label,{children:x.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx($t,{tooltip:`Next Run: ${new Date(x.nextRun).toLocaleString()} ${x.timezone}`,children:e.jsx(nn,{className:"size-3.5"})}),e.jsx($t,{tooltip:`${x.endUserEmail}`,children:e.jsx(wn,{className:"size-3.5"})}),l===x.id?e.jsx(ue,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(x.id),className:"size-3.5 cursor-pointer"})]})]},x.id))})]})]})]})})]})})}const $t=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function _n(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),l=t.useDashboardStore(T=>T.authToken),u=t.useDashboardStore(T=>T.dashboard.id),c=t.useDashboardStore(T=>T.dashboard.title),{endUserId:m}=t.getTenantAndEndUserId((l==null?void 0:l.accessToken)||""),d="https://semaphor.cloud/api/v1/subscriptions/get",h={dashboardId:u,endUserId:m},{data:S,isLoading:f,isError:y,isFetching:x,refetch:g}=t.useQuery({queryKey:["subscriptions",u,m],queryFn:()=>t.getRequest(d,(l==null?void 0:l.accessToken)||"",h),enabled:!!(l!=null&&l.accessToken)&&!!u&&!!m});async function p({email:T,subject:E,frequency:j,time:b}){const{authToken:v,...w}=os(),I=Intl.DateTimeFormat().resolvedOptions().timeZone,D={email:T,frequency:j,time:b,timezone:I,endUserId:m,endUserEmail:T,subject:E||c||"Scheduled Dashboard",dashboardId:u,dashboardParams:w};a("loading");const N="https://semaphor.cloud/api/v1/subscriptions/create";try{const F=await t.postRequestRegular(N,(v==null?void 0:v.accessToken)||"",{...D});a("success"),r(""),g(),setTimeout(()=>{a("idle")},2e3)}catch(F){console.error(F),a("error"),r(F.message)}}async function C(T){const E="https://semaphor.cloud/api/v1/subscriptions/delete";i(T);try{await t.postRequestRegular(E,(l==null?void 0:l.accessToken)||"",{id:T}),g(),setTimeout(()=>{i(null)},2e3)}catch(j){console.error(j),i(null),a("error"),r(j.message)}}return{data:S,isLoading:f,isFetching:x,isError:y,isDeleting:o,refetch:g,handleScheduleSubscription:p,handleDeleteSubscription:C,status:s,error:n}}function Gn(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(D=>D.theme);const a=t.useDashboardStore(D=>D.lenses),n=t.useDashboardStore(D=>D.selectedLensId),r=a==null?void 0:a.find(D=>D.id===n),o=t.useDashboardStore(D=>D.dashboard);t.useDashboardStore(D=>D.selectedSheetId);const i=t.useDashboardStore(D=>D.isDashboardEditing),l=t.useEditorStore(D=>D.selectedConnectionId),[u,c]=L.useState(!1),m=t.useDashboardStore(D=>D.filterValues),d=t.useDashboardStore(D=>D.isVisualEditing),h=t.useDashboardStore(D=>D.showFilters);t.useDashboardStore(D=>D.showDashboardJSON);const S=t.useDashboardStore(D=>D.onSaveFunction),f=t.useDashboardStore(D=>D.actions.setShowFilters),{addFrame:y,setSelectedFrameId:x}=t.useDashboardStore(D=>D.actions),{getSelectedSheet:g,setIsDashboardEditing:p,setShowDashboardJSON:C}=t.useDashboardStore(D=>D.actions),T=g(),{tenantId:E,endUserId:j}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),b=L.useMemo(()=>E||j,[E,j]),v=()=>{if(!i||!T)return;const D={connectionId:l,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},N={id:t.v4(),cards:[D],activeCardId:D.id};y(T.id,N),x(N.id)},w=()=>{p(!0)};async function I(){if(c(!0),!n||!r)return;const D=Dt(o),N=JSON.stringify(D),F={...r,template:N,filterValues:m};await mt(F,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),S==null||S(D),c(!1)}return d?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!d&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!d&&e.jsx(qn,{}),!d&&e.jsx(ls,{}),i&&!d&&b&&e.jsx(Vn,{}),!d&&b&&e.jsx(Pn,{}),i&&!d&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:v,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:w,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!d&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{p(!1),C(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!d&&b&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:u,onClick:I,size:"sm",children:e.jsx(An,{className:"h-4 w-4"})}),!h&&!d&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>f(!0),size:"sm",children:e.jsx(Ct,{className:"h-4 w-4"})}),!d&&i&&!1,!d&&!1]})]})}function $n({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:l,className:u,icon:c,showNone:m=!1}){const d=ie.useRef(null),[h,S]=ie.useState(!1),[f,y]=ie.useState("100%"),x=m?[...a||[],{id:"none",name:"None"}]:a;ie.useLayoutEffect(()=>{d.current&&y(d.current.offsetWidth)},[]);function g(){var C;return o?"Loading...":i?"Error":n?(C=a==null?void 0:a.find(T=>T.id===n))==null?void 0:C.name:`Select ${s}`}function p(C,T){r(T),S(!1)}return e.jsxs(t.Popover,{open:h,onOpenChange:S,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:d,variant:"outline",role:"combobox","aria-expanded":h,className:t.cn("flex h-9 w-full justify-between",u),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("div",{className:"mr-2",children:c}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:g()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:f},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:l,children:e.jsx(es,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:x==null?void 0:x.map(C=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:C.name,onSelect:T=>p(T,C.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===C.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:C.name,children:C.name})]})},C.id))})]})]})})]})}function ke({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:l,showNone:u=!1,className:c,disabled:m=!1,type:d="combobox"}){const h=r?"Loading...":o?"Error":n;function S(){if(s==="Connection")return e.jsx(Tn,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(Dn,{className:"size-4"});if(s==="Table")return e.jsx(Qe,{className:"size-4"});if(s==="Model")return e.jsx(Xs,{className:"size-4"})}function f(){return e.jsxs(t.Select,{disabled:m,value:h,onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",c),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(es,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[u&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((x,g)=>e.jsx(t.SelectItem,{value:x.id,children:x.name},g))]}),(r||o)&&e.jsx(t.SelectItem,{value:h,children:h})]})})]})}function y(){return e.jsx($n,{icon:S(),items:a,value:h,onChange:l||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:u})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:d==="select"?f():y()})})}function Hn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(x=>x.selectedTableName),o=t.useEditorStore(x=>x.selectedSchemaName),i=t.useEditorStore(x=>x.selectedDatabaseName),l=t.useEditorStore(x=>x.selectedDatamodelId),u=t.useEditorStore(x=>x.sqlGen),{modelItems:c,connectionType:m}=t.useEditorAside(),d=t.useEditorStore(x=>x.actions.setSqlGen),h=t.useEditorStore(x=>x.actions.setCardSql),S=t.useEditorStore(x=>x.actions.setRunSql);function f(x,g){var E;const p=t.createSqlGenConfig(x,u,g),C=(E=c==null?void 0:c.find(j=>j.id===l))==null?void 0:E.name;d(p);const T=t.getSql(p,t.fmt(o||""),t.fmt(r),C||"",m,i||"");T&&(h(T),S(!0)),n(!1)}function y(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>f(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>f(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>f(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>f(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>f(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:y()})]})}function Tt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(St,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(ns,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Zs,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Ze({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(Tt,{column:s}),e.jsx("span",{children:s.column_name})]})}function Jn({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:l}=t.useDraggable({id:s,data:{type:n}}),u=l?{translate:t.CSS.Translate.toString(l),transform:t.CSS.Transform.toString(l)}:void 0;return e.jsx("div",{ref:i,style:u,...o,...r,children:a})}function Un({onClick:s,column:a}){const n=t.useDndStore(d=>d.activeId),r=t.useEditorStore(d=>{var h;return(h=d.card.queryConfig)==null?void 0:h.groupByColumns}),o=t.useEditorStore(d=>{var h;return(h=d.card.queryConfig)==null?void 0:h.metricColumns}),i=t.useEditorStore(d=>{var h;return(h=d.card.queryConfig)==null?void 0:h.filterColumns});function l(d){return u(d)||c(d)||m(d)}function u(d){return r==null?void 0:r.some(h=>h.name===d.column_name)}function c(d){return o==null?void 0:o.some(h=>h.name===d.column_name)}function m(d){return i==null?void 0:i.some(h=>h.name===d.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":l(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Ze,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Ze,{column:a})}),e.jsx(Jn,{id:a.column_name,type:"column",children:e.jsx(Ze,{column:a})})]})}const et={id:"__placeholder__",role:"groupby",type:"string"},tt={id:"__placeholder__",role:"groupby",type:"string"},st={id:"__placeholder__",role:"metric",type:"number"},nt={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},cs={id:"__placeholder__"},ge="droppable-group-by",je="droppable-metrics",ye="droppable-pivot-by",_e="sortable-group-by",ht="sortable-metrics",Ge="sortable-pivot-by",xt="droppable-filters",pt="sortable-filters",Mt="sortable-order-by";function Yn(){const s=t.useDndStore(A=>A.insertIndex),a=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.groupByColumns)||[]}),n=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.metricColumns)||[]}),r=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.filterColumns)||[]}),o=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.orderBy)||[]}),i=t.useEditorStore(A=>{var k;return((k=A.card.queryConfig)==null?void 0:k.pivotColumns)||[]}),{setInsertIndex:l,setActiveId:u,setPreviewGroupByColumns:c,setPreviewMetricColumns:m,setPreviewFilterColumns:d,setPreviewPivotColumns:h}=t.useDndActions(),{setGroupByColumns:S,setMetricColumns:f,setFilterColumns:y,setOrderByColumns:x,setPivotByColumns:g}=t.useEditorActions(),{columns:p}=t.useDataColumns(),{formattedTableName:C}=t.useEditorAside(),T=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),E=A=>{var B;const{active:k,over:M}=A;if(((B=k.data.current)==null?void 0:B.type)==="column"&&M){const z=M.id,V=p.find(_=>_.column_name===k.id);if(!V)return;const R=t.isNumberDataType(V.data_type),K=t.isTextDataType(V.data_type),J=t.isDateDataType(V.data_type);if(K||J){if(a.some(U=>U.id===z)){const U=a.findIndex(P=>P.id===z);l(U);const q=a.filter(P=>P.id!==et.id);q.splice(U,0,et),c(q)}else if(M.id===ge){l(a.length);const U=[...a,et];c(U),m(n),d(r)}}if(K||J){if(i.some(U=>U.id===z)){const U=i.findIndex(P=>P.id===z);l(U);const q=i.filter(P=>P.id!==tt.id);q.splice(U,0,tt),h(q)}else if(M.id===ye){l(i.length);const U=[...i,tt];h(U),c(a),m(n),d(r)}}if(R||K){if(n.some(U=>U.id===z)){console.log("isOverMetricSortable",z);const U=n.findIndex(P=>P.id===z);l(U);const q=n.filter(P=>P.id!==st.id);q.splice(U,0,st),m(q)}else if(M.id===je){l(n.length);const U=[...n,st];m(U),d(r),c(a),h(i)}}if(b(V)){if(r.some(U=>U.id===z)){const U=r.findIndex(P=>P.id===z);l(U);const q=r.filter(P=>P.id!==nt.id);q.splice(U,0,nt),d(q)}else if(M.id===xt){l(r.length);const U=[...r,nt];d(U),m(n),c(a),h(i)}}}else c(a),m(n),d(r),h(i)};function j(A){u(A.active.id),l(null),c(a),m(n),d(r),h(i)}function b(A){return!r.some(k=>k.name===A.column_name)}function v(A,k="SUM"){const{column_name:M,data_type:B}=A,z=[...n],V=s!==null?s:n.length,R={...A,id:me(M),name:M,label:Le(M,k),type:B,role:"metric",aggregate:k};z.splice(V,0,R),f(z)}function w(A){const k=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...i],B=s!==null?s:i.length;let z;k?z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:De(A.column_name,"month"),granularity:"month"},M.splice(B,0,z),g(M)}function I(A){const k=t.isTextDataType(A.data_type);t.isDateDataType(A.data_type);const M=[...a],B=s!==null?s:a.length;let z;k?z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby"}:z={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,role:"groupby",label:De(A.column_name,"month"),granularity:"month"},M.splice(B,0,z),S(M)}function D(A){const k=[...r],M=s!==null?s:r.length,B={...A,id:me(A.column_name),name:A.column_name,type:A.data_type,sql:t.getDefaultFilterSql(A.data_type,C,t.fmt(A.column_name)),role:"filter"};k.splice(M,0,B),y(k)}function N(A){var z,V,R,K,J,_,U,q;const{active:k,over:M}=A,B=k.data.current;if((B==null?void 0:B.type)==="column"&&M){const P=p.find(Z=>Z.column_name===k.id);if(!P)return;const $=t.isNumberDataType(P.data_type),H=t.isTextDataType(P.data_type),Y=t.isDateDataType(P.data_type);(H||Y)&&(M.id===ge||((z=M.data.current)==null?void 0:z.type)===_e)&&I(P),(H||Y)&&(M.id===ye||((V=M.data.current)==null?void 0:V.type)===Ge)?w(P):($||H)&&(M.id===je||((R=M.data.current)==null?void 0:R.type)===ht)?($&&v(P),H&&v(P,"COUNT")):b(P)&&(M.id===xt||((K=M.data.current)==null?void 0:K.type)===pt)&&D(P)}if(M&&((J=M.data.current)==null?void 0:J.type)===_e&&a.some(P=>P.id===k.id)){const P=a.findIndex(H=>H.id===k.id),$=a.findIndex(H=>H.id===M.id);if(P!==-1&&$!==-1&&P!==$){const H=[...a],[Y]=H.splice(P,1);H.splice($,0,Y),S(H)}}if(M&&((_=M.data.current)==null?void 0:_.type)===Ge&&i.some(P=>P.id===k.id)){const P=i.findIndex(H=>H.id===k.id),$=i.findIndex(H=>H.id===M.id);if(P!==-1&&$!==-1&&P!==$){const H=[...i],[Y]=H.splice(P,1);H.splice($,0,Y),g(H)}}if(M&&((U=M.data.current)==null?void 0:U.type)===ht&&n.some(P=>P.id===k.id)){const P=n.findIndex(H=>H.id===k.id),$=n.findIndex(H=>H.id===M.id);if(P!==-1&&$!==-1&&P!==$){const H=[...n],[Y]=H.splice(P,1);H.splice($,0,Y),f(H)}}if(M&&((q=M.data.current)==null?void 0:q.type)===pt&&r.some(P=>P.id===k.id)){const P=r.findIndex(H=>H.id===k.id),$=r.findIndex(H=>H.id===M.id);if(P!==-1&&$!==-1&&P!==$){const H=[...r],[Y]=H.splice(P,1);H.splice($,0,Y),y(H)}}F(A),u(null),l(null),c(a),m(n),d(r),h(i)}function F(A){const{active:k,over:M}=A,B=k.data.current;if((B==null?void 0:B.type)===Mt&&M){const z=o.findIndex(R=>Ae(R.columnId)===k.id),V=o.findIndex(R=>Ae(R.columnId)===M.id);if(z!==-1&&V!==-1&&z!==V){const R=[...o],[K]=R.splice(z,1);R.splice(V,0,K),x(R)}}}function O(){u(null),l(null),c(a),m(n),d(r)}return{handleDragOver:E,handleDragEnd:N,handleDragStart:j,handleDragCancel:O,sensors:T}}function me(s){return`${s}-${t.v4()}`}function Le(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ae(s){return`${Mt}-${s}`}function De(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Kn({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(k=>k.sqlGen),i=t.useEditorStore(k=>k.isDevMode),l=t.useEditorStore(k=>k.selectedConnectionId),u=t.useEditorStore(k=>{var M,B;return(B=(M=k.card)==null?void 0:M.queryConfig)==null?void 0:B.metricColumns});t.useEditorStore(k=>{var M,B;return(B=(M=k.card)==null?void 0:M.queryConfig)==null?void 0:B.groupByColumns});const c=t.useEditorStore(k=>k.selectedDatabaseName),m=t.useEditorStore(k=>k.selectedSchemaName),d=t.useEditorStore(k=>k.selectedTableName),h=t.useEditorStore(k=>k.selectedDatamodelId),S=t.useDashboardStore(k=>k.dashboard.aiScopeTables),{addToAIScope:f,removeFromAIScope:y}=t.useDashboardActions(),{addColumnToMetricColumns:x,addColumnToGroupBy:g,setCardSql:p,setRunSql:C,setSqlGen:T,setIsShowingVisual:E}=t.useEditorActions(),{connectionType:j,modelItems:b,selectedDatamodelName:v}=t.useEditorAside();function w(k){var M;if(i){const B=t.createSqlGenConfig(k,o);T(B);const z=(M=b==null?void 0:b.find(R=>R.id===h))==null?void 0:M.name,V=t.getSql(B,t.fmt(s),t.fmt(a),z||"",j,c||"");V&&(p(V),C(!0))}if(!i){if(t.isTextDataType(k.data_type))if(u&&u.length>0){const B={...k,role:"groupby",id:me(k.column_name),name:k.column_name,type:k.data_type};g(B)}else{const B={...k,role:"metric",id:me(k.column_name),name:k.column_name,label:Le(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};x(B)}if(t.isDateDataType(k.data_type)){const B={...k,role:"groupby",id:me(k.column_name),name:k.column_name,type:k.data_type,label:De(k.column_name,"month"),granularity:"month"};g(B)}if(t.isNumberDataType(k.data_type)){const B={...k,role:"metric",id:me(k.column_name),name:k.column_name,label:Le(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};x(B)}}}function I(k){k===!0&&(d||v)&&l?(f({connectionId:l,connectionType:j==="S3"||j==="API"?"DuckDb":j||"",databaseName:c||"",schemaName:m||"",tableName:d||"",datamodelName:t.resolveDatamodelName(v),datamodelId:h||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(y({connectionId:l||"",connectionType:j||"",tableName:d||"",datamodelName:t.resolveDatamodelName(v),datamodelId:h||"",databaseName:c||"",schemaName:m||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function D(){const k=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:v,connectionType:j,databaseName:c||""});E(!1);const M=j==="MSSQL"?`SELECT top 10 * FROM ${k}`:`SELECT * FROM ${k} LIMIT 10`;p(M),C(!0)}function N(){const k=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:v,connectionType:j,databaseName:c||""});p(`SELECT COUNT(*) as count FROM ${k}`),C(!0)}function F(){return(S==null?void 0:S.find(k=>k.connectionId===l&&(k.tableName===d||k.datamodelName===v)))!==void 0}function O(k){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(k),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Tt,{column:k}),e.jsx("span",{children:k.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(k.data_type)&&e.jsx(Hn,{column:k})})]}):e.jsx(Un,{onClick:w,column:k})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${F()?"Remove from":"Add to"} Assistant Scope`,pressed:F(),onPressedChange:I,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":F(),"text-muted-foreground":!F()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:D,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Sn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:N,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(ts,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((k,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:A()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(k=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:O(k)},k.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function ds({ColumnsComponent:s,type:a}){var Me;const n=t.useEditorStore(W=>W.card),r=t.useEditorStore(W=>W.selectedConnectionId),o=t.useDashboardStore(W=>W.showFilters),i=t.useEditorStore(W=>W.selectedDatamodelId),l=t.useEditorStore(W=>W.selectedDatabaseName),u=t.useEditorStore(W=>W.selectedSchemaName),c=t.useEditorStore(W=>W.selectedTableName),m=t.useEditorStore(W=>W.isDevMode),{setSelectedTableName:d,setIsDevMode:h,setCardSql:S}=t.useEditorActions(),{connectionItems:f,modelItems:y,schemaItems:x,databaseItems:g,tableItems:p,columns:C,isConnectionsLoading:T,isModelsLoading:E,isConnectionsError:j,isModelsError:b,isDatabasesLoadingOrFetching:v,isDatabaseError:w,isSchemaLoadingOrFetching:I,isSchemaError:D,isColumnsError:N,isColumnsLoadingOrFetching:F,isTableLoadingOrFetching:O,isTableError:A,connectionType:k,isNonDbConnection:M,refetchDatabases:B,refetchModels:z,refetchSchemas:V,refetchTables:R,refetchColumns:K,refetchConnections:J,handleConnectionChange:_,handleDatabaseChange:U,handleSchemaChange:q,handleDatamodelChange:P,handleTableChange:$,tableName:H,schemaName:Y}=t.useEditorAside(),{data:Z,refetch:ae}=t.useDashboardCardQuery(n);function Ne(){return s?s(Y,H,C):e.jsx(Kn,{schemaName:Y,tableName:H,columns:C,status:F?"Loading...":N?"Error":"Success"})}function pe(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function Ce(W){W===!0?Z&&(S(Z.userSql),setTimeout(()=>{ae()},100)):S(""),h(W)}function Se(){if(!r||k==="S3"||k==="API")return null;if(!i||i==="none")return e.jsx(ke,{refetch:B,showNone:!0,onChange:U,isError:w,isLoading:v,items:g,value:l||"",title:"Database",type:"combobox"})}function G(){if(r&&!M&&(!l||l==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function Q(){if(!r||k==="S3"||k==="API")return null;if(!l||l==="none")return e.jsx(ke,{refetch:z,showNone:!0,onChange:P,isError:b,isLoading:E,items:y,value:i||"",title:"Model",type:"combobox"})}function he(){return!r||k==="S3"||k==="API"||!l||l==="none"?null:e.jsx(ke,{refetch:V,onChange:q,isError:D,isLoading:I,items:x,value:u||"",title:"Schema",type:"combobox"})}function we(){function W(){let se=!1;return k==="API"?(se=!1,se):((k==="S3"||r&&l&&l!=="none"&&u)&&(se=!0),se)}return W()?e.jsx(ke,{refetch:R,onChange:$,isError:A,items:p,isLoading:O,value:c||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(ke,{refetch:J,items:f,title:"Connection",value:r||"",onChange:_,isLoading:T,isError:j,type:"combobox",connectionTooltip:((Me=f==null?void 0:f.find(W=>W.id===r))==null?void 0:Me.type)||""}),Se(),G(),Q(),he(),we()]}),Ne(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:m,onCheckedChange:Ce,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:pe,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(En,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function us({sql:s,error:a,onClick:n}){const r=t.useEditorStore(c=>c.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:l}=t.useEditorActions();function u(){o(!r),i(s),setTimeout(()=>{l(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&a,s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&e.jsxs(t.Button,{onClick:u,variant:"secondary",size:"sm",children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(jn,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function ms({sql:s,error:a,onClick:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Xt,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"w-full min-w-fit max-w-[700px]",children:e.jsx(us,{sql:s,error:a,onClick:n})})]})}var hs={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Ht=L.createContext&&L.createContext(hs),Qn=["attr","size","title"];function Wn(s,a){if(s==null)return{};var n=Xn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Xn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function $e(){return $e=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},$e.apply(this,arguments)}function Jt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function He(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Jt(Object(n),!0).forEach(function(r){Zn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):Jt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function Zn(s,a,n){return a=ea(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function ea(s){var a=ta(s,"string");return typeof a=="symbol"?a:a+""}function ta(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function xs(s){return s&&s.map((a,n)=>L.createElement(a.tag,He({key:n},a.attr),xs(a.child)))}function be(s){return a=>L.createElement(sa,$e({attr:He({},s.attr)},a),xs(s.child))}function sa(s){var a=n=>{var{attr:r,size:o,title:i}=s,l=Wn(s,Qn),u=o||n.size||"1em",c;return n.className&&(c=n.className),s.className&&(c=(c?c+" ":"")+s.className),L.createElement("svg",$e({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,l,{className:c,style:He(He({color:s.color||n.color},n.style),s.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return Ht!==void 0?L.createElement(Ht.Consumer,null,n=>a(n)):a(hs)}function na(s){return be({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}function ps(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(x=>x.theme),r=t.useEditorStore(x=>x.frame),o=t.useEditorStore(x=>x.card),i=t.useEditorStore(x=>x.activeTabCardId),l=t.Le(),{refetch:u}=t.useDashboardCardQuery(o),{updateCardTab:c,setRunSql:m}=t.useEditorActions(),d=L.useRef(),h=L.useRef({}),S=r.cards.find(x=>x.id===i),f=L.useCallback(()=>{let x="";return s==="python"&&(x=(S==null?void 0:S.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(x=(S==null?void 0:S.sql)||""),x},[s,S]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(d.current&&l){const x=d.current.getModel();x&&(h.current[o.id]=x);let g=h.current[i];if(!g){const p=f();g=l.editor.createModel(p,s),h.current[i]=g}d.current.setModel(g)}c(i,o),m(!0)}},[i,o,c,l,m,s,f]),L.useEffect(()=>{if(!l)return;const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",g=n==="system"?x:n;l.editor.defineTheme("default",{base:g==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":g==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),l.editor.setTheme("default")},[a,n,l]),L.useEffect(()=>{const x=d.current;x&&l&&o&&x.addCommand(l.KeyMod.Shift|l.KeyCode.Enter,function(){return u(),!1})},[l,u,o]);function y(x,g){if(d.current=x,!h.current[o.id]){const p=x.getModel(),C=f();h.current[o.id]=p||(g==null?void 0:g.editor.createModel(C,s))||x.getModel()}x.setModel(h.current[o.id])}return{handleEditorDidMount:y}}function aa(){const s=t.useEditorStore(l=>l.card.sql),a=t.useEditorStore(l=>l.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=ps("sql");function i(l){n(l),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function ra(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=ps("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function oa({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function ia(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(R=>R.frame);const i=t.useEditorStore(R=>R.card);t.useEditorStore(R=>R.isShowingVisual),t.useEditorStore(R=>R.selectedConnectionId),t.useEditorStore(R=>R.tempQueryData),t.useEditorStore(R=>R.selectedDatabaseName),t.useEditorStore(R=>R.selectedDatamodelId),t.useEditorStore(R=>R.selectedSchemaName);const l=t.useEditorStore(R=>R.showAIDialog);t.useEditorStore(R=>R.selectedTableName);const u=t.useEditorStore(R=>{var K;return(K=R==null?void 0:R.card)==null?void 0:K.sql}),c=t.useEditorStore(R=>{var K;return(K=R==null?void 0:R.card)==null?void 0:K.python}),{sheetFilterValues:m}=t.useSheetFilterValues(),{setCardCustomCfg:d,setQueryResultColumns:h,setCardSql:S,setTempQueryData:f,setPythonStdOut:y,setCardPreferences:x,setCardType:g,setCardPython:p,runAssistant:C,setShowAIDialog:T}=t.useEditorActions();t.useEditorStore(R=>R.onSave),t.useEditorStore(R=>R.onClose),t.useEditorStore(R=>R.actions.setSqlGen);const E=t.useEditorStore(R=>R.runSql),j=t.useEditorStore(R=>R.actions.setRunSql),b=t.useEditorStore(R=>R.actions.setIsSqlRunning),{data:v,isLoading:w,isFetching:I,isSuccess:D,isError:N,error:F,queryKey:O,refetch:A,errorMessage:k}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(v&&(v.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),y((v==null?void 0:v.output)||""),v.records.length>0)){const{dimensionKeys:R}=t.getKeys(v.records);h(R)}},[v,h,y]),L.useEffect(()=>{(w||I)&&b(!0),(N||D)&&b(!1),N&&(h([]),y(""))},[w,I,v,y,N,D,b,h,F]),L.useEffect(()=>{E&&(s.getQueryData(O)||A(),j(!1))},[E,A,j,O,s]);async function M(){const R=`Can you help me debug this query in the current table scope?
|
|
387
387
|
|
|
388
388
|
Error:
|
|
389
389
|
|
|
@@ -395,11 +395,11 @@
|
|
|
395
395
|
|
|
396
396
|
${c?`Python:
|
|
397
397
|
${c}`:""}
|
|
398
|
-
`;C(R)}function B(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(oa,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(Ct,{className:"size-3.5 text-muted-foreground"})})]})}function z(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(aa,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(ra,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function P(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:w||I,onClick:()=>{A()},className:"h-8 shrink-0",size:"sm",children:[w||I?e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(hs,{sql:v==null?void 0:v.sql,error:k,onClick:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:R=>n(R),className:"",size:"sm",children:e.jsx(na,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:l,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:l?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[z(),B()]}),P()]})}function la({data:s}){var l;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(u=>({accessorKey:u,header:({column:c})=>{const m=c.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>c.toggleSorting(c.getIsSorted()==="asc"),children:[u,m==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(u=>e.jsx(t.TableRow,{className:"",children:u.headers.map(c=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:c.isPlaceholder?null:t.flexRender(c.column.columnDef.header,c.getContext())},c.id))},u.id))}),e.jsx(t.TableBody,{children:(l=i.getRowModel().rows)!=null&&l.length?i.getRowModel().rows.map(u=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":u.getIsSelected()&&"selected",children:u.getVisibleCells().map(c=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(c.column.columnDef.cell,c.getContext())},c.id))},u.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function ca({card:s}){var C,T,E,j,b,v,w,I,D,N,F;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),l=t.getTokenParams(i==null?void 0:i.accessToken),u=t.useDashboardStore(O=>O.themeStyle),c={colors:((T=(C=u==null?void 0:u.chart)==null?void 0:C.dataset)==null?void 0:T.backgroundColor)||[]};(E=s.customCardPreferences)!=null&&E.inputData;const{getCard:m}=t.useCustomVisual(((j=s.customCardPreferences)==null?void 0:j.url)||""),d=((b=s.customCardPreferences)==null?void 0:b.visualType)||"single",h=t.useEditorStore(O=>O.frame),{setCustomCardPreferences:S}=t.useEditorActions(),{data:f}=t.useDashboardCardQuery(s),y=L.useCallback((O,A)=>{o(k=>({...k,[O]:A}))},[]);if(!((v=s.customCardPreferences)!=null&&v.componentName))return null;const x=m((w=s.customCardPreferences)==null?void 0:w.componentName);function g(O){n(O)}const p=Object.keys(((I=s.customCardPreferences)==null?void 0:I.dataInputCardIds)||{}).map(O=>{var M,B,z;const A=(B=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:B[O].cardId,k=(z=h==null?void 0:h.cards)==null?void 0:z.find(P=>P.id===A);return k||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&d==="single"&&e.jsx(x,{params:l,theme:c,settings:(D=s.customCardPreferences)==null?void 0:D.settings,onDataChange:y,data:(f==null?void 0:f.records)||[]}),x&&d==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((N=s.customCardPreferences)==null?void 0:N.dataInputCardIds)||{}).map(O=>{var M,B,z;const A=(B=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:B[O].cardId,k=(z=h==null?void 0:h.cards)==null?void 0:z.find(P=>P.id===A);if(k)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:g,onDataChange:y,dataInputIndex:O,card:k},k.id+O)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:c,onDataChange:y,settings:p.map(O=>{var A;return(A=O==null?void 0:O.customCardPreferences)==null?void 0:A.settings}),data:p.map(O=>O!=null&&O.id?r==null?void 0:r[O.id]:[])})})]})]},(F=s.customCardPreferences)==null?void 0:F.componentName)})}function gs({className:s,...a}){var g;const n=t.useEditorStore(p=>p.card),r=((g=n.customCardPreferences)==null?void 0:g.showCardHeader)??!0,o=t.useEditorStore(p=>p.frame),i=t.useDashboardStore(p=>p.dashboard.filters);t.useEditorStore(p=>p.actions.setRunSql);const{updateFilter:l}=t.useDashboardActions(),u=i==null?void 0:i.find(p=>p.id===o.filterId),{data:c,isLoading:m,isFetching:d}=t.useDashboardCardQuery(n),{setCard:h}=t.useEditorActions(),{data:S}=t.useTopoJson(n),f=L.useMemo(()=>!n.id||!(c!=null&&c.records)?null:t.createChartConfig({card:n,data:c==null?void 0:c.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:S}),[n.id,c==null?void 0:c.records,n.type,n.queryConfig,n.customCfg,n.preferences,S]);function y(p){return e.jsx(ca,{card:p})}function x(){if(c!=null&&c.records&&(c==null?void 0:c.records.length)===0&&!m&&!d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return y(n);if(!["table","custom"].includes(n.type)&&f)return e.jsx(e.Fragment,{children:m||d?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:f})});if(n.type==="table"&&(c!=null&&c.records)&&(c==null?void 0:c.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:n,data:c==null?void 0:c.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:p=>h({...n,title:p}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:p=>h({...n,description:p}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:u.title||u.column,onSave:p=>l({...u,title:p}),children:e.jsx(t.Label,{children:u.title})}),e.jsx(t.FilterComponent,{filter:u})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:x()})]})}const at=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:a,onChange:n}),da=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),ua=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(at,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(at,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(at,{language:"javascript",value:s,onChange:o})})]}),ma=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function ha(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[l,u]=L.useState(""),[c,m]=L.useState(""),d=t.useEditorStore(j=>j.card),h=t.useEditorStore(j=>j.card.customCfg),S=h?JSON.stringify(h,null,2):"",{data:f}=t.useDashboardCardQuery(d),{data:y}=t.useTopoJson(d),{setCardCustomCfg:x,setCustomVisualCode:g}=t.useEditorActions(),p=j=>{var b,v;return JSON.stringify({...j,data:{...j.data,datasets:(v=(b=j.data)==null?void 0:b.datasets)==null?void 0:v.map(w=>({...w,data:[]}))}},null,2)},C=()=>{var b,v;if(!((b=f==null?void 0:f.records)!=null&&b.length))return;const j=t.createChartConfig({card:d,data:f.records,cardType:d.type,queryConfig:d.queryConfig,preferences:d.preferences,topoJson:y});if(j){r(p(j)),u(((v=d.preferences)==null?void 0:v.customVisualCode)||"");const w=t.merge(j,h);i(p(w))}},T=()=>{try{if(l&&g(l),o){const j=JSON.parse(o),b=t.getObjectDiff(JSON.parse(n),j);x(b),m("")}}catch{m("Invalid JSON configuration")}},E=Object.keys(h||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:C,className:E?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(da,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(gs,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ua,{customCode:l,cardCustomCfgString:S,mergedConfig:o,onConfigChange:j=>i(j??""),onCodeChange:j=>u(j??"")})]}),e.jsx(ma,{error:c,hasCardCustomConfig:!!h,onReset:()=>{i(n),x(null)},onApply:T,onClose:()=>a(!1)})]})]})}function js(s){const[a,n]=L.useState(null);return a}function ys(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function xa({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:l}=t.useEditorActions(),{data:u}=ys();function c(m,d){r(null),o({}),i(m),d&&l({type:"component",visualType:"single",url:d.url,componentName:d.name,icon:d.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var d;if(u){const S=(await Promise.all((d=u==null?void 0:u.plugins)==null?void 0:d.map(async f=>(await t.loadManifest(f.value)).visuals.map(g=>({name:g.name,icon:g.icon,url:f.value}))))).flat();n(S)}})()},[u]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((m,d)=>e.jsx(pa,{text:m.name,onClick:()=>c("custom",m),icon:m.icon},m.url+m.name+d))})]})}const pa=({text:s,icon:a,onClick:n})=>{const r=js(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function At(s){return be({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(s)}function fa(s){return be({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(s)}function Lt(s){return be({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(s)}function Ot(s){return be({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(s)}function Ft(s){return be({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(s)}function Bt(s){return be({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(s)}function bs({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(d=>d.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(d,h){i(null),r({}),n(d),["kpi","custom","text","map"].includes(d)&&(o(!0),u(void 0)),s==null||s()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(t.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>c("table"),className:"h-10 p-4",children:e.jsx(We,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>c("bar"),className:"h-10 p-4",children:e.jsx(Ke,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>c("line"),className:"h-10 p-4",children:e.jsx(Qe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>c("stackedBar"),className:"h-10 p-4",children:e.jsx(gt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>c("stackedLine"),className:"h-10 p-4",children:e.jsx(Ft,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>c("scatter"),className:"h-10 p-4",children:e.jsx(vt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>c("bubble"),className:"h-10 p-4",children:e.jsx(Lt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>c("pie"),className:"h-10 p-4",children:e.jsx(bt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>c("doughnut"),className:"h-10 p-4",children:e.jsx(Nt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>c("funnel"),className:"h-10 p-4",children:e.jsx(Ot,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>c("radar"),className:"h-10 p-4",children:e.jsx(kt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>c("polarArea"),className:"h-10 p-4",children:e.jsx(At,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>c("tornado"),className:"h-10 p-4",children:e.jsx(It,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>c("range"),className:"h-10 p-4",children:e.jsx(yt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>c("kpi"),className:"h-10 p-4",children:e.jsx(Bt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>c("text"),className:"h-10 p-4",children:e.jsx(Xt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>c("map"),className:"h-10 p-4",children:e.jsx(wt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>c("custom"),className:"h-10 p-4",children:e.jsx(Et,{className:t.cn("size-5",a)})})]})}function ga({chartType:s,className:a,customIcon:n,componentName:r}){const o=js();switch(s){case"bar":return e.jsx(Ke,{className:a});case"line":return e.jsx(Qe,{className:a});case"pie":return e.jsx(bt,{className:a});case"radar":return e.jsx(kt,{className:a});case"scatter":return e.jsx(vt,{className:a});case"bubble":return e.jsx(Lt,{className:a});case"doughnut":return e.jsx(Nt,{className:a});case"stackedBar":return e.jsx(gt,{className:a});case"stackedLine":return e.jsx(Ft,{className:a});case"polarArea":return e.jsx(At,{className:a});case"funnel":return e.jsx(Ot,{className:a});case"tornado":case"pyramid":return e.jsx(It,{className:a});case"range":return e.jsx(yt,{className:a});case"kpi":return e.jsx(Bt,{className:a});case"text":return e.jsx(rs,{className:a});case"map":return e.jsx(wt,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Et,{className:a});default:return e.jsx(We,{className:a})}}function vs({variant:s="ghost"}){var i,l;const[a,n]=L.useState(!1),r=t.useEditorStore(u=>u.card),o=r.type;return t.useDashboardStore(u=>u.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(ga,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(l=r.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:u=>u.preventDefault(),className:"w-72 p-1",children:[e.jsx(bs,{onChartTypeChange:()=>n(!1)}),e.jsx(xa,{onChartTypeChange:()=>n(!1)})]})]})}const Re="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Yt(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function ja(){var M,B,z,P,R,K;const[s,a]=L.useState(!1),n=t.useEditorStore(J=>{var _;return(_=J.card)==null?void 0:_.preferences}),r=t.useEditorStore(J=>{var _;return(_=J.card)==null?void 0:_.type}),o=t.getNumberAxis(n,{}),[i,l]=L.useState(Yt(n,r)),[u,c]=L.useState(((z=(B=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:B[o])==null?void 0:z.min)||""),[m,d]=L.useState(((K=(R=(P=n==null?void 0:n.chartOptions)==null?void 0:P.scales)==null?void 0:R[o])==null?void 0:K.max)||""),[h,S]=L.useState(u||m?"custom":"auto"),[f,y]=L.useState(""),[x,g]=L.useState(0),[p,C]=L.useState(""),[T,E]=L.useState(""),[j,b]=L.useState(""),v=t.useEditorStore(J=>J.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),I=t.useEditorStore(J=>J.card),D=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var J,_,U,q,V,G,H,Y,Z,ae,Ne,pe,Ce,Se;l(Yt(n,r)),c(((U=(_=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:_[o])==null?void 0:U.min)===0?0:""),d(((G=(V=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:V[o])==null?void 0:G.max)||""),y(((ae=(Z=(Y=(H=n==null?void 0:n.chartOptions)==null?void 0:H.scales)==null?void 0:Y[o])==null?void 0:Z.ticks)==null?void 0:ae.stepSize)||""),g(((Ne=n==null?void 0:n.numberAxisFormat)==null?void 0:Ne.decimalPlaces)||0),C(((pe=n==null?void 0:n.numberAxisFormat)==null?void 0:pe.suffix)||""),E(((Ce=n==null?void 0:n.numberAxisFormat)==null?void 0:Ce.currency)||""),b(((Se=n==null?void 0:n.numberAxisFormat)==null?void 0:Se.locale)||"")},[s,n,o,r]);function N(J,_){return _===""||/^[0-9\b]+$/.test(_)?Number(_):Number(J)}function F(){const J=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(_=>_.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(t.Select,{value:T||"none",onValueChange:_=>E(_==="none"?"":_),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),J.map(_=>e.jsx(t.SelectItem,{value:_,children:_},_))]})})]}),e.jsxs(t.Select,{value:j,onValueChange:_=>b(_),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map(_=>e.jsx(t.SelectItem,{value:_.locale,children:_.locale},_.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:x,onChange:_=>g(Number(_.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Re}`})]})]})}function O(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:D,value:i,onValueChange:J=>l(J),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:D,id:"scale-option",value:h,onValueChange:J=>S(J),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&i=="linear"&&A()]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:u,onChange:J=>c(_=>N(_,J.target.value)),className:`col-span-1 h-8 w-full ${Re}`}),e.jsx(t.Input,{value:m,onChange:J=>d(_=>N(_,J.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Re}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:f,onChange:J=>y(_=>N(_,J.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Re}`})]})]})}function k(){var q;let J={};h==="custom"&&(J={min:u,max:m,ticks:{stepSize:f}});const _={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:i,...i==="linear"?J:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:p,currency:T,locale:j}};console.log(_),v(_);const U={...I,preferences:_};w(U)}return e.jsxs(t.Popover,{onOpenChange:J=>a(J),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(dn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[F(),O(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:k,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function ya(){const s=t.useEditorStore(u=>{var c,m,d,h;return(h=(d=(m=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:m.plugins)==null?void 0:d.legend)==null?void 0:h.position}),a=t.useEditorStore(u=>{var c,m,d,h;return(h=(d=(m=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:m.plugins)==null?void 0:d.legend)==null?void 0:h.align}),n=t.useEditorStore(u=>{var c,m,d,h;return(h=(d=(m=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:m.plugins)==null?void 0:d.legend)==null?void 0:h.display}),{setLegendOptions:r}=t.useEditorActions(),o=u=>{r({display:u,position:s,align:a})},i=u=>{r({display:n,position:u,align:a})},l=u=>{r({display:n,position:s,align:u})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(bn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(Ye,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Js,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(Ue,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(Us,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>l("start"),children:e.jsx(qs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>l("center"),children:e.jsx(Vs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>l("end"),children:e.jsx(_s,{className:"size-4"})})]})]})]})]})]})})]})}function ba(){const s=t.useEditorStore(i=>{var l,u;return(u=(l=i.card.preferences)==null?void 0:l.chartOptions)==null?void 0:u.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx($t,{className:"size-4"}):e.jsx(_t,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx($t,{className:"size-4"}):e.jsx(_t,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function Ns(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>l.isShowingVisual),n=t.useEditorStore(l=>{var u,c;return(c=(u=l.card)==null?void 0:u.preferences)==null?void 0:c.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const l=["xy","none","x","y"],c=(l.indexOf(r)+1)%l.length;o(l[c])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(ba,{}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ja,{}),e.jsx(ya,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(gn,{className:"size-4"}),r==="x"&&e.jsx(on,{className:"size-4"}),r==="y"&&e.jsx(Mn,{className:"size-4"}),r==="none"&&e.jsx(On,{className:"size-4"})]})]}):null}function va(){const s=t.useEditorStore(y=>y.frame),a=t.useEditorStore(y=>y.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),l=(y,x)=>{y.dataTransfer.setData("tabIndex",x.toString())},u=y=>{y.preventDefault()},c=(y,x)=>{const g=y.dataTransfer.getData("tabIndex");if(g===x.toString())return;const p=Array.from(s.cards),[C]=p.splice(parseInt(g),1);p.splice(x,0,C),n({...s,cards:p})};function m(y){const x=s.cards.filter(C=>C.id!==y),g=x[0],p={...s,cards:x,activeCardId:g.id};n(p),r(g.id),o(g)}function d(y,x){const g={...s,cards:[...s.cards,x],activeCardId:y.id};n(g),r(x.id)}function h(){const y={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};d(a,y)}function S(y){const x={connectionId:y.connectionId,lastSelectedDatabase:y.lastSelectedDatabase,lastSelectedSchema:y.lastSelectedSchema,lastSelectedTable:y.lastSelectedTable,lastSelectedDatamodelId:y.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]};d(y,x)}function f(y,x){return y.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||y.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const g=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:g}),i({...x,displayTab:g})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(un,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((y,x)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:g=>l(g,x),onDragOver:u,onDrop:g=>c(g,x),className:"",value:y.id,children:[f(s,y),e.jsx(t.Editable,{enabled:s.activeCardId===y.id,text:y.tabTitle||y.title,onSave:g=>{o({...a,tabTitle:g}),i({...a,tabTitle:g})},children:y.tabTitle||y.title},y.id),s.activeCardId===y.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(y.id)})]},y.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>S(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(cn,{className:"h-4 w-4"})})]})})}function Cs(){const s=t.useEditorStore(x=>x.frame),a=t.useEditorStore(x=>x.card),n=t.useEditorStore(x=>x.isSqlRunning),r=t.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:l,setIsDevMode:u,setRunSql:c}=t.useEditorActions(),{data:m,isLoading:d,isFetching:h}=t.useDashboardCardQuery(a);function S(x){const g=s.cards.find(p=>p.id===x);if(g!=null&&g.sql){r||u(!0),i(x);return}if(g!=null&&g.queryConfig){r&&u(!1),f(x),i(x);return}r||f(x),i(x)}function f(x){const g={...s,cards:s.cards.map(C=>C.id===a.id?a:C),activeCardId:x};o(g);const p=g.cards.find(C=>C.id===x);p.sql&&c(!0),l(p)}function y(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.KPICard,{card:a,data:m==null?void 0:m.records,isPending:d})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(gs,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:S,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(x=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:x.id,children:y()},x.id)),e.jsx(va,{})]})}function Pe({children:s}){var C;t.useEditorStore(T=>T.frame);const a=t.useEditorStore(T=>T.card),n=t.useEditorStore(T=>T.isDevMode),r=t.useEditorStore(T=>T.isShowingVisual),o=t.useDashboardStore(T=>T.isVisualEditing),i=t.useEditorStore(T=>T.pythonStdOut);t.useEditorStore(T=>T.actions.setRunSql);const{setFrame:l,setCard:u,setActiveTabCardId:c,runAssistant:m,setIsDevMode:d}=t.useEditorActions(),{data:h,isLoading:S,isFetching:f,error:y}=t.useDashboardCardQuery(a);function x(){const T=JSON.stringify(h==null?void 0:h.records,null,2),E=new Blob([T],{type:"application/json"}),j=URL.createObjectURL(E),b=document.createElement("a");b.href=j,b.download=`${a.title}.json`,b.click()}function g(){const E=[Object.keys(h==null?void 0:h.records.reduce((w,I)=>({...w,...I}),{})).join(","),...((h==null?void 0:h.records)||[]).map(w=>Object.values(w).join(","))].join(`
|
|
399
|
-
`),j=new Blob([E],{type:"text/csv"}),b=URL.createObjectURL(j),v=document.createElement("a");v.href=b,v.download=`${a.title}.csv`,v.click()}function p(){const T=`Can you get the documentation for ${a.type} chart?`;m(T)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(S||f)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(ue,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(vs,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:p,children:e.jsx(Ws,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(ha,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:g,children:e.jsx(fa,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:x,children:e.jsx(hn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(h==null?void 0:h.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(Ns,{})]}),n&&e.jsx(Ca,{})]}),r?e.jsx(Cs,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(Na,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(la,{data:(h==null?void 0:h.records)||[]}),(y||(h==null?void 0:h.error))&&e.jsx("span",{className:"font-mono text-xs",children:(y==null?void 0:y.message)||((C=h==null?void 0:h.error)==null?void 0:C.message)})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Na(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Ca(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Sa(){var x,g;const s=t.useEditorStore(p=>p.card.customCardPreferences),{data:a}=ys(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(p=>p.card),o=t.useEditorStore(p=>p.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:l}=t.useEditorActions(),{components:u,manifest:c}=t.useCustomVisual((s==null?void 0:s.url)||""),m=(x=c==null?void 0:c.visuals)==null?void 0:x.find(p=>p.name===(s==null?void 0:s.componentName));function d(p,C){if(!s)return;const E={...(s==null?void 0:s.dataInputCardIds)||{},[p]:{cardId:C,hookRef:null}};l({...s,dataInputCardIds:E})}function h(p){var T,E;const C=(T=o==null?void 0:o.cards)==null?void 0:T.filter(j=>{var b;return((b=j==null?void 0:j.customCardPreferences)==null?void 0:b.visualType)!=="multiple"}).map(j=>({value:j.id,label:j.tabTitle||j.title}));return e.jsx("div",{className:"space-y-2",children:(E=p==null?void 0:p.dataInputs)==null?void 0:E.map((j,b)=>{var v,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:j}),e.jsx(de,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((w=(v=s==null?void 0:s.dataInputCardIds)==null?void 0:v[b])==null?void 0:w.cardId)||"",onValueChange:I=>d(b,I)})]},b+Math.random())})})}function S(p,C,T=[],E=""){var j,b;return s?p==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((j=s==null?void 0:s.settings)==null?void 0:j[C])||E,onChange:v=>{l({...s,settings:{...s==null?void 0:s.settings,[C]:v.target.value}})}},C):p==="select"?e.jsx(de,{className:"h-8 w-full",label:"",options:T,value:((b=s==null?void 0:s.settings)==null?void 0:b[C])||E,onValueChange:v=>{l({...s,settings:{...s==null?void 0:s.settings,[C]:v}})}}):null:null}function f(p){const C=Object.entries((p==null?void 0:p.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([T,E])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:E.title}),S(E.ui,T,E.options,E.defaultValue)]},T))})}function y(p){s&&l({...s,visualType:p,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(de,{icon:e.jsx(Qs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:p=>l({...s||{url:"",componentName:""},url:p})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:y,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:u&&e.jsx(de,{icon:e.jsx(ln,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.filter(p=>p.type===i).map(p=>({value:p.name,label:p.name})))||[],value:s.componentName,onValueChange:p=>{console.log("changing value",p),l({...s,componentName:p})}})})]})})]}),((g=r==null?void 0:r.customCardPreferences)==null?void 0:g.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function ve(){const[s,a]=L.useState([]),n=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(m=>m.actions),i=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var d;return(d=m.card.preferences)==null?void 0:d.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(m,d){var h,S;d?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):o({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(o({...n,onClickFilter:(S=n==null?void 0:n.onClickFilter)==null?void 0:S.filter(f=>f.columnIndex!==m)}),a(f=>{const y=[...f];return y[m]=!1,y}))}function u(m,d){var S;const h=(S=n==null?void 0:n.onClickFilter)==null?void 0:S.map(f=>f.columnIndex===m?{...f,expression:d.target.value}:f);o({...n,onClickFilter:h})}function c(m){var d,h,S,f;if(s!=null&&s[m]||(h=(d=n==null?void 0:n.onClickFilter)==null?void 0:d.find(y=>y.columnIndex===m))!=null&&h.expression)return e.jsx(t.Input,{value:(f=(S=n==null?void 0:n.onClickFilter)==null?void 0:S.find(y=>y.columnIndex===m))==null?void 0:f.expression,onChange:y=>u(m,y),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((m,d)=>{var h,S;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(f=>f.columnIndex===d)),onCheckedChange:f=>l(d,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((S=n==null?void 0:n.onClickFilter)==null?void 0:S.find(f=>f.columnIndex===d))&&e.jsx(t.Pencil,{onClick:()=>{a(f=>{const y=[...f];return y[d]=!f[d],y})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),c(d)]})},m)})]})}function wa({idx:s}){var u;const a=t.useEditorStore(c=>{var m;return(m=c.card)==null?void 0:m.preferences}),n=t.useEditorStore(c=>{var m;return(m=c.card.preferences)==null?void 0:m.datasetOptions}),r=t.useEditorStore(c=>c.actions.setCardPreferences),o=(u=a==null?void 0:a.chartOptions)==null?void 0:u.indexAxis,i=n==null?void 0:n.find(c=>c.idx===s);function l(c,m){(c==="end"||c==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const d={display:c!=="none",align:c,anchor:c,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:d}]});else{const h={...i};h.datalabels=d;const S=n==null?void 0:n.map(f=>f.idx===m?h:f);r({...a,datasetOptions:S})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(ns,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Cn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function Ss(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);o=l.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Je({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ws(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var m,d,h;return(h=(d=(m=c==null?void 0:c.card)==null?void 0:m.preferences)==null?void 0:d.chartOptions)==null?void 0:h.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:l,keys:u}=Ss();return u.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(c=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:c,children:ks(c)},c))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:l.map((c,m)=>e.jsx(Es,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:c,idx:m},c))})]})]})}function ks(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function Es({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(d=>{var h;return(h=d.card)==null?void 0:h.preferences}),l=t.useEditorStore(d=>{var h,S;return(S=(h=d.card)==null?void 0:h.preferences)==null?void 0:S.datasetOptions}),u=l==null?void 0:l.find(d=>d.idx===a),{setCardPreferences:c}=t.useEditorStore(d=>d.actions);function m(d){if(!u)c({...i,datasetOptions:[...l||[],{idx:a,type:d==="area"?"line":d,fill:d==="area"?"origin":""}]});else{const h={...u};h.type=d==="area"?"line":d,h.fill=d==="area"?"origin":"";const S=l==null?void 0:l.map(f=>f.idx===a?h:f);c({...i,datasetOptions:S})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Je,{className:"max-w-[100px]",title:s,children:ks(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ke,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Qe,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(tn,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(wa,{idx:a})]})]})}function Is(){const s=t.useEditorStore(f=>f.selectedConnectionId),a=t.useEditorStore(f=>f.selectedDatamodelId),n=t.useEditorStore(f=>f.selectedDatabaseName),r=t.useEditorStore(f=>f.selectedSchemaName),o=t.useEditorStore(f=>f.selectedTableName),i=t.useDashboardStore(f=>f.dashboard.filters)||[],l=t.useDashboardStore(f=>f.actions.addFilter),u=t.useDashboardStore(f=>f.actions.removeFilter),{removeFilterValues:c}=t.useDashboardActions(),{modelItems:m,tableName:d,connectionType:h}=t.useEditorAside();function S(f,y="dashboard"){var v;const x=t.fmt(f.column_name),g=t.fmt(n||""),p=t.fmt(r||""),C=t.fmt(d);let T=t.getQualifiedTableName({schemaName:p,tableName:C,connectionType:h,databaseName:g}),E=`${T}.${x}`;const j=(v=m==null?void 0:m.find(w=>w.id===a))==null?void 0:v.name;a&&a!=="none"&&(E=`${t.DATAMODEL_NAMESPCACE}.${j}.${x}`,T=`${t.DATAMODEL_NAMESPCACE}.${j}`);const b=i==null?void 0:i.find(w=>w.column===E&&w.table===C&&(w.database===g||w.database===n));if(b)c(b.id),u(b.id);else{const w=t.v4();return d==="api"&&s?(l({location:y,id:w,column:E,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(f.data_type,T,x)}),w):(l({id:w,location:y,column:E,title:f.column_name,dataType:f.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(f.data_type,T,x)}),w)}}return{assignFilter:S}}function Te(){const s=t.useDashboardStore(u=>u.dashboard.filters),a=t.useEditorStore(u=>u.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=Is();function i(u){const c=o(u,"frame");n({...a,filterId:c})}const l=s==null?void 0:s.find(u=>u.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(ka,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function ka({columns:s,onSelect:a}){var l;const[n,r]=ie.useState(!1),[o,i]=ie.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(l=s.find(u=>u.column_name===o))==null?void 0:l.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(u=>e.jsxs(t.CommandItem,{value:u.column_name,onSelect:c=>{const m=c===o?"":c;i(m),r(!1),m&&a(u)},children:[u.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===u.column_name?"opacity-100":"opacity-0")})]},u.column_name))})]})]})})]})}function Ea({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(ws,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}function zt(){var o,i,l;const s=t.useEditorStore(u=>u.card.type),a=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:n}=t.useEditorStore(u=>u.actions);function r(u){var d;const c={datalabels:{display:u!=="none",align:u,anchor:u,clamp:!0}},m={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins,...c}}};n(m),console.log(u)}return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((l=(i=(o=a==null?void 0:a.chartOptions)==null?void 0:o.plugins)==null?void 0:i.datalabels)==null?void 0:l.anchor)||"none",onValueChange:r,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function Ia({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(zt,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}const Da={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Ta={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Ma(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:Aa(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(zt,{}),e.jsx(ve,{}),e.jsx(Te,{})]})]})}function Aa(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(Da,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Ta,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function La(){var c,m,d,h,S;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.actions.setCardPreferences),n=t.useEditorStore(f=>f.actions.setNumberFormat);t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.decimalPlaces});const r=t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.locale}),o=t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.currency});t.useEditorStore(f=>f.actions.setFilterOnClickField);const i=t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.colorRanges})||[],l=t.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((c=s==null?void 0:s.formatNumber)!=null&&c.enabled),onCheckedChange:f=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:f}})}}),e.jsx(t.Label,{children:"Format Number"})]}),((m=s==null?void 0:s.formatNumber)==null?void 0:m.enabled)===!0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:r||"none",onValueChange:f=>{var y,x,g;return n(((y=s==null?void 0:s.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=s==null?void 0:s.formatNumber)==null?void 0:x.currency)||"",f,((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),t.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(t.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:f=>{var y,x,g;console.log("currency",f),n(((y=s==null?void 0:s.formatNumber)==null?void 0:y.decimalPlaces)||0,f==="none"?"":f,((x=s==null?void 0:s.formatNumber)==null?void 0:x.locale)||"",((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(t.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((h=(d=s==null?void 0:s.formatNumber)==null?void 0:d.decimalPlaces)==null?void 0:h.toString())||"0",onValueChange:f=>{var y,x,g;return n(Number(f),((y=s==null?void 0:s.formatNumber)==null?void 0:y.currency)||"",((x=s==null?void 0:s.formatNumber)==null?void 0:x.locale)||"",((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(t.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((S=s==null?void 0:s.formatNumber)==null?void 0:S.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:f=>{var y,x,g;return n(((y=s==null?void 0:s.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=s==null?void 0:s.formatNumber)==null?void 0:x.currency)||"",((g=s==null?void 0:s.formatNumber)==null?void 0:g.locale)||"",f.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(t.ColorFormat,{colorRanges:i,setColorRanges:l})]})]})}function Oa(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(La,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function rt({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const Fa=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],Ba=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],za=Ba.map(s=>({label:s,value:s}));function Ra(){var c,m,d,h,S,f,y,x,g,p,C,T,E,j,b,v,w,I;const s=t.useEditorStore(D=>D.card),a=(m=(c=s==null?void 0:s.preferences)==null?void 0:c.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=L.useState(((h=(d=s==null?void 0:s.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(D=>({label:D,value:D}))||[],u=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(rt,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(rt,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(de,{className:"h-9",options:u,onValueChange:D=>{console.log("value",D),o({...s.preferences,mapVisualOptions:{topoJsonUrl:D}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:D=>{r(D.target.value)},onBlur:()=>{var D;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(D=s.preferences)==null?void 0:D.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(de,{className:"h-9",options:l,value:((f=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,objectKey:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(de,{className:"h-9",options:Fa,value:((x=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projection:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(de,{className:"h-9",options:za,value:((p=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:p.colorScale)||"",label:"Select Color Scale",onValueChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,colorScale:D}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(rt,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((T=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projectionScale:Number(D.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((b=(j=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:b[0])||0,onChange:D=>{var N,F,O,A;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[Number(D.target.value),((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((I=(w=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:I[1])||0,onChange:D=>{var N,F,O,A;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[0])||0,Number(D.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(ve,{})]})}function Pa(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Ve({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(zt,{}),s==="text"&&e.jsx(Pa,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}function Va(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(de,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(ws,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}function qa({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const _a=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),$a=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Ga=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Ha(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Va,{});case"tornado":case"pyramid":return e.jsx(Ve,{docContent:_a,cardType:n});case"kpi":return e.jsx(Oa,{});case"line":case"bar":return e.jsx(Ea,{cardType:n});case"range":return e.jsx(Ve,{docContent:$a,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Ve,{cardType:n});case"bubble":case"scatter":return e.jsx(Ia,{cardType:n});case"table":return e.jsx(qa,{cardType:n});case"text":return e.jsx(Ve,{docContent:Ga,cardType:n,suffix:"Visual"});case"map":return e.jsx(Ra,{});case"custom":return e.jsx(Sa,{});default:return e.jsx(Ma,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Ds({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(l=>l.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(l=>l.value===a.granularity)||n[0]);function i(l){r(l)}return e.jsx(de,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:l=>i(l),label:s,showPlaceholderLabel:!1})}const Ja=[{label:"Sum",value:"SUM",logo:e.jsx(ss,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(St,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(pn,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Hs,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(Ue,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(Ye,{className:"size-3.5"})}];function Ua({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ja;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:Le(s.name,o)};a(s.id,i)}return e.jsx(Ds,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Ya=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Ka({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:De(s.name,r)};a(s.id,o)}return e.jsx(Ds,{column:s,functions:Ya,onFunctionChange:r=>n(r),label:"Granularity"})}function Qa({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let u=[];(n===ge||n===je||n===ye)&&(u=r);const c=u==null?void 0:u.filter(m=>m.column_name!==s.name);return c==null?void 0:c.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function l(u){const c=r==null?void 0:r.find(m=>{var d;return m.column_name===((d=u[0])==null?void 0:d.id)});c&&a(c)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:l,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:s.name})}function Wa({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions(),{transformedMetricKeys:n,dimensionKeys:r}=Ss();console.log(n,r);const o=t.useEditorStore(c=>{var m;return(m=c.card.queryConfig)==null?void 0:m.pivotColumns}),i=!!(o&&o.length>0),l=n.find(c=>c===s.label||c===s.name),u=l?n.indexOf(l):-1;return e.jsxs("div",{className:"space-y-3",children:[l&&e.jsx(Es,{idx:u,col:l,children:e.jsx(t.Editable,{enabled:!0,className:"w-[130px]",text:s.label||"",placeholder:"Enter label",onSave:c=>{a(s.id,{...s,label:c||s.name})},children:e.jsx(Je,{className:"w-[130px]",children:s.label||s.name})})}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(t.Label,{children:"Pivot Header"}),e.jsx(t.Editable,{enabled:!0,text:s.aliasTemplate||"",placeholder:"{label} ({pivot})",onSave:c=>{a(s.id,{...s,aliasTemplate:c||""})},children:e.jsx(Je,{className:"font-mono text-xs text-muted-foreground",children:s.aliasTemplate||"{label} ({pivot})"})})]})]})}function Xa({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:l,updateMetricColumnOld:u,updatePivotByColumnOld:c}=t.useEditorActions(),{attributes:m,listeners:d,setNodeRef:h,transform:S,transition:f,isDragging:y}=t.useSortable({id:s.id,data:{type:a}}),x=S?{opacity:y?.5:void 0,transform:t.CSS.Translate.toString(S),transition:f}:void 0,g=t.isTextDataType(s.type);function p(b){const v=t.isNumberDataType(b.data_type),w=t.isTextDataType(b.data_type),I=t.isDateDataType(b.data_type),D=v?"number":w?"string":I?"date":"string";if(r===ge){if(w){const N={id:s.id,name:b.column_name,type:D,role:"groupby"};l(s.id,N)}if(I){const N={id:s.id,name:b.column_name,type:D,role:"groupby",label:De(b.column_name,"month"),granularity:"month"};l(s.id,N)}}if(r===ye){if(w){const N={id:s.id,name:b.column_name,type:D,role:"groupby"};c(s.id,N)}if(I){const N={id:s.id,name:b.column_name,type:D,label:De(b.column_name,"month"),granularity:"month",role:"groupby"};c(s.id,N)}}if(r===je){const N={id:s.id,name:b.column_name,type:D,role:"metric",label:Le(b.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};u(s.id,N)}}function C(){if(r===je)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Wa,{column:s})})}function T(){const b=t.isDateDataType(s.type);if(r===je)return e.jsx(Ua,{column:s});if((r===ge||r===ye)&&b)return e.jsx(Ka,{column:s})}function E(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===ge||r===ye)&&g}),children:e.jsx(Qa,{col:s,onChange:p,droppableId:r})})}function j(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(Ln,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(es,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...d,...m,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[j(),T(),E()]}),o&&C()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function ot({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var x,g;const{setNodeRef:l,isOver:u,over:c}=t.useDroppable({id:s}),m=t.useDndStore(p=>p.activeId),d=t.useEditorStore(p=>{var C;return(C=p.card)==null?void 0:C.type}),h=u||((g=(x=c==null?void 0:c.data)==null?void 0:x.current)==null?void 0:g.type)===o,S=m?r:n,f=o===_e?"Rows":o===$e?"Pivot Columns":"Columns";function y(){if(!S||S.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(p=>p.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:l,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),d!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:f})]}),y(),e.jsx("div",{className:"space-y-2",children:S==null?void 0:S.map(p=>p.id===ds.id?e.jsx(Za,{},p.id):e.jsx(Xa,{droppableId:s,type:o,column:p,onRemoveColumn:i},p.id))})]})})}function Za(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Ts({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:l,transition:u,isDragging:c}=t.useSortable({id:a,data:{type:n}}),m=l?{opacity:c?.5:void 0,transform:t.CSS.Translate.toString(l),transition:u}:void 0;return e.jsx("div",{...o,...r,ref:i,style:m,children:s})}function er(){const s=t.useEditorStore(p=>{var C;return(C=p.card.queryConfig)==null?void 0:C.orderBy})||[],a=t.useEditorStore(p=>{var C;return(C=p.card.queryConfig)==null?void 0:C.groupByColumns})||[],n=t.useEditorStore(p=>{var C;return(C=p.card.queryConfig)==null?void 0:C.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),l=[...a,...n];if(l.length===0)return e.jsx(e.Fragment,{});const u=e.jsx(Ks,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),c=e.jsx(Gs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(Ys,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx($s,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=l==null?void 0:l.filter(p=>!s.some(C=>C.columnId===p.id)).map(p=>({id:p.id,value:p.label||p.name}));function S(p,C){const T=f(p);return T?T.role==="metric"?C==="asc"?m:d:C==="asc"?u:c:null}function f(p){return l.find(C=>C.id===p)}function y(p){const C=s.find(T=>T.columnId===p);if(C){const T={...C,direction:C.direction==="asc"?"desc":"asc"};i(T)}}const x=p=>{r({columnId:p.id,direction:"asc"})};function g(p){const C=s.find(T=>T.columnId===p);C&&o(C)}return e.jsx(t.SortableContext,{items:s.map(p=>Ae(p.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:p=>x(p[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(p=>{var C,T;return e.jsx(Ts,{id:Ae(p.columnId),type:Mt,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(es,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Je,{className:"w-[175px] text-sm",children:((C=f(p.columnId))==null?void 0:C.label)||((T=f(p.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:p.direction==="asc"?"Ascending":"Descending",onClick:()=>y(p.columnId),className:"rounded-sm p-0",children:S(p.columnId,p.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>g(p.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},p.columnId)},Ae(p.columnId))})]})})}function tr(){const s=t.useEditorStore(g=>{var p;return((p=g.card.queryConfig)==null?void 0:p.groupByColumns)||[]}),a=t.useEditorStore(g=>g.card.type),n=t.useDndStore(g=>g.previewGroupByColumns),r=t.useEditorStore(g=>{var p;return((p=g.card.queryConfig)==null?void 0:p.metricColumns)||[]}),o=t.useDndStore(g=>g.previewMetricColumns),i=t.useEditorStore(g=>{var p;return((p=g.card.queryConfig)==null?void 0:p.pivotColumns)||[]}),l=t.useDndStore(g=>g.previewPivotColumns),{removeColumnFromGroupBy:u,removeColumnFromMetricColumns:c,removeColumnFromPivotBy:m}=t.useEditorActions();function d(g){u(g)}function h(g){c(g)}function S(g){m(g)}let f="Group By",y="Metrics",x="Stack By";return a==="table"&&(f="Rows",y="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(bs,{iconClassName:"size-[19px]"}),e.jsxs(t.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(ot,{onRemoveColumn:d,sortableType:_e,id:ge,label:f,columns:s,previewColumns:n}),e.jsx(ot,{onRemoveColumn:S,sortableType:$e,id:ye,label:x,columns:i,previewColumns:l}),e.jsx(ot,{onRemoveColumn:h,sortableType:ht,id:je,label:y,columns:r,previewColumns:o}),e.jsx(er,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Rt({children:s,column:a,id:n,sortableType:r,className:o}){const[i,l]=L.useState(!1),{removeEditorFilter:u,clearEditorFilter:c}=t.useEditorActions(),m=t.useEditorStore(h=>{var S,f;return(f=(S=h.card.queryConfig)==null?void 0:S.filters)==null?void 0:f.some(y=>y.filterColumnName===a.name)});function d(h){u(h)}return e.jsx(Ts,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),m&&e.jsx("button",{onClick:()=>c(a),children:e.jsx(t.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>d(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function sr({column:s,sortableType:a}){const n=t.useDashboardStore(T=>T.themeStyle),r=t.useEditorStore(T=>{var E,j;return(j=(E=T.card)==null?void 0:E.queryConfig)==null?void 0:j.filters}),o=t.useEditorStore(T=>{var E,j;return(j=(E=T.card.queryConfig)==null?void 0:E.filterColumns)==null?void 0:j.find(b=>b.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:l,selectedTableName:u}=t.useEditorAside(),c=L.useMemo(()=>{var T;return(T=r==null?void 0:r.find(E=>E.filterColumnName===s.name))==null?void 0:T.filterValue},[r,s.name]),m=L.useMemo(()=>Array.isArray(c)?c.map(T=>({id:T,value:T})):[],[c]),{updateEditorFilterValue:d}=t.useEditorActions(),h={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:S,isLoading:f,isFetching:y,isError:x}=t.useFilterQuery(h),g=L.useMemo(()=>{var E;return h.column?(E=S==null?void 0:S.records)==null?void 0:E.map(j=>{let b=h.column.split(".").slice(-1)[0].replace(/"/g,"");return j[b]===void 0&&(b=b.toLowerCase()),{id:j[b],value:j[b]}}):[]},[S,h.column]);function p(T){const E=T.map(j=>j.id);d(s.name,E)}function C(){return f||y?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(nr,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:g,onChange:p,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Rt,{className:"w-60",id:s.id,sortableType:a,column:s,children:C()})}function nr({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,l;return(l=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:l.find(u=>u.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function ar({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:l}=t.useEditorAside(),u={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:c,isFetching:m,isError:d,data:h}=t.useFilterQuery(u),S=h==null?void 0:h.records,{dateRange:f,setDateRange:y,initialDateRange:x}=t.useDateRangeFromRecords(S),{updateEditorFilterValue:g}=t.useEditorActions();function p(E){var b,v;const j={gte:(b=E==null?void 0:E.from)==null?void 0:b.toISOString(),lte:(v=E==null?void 0:E.to)==null?void 0:v.toISOString()};g(s.name,j)}function C(){g(s.name,null,!0),y(x)}function T(){return c||m?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):d?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):S?e.jsx(t.DateRangePopover,{title:u.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:y,onApply:p,onClear:C}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Rt,{className:"w-72",id:s.id,sortableType:a,column:s,children:T()})}function rr({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var y,x;const{setNodeRef:i,isOver:l,over:u}=t.useDroppable({id:s}),c=t.useDndStore(g=>g.activeId),m={},d=l||((x=(y=u==null?void 0:u.data)==null?void 0:y.current)==null?void 0:x.type)===o;function h(){if(!f||f.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function S(g){const p=t.isDateDataType(g.type);return g.id===ds.id?e.jsx(Rt,{id:g.id,sortableType:o,column:g,children:e.jsx(or,{})},g.id):p?e.jsx(ar,{droppableId:s,sortableType:o,column:g},g.id):e.jsx(sr,{droppableId:s,sortableType:o,column:g},g.id)}const f=c?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(g=>g.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",d&&"border border-muted-foreground/20"),ref:i,style:m,children:[e.jsx(t.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(g=>S(g))})]})})}function or(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function ir(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(rr,{onRemoveColumn:r,sortableType:pt,id:xt,label:"Filters",columns:s,previewColumns:a})})}function lr(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(In,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(hs,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function cr(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(u=>u.isShowingVisual),r=t.useEditorStore(u=>u.showAIDialog),o=t.useEditorStore(u=>u.isDevMode);L.useEffect(()=>{var u,c,m,d;r?((u=s.current)==null||u.resize(0),(c=a.current)==null||c.resize(0)):((m=s.current)==null||m.resize(25),(d=a.current)==null||d.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(ia,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Ha,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Pe,{})})]}):e.jsx(Pe,{})})]})}function l(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(tr,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(lr,{}),e.jsx(ir,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Pe,{})})]})})]}):e.jsx(Pe,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():l()})}function dr(s,a){const[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:l}=t.useSemaphorContext(),u=t.useEditorStore($=>{var Q;return(Q=$==null?void 0:$.card)==null?void 0:Q.sql}),c=t.useEditorStore($=>$.isDevMode),m=t.useEditorStore($=>{var Q;return(Q=$==null?void 0:$.card)==null?void 0:Q.python}),{setCardPython:d,setCardSql:h,setRunSql:S,switchCardType:f,setQueryConfig:y}=t.useEditorActions(),x=t.useEditorStore($=>$.currentAssitantScope)||[],g=t.useEditorStore($=>$.userInputForAI),p=t.useEditorStore($=>$.triggerAIRun),C=t.useEditorStore($=>$.card),T=t.useEditorStore($=>$.selectedDatabaseName),E=t.useEditorStore($=>$.selectedTableName),j=t.useEditorStore($=>$.selectedConnectionId),b=t.useEditorStore($=>$.selectedSchemaName),v=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:w,refetch:I,data:D}=t.useDashboardCardQuery(C),{setTriggerAIRun:N,setCurrentAssitantScope:F,setCardConfig:O}=t.useEditorActions(),{selectedDatamodelName:A,connectionType:k,selectedDatamodelId:M}=t.useEditorAside(),{messages:B,setMessages:z,reload:P,error:R,append:K,input:J,setInput:_,status:U,handleInputChange:q,handleSubmit:V,stop:G}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${l==null?void 0:l.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:c,aiContext:s},maxSteps:10,onError:$=>{console.log("on error",$)},onToolCall:H,onFinish($,Q){Y(Q.usage),r(""),Q.finishReason==="stop"&&r("")}});L.useEffect(()=>{p&&g&&(q({target:{value:g}}),setTimeout(()=>{V(),N(!1)},100))},[p,V,g,N,q]);async function H({toolCall:$}){var Q,he,we,Me;if(["createChartFromSql","createForecast"].includes($.toolName)){const W=$.args.sql,se=$.args.python,ne=$.args.chartType;return f(ne),h(W),d(se),S(!0),{status:"success",message:"Let the user know that chart is created"}}else if($.toolName==="getTableColumns")r("Getting table columns...");else{if($.toolName==="getUserSql")return u?{status:"success",sql:u,python:m||""}:{status:"error",message:"No SQL found"};if($.toolName==="getCurrentTableScope")return r("Getting table scope..."),pe(),{status:"success",tables:x};if($.toolName==="generateQueryConfig"){r("Generating query config...");const W=$.args.chartType,se=$.args.queryConfig;$.args.cardConfig,f(W),O(se),h(void 0),d(void 0);const ne=await I();return(Q=ne==null?void 0:ne.data)!=null&&Q.error?{status:"error",queryConfig:se,message:(he=ne==null?void 0:ne.data)==null?void 0:he.error.message}:(we=ne==null?void 0:ne.data)!=null&&we.records?{status:"success",queryConfig:se,message:"The data has been visualized"}:{status:"success",queryConfig:se,message:"The data has been visualized",records:(Me=ne==null?void 0:ne.data)==null?void 0:Me.records}}else r("Analyzing...")}}function Y($){i(Q=>Q?{promptTokens:Q.promptTokens+$.promptTokens,completionTokens:Q.completionTokens+$.completionTokens,totalTokens:Q.totalTokens+$.totalTokens}:$)}function Z($){const Q=t.removeFromScopeArray(x,$);ae(Q)}function ae($){const Q=t.sanitizeAIScope($);F(Q),z(he=>[...he,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}])}function Ne(){const $={databaseName:T||"",schemaName:b||"",tableName:E||"",datamodelId:M||"",datamodelName:t.resolveDatamodelName(A),connectionId:j||"",connectionType:k||""},Q=t.dedup([...x,$]);ae(Q)}function pe(){const $={databaseName:T||"",schemaName:b||"",tableName:E||"",datamodelName:t.resolveDatamodelName(A),connectionId:j||"",connectionType:k||"",datamodelId:M||""};if(!t.isInAiScopeArray([...v||[],...x],$)||x.length===0){const he=t.dedup([...v||[],...x,$]).filter(we=>we.connectionId===$.connectionId);ae(he)}}const Ce=!["ready","error"].includes(U),Se=t.getErrorMessage(R);return{messages:B,setMessages:z,reload:P,append:K,input:J,setInput:_,isLoading:Ce,handleSetAIScope:pe,handleAddCurrentTableToScope:Ne,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:F,handleInputChange:q,handleSubmit:V,stop:G,chatStatus:U,toolStatus:n,llmUsage:o,onFinish:a,errorMessage:Se}}const ur=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Kt(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[l,u]=L.useState(!1),[c,m]=L.useState(!1),[d,h]=L.useState({selectedEntities:[]}),S=t.useDashboardStore(G=>G.dashboard.aiContext),f=t.useEditorStore(G=>G.card.dataSource),y=t.useEditorStore(G=>G.actions.setCardSql),x=t.useEditorStore(G=>G.actions.setRunSql),g=t.useEditorStore(G=>G.showAIDialog),p=t.useDashboardStore(G=>G.handleOpenAssistantProfile),{setShowAIDialog:C,setCardPython:T}=t.useEditorActions(),{setDataSource:E}=t.useEditorActions(),{assistantProfile:j}=t.useAssistantProfile(),{messages:b,setMessages:v,reload:w,append:I,input:D,setInput:N,isLoading:F,handleInputChange:O,handleSubmit:A,stop:k,chatStatus:M,llmUsage:B,errorMessage:z}=dr(d);t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:b}),L.useEffect(()=>{var G;g&&((G=a.current)==null||G.focus(),h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[g,f]);function P(G,H){H==="sql"?(y(G),x(!0)):H==="python"&&(T(G),x(!0))}function R(){var G;(G=S==null?void 0:S.selectedEntities)==null||G[0],m(!0)}function K(){d.selectedEntities.length===0&&h({selectedEntities:(S==null?void 0:S.selectedEntities)||[]})}function J(G){K();const H={role:"user",content:G.title+" "+G.subtitle};I(H)}function _(G){K(),I({role:"user",content:G})}function U(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const V=(D==null?void 0:D.length)===0&&(b==null?void 0:b.filter(G=>G.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[q(),p&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:p,children:(j==null?void 0:j.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[U(),e.jsx(t.IconButton,{tooltip:"Add Context",className:"h-7 p-2",onClick:R,children:e.jsx(t.Settings,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2",tooltip:"New Chat",onClick:()=>{v([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{C(!1)},children:e.jsx(t.PanelRight,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(t.PrintMessages,{messages:b,showTools:o,handleRun:P,showSystemMessage:l}),e.jsx(t.ChatStatus,{messages:b,chatStatus:M,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[V&&!j&&e.jsx(t.Placeholders,{onClick:J,placeholders:ur}),e.jsx("div",{children:V&&j&&e.jsx(t.SeedQuestions,{seedQuestions:j.seedQuestions||[],handleSeedQuestionClick:_})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:N,stop:k,input:D,localAiContext:d,setLocalAiContext:h,handleInputChange:O,handleSubmit:G=>{K(),A(G)},isLoading:F,onFocus:()=>{}}),B&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",B.promptTokens," prompt tokens,"," ",B.completionTokens," completion tokens,"," ",B.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:c,onOpenChange:m,dataSource:f||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function mr(s){return s.flatMap(a=>a.columns.map(n=>({id:`${a.entityId}-${n.name}`,name:n.name,dataType:n.dataType,qualifiedEntityName:a.qualifiedEntityName,label:n.label||t.toTitleCase(n.name),description:n.description,entityId:a.entityId,entityName:a.entityName,entityType:a.entityType})))}function ft(s){if(s.type==="table"||s.type==="view"){if(s.database&&s.schema)return`${s.database}.${s.schema}.${s.name}`;if(s.database)return`${s.database}.${s.name}`}return s.name}function ze(s){var x;const a=t.useDashboardStore(g=>g.authToken)||s,{hasSchemaSupport:n}=t.useSelectedConnection(s),r=t.useEditorStore(g=>{var p;return(p=g.card.dataSource)==null?void 0:p.connectionId}),o=t.useEditorStore(g=>{var p,C;return(C=(p=g.card.dataSource)==null?void 0:p.selectedEntities)==null?void 0:C.filter(T=>T.type==="model")})||[],i=t.useEditorStore(g=>{var p,C;return(C=(p=g.card.dataSource)==null?void 0:p.selectedEntities)==null?void 0:C.filter(T=>T.type==="table"||T.type==="view")})||[],l=t.useEditorStore(g=>{var p,C;return(C=(p=g.card.dataSource)==null?void 0:p.selectedEntities)==null?void 0:C.filter(T=>T.type==="dataset")})||[];function u(g){return g.type==="dataset"?!!r&&!!g.domainId&&!!g.name:g.type==="model"?!!r&&!!g.id:g.type==="table"||g.type==="view"?n?!!r&&!!g.name&&!!g.database&&!!g.schema:!!r&&!!g.name&&!!g.database:!1}const c=[...o,...i,...l],m=Ps({queries:c.map(g=>{let p={};return g.type==="model"?p={connection_id:r,datamodel_id:g.id,database_name:"",schema_name:"",table_name:"",domain_id:g.domainId,dataset_name:g.name}:g.type==="dataset"?p={connection_id:g.connectionId,domain_id:g.domainId,dataset_name:g.name}:p={connection_id:r,datamodel_id:"",database_name:g.database,schema_name:g.schema,table_name:g.name},{queryKey:["columns",r,g],queryFn:()=>t.getRequest("https://semaphor.cloud/api/v1/columns",(a==null?void 0:a.accessToken)||"",p),enabled:!!r&&u(g)}})}),d=m.some(g=>g.isPending),h=m.some(g=>g.isError),S=(x=m.find(g=>g.isError))==null?void 0:x.error,f=m.map((g,p)=>{var E;const C=c[p],T=ft(C);return{entityId:C.id||C.name,entityType:C.type,entityName:C.name,label:C.label,description:C.description,qualifiedEntityName:T,columns:(E=g.data)==null?void 0:E.columns.map(j=>({id:`${C.name}-${j.column_name}`,name:j.column_name,dataType:j.data_type,label:j.label||t.toLabel(j.column_name),description:j.description||"",qualifiedEntityName:T,entityId:C.id||C.id||C.name,entityName:C.name,entityType:C.type}))}}).filter(g=>{var p;return((p=g==null?void 0:g.columns)==null?void 0:p.length)>0})||[],y=mr(f);return{columnGroups:f,columns:y,isLoading:d,hasError:h,error:S,refetch:()=>{m.forEach(g=>g.refetch())}}}function hr({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:l}=t.useSortable({id:s.id}),[u,c]=L.useState(!1),m={transform:t.CSS.Transform.toString(o),transition:i},d=t.getDataType(s.dataType),S=(f=>{const y=(f||"").toLowerCase();switch(t.getDataType(y)){case"number":return St;case"date":return t.Calendar;case"boolean":return as;case"json":return rn;case"geo":return kn;default:return rs}})(s.dataType);return e.jsxs("div",{ref:r,style:m,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${l?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>c(!u),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(S,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",d==="string"?"text-blue-500":"",d==="number"?"text-green-500":"",d==="date"?"text-purple-500":"",d==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm dark:text-muted-foreground ${u?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:t.cn("font-medium",{"text-blue-500":d==="string","text-green-500":d==="number","text-purple-500":d==="date","text-orange-500":d==="boolean"}),children:s.label||s.name}),e.jsx("p",{className:t.cn("pr-0.5 text-xs font-normal italic text-gray-500"),children:s.dataType})]}),s.description&&e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:s.description}),e.jsx("div",{className:"mt-2 text-xs italic text-muted-foreground",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name})]})})]})}),e.jsx("button",{onClick:f=>{f.stopPropagation(),c(!u)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:u?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),u&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function xr({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(hr,{field:o},o.id))})})]})}function pr(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all"),l=t.useEditorStore(E=>E.card.dataSource),{columns:u=[],columnGroups:c=[],isLoading:m,error:d}=ze(),h=u.filter(E=>E.name.toLowerCase().includes(s.toLowerCase())||E.dataType.toLowerCase().includes(s.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),S=E=>E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency"?"metrics":"dimensions",y=(o==="all"?h:h.filter(E=>S(E)===o)).reduce((E,j)=>{const b=j.qualifiedEntityName||"Other Fields";return E[b]||(E[b]={label:t.toLabel(j.entityName),fields:[]}),E[b].fields.push(j),E},{});L.useEffect(()=>{const E=Object.keys(y);r(new Set(E))},[Object.keys(y).join(",")]);const x=E=>{const j=new Set(n);j.has(E)?j.delete(E):j.add(E),r(j)},g=h.filter(E=>S(E)==="dimensions").length,p=h.filter(E=>S(E)==="metrics").length,C=h.filter(E=>S(E)==="calculated").length,T=h.length>0;return m?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(ue,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(t.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:E=>a(E.target.value)})}),T&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:E=>i(E),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:h.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(jt,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(en,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]})]})})]}),e.jsxs(t.CustomScrollArea,{className:"py-2",children:[e.jsxs("div",{className:"space-y-2",children:[Object.entries(y).map(([E,j])=>{const b=c.find(v=>v.entityName===E)||{entityName:E,label:j.label};return e.jsx(xr,{entityGroup:b,fields:j.fields,isOpen:n.has(E),onToggle:()=>x(E)},E)}),Object.keys(y).length===0&&u.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(y).length===0&&u.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function fr(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(pr,{})," "]})}function gr({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),l=()=>{const b=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:b,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,v]}),i(new Set([...o,v.id]))},u=b=>{r({...n,joins:n.joins.filter(v=>v.id!==b)}),i(new Set([...o].filter(v=>v!==b)))},c=(b,v)=>{var N,F;const w=n.joins.find(O=>O.id===b);if(!w)return;const I={...w,...v},D=n.joins.map(O=>O.id===b?I:O);if((N=I.source)!=null&&N.name&&((F=I.target)!=null&&F.name)&&I.joinKeyGroups[0].keys.length===0){const O=a.find(B=>{var z;return B.name===((z=I.source)==null?void 0:z.name)}),A=a.find(B=>{var z;return B.name===((z=I.target)==null?void 0:z.name)}),k={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},operator:"="},M=[...I.joinKeyGroups];M[0]={...M[0],keys:[k]},I.joinKeyGroups=M,D[D.findIndex(B=>B.id===b)]=I}r({...n,joins:D})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:l,removeJoin:u,updateJoin:c,moveJoinUp:b=>{const v=n.joins.findIndex(w=>w.id===b);if(v>0){const w=[...n.joins],I={...w[v]},D={...w[v-1]};w[v]=D,w[v-1]=I,w.forEach((F,O)=>{F.sequence=O+1});const N={...n,joins:w};r(N)}},moveJoinDown:b=>{const v=n.joins.findIndex(w=>w.id===b);if(v<n.joins.length-1){const w=[...n.joins],I={...w[v]},D={...w[v+1]};w[v]=D,w[v+1]=I,w.forEach((F,O)=>{F.sequence=O+1});const N={...n,joins:w};r(N)}},toggleJoinExpansion:b=>{const v=new Set(o);v.has(b)?v.delete(b):v.add(b),i(v)},getAvailableSourceEntities:b=>{if(n.joins.length===0)return a;const v=n.joins.findIndex(I=>I.id===b);if(v===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,v).forEach(I=>{w.add(I.source.name),w.add(I.target.name)}),a.filter(I=>w.has(I.name))},getAvailableTargetEntities:b=>a.filter(v=>v.name!==b),addJoinKeyGroup:b=>{const v=n.joins.find(I=>I.id===b);if(!v)return;const w=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];c(b,{joinKeyGroups:w})},updateGroupOperator:(b,v,w)=>{const I=n.joins.find(N=>N.id===b);if(!I)return;const D=[...I.joinKeyGroups];D[v]={...D[v],operator:w},c(b,{joinKeyGroups:D})},removeJoinKeyGroup:(b,v)=>{const w=n.joins.find(D=>D.id===b);if(!w)return;const I=[...w.joinKeyGroups];I.splice(v,1),c(b,{joinKeyGroups:I})},addJoinKey:(b,v)=>{const w=n.joins.find(O=>O.id===b);if(!w)return;const I=a.find(O=>O.name===w.source.name),D=a.find(O=>O.name===w.target.name),N=[...w.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="};N[v]={...N[v],keys:[...N[v].keys,F]},c(b,{joinKeyGroups:N})},updateJoinKey:(b,v,w,I,D)=>{const N=n.joins.find(M=>M.id===b);if(!N)return;const F=a.find(M=>M.name===N.source.name),O=a.find(M=>M.name===N.target.name),A=[...N.joinKeyGroups],k=A[v].keys[w];I==="sourceColumnName"&&F?A[v].keys[w]={...k,source:{...k.source,name:D}}:I==="targetColumnName"&&O?A[v].keys[w]={...k,target:{...k.target,name:D}}:I==="operator"&&(A[v].keys[w]={...k,operator:D}),c(b,{joinKeyGroups:A})},removeJoinKey:(b,v,w)=>{const I=n.joins.find(N=>N.id===b);if(!I)return;const D=[...I.joinKeyGroups];D[v].keys.splice(w,1),c(b,{joinKeyGroups:D})},generateSQLPreview:()=>{const b=[...n.joins].sort((I,D)=>I.sequence-D.sequence),v=n.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
|
|
400
|
-
FROM ${v.name}`;return b.forEach(I=>{const D=a.find(O=>O.name===I.target.name);if(!D)return;const N=I.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const A=O.keys.filter(k=>{var M,B,z,
|
|
398
|
+
`;C(R)}function B(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(oa,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(Ct,{className:"size-3.5 text-muted-foreground"})})]})}function z(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(aa,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(ra,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:w||I,onClick:()=>{A()},className:"h-8 shrink-0",size:"sm",children:[w||I?e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(ms,{sql:v==null?void 0:v.sql,error:k,onClick:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:R=>n(R),className:"",size:"sm",children:e.jsx(na,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:l,onClick:()=>{T(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:l?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[z(),B()]}),V()]})}function la({data:s}){var l;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(u=>({accessorKey:u,header:({column:c})=>{const m=c.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>c.toggleSorting(c.getIsSorted()==="asc"),children:[u,m==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):m==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(u=>e.jsx(t.TableRow,{className:"",children:u.headers.map(c=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:c.isPlaceholder?null:t.flexRender(c.column.columnDef.header,c.getContext())},c.id))},u.id))}),e.jsx(t.TableBody,{children:(l=i.getRowModel().rows)!=null&&l.length?i.getRowModel().rows.map(u=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":u.getIsSelected()&&"selected",children:u.getVisibleCells().map(c=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(c.column.columnDef.cell,c.getContext())},c.id))},u.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function ca({card:s}){var C,T,E,j,b,v,w,I,D,N,F;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),l=t.getTokenParams(i==null?void 0:i.accessToken),u=t.useDashboardStore(O=>O.themeStyle),c={colors:((T=(C=u==null?void 0:u.chart)==null?void 0:C.dataset)==null?void 0:T.backgroundColor)||[]};(E=s.customCardPreferences)!=null&&E.inputData;const{getCard:m}=t.useCustomVisual(((j=s.customCardPreferences)==null?void 0:j.url)||""),d=((b=s.customCardPreferences)==null?void 0:b.visualType)||"single",h=t.useEditorStore(O=>O.frame),{setCustomCardPreferences:S}=t.useEditorActions(),{data:f}=t.useDashboardCardQuery(s),y=L.useCallback((O,A)=>{o(k=>({...k,[O]:A}))},[]);if(!((v=s.customCardPreferences)!=null&&v.componentName))return null;const x=m((w=s.customCardPreferences)==null?void 0:w.componentName);function g(O){n(O)}const p=Object.keys(((I=s.customCardPreferences)==null?void 0:I.dataInputCardIds)||{}).map(O=>{var M,B,z;const A=(B=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:B[O].cardId,k=(z=h==null?void 0:h.cards)==null?void 0:z.find(V=>V.id===A);return k||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&d==="single"&&e.jsx(x,{params:l,theme:c,settings:(D=s.customCardPreferences)==null?void 0:D.settings,onDataChange:y,data:(f==null?void 0:f.records)||[]}),x&&d==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((N=s.customCardPreferences)==null?void 0:N.dataInputCardIds)||{}).map(O=>{var M,B,z;const A=(B=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:B[O].cardId,k=(z=h==null?void 0:h.cards)==null?void 0:z.find(V=>V.id===A);if(k)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:g,onDataChange:y,dataInputIndex:O,card:k},k.id+O)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:c,onDataChange:y,settings:p.map(O=>{var A;return(A=O==null?void 0:O.customCardPreferences)==null?void 0:A.settings}),data:p.map(O=>O!=null&&O.id?r==null?void 0:r[O.id]:[])})})]})]},(F=s.customCardPreferences)==null?void 0:F.componentName)})}function fs({className:s,...a}){var g;const n=t.useEditorStore(p=>p.card),r=((g=n.customCardPreferences)==null?void 0:g.showCardHeader)??!0,o=t.useEditorStore(p=>p.frame),i=t.useDashboardStore(p=>p.dashboard.filters);t.useEditorStore(p=>p.actions.setRunSql);const{updateFilter:l}=t.useDashboardActions(),u=i==null?void 0:i.find(p=>p.id===o.filterId),{data:c,isLoading:m,isFetching:d}=t.useDashboardCardQuery(n),{setCard:h}=t.useEditorActions(),{data:S}=t.useTopoJson(n),f=L.useMemo(()=>!n.id||!(c!=null&&c.records)?null:t.createChartConfig({card:n,data:c==null?void 0:c.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:S}),[n.id,c==null?void 0:c.records,n.type,n.queryConfig,n.customCfg,n.preferences,S]);function y(p){return e.jsx(ca,{card:p})}function x(){if(c!=null&&c.records&&(c==null?void 0:c.records.length)===0&&!m&&!d)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return y(n);if(!["table","custom"].includes(n.type)&&f)return e.jsx(e.Fragment,{children:m||d?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:f})});if(n.type==="table"&&(c!=null&&c.records)&&(c==null?void 0:c.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:n,data:c==null?void 0:c.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:p=>h({...n,title:p}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:p=>h({...n,description:p}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:u.title||u.column,onSave:p=>l({...u,title:p}),children:e.jsx(t.Label,{children:u.title})}),e.jsx(t.FilterComponent,{filter:u})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:x()})]})}const at=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:a,onChange:n}),da=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),ua=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(at,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(at,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(at,{language:"javascript",value:s,onChange:o})})]}),ma=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function ha(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[l,u]=L.useState(""),[c,m]=L.useState(""),d=t.useEditorStore(j=>j.card),h=t.useEditorStore(j=>j.card.customCfg),S=h?JSON.stringify(h,null,2):"",{data:f}=t.useDashboardCardQuery(d),{data:y}=t.useTopoJson(d),{setCardCustomCfg:x,setCustomVisualCode:g}=t.useEditorActions(),p=j=>{var b,v;return JSON.stringify({...j,data:{...j.data,datasets:(v=(b=j.data)==null?void 0:b.datasets)==null?void 0:v.map(w=>({...w,data:[]}))}},null,2)},C=()=>{var b,v;if(!((b=f==null?void 0:f.records)!=null&&b.length))return;const j=t.createChartConfig({card:d,data:f.records,cardType:d.type,queryConfig:d.queryConfig,preferences:d.preferences,topoJson:y});if(j){r(p(j)),u(((v=d.preferences)==null?void 0:v.customVisualCode)||"");const w=t.merge(j,h);i(p(w))}},T=()=>{try{if(l&&g(l),o){const j=JSON.parse(o),b=t.getObjectDiff(JSON.parse(n),j);x(b),m("")}}catch{m("Invalid JSON configuration")}},E=Object.keys(h||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:C,className:E?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(da,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(fs,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ua,{customCode:l,cardCustomCfgString:S,mergedConfig:o,onConfigChange:j=>i(j??""),onCodeChange:j=>u(j??"")})]}),e.jsx(ma,{error:c,hasCardCustomConfig:!!h,onReset:()=>{i(n),x(null)},onApply:T,onClose:()=>a(!1)})]})]})}function gs(s){const[a,n]=L.useState(null);return a}function js(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function xa({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:l}=t.useEditorActions(),{data:u}=js();function c(m,d){r(null),o({}),i(m),d&&l({type:"component",visualType:"single",url:d.url,componentName:d.name,icon:d.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var d;if(u){const S=(await Promise.all((d=u==null?void 0:u.plugins)==null?void 0:d.map(async f=>(await t.loadManifest(f.value)).visuals.map(g=>({name:g.name,icon:g.icon,url:f.value}))))).flat();n(S)}})()},[u]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((m,d)=>e.jsx(pa,{text:m.name,onClick:()=>c("custom",m),icon:m.icon},m.url+m.name+d))})]})}const pa=({text:s,icon:a,onClick:n})=>{const r=gs(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function At(s){return be({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(s)}function fa(s){return be({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(s)}function Lt(s){return be({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(s)}function Ot(s){return be({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(s)}function Ft(s){return be({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(s)}function Bt(s){return be({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(s)}function ys({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(d=>d.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(d,h){i(null),r({}),n(d),["kpi","custom","text","map"].includes(d)&&(o(!0),u(void 0)),s==null||s()}const m=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(t.IconButton,{openDelay:m,tooltip:"Table",onClick:()=>c("table"),className:"h-10 p-4",children:e.jsx(Qe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Bar Chart",onClick:()=>c("bar"),className:"h-10 p-4",children:e.jsx(Ye,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Line Chart",onClick:()=>c("line"),className:"h-10 p-4",children:e.jsx(Ke,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Stacked Bar Chart",onClick:()=>c("stackedBar"),className:"h-10 p-4",children:e.jsx(gt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Stacked Line Chart",onClick:()=>c("stackedLine"),className:"h-10 p-4",children:e.jsx(Ft,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Scatter Chart",onClick:()=>c("scatter"),className:"h-10 p-4",children:e.jsx(vt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Bubble Chart",onClick:()=>c("bubble"),className:"h-10 p-4",children:e.jsx(Lt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Pie Chart",onClick:()=>c("pie"),className:"h-10 p-4",children:e.jsx(bt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Doughnut Chart",onClick:()=>c("doughnut"),className:"h-10 p-4",children:e.jsx(Nt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Funnel Chart",onClick:()=>c("funnel"),className:"h-10 p-4",children:e.jsx(Ot,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Radar Chart",onClick:()=>c("radar"),className:"h-10 p-4",children:e.jsx(kt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Polar Area Chart",onClick:()=>c("polarArea"),className:"h-10 p-4",children:e.jsx(At,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Tornado Chart",onClick:()=>c("tornado"),className:"h-10 p-4",children:e.jsx(It,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>c("range"),className:"h-10 p-4",children:e.jsx(yt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"KPI",onClick:()=>c("kpi"),className:"h-10 p-4",children:e.jsx(Bt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Text",onClick:()=>c("text"),className:"h-10 p-4",children:e.jsx(Wt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>c("map"),className:"h-10 p-4",children:e.jsx(wt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:m,tooltip:"Custom",onClick:()=>c("custom"),className:"h-10 p-4",children:e.jsx(Et,{className:t.cn("size-5",a)})})]})}function ga({chartType:s,className:a,customIcon:n,componentName:r}){const o=gs();switch(s){case"bar":return e.jsx(Ye,{className:a});case"line":return e.jsx(Ke,{className:a});case"pie":return e.jsx(bt,{className:a});case"radar":return e.jsx(kt,{className:a});case"scatter":return e.jsx(vt,{className:a});case"bubble":return e.jsx(Lt,{className:a});case"doughnut":return e.jsx(Nt,{className:a});case"stackedBar":return e.jsx(gt,{className:a});case"stackedLine":return e.jsx(Ft,{className:a});case"polarArea":return e.jsx(At,{className:a});case"funnel":return e.jsx(Ot,{className:a});case"tornado":case"pyramid":return e.jsx(It,{className:a});case"range":return e.jsx(yt,{className:a});case"kpi":return e.jsx(Bt,{className:a});case"text":return e.jsx(as,{className:a});case"map":return e.jsx(wt,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Et,{className:a});default:return e.jsx(Qe,{className:a})}}function bs({variant:s="ghost"}){var i,l;const[a,n]=L.useState(!1),r=t.useEditorStore(u=>u.card),o=r.type;return t.useDashboardStore(u=>u.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(ga,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(l=r.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:u=>u.preventDefault(),className:"w-72 p-1",children:[e.jsx(ys,{onChartTypeChange:()=>n(!1)}),e.jsx(xa,{onChartTypeChange:()=>n(!1)})]})]})}const Re="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Ut(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function ja(){var M,B,z,V,R,K;const[s,a]=L.useState(!1),n=t.useEditorStore(J=>{var _;return(_=J.card)==null?void 0:_.preferences}),r=t.useEditorStore(J=>{var _;return(_=J.card)==null?void 0:_.type}),o=t.getNumberAxis(n,{}),[i,l]=L.useState(Ut(n,r)),[u,c]=L.useState(((z=(B=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:B[o])==null?void 0:z.min)||""),[m,d]=L.useState(((K=(R=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:R[o])==null?void 0:K.max)||""),[h,S]=L.useState(u||m?"custom":"auto"),[f,y]=L.useState(""),[x,g]=L.useState(0),[p,C]=L.useState(""),[T,E]=L.useState(""),[j,b]=L.useState(""),v=t.useEditorStore(J=>J.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),I=t.useEditorStore(J=>J.card),D=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var J,_,U,q,P,$,H,Y,Z,ae,Ne,pe,Ce,Se;l(Ut(n,r)),c(((U=(_=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:_[o])==null?void 0:U.min)===0?0:""),d((($=(P=(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales)==null?void 0:P[o])==null?void 0:$.max)||""),y(((ae=(Z=(Y=(H=n==null?void 0:n.chartOptions)==null?void 0:H.scales)==null?void 0:Y[o])==null?void 0:Z.ticks)==null?void 0:ae.stepSize)||""),g(((Ne=n==null?void 0:n.numberAxisFormat)==null?void 0:Ne.decimalPlaces)||0),C(((pe=n==null?void 0:n.numberAxisFormat)==null?void 0:pe.suffix)||""),E(((Ce=n==null?void 0:n.numberAxisFormat)==null?void 0:Ce.currency)||""),b(((Se=n==null?void 0:n.numberAxisFormat)==null?void 0:Se.locale)||"")},[s,n,o,r]);function N(J,_){return _===""||/^[0-9\b]+$/.test(_)?Number(_):Number(J)}function F(){const J=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(_=>_.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(t.Select,{value:T||"none",onValueChange:_=>E(_==="none"?"":_),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),J.map(_=>e.jsx(t.SelectItem,{value:_,children:_},_))]})})]}),e.jsxs(t.Select,{value:j,onValueChange:_=>b(_),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map(_=>e.jsx(t.SelectItem,{value:_.locale,children:_.locale},_.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:x,onChange:_=>g(Number(_.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Re}`})]})]})}function O(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:D,value:i,onValueChange:J=>l(J),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:D,id:"scale-option",value:h,onValueChange:J=>S(J),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),h==="custom"&&i=="linear"&&A()]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:u,onChange:J=>c(_=>N(_,J.target.value)),className:`col-span-1 h-8 w-full ${Re}`}),e.jsx(t.Input,{value:m,onChange:J=>d(_=>N(_,J.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Re}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:f,onChange:J=>y(_=>N(_,J.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Re}`})]})]})}function k(){var q;let J={};h==="custom"&&(J={min:u,max:m,ticks:{stepSize:f}});const _={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(q=n==null?void 0:n.chartOptions)==null?void 0:q.scales,[o]:{type:i,...i==="linear"?J:{}}}},numberAxisFormat:{decimalPlaces:x,suffix:p,currency:T,locale:j}};console.log(_),v(_);const U={...I,preferences:_};w(U)}return e.jsxs(t.Popover,{onOpenChange:J=>a(J),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(dn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[F(),O(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:k,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function ya(){const s=t.useEditorStore(u=>{var c,m,d,h;return(h=(d=(m=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:m.plugins)==null?void 0:d.legend)==null?void 0:h.position}),a=t.useEditorStore(u=>{var c,m,d,h;return(h=(d=(m=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:m.plugins)==null?void 0:d.legend)==null?void 0:h.align}),n=t.useEditorStore(u=>{var c,m,d,h;return(h=(d=(m=(c=u.card.preferences)==null?void 0:c.chartOptions)==null?void 0:m.plugins)==null?void 0:d.legend)==null?void 0:h.display}),{setLegendOptions:r}=t.useEditorActions(),o=u=>{r({display:u,position:s,align:a})},i=u=>{r({display:n,position:u,align:a})},l=u=>{r({display:n,position:s,align:u})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(bn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(Ue,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Js,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(Je,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(Us,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>l("start"),children:e.jsx(qs,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>l("center"),children:e.jsx(Ps,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>l("end"),children:e.jsx(_s,{className:"size-4"})})]})]})]})]})]})})]})}function ba(){const s=t.useEditorStore(i=>{var l,u;return(u=(l=i.card.preferences)==null?void 0:l.chartOptions)==null?void 0:u.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(_t,{className:"size-4"}):e.jsx(qt,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(_t,{className:"size-4"}):e.jsx(qt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function vs(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>l.isShowingVisual),n=t.useEditorStore(l=>{var u,c;return(c=(u=l.card)==null?void 0:u.preferences)==null?void 0:c.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const l=["xy","none","x","y"],c=(l.indexOf(r)+1)%l.length;o(l[c])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(e.Fragment,{children:e.jsx(ba,{})}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ja,{}),e.jsx(ya,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(gn,{className:"size-4"}),r==="x"&&e.jsx(on,{className:"size-4"}),r==="y"&&e.jsx(Mn,{className:"size-4"}),r==="none"&&e.jsx(On,{className:"size-4"})]})]}):null}function va(){const s=t.useEditorStore(y=>y.frame),a=t.useEditorStore(y=>y.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),l=(y,x)=>{y.dataTransfer.setData("tabIndex",x.toString())},u=y=>{y.preventDefault()},c=(y,x)=>{const g=y.dataTransfer.getData("tabIndex");if(g===x.toString())return;const p=Array.from(s.cards),[C]=p.splice(parseInt(g),1);p.splice(x,0,C),n({...s,cards:p})};function m(y){const x=s.cards.filter(C=>C.id!==y),g=x[0],p={...s,cards:x,activeCardId:g.id};n(p),r(g.id),o(g)}function d(y,x){const g={...s,cards:[...s.cards,x],activeCardId:y.id};n(g),r(x.id)}function h(){const y={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};d(a,y)}function S(y){const x={connectionId:y.connectionId,lastSelectedDatabase:y.lastSelectedDatabase,lastSelectedSchema:y.lastSelectedSchema,lastSelectedTable:y.lastSelectedTable,lastSelectedDatamodelId:y.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]};d(y,x)}function f(y,x){return y.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||y.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const g=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:g}),i({...x,displayTab:g})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(un,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((y,x)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:g=>l(g,x),onDragOver:u,onDrop:g=>c(g,x),className:"",value:y.id,children:[f(s,y),e.jsx(t.Editable,{enabled:s.activeCardId===y.id,text:y.tabTitle||y.title,onSave:g=>{o({...a,tabTitle:g}),i({...a,tabTitle:g})},children:y.tabTitle||y.title},y.id),s.activeCardId===y.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>m(y.id)})]},y.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>S(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(cn,{className:"h-4 w-4"})})]})})}function Ns(){const s=t.useEditorStore(x=>x.frame),a=t.useEditorStore(x=>x.card),n=t.useEditorStore(x=>x.isSqlRunning),r=t.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:l,setIsDevMode:u,setRunSql:c}=t.useEditorActions(),{data:m,isLoading:d,isFetching:h}=t.useDashboardCardQuery(a);function S(x){const g=s.cards.find(p=>p.id===x);if(g!=null&&g.sql){r||u(!0),i(x);return}if(g!=null&&g.queryConfig){r&&u(!1),f(x),i(x);return}r||f(x),i(x)}function f(x){const g={...s,cards:s.cards.map(C=>C.id===a.id?a:C),activeCardId:x};o(g);const p=g.cards.find(C=>C.id===x);p.sql&&c(!0),l(p)}function y(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.KPICard,{card:a,data:m==null?void 0:m.records,isPending:d})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:m==null?void 0:m.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(fs,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:S,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(x=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:x.id,children:y()},x.id)),e.jsx(va,{})]})}function Ve({children:s}){var C;t.useEditorStore(T=>T.frame);const a=t.useEditorStore(T=>T.card),n=t.useEditorStore(T=>T.isDevMode),r=t.useEditorStore(T=>T.isShowingVisual),o=t.useDashboardStore(T=>T.isVisualEditing),i=t.useEditorStore(T=>T.pythonStdOut);t.useEditorStore(T=>T.actions.setRunSql);const{setFrame:l,setCard:u,setActiveTabCardId:c,runAssistant:m,setIsDevMode:d}=t.useEditorActions(),{data:h,isLoading:S,isFetching:f,error:y}=t.useDashboardCardQuery(a);function x(){const T=JSON.stringify(h==null?void 0:h.records,null,2),E=new Blob([T],{type:"application/json"}),j=URL.createObjectURL(E),b=document.createElement("a");b.href=j,b.download=`${a.title}.json`,b.click()}function g(){const E=[Object.keys(h==null?void 0:h.records.reduce((w,I)=>({...w,...I}),{})).join(","),...((h==null?void 0:h.records)||[]).map(w=>Object.values(w).join(","))].join(`
|
|
399
|
+
`),j=new Blob([E],{type:"text/csv"}),b=URL.createObjectURL(j),v=document.createElement("a");v.href=b,v.download=`${a.title}.csv`,v.click()}function p(){const T=`Can you get the documentation for ${a.type} chart?`;m(T)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(S||f)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(ue,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(bs,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:p,children:e.jsx(Ws,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(ha,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:g,children:e.jsx(fa,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:x,children:e.jsx(hn,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(h==null?void 0:h.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(vs,{})]}),n&&e.jsx(Ca,{})]}),r?e.jsx(Ns,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(Na,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(la,{data:(h==null?void 0:h.records)||[]}),(y||(h==null?void 0:h.error))&&e.jsx("span",{className:"font-mono text-xs",children:(y==null?void 0:y.message)||((C=h==null?void 0:h.error)==null?void 0:C.message)})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Na(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Ca(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Sa(){var x,g;const s=t.useEditorStore(p=>p.card.customCardPreferences),{data:a}=js(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(p=>p.card),o=t.useEditorStore(p=>p.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:l}=t.useEditorActions(),{components:u,manifest:c}=t.useCustomVisual((s==null?void 0:s.url)||""),m=(x=c==null?void 0:c.visuals)==null?void 0:x.find(p=>p.name===(s==null?void 0:s.componentName));function d(p,C){if(!s)return;const E={...(s==null?void 0:s.dataInputCardIds)||{},[p]:{cardId:C,hookRef:null}};l({...s,dataInputCardIds:E})}function h(p){var T,E;const C=(T=o==null?void 0:o.cards)==null?void 0:T.filter(j=>{var b;return((b=j==null?void 0:j.customCardPreferences)==null?void 0:b.visualType)!=="multiple"}).map(j=>({value:j.id,label:j.tabTitle||j.title}));return e.jsx("div",{className:"space-y-2",children:(E=p==null?void 0:p.dataInputs)==null?void 0:E.map((j,b)=>{var v,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:j}),e.jsx(de,{className:"col-span-6 h-8 w-full justify-between",label:"",options:C||[],value:((w=(v=s==null?void 0:s.dataInputCardIds)==null?void 0:v[b])==null?void 0:w.cardId)||"",onValueChange:I=>d(b,I)})]},b+Math.random())})})}function S(p,C,T=[],E=""){var j,b;return s?p==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((j=s==null?void 0:s.settings)==null?void 0:j[C])||E,onChange:v=>{l({...s,settings:{...s==null?void 0:s.settings,[C]:v.target.value}})}},C):p==="select"?e.jsx(de,{className:"h-8 w-full",label:"",options:T,value:((b=s==null?void 0:s.settings)==null?void 0:b[C])||E,onValueChange:v=>{l({...s,settings:{...s==null?void 0:s.settings,[C]:v}})}}):null:null}function f(p){const C=Object.entries((p==null?void 0:p.settings)||{});return e.jsx("div",{className:"space-y-3",children:C.map(([T,E])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:E.title}),S(E.ui,T,E.options,E.defaultValue)]},T))})}function y(p){s&&l({...s,visualType:p,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(de,{icon:e.jsx(Qs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:p=>l({...s||{url:"",componentName:""},url:p})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:y,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:u&&e.jsx(de,{icon:e.jsx(ln,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.filter(p=>p.type===i).map(p=>({value:p.name,label:p.name})))||[],value:s.componentName,onValueChange:p=>{console.log("changing value",p),l({...s,componentName:p})}})})]})})]}),((g=r==null?void 0:r.customCardPreferences)==null?void 0:g.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[m&&m.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(m)})]}),m&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:f(m)})})]})]})]})}function ve(){const[s,a]=L.useState([]),n=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(m=>m.actions),i=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var d;return(d=m.card.preferences)==null?void 0:d.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(m,d){var h,S;d?n!=null&&n.onClickFilter&&((h=n==null?void 0:n.onClickFilter)==null?void 0:h.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:m,expression:""}]}):o({...n,onClickFilter:[{columnIndex:m,expression:""}]}):(o({...n,onClickFilter:(S=n==null?void 0:n.onClickFilter)==null?void 0:S.filter(f=>f.columnIndex!==m)}),a(f=>{const y=[...f];return y[m]=!1,y}))}function u(m,d){var S;const h=(S=n==null?void 0:n.onClickFilter)==null?void 0:S.map(f=>f.columnIndex===m?{...f,expression:d.target.value}:f);o({...n,onClickFilter:h})}function c(m){var d,h,S,f;if(s!=null&&s[m]||(h=(d=n==null?void 0:n.onClickFilter)==null?void 0:d.find(y=>y.columnIndex===m))!=null&&h.expression)return e.jsx(t.Input,{value:(f=(S=n==null?void 0:n.onClickFilter)==null?void 0:S.find(y=>y.columnIndex===m))==null?void 0:f.expression,onChange:y=>u(m,y),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((m,d)=>{var h,S;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((h=n==null?void 0:n.onClickFilter)!=null&&h.find(f=>f.columnIndex===d)),onCheckedChange:f=>l(d,f)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((S=n==null?void 0:n.onClickFilter)==null?void 0:S.find(f=>f.columnIndex===d))&&e.jsx(t.Pencil,{onClick:()=>{a(f=>{const y=[...f];return y[d]=!f[d],y})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),c(d)]})},m)})]})}function wa({idx:s}){var u;const a=t.useEditorStore(c=>{var m;return(m=c.card)==null?void 0:m.preferences}),n=t.useEditorStore(c=>{var m;return(m=c.card.preferences)==null?void 0:m.datasetOptions}),r=t.useEditorStore(c=>c.actions.setCardPreferences),o=(u=a==null?void 0:a.chartOptions)==null?void 0:u.indexAxis,i=n==null?void 0:n.find(c=>c.idx===s);function l(c,m){(c==="end"||c==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const d={display:c!=="none",align:c,anchor:c,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:m,datalabels:d}]});else{const h={...i};h.datalabels=d;const S=n==null?void 0:n.map(f=>f.idx===m?h:f);r({...a,datasetOptions:S})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(ss,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Cn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function ka(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);o=l.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function Cs({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function Ss(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var m,d,h;return(h=(d=(m=c==null?void 0:c.card)==null?void 0:m.preferences)==null?void 0:d.chartOptions)==null?void 0:h.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:l,keys:u}=ka();return u.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(c=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:c,children:ws(c)},c))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:l.map((c,m)=>e.jsx(ks,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:c,idx:m},c))})]})]})}function ws(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function ks({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(d=>{var h;return(h=d.card)==null?void 0:h.preferences}),l=t.useEditorStore(d=>{var h,S;return(S=(h=d.card)==null?void 0:h.preferences)==null?void 0:S.datasetOptions}),u=l==null?void 0:l.find(d=>d.idx===a),{setCardPreferences:c}=t.useEditorStore(d=>d.actions);function m(d){if(!u)c({...i,datasetOptions:[...l||[],{idx:a,type:d==="area"?"line":d,fill:d==="area"?"origin":""}]});else{const h={...u};h.type=d==="area"?"line":d,h.fill=d==="area"?"origin":"";const S=l==null?void 0:l.map(f=>f.idx===a?h:f);c({...i,datasetOptions:S})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(Cs,{className:"max-w-[100px]",title:s,children:ws(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ye,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Ke,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(tn,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(wa,{idx:a})]})]})}function Es(){const s=t.useEditorStore(f=>f.selectedConnectionId),a=t.useEditorStore(f=>f.selectedDatamodelId),n=t.useEditorStore(f=>f.selectedDatabaseName),r=t.useEditorStore(f=>f.selectedSchemaName),o=t.useEditorStore(f=>f.selectedTableName),i=t.useDashboardStore(f=>f.dashboard.filters)||[],l=t.useDashboardStore(f=>f.actions.addFilter),u=t.useDashboardStore(f=>f.actions.removeFilter),{removeFilterValues:c}=t.useDashboardActions(),{modelItems:m,tableName:d,connectionType:h}=t.useEditorAside();function S(f,y="dashboard"){var v;const x=t.fmt(f.column_name),g=t.fmt(n||""),p=t.fmt(r||""),C=t.fmt(d);let T=t.getQualifiedTableName({schemaName:p,tableName:C,connectionType:h,databaseName:g}),E=`${T}.${x}`;const j=(v=m==null?void 0:m.find(w=>w.id===a))==null?void 0:v.name;a&&a!=="none"&&(E=`${t.DATAMODEL_NAMESPCACE}.${j}.${x}`,T=`${t.DATAMODEL_NAMESPCACE}.${j}`);const b=i==null?void 0:i.find(w=>w.column===E&&w.table===C&&(w.database===g||w.database===n));if(b)c(b.id),u(b.id);else{const w=t.v4();return d==="api"&&s?(l({location:y,id:w,column:E,title:f.column_name,dataType:f.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(f.data_type,T,x)}),w):(l({id:w,location:y,column:E,title:f.column_name,dataType:f.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(f.data_type,T,x)}),w)}}return{assignFilter:S}}function Te(){const s=t.useDashboardStore(u=>u.dashboard.filters),a=t.useEditorStore(u=>u.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=Es();function i(u){const c=o(u,"frame");n({...a,filterId:c})}const l=s==null?void 0:s.find(u=>u.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(Ea,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function Ea({columns:s,onSelect:a}){var l;const[n,r]=ie.useState(!1),[o,i]=ie.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(l=s.find(u=>u.column_name===o))==null?void 0:l.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(u=>e.jsxs(t.CommandItem,{value:u.column_name,onSelect:c=>{const m=c===o?"":c;i(m),r(!1),m&&a(u)},children:[u.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===u.column_name?"opacity-100":"opacity-0")})]},u.column_name))})]})]})})]})}function Ia({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Ss,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}function We(){const s=t.useEditorStore(u=>u.card.type),a=t.useEditorStore(u=>u.isDevMode),n=t.useEditorStore(u=>u.card.preferences),{setCardPreferences:r}=t.useEditorStore(u=>u.actions);function o(u){var d;const c={datalabels:{display:u!=="none",align:u,anchor:u,clamp:!0}},m={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins,...c}}};r(m)}function i(){var u,c,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((m=(c=(u=n==null?void 0:n.chartOptions)==null?void 0:u.plugins)==null?void 0:c.datalabels)==null?void 0:m.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function l(){var u,c,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(c=(u=n==null?void 0:n.chartOptions)==null?void 0:u.plugins)==null?void 0:c.datalabels)==null?void 0:m.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():l()})}function Da({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(We,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}const Ta={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Ma={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Aa(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:La(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(We,{}),e.jsx(ve,{}),e.jsx(Te,{})]})]})}function La(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(Ta,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Ma,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function Oa(){var c,m,d,h,S;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.actions.setCardPreferences),n=t.useEditorStore(f=>f.actions.setNumberFormat);t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.decimalPlaces});const r=t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.locale}),o=t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.currency});t.useEditorStore(f=>f.actions.setFilterOnClickField);const i=t.useEditorStore(f=>{var y,x;return(x=(y=f.card.preferences)==null?void 0:y.formatNumber)==null?void 0:x.colorRanges})||[],l=t.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((c=s==null?void 0:s.formatNumber)!=null&&c.enabled),onCheckedChange:f=>{a({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:f}})}}),e.jsx(t.Label,{children:"Format Number"})]}),((m=s==null?void 0:s.formatNumber)==null?void 0:m.enabled)===!0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:r||"none",onValueChange:f=>{var y,x,g;return n(((y=s==null?void 0:s.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=s==null?void 0:s.formatNumber)==null?void 0:x.currency)||"",f,((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),t.LOCALE_CURRENCY_PAIRS.map(f=>e.jsx(t.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:f=>{var y,x,g;console.log("currency",f),n(((y=s==null?void 0:s.formatNumber)==null?void 0:y.decimalPlaces)||0,f==="none"?"":f,((x=s==null?void 0:s.formatNumber)==null?void 0:x.locale)||"",((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(f=>e.jsx(t.SelectItem,{value:f,children:f},f))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((h=(d=s==null?void 0:s.formatNumber)==null?void 0:d.decimalPlaces)==null?void 0:h.toString())||"0",onValueChange:f=>{var y,x,g;return n(Number(f),((y=s==null?void 0:s.formatNumber)==null?void 0:y.currency)||"",((x=s==null?void 0:s.formatNumber)==null?void 0:x.locale)||"",((g=s==null?void 0:s.formatNumber)==null?void 0:g.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(f=>e.jsx(t.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((S=s==null?void 0:s.formatNumber)==null?void 0:S.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:f=>{var y,x,g;return n(((y=s==null?void 0:s.formatNumber)==null?void 0:y.decimalPlaces)||0,((x=s==null?void 0:s.formatNumber)==null?void 0:x.currency)||"",((g=s==null?void 0:s.formatNumber)==null?void 0:g.locale)||"",f.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(t.ColorFormat,{colorRanges:i,setColorRanges:l})]})]})}function Fa(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Oa,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function rt({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const Ba=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],za=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],Ra=za.map(s=>({label:s,value:s}));function Va(){var c,m,d,h,S,f,y,x,g,p,C,T,E,j,b,v,w,I;const s=t.useEditorStore(D=>D.card),a=(m=(c=s==null?void 0:s.preferences)==null?void 0:c.mapVisualOptions)==null?void 0:m.topoJsonUrl,[n,r]=L.useState(((h=(d=s==null?void 0:s.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(D=>({label:D,value:D}))||[],u=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(rt,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(rt,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(de,{className:"h-9",options:u,onValueChange:D=>{console.log("value",D),o({...s.preferences,mapVisualOptions:{topoJsonUrl:D}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:D=>{r(D.target.value)},onBlur:()=>{var D;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(D=s.preferences)==null?void 0:D.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(de,{className:"h-9",options:l,value:((f=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:f.objectKey)||"",label:"Map Object",onValueChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,objectKey:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(de,{className:"h-9",options:Ba,value:((x=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projection:D}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(de,{className:"h-9",options:Ra,value:((p=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:p.colorScale)||"",label:"Select Color Scale",onValueChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,colorScale:D}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(rt,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((T=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:T.projectionScale)||1,onChange:D=>{var N;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projectionScale:Number(D.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((b=(j=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:b[0])||0,onChange:D=>{var N,F,O,A;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[Number(D.target.value),((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((I=(w=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:I[1])||0,onChange:D=>{var N,F,O,A;o({...s.preferences,mapVisualOptions:{...(N=s.preferences)==null?void 0:N.mapVisualOptions,projectionOffset:[((A=(O=(F=s.preferences)==null?void 0:F.mapVisualOptions)==null?void 0:O.projectionOffset)==null?void 0:A[0])||0,Number(D.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(ve,{})]})}function Pa(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Pe({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(We,{}),s==="text"&&e.jsx(Pa,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}function qa(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(de,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Ss,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})]})})}function _a({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ve,{}),e.jsx(Te,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const Ga=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),$a=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Ha=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Ja(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(qa,{});case"tornado":case"pyramid":return e.jsx(Pe,{docContent:Ga,cardType:n});case"kpi":return e.jsx(Fa,{});case"line":case"bar":return e.jsx(Ia,{cardType:n});case"range":return e.jsx(Pe,{docContent:$a,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Pe,{cardType:n});case"bubble":case"scatter":return e.jsx(Da,{cardType:n});case"table":return e.jsx(_a,{cardType:n});case"text":return e.jsx(Pe,{docContent:Ha,cardType:n,suffix:"Visual"});case"map":return e.jsx(Va,{});case"custom":return e.jsx(Sa,{});default:return e.jsx(Aa,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Is({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(l=>l.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(l=>l.value===a.granularity)||n[0]);function i(l){r(l)}return e.jsx(de,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:l=>i(l),label:s,showPlaceholderLabel:!1})}const Ua=[{label:"Sum",value:"SUM",logo:e.jsx(ts,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(St,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(pn,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Hs,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(Je,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(Ue,{className:"size-3.5"})}];function Ya({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ua;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:Le(s.name,o)};a(s.id,i)}return e.jsx(Is,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Ka=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Qa({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:De(s.name,r)};a(s.id,o)}return e.jsx(Is,{column:s,functions:Ka,onFunctionChange:r=>n(r),label:"Granularity"})}function Wa({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let u=[];(n===ge||n===je||n===ye)&&(u=r);const c=u==null?void 0:u.filter(m=>m.column_name!==s.name);return c==null?void 0:c.map(m=>({id:m.column_name,value:m.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function l(u){const c=r==null?void 0:r.find(m=>{var d;return m.column_name===((d=u[0])==null?void 0:d.id)});c&&a(c)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:l,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:s.name})}function Ds({column:s}){const a=t.useEditorStore(c=>c.card.type),n=t.useEditorStore(c=>{var m,d;return(d=(m=c.card)==null?void 0:m.config)==null?void 0:d.metricColumns}),r=(n==null?void 0:n.map(c=>c.label))||[],o=r==null?void 0:r.find(c=>c===s.label||c===s.name),i=o?r.indexOf(o):-1;function l(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(ks,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function u(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(We,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&u()]})}function Xa({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:l,updateMetricColumnOld:u,updatePivotByColumnOld:c}=t.useEditorActions(),{attributes:m,listeners:d,setNodeRef:h,transform:S,transition:f,isDragging:y}=t.useSortable({id:s.id,data:{type:a}}),x=S?{opacity:y?.5:void 0,transform:t.CSS.Translate.toString(S),transition:f}:void 0,g=t.isTextDataType(s.type);function p(b){const v=t.isNumberDataType(b.data_type),w=t.isTextDataType(b.data_type),I=t.isDateDataType(b.data_type),D=v?"number":w?"string":I?"date":"string";if(r===ge){if(w){const N={id:s.id,name:b.column_name,type:D,role:"groupby"};l(s.id,N)}if(I){const N={id:s.id,name:b.column_name,type:D,role:"groupby",label:De(b.column_name,"month"),granularity:"month"};l(s.id,N)}}if(r===ye){if(w){const N={id:s.id,name:b.column_name,type:D,role:"groupby"};c(s.id,N)}if(I){const N={id:s.id,name:b.column_name,type:D,label:De(b.column_name,"month"),granularity:"month",role:"groupby"};c(s.id,N)}}if(r===je){const N={id:s.id,name:b.column_name,type:D,role:"metric",label:Le(b.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};u(s.id,N)}}function C(){if(r===je)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Ds,{column:s})})}function T(){const b=t.isDateDataType(s.type);if(r===je)return e.jsx(Ya,{column:s});if((r===ge||r===ye)&&b)return e.jsx(Qa,{column:s})}function E(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===ge||r===ye)&&g}),children:e.jsx(Wa,{col:s,onChange:p,droppableId:r})})}function j(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(Ln,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Zt,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...d,...m,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[j(),T(),E()]}),o&&C()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function ot({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var x,g;const{setNodeRef:l,isOver:u,over:c}=t.useDroppable({id:s}),m=t.useDndStore(p=>p.activeId),d=t.useEditorStore(p=>{var C;return(C=p.card)==null?void 0:C.type}),h=u||((g=(x=c==null?void 0:c.data)==null?void 0:x.current)==null?void 0:g.type)===o,S=m?r:n,f=o===_e?"Rows":o===Ge?"Pivot Columns":"Columns";function y(){if(!S||S.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(p=>p.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:l,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),d!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:f})]}),y(),e.jsx("div",{className:"space-y-2",children:S==null?void 0:S.map(p=>p.id===cs.id?e.jsx(Za,{},p.id):e.jsx(Xa,{droppableId:s,type:o,column:p,onRemoveColumn:i},p.id))})]})})}function Za(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Ts({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:l,transition:u,isDragging:c}=t.useSortable({id:a,data:{type:n}}),m=l?{opacity:c?.5:void 0,transform:t.CSS.Translate.toString(l),transition:u}:void 0;return e.jsx("div",{...o,...r,ref:i,style:m,children:s})}function er(){const s=t.useEditorStore(p=>{var C;return(C=p.card.queryConfig)==null?void 0:C.orderBy})||[],a=t.useEditorStore(p=>{var C;return(C=p.card.queryConfig)==null?void 0:C.groupByColumns})||[],n=t.useEditorStore(p=>{var C;return(C=p.card.queryConfig)==null?void 0:C.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),l=[...a,...n];if(l.length===0)return e.jsx(e.Fragment,{});const u=e.jsx(Ks,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),c=e.jsx($s,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(Ys,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(Gs,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=l==null?void 0:l.filter(p=>!s.some(C=>C.columnId===p.id)).map(p=>({id:p.id,value:p.label||p.name}));function S(p,C){const T=f(p);return T?T.role==="metric"?C==="asc"?m:d:C==="asc"?u:c:null}function f(p){return l.find(C=>C.id===p)}function y(p){const C=s.find(T=>T.columnId===p);if(C){const T={...C,direction:C.direction==="asc"?"desc":"asc"};i(T)}}const x=p=>{r({columnId:p.id,direction:"asc"})};function g(p){const C=s.find(T=>T.columnId===p);C&&o(C)}return e.jsx(t.SortableContext,{items:s.map(p=>Ae(p.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:p=>x(p[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(p=>{var C,T;return e.jsx(Ts,{id:Ae(p.columnId),type:Mt,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(Cs,{className:"w-[175px] text-sm",children:((C=f(p.columnId))==null?void 0:C.label)||((T=f(p.columnId))==null?void 0:T.name)})]}),e.jsx("button",{title:p.direction==="asc"?"Ascending":"Descending",onClick:()=>y(p.columnId),className:"rounded-sm p-0",children:S(p.columnId,p.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>g(p.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},p.columnId)},Ae(p.columnId))})]})})}function tr(){const s=t.useEditorStore(g=>{var p;return((p=g.card.queryConfig)==null?void 0:p.groupByColumns)||[]}),a=t.useEditorStore(g=>g.card.type),n=t.useDndStore(g=>g.previewGroupByColumns),r=t.useEditorStore(g=>{var p;return((p=g.card.queryConfig)==null?void 0:p.metricColumns)||[]}),o=t.useDndStore(g=>g.previewMetricColumns),i=t.useEditorStore(g=>{var p;return((p=g.card.queryConfig)==null?void 0:p.pivotColumns)||[]}),l=t.useDndStore(g=>g.previewPivotColumns),{removeColumnFromGroupBy:u,removeColumnFromMetricColumns:c,removeColumnFromPivotBy:m}=t.useEditorActions();function d(g){u(g)}function h(g){c(g)}function S(g){m(g)}let f="Group By",y="Metrics",x="Stack By";return a==="table"&&(f="Rows",y="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(ys,{iconClassName:"size-[19px]"}),e.jsxs(t.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(ot,{onRemoveColumn:d,sortableType:_e,id:ge,label:f,columns:s,previewColumns:n}),e.jsx(ot,{onRemoveColumn:S,sortableType:Ge,id:ye,label:x,columns:i,previewColumns:l}),e.jsx(ot,{onRemoveColumn:h,sortableType:ht,id:je,label:y,columns:r,previewColumns:o}),e.jsx(er,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function zt({children:s,column:a,id:n,sortableType:r,className:o}){const[i,l]=L.useState(!1),{removeEditorFilter:u,clearEditorFilter:c}=t.useEditorActions(),m=t.useEditorStore(h=>{var S,f;return(f=(S=h.card.queryConfig)==null?void 0:S.filters)==null?void 0:f.some(y=>y.filterColumnName===a.name)});function d(h){u(h)}return e.jsx(Ts,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),m&&e.jsx("button",{onClick:()=>c(a),children:e.jsx(t.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>d(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function sr({column:s,sortableType:a}){const n=t.useDashboardStore(T=>T.themeStyle),r=t.useEditorStore(T=>{var E,j;return(j=(E=T.card)==null?void 0:E.queryConfig)==null?void 0:j.filters}),o=t.useEditorStore(T=>{var E,j;return(j=(E=T.card.queryConfig)==null?void 0:E.filterColumns)==null?void 0:j.find(b=>b.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:l,selectedTableName:u}=t.useEditorAside(),c=L.useMemo(()=>{var T;return(T=r==null?void 0:r.find(E=>E.filterColumnName===s.name))==null?void 0:T.filterValue},[r,s.name]),m=L.useMemo(()=>Array.isArray(c)?c.map(T=>({id:T,value:T})):[],[c]),{updateEditorFilterValue:d}=t.useEditorActions(),h={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:S,isLoading:f,isFetching:y,isError:x}=t.useFilterQuery(h),g=L.useMemo(()=>{var E;return h.column?(E=S==null?void 0:S.records)==null?void 0:E.map(j=>{let b=h.column.split(".").slice(-1)[0].replace(/"/g,"");return j[b]===void 0&&(b=b.toLowerCase()),{id:j[b],value:j[b]}}):[]},[S,h.column]);function p(T){const E=T.map(j=>j.id);d(s.name,E)}function C(){return f||y?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(nr,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:g,onChange:p,selectedOptions:m,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(zt,{className:"w-60",id:s.id,sortableType:a,column:s,children:C()})}function nr({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,l;return(l=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:l.find(u=>u.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function ar({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:l}=t.useEditorAside(),u={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:c,isFetching:m,isError:d,data:h}=t.useFilterQuery(u),S=h==null?void 0:h.records,{dateRange:f,setDateRange:y,initialDateRange:x}=t.useDateRangeFromRecords(S),{updateEditorFilterValue:g}=t.useEditorActions();function p(E){var b,v;const j={gte:(b=E==null?void 0:E.from)==null?void 0:b.toISOString(),lte:(v=E==null?void 0:E.to)==null?void 0:v.toISOString()};g(s.name,j)}function C(){g(s.name,null,!0),y(x)}function T(){return c||m?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):d?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):S?e.jsx(t.DateRangePopover,{title:u.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:f,setDateRange:y,onApply:p,onClear:C}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(zt,{className:"w-72",id:s.id,sortableType:a,column:s,children:T()})}function rr({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var y,x;const{setNodeRef:i,isOver:l,over:u}=t.useDroppable({id:s}),c=t.useDndStore(g=>g.activeId),m={},d=l||((x=(y=u==null?void 0:u.data)==null?void 0:y.current)==null?void 0:x.type)===o;function h(){if(!f||f.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function S(g){const p=t.isDateDataType(g.type);return g.id===cs.id?e.jsx(zt,{id:g.id,sortableType:o,column:g,children:e.jsx(or,{})},g.id):p?e.jsx(ar,{droppableId:s,sortableType:o,column:g},g.id):e.jsx(sr,{droppableId:s,sortableType:o,column:g},g.id)}const f=c?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(g=>g.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",d&&"border border-muted-foreground/20"),ref:i,style:m,children:[e.jsx(t.Label,{className:"text-sm",children:a}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:f==null?void 0:f.map(g=>S(g))})]})})}function or(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function ir(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(rr,{onRemoveColumn:r,sortableType:pt,id:xt,label:"Filters",columns:s,previewColumns:a})})}function lr(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(In,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(ms,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function cr(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(u=>u.isShowingVisual),r=t.useEditorStore(u=>u.showAIDialog),o=t.useEditorStore(u=>u.isDevMode);L.useEffect(()=>{var u,c,m,d;r?((u=s.current)==null||u.resize(0),(c=a.current)==null||c.resize(0)):((m=s.current)==null||m.resize(25),(d=a.current)==null||d.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(ia,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Ja,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ve,{})})]}):e.jsx(Ve,{})})]})}function l(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(tr,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(lr,{}),e.jsx(ir,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Ve,{})})]})})]}):e.jsx(Ve,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():l()})}function dr(s,a){const[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:l}=t.useSemaphorContext(),u=t.useEditorStore(G=>{var Q;return(Q=G==null?void 0:G.card)==null?void 0:Q.sql}),c=t.useEditorStore(G=>G.isDevMode),m=t.useEditorStore(G=>{var Q;return(Q=G==null?void 0:G.card)==null?void 0:Q.python}),{setCardPython:d,setCardSql:h,setRunSql:S,switchCardType:f,setQueryConfig:y}=t.useEditorActions(),x=t.useEditorStore(G=>G.currentAssitantScope)||[],g=t.useEditorStore(G=>G.userInputForAI),p=t.useEditorStore(G=>G.triggerAIRun),C=t.useEditorStore(G=>G.card),T=t.useEditorStore(G=>G.selectedDatabaseName),E=t.useEditorStore(G=>G.selectedTableName),j=t.useEditorStore(G=>G.selectedConnectionId),b=t.useEditorStore(G=>G.selectedSchemaName),v=t.useDashboardStore(G=>G.dashboard.aiScopeTables),{errorMessage:w,refetch:I,data:D}=t.useDashboardCardQuery(C),{setTriggerAIRun:N,setCurrentAssitantScope:F,setCardConfig:O}=t.useEditorActions(),{selectedDatamodelName:A,connectionType:k,selectedDatamodelId:M}=t.useEditorAside(),{messages:B,setMessages:z,reload:V,error:R,append:K,input:J,setInput:_,status:U,handleInputChange:q,handleSubmit:P,stop:$}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${l==null?void 0:l.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:c,aiContext:s},maxSteps:10,onError:G=>{console.log("on error",G)},onToolCall:H,onFinish(G,Q){Y(Q.usage),r(""),Q.finishReason==="stop"&&r("")}});L.useEffect(()=>{p&&g&&(q({target:{value:g}}),setTimeout(()=>{P(),N(!1)},100))},[p,P,g,N,q]);async function H({toolCall:G}){var Q,he,we,Me;if(["createChartFromSql","createForecast"].includes(G.toolName)){const W=G.args.sql,se=G.args.python,ne=G.args.chartType;return f(ne),h(W),d(se),S(!0),{status:"success",message:"Let the user know that chart is created"}}else if(G.toolName==="getTableColumns")r("Getting table columns...");else{if(G.toolName==="getUserSql")return u?{status:"success",sql:u,python:m||""}:{status:"error",message:"No SQL found"};if(G.toolName==="getCurrentTableScope")return r("Getting table scope..."),pe(),{status:"success",tables:x};if(G.toolName==="generateQueryConfig"){r("Generating query config...");const W=G.args.chartType,se=G.args.queryConfig;G.args.cardConfig,f(W),O(se),h(void 0),d(void 0);const ne=await I();return(Q=ne==null?void 0:ne.data)!=null&&Q.error?{status:"error",queryConfig:se,message:(he=ne==null?void 0:ne.data)==null?void 0:he.error.message}:(we=ne==null?void 0:ne.data)!=null&&we.records?{status:"success",queryConfig:se,message:"The data has been visualized"}:{status:"success",queryConfig:se,message:"The data has been visualized",records:(Me=ne==null?void 0:ne.data)==null?void 0:Me.records}}else r("Analyzing...")}}function Y(G){i(Q=>Q?{promptTokens:Q.promptTokens+G.promptTokens,completionTokens:Q.completionTokens+G.completionTokens,totalTokens:Q.totalTokens+G.totalTokens}:G)}function Z(G){const Q=t.removeFromScopeArray(x,G);ae(Q)}function ae(G){const Q=t.sanitizeAIScope(G);F(Q),z(he=>[...he,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}])}function Ne(){const G={databaseName:T||"",schemaName:b||"",tableName:E||"",datamodelId:M||"",datamodelName:t.resolveDatamodelName(A),connectionId:j||"",connectionType:k||""},Q=t.dedup([...x,G]);ae(Q)}function pe(){const G={databaseName:T||"",schemaName:b||"",tableName:E||"",datamodelName:t.resolveDatamodelName(A),connectionId:j||"",connectionType:k||"",datamodelId:M||""};if(!t.isInAiScopeArray([...v||[],...x],G)||x.length===0){const he=t.dedup([...v||[],...x,G]).filter(we=>we.connectionId===G.connectionId);ae(he)}}const Ce=!["ready","error"].includes(U),Se=t.getErrorMessage(R);return{messages:B,setMessages:z,reload:V,append:K,input:J,setInput:_,isLoading:Ce,handleSetAIScope:pe,handleAddCurrentTableToScope:Ne,removeFromCurrentSelections:Z,currentAssitantScope:x,setCurrentAssitantScope:F,handleInputChange:q,handleSubmit:P,stop:$,chatStatus:U,toolStatus:n,llmUsage:o,onFinish:a,errorMessage:Se}}const ur=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Yt(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[l,u]=L.useState(!1),[c,m]=L.useState(!1),[d,h]=L.useState({selectedEntities:[]}),S=t.useDashboardStore($=>$.dashboard.aiContext),f=t.useEditorStore($=>$.card.dataSource),y=t.useEditorStore($=>$.actions.setCardSql),x=t.useEditorStore($=>$.actions.setRunSql),g=t.useEditorStore($=>$.showAIDialog),p=t.useDashboardStore($=>$.handleOpenAssistantProfile),{setShowAIDialog:C,setCardPython:T}=t.useEditorActions(),{setDataSource:E}=t.useEditorActions(),{assistantProfile:j}=t.useAssistantProfile(),{messages:b,setMessages:v,reload:w,append:I,input:D,setInput:N,isLoading:F,handleInputChange:O,handleSubmit:A,stop:k,chatStatus:M,llmUsage:B,errorMessage:z}=dr(d);t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:b}),L.useEffect(()=>{var $;g&&(($=a.current)==null||$.focus(),h({selectedEntities:(f==null?void 0:f.selectedEntities)||[]}))},[g,f]);function V($,H){H==="sql"?(y($),x(!0)):H==="python"&&(T($),x(!0))}function R(){var $;($=S==null?void 0:S.selectedEntities)==null||$[0],m(!0)}function K(){d.selectedEntities.length===0&&h({selectedEntities:(S==null?void 0:S.selectedEntities)||[]})}function J($){K();const H={role:"user",content:$.title+" "+$.subtitle};I(H)}function _($){K(),I({role:"user",content:$})}function U(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"System Message"})]})]})}function q(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const P=(D==null?void 0:D.length)===0&&(b==null?void 0:b.filter($=>$.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[q(),p&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:p,children:(j==null?void 0:j.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[U(),e.jsx(t.IconButton,{tooltip:"Add Context",className:"h-7 p-2",onClick:R,children:e.jsx(t.Settings,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2",tooltip:"New Chat",onClick:()=>{v([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{C(!1)},children:e.jsx(t.PanelRight,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(t.PrintMessages,{messages:b,showTools:o,handleRun:V,showSystemMessage:l}),e.jsx(t.ChatStatus,{messages:b,chatStatus:M,errorMessage:z})]})}),e.jsxs("div",{className:"mb-3",children:[P&&!j&&e.jsx(t.Placeholders,{onClick:J,placeholders:ur}),e.jsx("div",{children:P&&j&&e.jsx(t.SeedQuestions,{seedQuestions:j.seedQuestions||[],handleSeedQuestionClick:_})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:N,stop:k,input:D,localAiContext:d,setLocalAiContext:h,handleInputChange:O,handleSubmit:$=>{K(),A($)},isLoading:F,onFocus:()=>{}}),B&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",B.promptTokens," prompt tokens,"," ",B.completionTokens," completion tokens,"," ",B.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(f==null?void 0:f.selectedEntities)||[],open:c,onOpenChange:m,dataSource:f||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function mr(s){return s.flatMap(a=>a.columns.map(n=>({id:`${a.entityId}-${n.name}`,name:n.name,dataType:n.dataType,qualifiedEntityName:a.qualifiedEntityName,label:n.label||t.toTitleCase(n.name),description:n.description,entityId:a.entityId,entityName:a.entityName,entityType:a.entityType})))}function ft(s){if(s.type==="table"||s.type==="view"){if(s.database&&s.schema)return`${s.database}.${s.schema}.${s.name}`;if(s.database)return`${s.database}.${s.name}`}return s.name}function ze(s){var x;const a=t.useDashboardStore(g=>g.authToken)||s,{hasSchemaSupport:n}=t.useSelectedConnection(s),r=t.useEditorStore(g=>{var p;return(p=g.card.dataSource)==null?void 0:p.connectionId}),o=t.useEditorStore(g=>{var p,C;return(C=(p=g.card.dataSource)==null?void 0:p.selectedEntities)==null?void 0:C.filter(T=>T.type==="model")})||[],i=t.useEditorStore(g=>{var p,C;return(C=(p=g.card.dataSource)==null?void 0:p.selectedEntities)==null?void 0:C.filter(T=>T.type==="table"||T.type==="view")})||[],l=t.useEditorStore(g=>{var p,C;return(C=(p=g.card.dataSource)==null?void 0:p.selectedEntities)==null?void 0:C.filter(T=>T.type==="dataset")})||[];function u(g){return g.type==="dataset"?!!r&&!!g.domainId&&!!g.name:g.type==="model"?!!r&&!!g.id:g.type==="table"||g.type==="view"?n?!!r&&!!g.name&&!!g.database&&!!g.schema:!!r&&!!g.name&&!!g.database:!1}const c=[...o,...i,...l],m=Vs({queries:c.map(g=>{let p={};return g.type==="model"?p={connection_id:r,datamodel_id:g.id,database_name:"",schema_name:"",table_name:"",domain_id:g.domainId,dataset_name:g.name}:g.type==="dataset"?p={connection_id:g.connectionId,domain_id:g.domainId,dataset_name:g.name}:p={connection_id:r,datamodel_id:"",database_name:g.database,schema_name:g.schema,table_name:g.name},{queryKey:["columns",r,g],queryFn:()=>t.getRequest("https://semaphor.cloud/api/v1/columns",(a==null?void 0:a.accessToken)||"",p),enabled:!!r&&u(g)}})}),d=m.some(g=>g.isPending),h=m.some(g=>g.isError),S=(x=m.find(g=>g.isError))==null?void 0:x.error,f=m.map((g,p)=>{var E;const C=c[p],T=ft(C);return{entityId:C.id||C.name,entityType:C.type,entityName:C.name,label:C.label,description:C.description,qualifiedEntityName:T,columns:(E=g.data)==null?void 0:E.columns.map(j=>({id:`${C.name}-${j.column_name}`,name:j.column_name,dataType:j.data_type,label:j.label||t.toLabel(j.column_name),description:j.description||"",qualifiedEntityName:T,entityId:C.id||C.id||C.name,entityName:C.name,entityType:C.type}))}}).filter(g=>{var p;return((p=g==null?void 0:g.columns)==null?void 0:p.length)>0})||[],y=mr(f);return{columnGroups:f,columns:y,isLoading:d,hasError:h,error:S,refetch:()=>{m.forEach(g=>g.refetch())}}}function hr({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:l}=t.useSortable({id:s.id}),[u,c]=L.useState(!1),m={transform:t.CSS.Transform.toString(o),transition:i},d=t.getDataType(s.dataType),S=(f=>{const y=(f||"").toLowerCase();switch(t.getDataType(y)){case"number":return St;case"date":return t.Calendar;case"boolean":return ns;case"json":return rn;case"geo":return kn;default:return as}})(s.dataType);return e.jsxs("div",{ref:r,style:m,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${l?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",onClick:()=>c(!u),children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(S,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",d==="string"?"text-blue-500":"",d==="number"?"text-green-500":"",d==="date"?"text-purple-500":"",d==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm dark:text-muted-foreground ${u?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:t.cn("font-medium",{"text-blue-500":d==="string","text-green-500":d==="number","text-purple-500":d==="date","text-orange-500":d==="boolean"}),children:s.label||s.name}),e.jsx("p",{className:t.cn("pr-0.5 text-xs font-normal italic text-gray-500"),children:s.dataType})]}),s.description&&e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:s.description}),e.jsx("div",{className:"mt-2 text-xs italic text-muted-foreground",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name})]})})]})}),e.jsx("button",{onClick:f=>{f.stopPropagation(),c(!u)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:u?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),u&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function xr({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(hr,{field:o},o.id))})})]})}function pr(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all"),l=t.useEditorStore(E=>E.card.dataSource),{columns:u=[],columnGroups:c=[],isLoading:m,error:d}=ze(),h=u.filter(E=>E.name.toLowerCase().includes(s.toLowerCase())||E.dataType.toLowerCase().includes(s.toLowerCase())||E.qualifiedEntityName&&E.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),S=E=>E.dataType==="number"||E.dataType==="integer"||E.dataType==="float"||E.dataType==="decimal"||E.dataType==="currency"?"metrics":"dimensions",y=(o==="all"?h:h.filter(E=>S(E)===o)).reduce((E,j)=>{const b=j.qualifiedEntityName||"Other Fields";return E[b]||(E[b]={label:t.toLabel(j.entityName),fields:[]}),E[b].fields.push(j),E},{});L.useEffect(()=>{const E=Object.keys(y);r(new Set(E))},[Object.keys(y).join(",")]);const x=E=>{const j=new Set(n);j.has(E)?j.delete(E):j.add(E),r(j)},g=h.filter(E=>S(E)==="dimensions").length,p=h.filter(E=>S(E)==="metrics").length,C=h.filter(E=>S(E)==="calculated").length,T=h.length>0;return m?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(ue,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!l||!l.selectedEntities||l.selectedEntities.length===0?e.jsx(t.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:E=>a(E.target.value)})}),T&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:E=>i(E),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:h.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(jt,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(en,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]})]})})]}),e.jsxs(t.CustomScrollArea,{className:"py-2",children:[e.jsxs("div",{className:"space-y-2",children:[Object.entries(y).map(([E,j])=>{const b=c.find(v=>v.entityName===E)||{entityName:E,label:j.label};return e.jsx(xr,{entityGroup:b,fields:j.fields,isOpen:n.has(E),onToggle:()=>x(E)},E)}),Object.keys(y).length===0&&u.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(y).length===0&&u.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function fr(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(pr,{})," "]})}function gr({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),l=()=>{const b=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:b,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,v]}),i(new Set([...o,v.id]))},u=b=>{r({...n,joins:n.joins.filter(v=>v.id!==b)}),i(new Set([...o].filter(v=>v!==b)))},c=(b,v)=>{var N,F;const w=n.joins.find(O=>O.id===b);if(!w)return;const I={...w,...v},D=n.joins.map(O=>O.id===b?I:O);if((N=I.source)!=null&&N.name&&((F=I.target)!=null&&F.name)&&I.joinKeyGroups[0].keys.length===0){const O=a.find(B=>{var z;return B.name===((z=I.source)==null?void 0:z.name)}),A=a.find(B=>{var z;return B.name===((z=I.target)==null?void 0:z.name)}),k={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},operator:"="},M=[...I.joinKeyGroups];M[0]={...M[0],keys:[k]},I.joinKeyGroups=M,D[D.findIndex(B=>B.id===b)]=I}r({...n,joins:D})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:l,removeJoin:u,updateJoin:c,moveJoinUp:b=>{const v=n.joins.findIndex(w=>w.id===b);if(v>0){const w=[...n.joins],I={...w[v]},D={...w[v-1]};w[v]=D,w[v-1]=I,w.forEach((F,O)=>{F.sequence=O+1});const N={...n,joins:w};r(N)}},moveJoinDown:b=>{const v=n.joins.findIndex(w=>w.id===b);if(v<n.joins.length-1){const w=[...n.joins],I={...w[v]},D={...w[v+1]};w[v]=D,w[v+1]=I,w.forEach((F,O)=>{F.sequence=O+1});const N={...n,joins:w};r(N)}},toggleJoinExpansion:b=>{const v=new Set(o);v.has(b)?v.delete(b):v.add(b),i(v)},getAvailableSourceEntities:b=>{if(n.joins.length===0)return a;const v=n.joins.findIndex(I=>I.id===b);if(v===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,v).forEach(I=>{w.add(I.source.name),w.add(I.target.name)}),a.filter(I=>w.has(I.name))},getAvailableTargetEntities:b=>a.filter(v=>v.name!==b),addJoinKeyGroup:b=>{const v=n.joins.find(I=>I.id===b);if(!v)return;const w=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];c(b,{joinKeyGroups:w})},updateGroupOperator:(b,v,w)=>{const I=n.joins.find(N=>N.id===b);if(!I)return;const D=[...I.joinKeyGroups];D[v]={...D[v],operator:w},c(b,{joinKeyGroups:D})},removeJoinKeyGroup:(b,v)=>{const w=n.joins.find(D=>D.id===b);if(!w)return;const I=[...w.joinKeyGroups];I.splice(v,1),c(b,{joinKeyGroups:I})},addJoinKey:(b,v)=>{const w=n.joins.find(O=>O.id===b);if(!w)return;const I=a.find(O=>O.name===w.source.name),D=a.find(O=>O.name===w.target.name),N=[...w.joinKeyGroups],F={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="};N[v]={...N[v],keys:[...N[v].keys,F]},c(b,{joinKeyGroups:N})},updateJoinKey:(b,v,w,I,D)=>{const N=n.joins.find(M=>M.id===b);if(!N)return;const F=a.find(M=>M.name===N.source.name),O=a.find(M=>M.name===N.target.name),A=[...N.joinKeyGroups],k=A[v].keys[w];I==="sourceColumnName"&&F?A[v].keys[w]={...k,source:{...k.source,name:D}}:I==="targetColumnName"&&O?A[v].keys[w]={...k,target:{...k.target,name:D}}:I==="operator"&&(A[v].keys[w]={...k,operator:D}),c(b,{joinKeyGroups:A})},removeJoinKey:(b,v,w)=>{const I=n.joins.find(N=>N.id===b);if(!I)return;const D=[...I.joinKeyGroups];D[v].keys.splice(w,1),c(b,{joinKeyGroups:D})},generateSQLPreview:()=>{const b=[...n.joins].sort((I,D)=>I.sequence-D.sequence),v=n.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
|
|
400
|
+
FROM ${v.name}`;return b.forEach(I=>{const D=a.find(O=>O.name===I.target.name);if(!D)return;const N=I.joinKeyGroups.filter(O=>O.keys&&O.keys.length>0).map(O=>{const A=O.keys.filter(k=>{var M,B,z,V;return((M=k.source)==null?void 0:M.name)&&((B=k.target)==null?void 0:B.name)&&((z=k.source)==null?void 0:z.entityName)&&((V=k.target)==null?void 0:V.entityName)}).map(k=>`${k.source.entityName}.${k.source.name} ${k.operator} ${k.target.entityName}.${k.target.name}`);return A.length>1?`(${A.join(` ${O.operator} `)})`:A[0]}).filter(Boolean),F=N.length>1?N.join(" OR "):N[0]||"condition_here";w+=`
|
|
401
401
|
${I.joinType} JOIN ${D.name}
|
|
402
|
-
ON ${F}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(I=>!I.source.name||!I.target.name)||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.length===0))||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.some(N=>!N.source.name||!N.target.name||!N.operator))))}}function jr({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(N=>N.card.config);const{columnGroups:l}=ze(),{joinPlan:u,expandedJoins:c,setJoinPlan:m,addJoin:d,removeJoin:h,updateJoin:S,moveJoinUp:f,moveJoinDown:y,toggleJoinExpansion:x,getAvailableSourceEntities:g,getAvailableTargetEntities:p,addJoinKeyGroup:C,updateGroupOperator:T,removeJoinKeyGroup:E,addJoinKey:j,updateJoinKey:b,removeJoinKey:v,generateSQLPreview:w,isValidConfiguration:I}=gr({initialJoinPlan:s,availableDataSources:a}),D=N=>{const F=l.find(O=>O.entityName===N);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:u.baseEntity.name,onValueChange:N=>{const F=a.find(O=>O.name===N);m({...u,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:N,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(N=>e.jsx(t.SelectItem,{value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",u.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:d,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),u.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:u.joins.map(N=>{const F=a.find(k=>k.name===N.source.name),O=a.find(k=>k.name===N.target.name),A=c.has(N.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:N.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",N.sequence,F&&O&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",O.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>f(N.id),disabled:N.sequence===1,children:e.jsx(Ye,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(N.id),disabled:N.sequence===u.joins.length,children:e.jsx(Ue,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>x(N.id),children:A?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>h(N.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),A&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:N.source.name,onValueChange:k=>{const M=a.find(B=>B.name===k);S(N.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:k,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:g(N.id).map(k=>e.jsx(t.SelectItem,{value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name]})},k.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:N.joinType,onValueChange:k=>S(N.id,{joinType:k}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:N.target.name,onValueChange:k=>{const M=a.find(B=>B.name===k);S(N.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:k,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!N.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:N.source.name?p(N.source.name).map(k=>e.jsx(t.SelectItem,{value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,k.name===N.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},k.name)):[]})]})]})]}),N.source.name&&N.target.name&&F&&O&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:N.joinKeyGroups.map((k,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:k.operator,onValueChange:B=>T(N.id,M,B),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(N.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[k.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:k.keys.map((B,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:k.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:B.source.name,onValueChange:P=>b(N.id,M,z,"sourceColumnName",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:D(N.source.name).map(P=>e.jsx(t.SelectItem,{value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:B.operator,onValueChange:P=>b(N.id,M,z,"operator",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"=",children:"="}),e.jsx(t.SelectItem,{value:"<",children:"<"}),e.jsx(t.SelectItem,{value:">",children:">"}),e.jsx(t.SelectItem,{value:"<=",children:"<="}),e.jsx(t.SelectItem,{value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:B.target.name,onValueChange:P=>b(N.id,M,z,"targetColumnName",P),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:D(N.target.name).map(P=>e.jsx(t.SelectItem,{value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(N.id,M,z),children:e.jsx(t.X,{className:"size-3.5"})})]},B.id||z))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>j(N.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},k.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(u),disabled:!I(),children:"Save"})]})]})}function Qt({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:l,onCancel:u}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(jr,{joinPlan:r,availableDataSources:o,onSave:l,onCancel:u,onRemove:i})]}),s]})}function yr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...s].sort((l,u)=>l.sequence-u.sequence),i=n.find(l=>l.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(l=>{const u=n.find(c=>c.name===l.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:l.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:u==null?void 0:u.type}),e.jsx("span",{className:"text-xs font-medium",children:u==null?void 0:u.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const l=n.find(c=>c.name===o.source.name),u=n.find(c=>c.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[l==null?void 0:l.name," → ",u==null?void 0:u.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((c,m)=>c+m.keys.length,0)," ","condition",o.joinKeyGroups.reduce((c,m)=>c+m.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function br(){var h,S;ze(),t.useEditorStore(f=>f.card.dataSource);const s=t.useEditorStore(f=>f.frame),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.actions.updateCardConfig),r=((h=a==null?void 0:a.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[o,i]=L.useState(!1),l=((S=a==null?void 0:a.dataSource)==null?void 0:S.selectedEntities)||[],u=f=>{s.activeCardId&&(n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:f}),i(!1))},c=()=>{n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:void 0})},m=()=>{i(!1)},d=()=>{const f=[...r.joins].sort((g,p)=>g.sequence-p.sequence),y=r.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let x=`SELECT *
|
|
402
|
+
ON ${F}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(I=>!I.source.name||!I.target.name)||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.length===0))||n.joins.some(I=>I.joinKeyGroups.some(D=>D.keys.some(N=>!N.source.name||!N.target.name||!N.operator))))}}function jr({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(N=>N.card.config);const{columnGroups:l}=ze(),{joinPlan:u,expandedJoins:c,setJoinPlan:m,addJoin:d,removeJoin:h,updateJoin:S,moveJoinUp:f,moveJoinDown:y,toggleJoinExpansion:x,getAvailableSourceEntities:g,getAvailableTargetEntities:p,addJoinKeyGroup:C,updateGroupOperator:T,removeJoinKeyGroup:E,addJoinKey:j,updateJoinKey:b,removeJoinKey:v,generateSQLPreview:w,isValidConfiguration:I}=gr({initialJoinPlan:s,availableDataSources:a}),D=N=>{const F=l.find(O=>O.entityName===N);return(F==null?void 0:F.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:u.baseEntity.name,onValueChange:N=>{const F=a.find(O=>O.name===N);m({...u,baseEntity:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:N,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(N=>e.jsx(t.SelectItem,{value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},N.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",u.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:d,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),u.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:u.joins.map(N=>{const F=a.find(k=>k.name===N.source.name),O=a.find(k=>k.name===N.target.name),A=c.has(N.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:N.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",N.sequence,F&&O&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",F.name," → ",O.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>f(N.id),disabled:N.sequence===1,children:e.jsx(Ue,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(N.id),disabled:N.sequence===u.joins.length,children:e.jsx(Je,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>x(N.id),children:A?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>h(N.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),A&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:N.source.name,onValueChange:k=>{const M=a.find(B=>B.name===k);S(N.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:k,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:g(N.id).map(k=>e.jsx(t.SelectItem,{value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name]})},k.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:N.joinType,onValueChange:k=>S(N.id,{joinType:k}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:N.target.name,onValueChange:k=>{const M=a.find(B=>B.name===k);S(N.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:k,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!N.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:N.source.name?p(N.source.name).map(k=>e.jsx(t.SelectItem,{value:k.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:k.type}),k.name,k.name===N.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},k.name)):[]})]})]})]}),N.source.name&&N.target.name&&F&&O&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>C(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),N.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:N.joinKeyGroups.map((k,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:k.operator,onValueChange:B=>T(N.id,M,B),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(N.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[k.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:k.keys.map((B,z)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[z>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:k.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:B.source.name,onValueChange:V=>b(N.id,M,z,"sourceColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:D(N.source.name).map(V=>e.jsx(t.SelectItem,{value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:B.operator,onValueChange:V=>b(N.id,M,z,"operator",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"=",children:"="}),e.jsx(t.SelectItem,{value:"<",children:"<"}),e.jsx(t.SelectItem,{value:">",children:">"}),e.jsx(t.SelectItem,{value:"<=",children:"<="}),e.jsx(t.SelectItem,{value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:B.target.name,onValueChange:V=>b(N.id,M,z,"targetColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:D(N.target.name).map(V=>e.jsx(t.SelectItem,{value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(N.id,M,z),children:e.jsx(t.X,{className:"size-3.5"})})]},B.id||z))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>j(N.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},k.id))})]})]})]},N.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(u),disabled:!I(),children:"Save"})]})]})}function Kt({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:l,onCancel:u}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(jr,{joinPlan:r,availableDataSources:o,onSave:l,onCancel:u,onRemove:i})]}),s]})}function yr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...s].sort((l,u)=>l.sequence-u.sequence),i=n.find(l=>l.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(l=>{const u=n.find(c=>c.name===l.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:l.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:u==null?void 0:u.type}),e.jsx("span",{className:"text-xs font-medium",children:u==null?void 0:u.name})]})]},l.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const l=n.find(c=>c.name===o.source.name),u=n.find(c=>c.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[l==null?void 0:l.name," → ",u==null?void 0:u.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((c,m)=>c+m.keys.length,0)," ","condition",o.joinKeyGroups.reduce((c,m)=>c+m.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function br(){var h,S;ze(),t.useEditorStore(f=>f.card.dataSource);const s=t.useEditorStore(f=>f.frame),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.actions.updateCardConfig),r=((h=a==null?void 0:a.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[o,i]=L.useState(!1),l=((S=a==null?void 0:a.dataSource)==null?void 0:S.selectedEntities)||[],u=f=>{s.activeCardId&&(n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:f}),i(!1))},c=()=>{n(s.activeCardId,{...a==null?void 0:a.config,joinPlan:void 0})},m=()=>{i(!1)},d=()=>{const f=[...r.joins].sort((g,p)=>g.sequence-p.sequence),y=r.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let x=`SELECT *
|
|
403
403
|
FROM ${y.name}`;return f.forEach(g=>{const p=l.find(E=>E.name===g.target.name);if(!p)return;const C=g.joinKeyGroups.filter(E=>E.keys&&E.keys.length>0).map(E=>{const j=E.keys.filter(b=>{var v,w,I,D;return((v=b.source)==null?void 0:v.name)&&((w=b.target)==null?void 0:w.name)&&((I=b.source)==null?void 0:I.entityName)&&((D=b.target)==null?void 0:D.entityName)}).map(b=>`${b.source.entityName}.${b.source.name} ${b.operator} ${b.target.entityName}.${b.target.name}`);return j.length>1?`(${j.join(` ${E.operator} `)})`:j[0]}).filter(Boolean),T=C.length>1?C.join(" OR "):C[0]||"condition_here";x+=`
|
|
404
404
|
${g.joinType} JOIN ${p.name}
|
|
405
|
-
ON ${T}`}),x};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[r.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>i(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(yr,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:l,generateSQLPreview:d})})]})}),e.jsx(Qt,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:m,onRemove:c,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Qt,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:m,onRemove:c,children:e.jsxs(t.Button,{onClick:()=>i(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function vr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(c=>c.card.dataSource),{updateDataSource:i}=t.useEditorActions(),l={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...l,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"text-brand h-5 w-5"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((c,m)=>e.jsxs(t.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[t.getDisplayName(c),e.jsx("button",{onClick:d=>{d.stopPropagation();const h=u.selectedEntities.filter(S=>!(S.name===c.name&&S.type===c.type));i({...l,...o,selectedEntities:h})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 text-red-500"})})]},`${c.type}-${c.name}-${m}`)),u.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})]}),e.jsx(br,{})]})]}),e.jsx(fr,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:u,fallbackDataSource:l})]})}const Nr=[{id:"table",icon:We,label:"Table"},{id:"bar",icon:Ke,label:"Bar Chart"},{id:"line",icon:Qe,label:"Line Chart"},{id:"stackedBar",icon:gt,label:"Stacked Bar Chart"},{id:"stackedLine",icon:Ft,label:"Stacked Line Chart"},{id:"scatter",icon:vt,label:"Scatter Chart"},{id:"bubble",icon:Lt,label:"Bubble Chart"},{id:"pie",icon:bt,label:"Pie Chart"},{id:"doughnut",icon:Nt,label:"Doughnut Chart"},{id:"funnel",icon:Ot,label:"Funnel Chart"},{id:"radar",icon:kt,label:"Radar Chart"},{id:"polarArea",icon:At,label:"Polar Area Chart"},{id:"tornado",icon:It,label:"Tornado Chart"},{id:"range",icon:yt,label:"Range Chart"},{id:"kpi",icon:Bt,label:"KPI"},{id:"text",icon:Xt,label:"Text"},{id:"map",icon:wt,label:"Map"},{id:"custom",icon:Et,label:"Custom"}];function Cr({selectedChart:s,onChartChange:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(m=>m.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(m){i(null),r({}),n(m),["kpi","custom","text","map"].includes(m)&&(o(!0),u(void 0)),a(m)}return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Select,{value:s,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"w-full",children:e.jsx(t.SelectValue,{placeholder:"Select chart type"})}),e.jsx(t.SelectContent,{children:Nr.map(m=>{const d=m.icon;return e.jsx(t.SelectItem,{value:m.id,className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{children:m.label})]})},m.id)})})]})})}const Ms=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function Sr({label:s,onLabelChange:a}){const[n,r]=L.useState(s??""),[o,i]=L.useState(!1);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Display Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:"Display label...",value:o?n:s??"",onChange:l=>{r(l.target.value),i(!0)},onFocus:()=>i(!0),onClick:l=>l.stopPropagation(),className:"h-8 text-xs",onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&o&&n!==(s??"")?(a(n),i(!1)):l.key==="Escape"&&(r(s??""),i(!1))},"aria-label":"Edit display label"}),o&&n!==(s??"")&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm label",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel label edit",onClick:()=>{r(s??""),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})]})}function wr({aliasTemplate:s,onAliasTemplateChange:a}){var c;const[n,r]=L.useState(s),[o,i]=L.useState(!1),l=(c=t.useEditorStore(m=>{var d;return(d=m.card.config)==null?void 0:d.pivotByColumns}))==null?void 0:c[0],u=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:u,value:o?n:s,onChange:m=>{r(m.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&o&&n!==s?(a(n),i(!1)):m.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function kr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[l,u]=L.useState(""),c=()=>{a({...s,"":""})},m=h=>{const S={...s};delete S[h],a(S)},d=h=>{const S={...s};delete S[h],S[o]=l,a(S),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([h,S],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:y=>i(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?d(h):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:l,onChange:y=>u(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?d(h):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>d(h),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),u(S)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:S,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),u(S)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},h+f)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:c,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Er({field:s,zone:a,onRemove:n,onLabelChange:r,sortDirection:o,onSortDirectionChange:i,onAliasTemplateChange:l,onValueAliasesChange:u,onAggregationChange:c,onDateFormatChange:m,onGranularityChange:d,hasPivotColumns:h=!1}){const{attributes:S,listeners:f,setNodeRef:y,transform:x,transition:g,isDragging:p}=t.useSortable({id:s.id}),[C,T]=L.useState(!1),[E,j]=L.useState(s.dateFormat||"YYYY-MM-DD"),[b,v]=L.useState(s.customFormat||""),[w,I]=L.useState(!!s.customFormat),[D,N]=L.useState(s.granularity||"day"),[F,O]=L.useState(s.aliasTemplate||""),[A,k]=L.useState(s.valueAliases||{}),M=q=>{q==="custom"?I(!0):(I(!1),j(q),a==="groupBy"&&m&&m(q,""))},B=q=>{v(q),a==="groupBy"&&m&&m("custom",q)},z=q=>{N(q),a==="groupBy"&&d&&d(q)},P=q=>{O(q),l&&l(q)},R=q=>{k(q),u&&u(q)},K={transform:t.CSS.Transform.toString(x),transition:g},J=t.getDataType(s.dataType),_=J==="date",U=[{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}];return e.jsxs("div",{ref:y,style:K,...S,...f,className:`group flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(Ms,{dataType:J}),e.jsx("span",{className:"max-w-[180px] flex-1 overflow-hidden truncate text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:q=>{q.stopPropagation(),T(!C)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${C?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:q=>{q.stopPropagation(),console.log("DraggableField - Current sortDirection:",o);const V=o==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",V),i(V)},children:o==="asc"?e.jsx(Ye,{className:"h-3 w-3"}):e.jsx(Ue,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:q=>{q.stopPropagation(),n()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),C&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("span",{className:"flex-1 overflow-hidden truncate px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),a!=="pivotBy"&&e.jsx(Sr,{label:s.label??"",onLabelChange:r}),_&&a!=="groupBy"&&e.jsx("div",{className:"space-y-1",children:e.jsxs(t.Select,{defaultValue:"day",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})}),_&&a==="groupBy"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:D,onValueChange:z,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:w?"custom":E,onValueChange:M,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:U.map(q=>e.jsx(t.SelectItem,{value:q.value,children:q.label},q.value))})]}),w&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:b,onChange:q=>{q.stopPropagation(),B(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}),a==="metrics"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:q=>{c&&c(q)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),h&&e.jsxs(e.Fragment,{children:[e.jsx(wr,{aliasTemplate:F,onAliasTemplateChange:P}),e.jsx(kr,{valueAliases:A,onValueAliasesChange:R})]})]})]})]})}function Ir({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-50 text-xs font-medium dark:bg-amber-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function qe({zone:s,fields:a,label:n,placeholder:r,onRemove:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:m,onValueAliasesChange:d,shouldShow:h,hasPivotColumns:S=!1}){const{isOver:f,setNodeRef:y}=t.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),g=t.useEditorStore(T=>T.card),p=a.length>0,C=(T,E)=>{var b;!((b=g.config)!=null&&b.sortByColumns)||g.config.sortByColumns.findIndex(v=>v.id===T)===-1||x(g.id,T,{direction:E})};return s==="sortBy"&&h===!1?null:e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:"block text-sm font-medium",children:n}),e.jsx(Ir,{concept:s})]}),e.jsx("div",{ref:y,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${f?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((T,E)=>{const b=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Er,{field:T,zone:s,onRemove:()=>o(E),onLabelChange:v=>i(E,v),sortDirection:b,onSortDirectionChange:v=>C(T.id,v),onAggregationChange:l?v=>l(E,v):void 0,onAliasTemplateChange:m?v=>m(E,v):void 0,onValueAliasesChange:d?v=>d(E,v):void 0,onDateFormatChange:u?(v,w)=>u(E,v,w):void 0,onGranularityChange:c?v=>c(E,v):void 0,hasPivotColumns:S})})},T.id)})})})})]})}function Dr({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,onRemoveField:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:m,onValueAliasesChange:d}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(qe,{zone:"groupBy",fields:s,label:"Rows",placeholder:"Drop fields to group data",onRemove:h=>o("groupBy",h),onLabelChange:(h,S)=>i("groupBy",h,S),onDateFormatChange:(h,S,f)=>u&&u(h,S,f),onGranularityChange:(h,S)=>c&&c(h,S)}),e.jsx(qe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",onRemove:h=>o("pivotBy",h),onLabelChange:(h,S)=>i("pivotBy",h,S)}),e.jsx(qe,{zone:"metrics",fields:n,label:"Metrics",placeholder:"Drop fields to measure",onRemove:h=>o("metrics",h),onLabelChange:(h,S)=>i("metrics",h,S),onAggregationChange:l,onAliasTemplateChange:m,onValueAliasesChange:d,hasPivotColumns:a.length>0}),r&&r.length>0&&e.jsx(qe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields to sort data",onRemove:h=>o("sortBy",h),onLabelChange:(h,S)=>i("sortBy",h,S),shouldShow:s.length>0||a.length>0||n.length>0})]})}function Tr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:m,onGranularityChange:d,onAliasTemplateChange:h,onValueAliasesChange:S}){t.useEditorStore(y=>y.showAIDialog);const{setShowAIDialog:f}=t.useEditorActions();return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"mt-1 space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"text-brand h-5 w-5"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(Cr,{selectedChart:s,onChartChange:a})]}),e.jsxs(t.ScrollArea,{className:"flex-1 p-6",children:[e.jsx(Dr,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:m,onGranularityChange:d,onAliasTemplateChange:h,onValueAliasesChange:S}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Mr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(j=>j.card.dataSource);const{columns:o,isLoading:i}=ze(),u=a||o||[],c={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=j=>{const b=v=>{if(v.id===j){const w=u[0]||c;return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...v,groups:v.groups.map(b)}};r(b(n))},d=j=>{const b=v=>{if(v.id===j){const w=u[0]||c;return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...v,groups:v.groups.map(b)}};r(b(n))},h=(j,b)=>{const v=w=>w.id===j?{...w,conditions:w.conditions.filter(I=>I.id!==b)}:{...w,groups:w.groups.map(v)};r(v(n))},S=(j,b)=>{const v=w=>w.id===j?{...w,groups:w.groups.filter(I=>I.id!==b)}:{...w,groups:w.groups.map(v)};r(v(n))},f=(j,b,v,w)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=D=>D.id===j?{...D,conditions:D.conditions.map(N=>N.id===b?{...N,[v]:w}:N)}:{...D,groups:D.groups.map(I)};r(I(n))},y=(j,b,v)=>{const w=I=>I.id===j?{...I,conditions:I.conditions.map(D=>D.id===b?{...D,...v}:D)}:{...I,groups:I.groups.map(w)};r(w(n))},x=(j,b)=>{const v=w=>w.id===j?{...w,logicalOperator:b}:{...w,groups:w.groups.map(v)};r(v(n))},g=(j,b)=>{const v=w=>w.id===j?{...w,negate:b}:{...w,groups:w.groups.map(v)};r(v(n))},p=(j,b,v)=>{const w=I=>I.id===j?{...I,conditions:t.arrayMove(I.conditions,b,v)}:{...I,groups:I.groups.map(w)};r(w(n))},C=(j,b,v)=>{const w=I=>I.id===j?{...I,groups:t.arrayMove(I.groups,b,v)}:{...I,groups:I.groups.map(w)};r(w(n))},T=j=>{if(!j||j.conditions.length===0&&j.groups.length===0)return"-- No filters defined";const b=w=>{let I="";typeof w.field=="object"?I=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:I=String(w.field);const D=w.operator;let N=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof N=="string"?N=`'${N}'`:Array.isArray(N)&&(N=`'${N.join(", ")}'`);else if(w.field.dataType==="date")(typeof N=="string"||N instanceof Date)&&(N=`DATE('${N}')`);else if(["in","not in"].includes(w.operator)){let F=[];Array.isArray(N)?F=N.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof N=="string"?F=N.split(",").map(O=>{const A=O.trim();return w.field.dataType==="string"?`'${A}'`:A}):typeof N=="number"&&(F=[String(N)]),N=`(${F.join(", ")})`}switch(D){case"contains":return typeof N=="string"?`${I} LIKE '%${N.replace(/'/g,"")}'`:`${I} LIKE '%${String(N)}'`;case"startsWith":return typeof N=="string"?`${I} LIKE '${N.replace(/'/g,"")}%'`:`${I} LIKE '${String(N)}%'`;case"endsWith":return typeof N=="string"?`${I} LIKE '%${N.replace(/'/g,"")}'`:`${I} LIKE '%${String(N)}'`;default:return`${I} ${D} ${N}`}},v=w=>{const I=w.conditions.map(b),D=w.groups.map(A=>v(A)),N=[...I,...D].filter(Boolean);if(N.length===0)return"";const F=N.join(` ${w.logicalOperator} `),O=N.length>1?`(${F})`:F;return w.negate?`NOT ${O}`:O};return v(j)},E=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:u,isLoading:i,addCondition:m,addGroup:d,removeCondition:h,removeGroup:S,updateCondition:f,updateConditionFields:y,updateGroupOperator:x,updateGroupNegate:g,reorderConditions:p,reorderGroups:C,generateSQLPreview:T,hasAnyFilters:E}}const Ar=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(jt,{className:"h-3 w-3"});case"file":return e.jsx(xn,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},Lr=s=>{switch(s){case"table":return"Table";case"view":return"View";case"dataset":return"Dataset";case"file":return"File";default:return"Table"}},Or=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Fr({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,l]=L.useState(!1),u=L.useMemo(()=>{const c={};return n.forEach(m=>{const d=Or(m);c[d]||(c[d]={}),c[d][m.entityId]||(c[d][m.entityId]=[]),c[d][m.entityId].push(m)}),c},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"truncate text-sm",children:[s.entityName,".",s.name]})}):r,e.jsx(sn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(u).map(([c,m])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),c]}),children:Object.entries(m).map(([d,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Ar(h[0].entityType),e.jsx("span",{children:h[0].entityName}),e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:Lr(h[0].entityType)})]}),h.map(S=>e.jsxs(t.CommandItem,{value:S.id,onSelect:()=>{a(S),l(!1)},className:"pl-6",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===S.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:S.label}),S.role&&e.jsx(t.Badge,{variant:"outline",className:"text-xs capitalize",children:S.role})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:S.dataType}),S.description&&e.jsxs("span",{children:["• ",S.description]}),S.customFormat&&e.jsxs("span",{children:["• ",S.customFormat]})]})]})]},S.id))]},`${c}-${d}`))},c))})]})})]})}function Pt(s){var f;const a=t.useEditorStore(y=>y.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(y=>y.card.config),o=r==null?void 0:r.joinPlan,i={...s,label:"value",role:"groupby"},l={...s,role:"metric",label:"count",aggregate:"COUNT"},u={joinPlan:o,groupByColumns:[i],metricColumns:[l]},c=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:m,isPending:d,error:h}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:c,cardConfig:u,cardDataSource:a.dataSource})}catch(y){console.log(s),console.error("error",y)}},enabled:!!c,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(y=>({label:y.value||"BLANK",value:y.value||"BLANK",count:y.count})),isPending:d,error:h}}function Br({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,l]=ie.useState(!1),{filterValues:u}=Pt(s),c=d=>{n(a.filter(h=>h!==d))},m=d=>{a.includes(d)?n(a.filter(h=>h!==d)):n([...a,d])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(d=>{const h=u.find(S=>S.value===d);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:S=>{S.key==="Enter"&&c(d)},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},onClick:S=>{S.stopPropagation(),c(d)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},d)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:u.map(d=>e.jsxs(t.CommandItem,{onSelect:()=>m(d.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(d.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.count})]})]},d.value))})]})]})})]})})}const As=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=As(n)}),a};function zr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:l,error:u}=Pt(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ue,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):u?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))})]})}const Rr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Pr=["=","!=","contains","startsWith","endsWith","in","not in"],Vr=["=","!=",">",">=","<","<=","in","not in"],qr=["=","!="],_r=["=","!=",">",">=","<","<=","in","not in"];function $r(s){switch(s){case"string":return Pr;case"number":return Vr;case"boolean":return qr;case"date":return _r;default:return Rr}}function Ls({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:u,updateConditionFields:c}){const{attributes:m,listeners:d,setNodeRef:h,transform:S,transition:f,isDragging:y}=t.useSortable({id:s.id}),{isPending:x,error:g}=Pt(s.field),p={transform:t.CSS.Transform.toString(S),transition:f};return e.jsxs("div",{ref:h,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${y?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...d,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:C=>l(n,C),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Fr,{value:s.field,onValueChange:C=>{c(n,s.id,{field:C,value:""})},availableFields:u,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:C=>{C==="in"||C==="not in"?c(n,s.id,{operator:C,value:[]}):c(n,s.id,{operator:C,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$r(t.getDataType(s.field.dataType)).map(C=>e.jsx(t.SelectItem,{value:C,children:C},C))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ue,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):g?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Br,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(C=>typeof C=="string")?s.value:[],onChange:C=>c(n,s.id,{value:C}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:C=>c(n,s.id,{value:C.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(zr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:C=>c(n,s.id,{value:C}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:C=>c(n,s.id,{value:C==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:C=>o(n,s.id,"value",C.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Gr({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onReorderConditions:m,onReorderGroups:d,onAddCondition:h,onAddGroup:S,availableFields:f,renderFilterGroup:y,updateConditionFields:x}){const{attributes:g,listeners:p,setNodeRef:C,transform:T,transition:E,isDragging:j}=t.useSortable({id:s.id}),b={transform:t.CSS.Transform.toString(T),transition:E},v=I=>{const{active:D,over:N}=I;if(N&&D.id!==N.id){const F=s.conditions.findIndex(A=>A.id===D.id),O=s.conditions.findIndex(A=>A.id===N.id);F!==-1&&O!==-1&&m(s.id,F,O)}},w=I=>{const{active:D,over:N}=I;if(N&&D.id!==N.id&&n){const F=s.groups.findIndex(A=>A.id===D.id),O=s.groups.findIndex(A=>A.id===N.id);F!==-1&&O!==-1&&d(n,F,O)}};return e.jsxs("div",{ref:C,style:b,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${j?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...g,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:I=>r(s.id,I),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:v,children:e.jsx(t.SortableContext,{items:s.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((I,D)=>e.jsx(Ls,{condition:I,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},I.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(I=>y(I,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>S(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Hr({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:l,isLoading:u,addCondition:c,addGroup:m,removeCondition:d,removeGroup:h,updateCondition:S,updateConditionFields:f,updateGroupOperator:y,updateGroupNegate:x,reorderConditions:g,reorderGroups:p,generateSQLPreview:C,hasAnyFilters:T,setCurrentFilters:E}=Mr({initialFilters:s,availableFields:a}),j=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[b,v]=L.useState(!1),w=(N,F,O)=>{const A=k=>k.id===N?{...k,conditions:k.conditions.map(M=>M.id===F?{...M,field:O,dataType:O.dataType}:M)}:{...k,groups:k.groups.map(A)};E(A(i))},I=(N,F=0,O)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:k,over:M}=A;if(M&&k.id!==M.id){const B=N.conditions.findIndex(P=>P.id===k.id),z=N.conditions.findIndex(P=>P.id===M.id);B!==-1&&z!==-1&&g(N.id,B,z)}},children:e.jsx(t.SortableContext,{items:N.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:N.conditions.map((A,k)=>e.jsx(Ls,{condition:A,index:k,groupId:N.id,groupLogicalOperator:N.logicalOperator,onUpdateCondition:S,onUpdateField:w,onRemoveCondition:d,onUpdateGroupOperator:y,availableFields:l,updateConditionFields:f},A.id))})}),e.jsx(t.DndContext,{sensors:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:k,over:M}=A;if(M&&k.id!==M.id){const B=N.groups.findIndex(P=>P.id===k.id),z=N.groups.findIndex(P=>P.id===M.id);B!==-1&&z!==-1&&p(N.id,B,z)}},children:e.jsx(t.SortableContext,{items:N.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:N.groups.map(A=>I(A,F+1,N.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>c(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),b&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},N.id):e.jsx(Gr,{group:N,depth:F,parentGroupId:O,onUpdateGroupOperator:y,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:S,onUpdateField:w,onRemoveCondition:d,onReorderConditions:g,onReorderGroups:p,onAddCondition:c,onAddGroup:m,availableFields:l,renderFilterGroup:I,updateConditionFields:f},N.id),D=As(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[u?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):I(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:b,onCheckedChange:N=>v(!!N)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),T&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),D>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(T?i:null),children:"Apply Filters"})]})]})}function Jr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:l}){const u=m=>{n(s,m),l(!1)},c=()=>{r(s),l(!1)};return e.jsx(t.Dialog,{open:i,onOpenChange:l,children:e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Hr,{filters:a,availableFields:o,onSave:u,onCancel:()=>l(!1),onClearAll:c})]})})}function Os(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}function Fs(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Ur({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[o,i]=L.useState(null),l=t.useEditorStore(p=>p.card),u=(g=l==null?void 0:l.config)==null?void 0:g.joinPlan,c=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=L.useCallback(p=>p.startsWith("card-")?null:p.startsWith("source-")||a.find(C=>C.id===p)?"source":n("groupBy").find(C=>C.id===p)?"groupBy":n("metrics").find(C=>C.id===p)?"metrics":n("pivotBy").find(C=>C.id===p)?"pivotBy":n("sortBy").find(C=>C.id===p)?"sortBy":null,[a,n]),d=L.useCallback((p,C)=>{var T;return!u||!((T=u.baseEntity)!=null&&T.name)||!u.joins?!1:p===C||p===u.baseEntity.name||C===u.baseEntity.name?!0:u.joins.some(E=>{const j=ft(E.source),b=ft(E.target);return console.log(j,b),console.log(j===p&&b===C||j===C&&b===p),j===p&&b===C||j===C&&b===p})},[u]),h=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),S=(p,C)=>{const T=Fs(C,p),E=t.getDataType(p.dataType),j=E==="date",b={id:T,name:p.name,dataType:p.dataType,label:t.toLabel(p.name),qualifiedEntityName:p.qualifiedEntityName,entityId:p.entityId,entityName:p.entityName,entityType:p.entityType};if(C==="metrics"){const v=E==="number"?"SUM":"COUNT",w=Os(p.label,v);return{...b,role:"metric",label:w,aggregate:v}}return C==="groupBy"?{...b,role:"groupby",...j&&{granularity:"month"}}:C==="pivotBy"?{...b,role:"pivotby"}:C==="sortBy"?{...b,role:"sortby",direction:"asc"}:null},f=L.useCallback(p=>{i(p.active.id)},[]),y=L.useCallback(p=>{const{active:C,over:T}=p;if(!T||!s){i(null);return}const E=C.id,j=T.id,b=m(E),v=m(j)||j;if(b==="source"&&v!=="source"){const w=[...a].find(O=>O.id===E);if(!w){i(null);return}const I=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(I.length>0){const O=I[0].qualifiedEntityName;if(!O){i(null);return}if(O!==w.qualifiedEntityName&&w.qualifiedEntityName)if(u){if(!d(O,w.qualifiedEntityName)){h(),i(null);return}}else{h(),i(null);return}}const D=n(v);if(D.some(O=>O.name===w.name&&O.qualifiedEntityName===w.qualifiedEntityName)){i(null);return}const F=S(w,v);i(null),r(v,[...D,F]);return}if(b&&v&&b!=="source"&&v!=="source"&&b!==v){const w=n(b),I=n(v),D=w.find(O=>O.id===E);if(!D){i(null);return}const N=S(D,v);i(null);const F=w.filter(O=>O.id!==E);r(b,F),r(v,[...I,N]);return}if(b&&v&&b===v&&b!=="source"){const w=n(b),I=w.findIndex(N=>N.id===E),D=w.findIndex(N=>N.id===j);if(I!==D){const N=t.arrayMove(w,I,D);r(b,N)}}i(null)},[s,a,n,r,m,u,h,d]),x=o?c.find(p=>p.id===o):null;return{activeId:o,activeField:x,handleDragStart:f,handleDragEnd:y}}const Yr=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:c,removeSortByColumn:m}=t.useEditorActions(),d=s==null?void 0:s.id,h=L.useCallback(E=>{if(!(s!=null&&s.config))return[];switch(E){case"groupBy":return(s.config.groupByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,dateFormat:j.dateFormat,customFormat:j.customFormat,granularity:j.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,direction:j.direction}));case"source":return[];default:return[]}},[s]),S=L.useCallback((E,j)=>{if(d)switch(E){case"groupBy":{a(d,{groupByColumns:j});break}case"metrics":{a(d,{metricColumns:j});break}case"pivotBy":{a(d,{pivotByColumns:j});break}case"sortBy":{a(d,{sortByColumns:j});break}}},[d,a]),f=L.useCallback((E,j,b)=>{if(!d)return;const w=h(E)[j];if(w)switch(E){case"groupBy":n(d,w.id,{label:b});break;case"metrics":r(d,w.id,{label:b});break;case"pivotBy":o(d,w.id,{label:b});break;case"sortBy":i(d,w.id,{label:b});break}},[d,h,n,r,o,i]),y=L.useCallback((E,j)=>{if(!d)return;const v=h("metrics")[E];v&&r(d,v.id,{aggregate:j,label:Os(v.name,j)})},[d,h,r]),x=L.useCallback((E,j,b)=>{if(!d)return;const w=h("groupBy")[E];if(!w)return;const I={dateFormat:j};j==="custom"&&b?I.customFormat=b:I.customFormat=void 0,n(d,w.id,I)},[d,h,n]),g=L.useCallback((E,j)=>{if(!d)return;const v=h("groupBy")[E];v&&n(d,v.id,{granularity:j})},[d,h,n]),p=L.useCallback((E,j)=>{if(!d)return;const v=h("metrics")[E];v&&r(d,v.id,{aliasTemplate:j})},[d,h,r]),C=L.useCallback((E,j)=>{if(console.log("handleValueAliasesChange",E,j),!d)return;console.log("handleValueAliasesChange",E,j);const v=h("metrics")[E];v&&(console.log("handleValueAliasesChange",j),r(d,v.id,{valueAliases:j}))},[d,h,r]),T=L.useCallback((E,j)=>{if(!d)return;const v=h(E)[j];if(v)switch(E){case"groupBy":l(d,v.id);break;case"metrics":u(d,v.id);break;case"pivotBy":c(d,v.id);break;case"sortBy":m(d,v.id);break}},[d,h,l,u,c,m]);return{getFieldsForContainer:h,setFieldsForContainer:S,updateLabel:f,handleAggregationChange:y,handleDateFormatChange:x,handleGranularityChange:g,handleAliasTemplateChange:p,handleValueAliasesChange:C,removeField:T}};function Kr({activeView:s,onViewChange:a}){return e.jsx(t.Tabs,{value:s,onValueChange:n=>a(n),children:e.jsxs(t.TabsList,{className:"h-9 w-fit bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Results"}),e.jsx(t.TabsTrigger,{value:"sql",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"SQL"})]})})}const Qr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Wr(){var c,m;const s=t.useEditorStore(d=>d.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),l=d=>{if(d==="custom"){r(!0);return}r(!1),a(s.id,parseInt(d))},u=d=>{const h=d.target.value;i(h),h&&!isNaN(parseInt(h))&&a(s.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:u,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((m=(c=s.config)==null?void 0:c.rowLimit)==null?void 0:m.toString())||"100",onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Qr.map(d=>e.jsx(t.SelectItem,{value:d.value,children:d.label},d.value))})]})})}function Xr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c,activeCard:m,columns:d,columnsLoading:h,columnsError:S}){var w;const f=t.useEditorStore(I=>I.card),{updateCardConfig:y}=t.useEditorActions(),x=t.useEditorStore(I=>I.showAIDialog),{data:g,errorMessage:p,isPending:C,isLoading:T,isFetching:E}=t.useDashboardCardQuery(m);function j(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(f.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":S?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})})}const b=I=>{if(!f.config)return;if(!I.length){y(f.id,{...f.config,sortByColumns:[]});return}const D=f.config,N=I.map(({id:F,desc:O})=>{var B,z;const A=(B=D.metricColumns)==null?void 0:B.find(P=>P.label===F),k=(z=D.groupByColumns)==null?void 0:z.find(P=>P.label===F),M=A||k;return M?{id:Fs("sortBy",M),name:M.name,dataType:M.dataType,label:M.label,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,role:"sortby",direction:O?"desc":"asc"}:null}).filter(F=>F!==null);y(f.id,{...D,sortByColumns:N})},v=L.useMemo(()=>{var I,D;return(D=(I=f.config)==null?void 0:I.sortByColumns)==null?void 0:D.map(N=>({id:N.label,desc:N.direction==="desc"}))},[(w=f.config)==null?void 0:w.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c}),n&&j(),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Kr,{activeView:s,onViewChange:a}),u&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"gap-1",onClick:u,children:[e.jsx(Ct,{className:"h-3.5 w-3.5"}),c>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:c})]}),e.jsx(Wr,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end",{"justify-between":x}),children:[s==="chart"&&x&&e.jsx(vs,{}),e.jsx("div",{className:"opacity-0 transition-opacity group-hover/visualization:opacity-100",children:s==="chart"&&e.jsx(Ns,{})})]})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:T||E?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(ue,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(Cs,{})}),s==="table"&&(g==null?void 0:g.records)&&e.jsx("div",{className:"flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(t.TableVisual,{card:m,data:g==null?void 0:g.records,onSortChange:b,sortState:v})}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(ms,{sql:g==null?void 0:g.sql,error:p})]})})]})]})]})}function Zr({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 text-muted-foreground"}),e.jsx(Ms,{dataType:s.dataType}),e.jsx("span",{className:"text-sm dark:text-muted-foreground",children:s.name})]}):null}const eo=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function to(){var G,H;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),l=t.useEditorStore(Y=>Y.showAIDialog),{setCardType:u}=t.useEditorActions(),c=t.useEditorStore(Y=>Y.card.type);L.useEffect(()=>eo(),[]);const m=()=>{console.log("Accept clicked - would save/apply current configuration")},d=()=>{console.log("Clear clicked - would reset all configurations")},h=()=>{console.log("Advanced mode toggled")},S=()=>{i(!0)},f=Y=>{u(Y)},y=t.useEditorStore(Y=>Y.frame),x=t.useEditorStore(Y=>Y.card);t.useEditorStore(Y=>Y.activeTabCardId),t.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:g,removeCard:p,updateCard:C,setActiveCard:T,updateFilters:E}=t.useEditorActions(),{columns:j=[],isLoading:b,error:v}=ze(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),I=x,{getFieldsForContainer:D,setFieldsForContainer:N,updateLabel:F,handleAggregationChange:O,handleDateFormatChange:A,handleGranularityChange:k,handleAliasTemplateChange:M,handleValueAliasesChange:B,removeField:z}=Yr(I),{activeField:P,handleDragStart:R,handleDragEnd:K}=Ur({activeCardId:y.activeCardId,sourceFields:j,getFieldsForContainer:D,setFieldsForContainer:N}),J=(Y,Z)=>{Z&&E(Y,Z)},_=Y=>{var Z;C(Y,{config:{...(Z=y.cards.find(ae=>ae.id===Y))==null?void 0:Z.config,filters:void 0}})},U=j,q=Y=>{if(!Y)return 0;let Z=Y.conditions.length;return Y.groups.forEach(ae=>{Z+=q(ae)}),Z},V=q(((G=I==null?void 0:I.config)==null?void 0:G.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:R,onDragEnd:K,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(vr,{}),!l&&e.jsx(Tr,{selectedChart:c,onChartChange:f,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),onRemoveField:z,onLabelChange:F,onAggregationChange:O,onDateFormatChange:A,onGranularityChange:k,onAliasTemplateChange:M,onValueAliasesChange:B}),e.jsx(Xr,{selectedChart:c,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:m,onClear:d,onAdvancedToggle:h,onFiltersClick:S,filterCount:V,activeCard:I,dataSourceState:x.dataSource||t.EMPTY_DATA_SOURCE,columns:j,columnsLoading:b,columnsError:v,getFieldsForContainer:D,cards:y.cards,activeCardId:y.activeCardId,addCard:g,setActiveCard:T})]}),I&&e.jsx(Jr,{cardId:I.id,filters:((H=I.config)==null?void 0:H.filters)||null,onFiltersChange:J,onClearFilters:_,availableFields:U,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Zr,{activeField:P||null})})]})}function so({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(C=>C.showAIDialog),i=t.useEditorStore(C=>C.isDevMode),{setAuthToken:l}=t.useDashboardActions(),{setShowAIDialog:u,setOnSave:c,setOnClose:m}=t.useEditorActions(),{handleDragOver:d,handleDragEnd:h,handleDragStart:S,handleDragCancel:f,sensors:y}=Yn();L.useEffect(()=>{a&&c(a),n&&m(n)},[a,c,n,m]),L.useEffect(()=>{s&&s.accessToken&&l(s)},[s,l]),L.useEffect(()=>{var C,T;o?((C=r.current)==null||C.resize(40),u(!0)):(u(!1),(T=r.current)==null||T.resize(0))},[o,u]);function x(C){C<1?u(!1):o||u(!0)}function g(){return e.jsxs(e.Fragment,{children:[e.jsx(us,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(cr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Kt,{})})]})]})}function p(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(to,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Kt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:y,onDragStart:S,onDragEnd:h,onDragOver:d,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:g()})}):p()})}function no(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(l=>l.actions),n=t.useDashboardStore(l=>l.isVisualEditing),r=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){s&&(r(s,l),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(so,{onSave:o,onClose:i})})}function ao(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=Is();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const l=n==null?void 0:n.find(u=>u.column===t.fmt(i.column_name)&&u.table===a&&u.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":l}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function ro(){t.useDashboardStore(a=>a.showFilters);const s=t.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(us,{type:"filter",ColumnsComponent:()=>e.jsx(ao,{})})})]})}function oo(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function io(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(oo,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(ro,{})})]})}function lo(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function co({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(lo,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx($n,{}),e.jsx(no,{}),e.jsx(io,{})]})]})]})})}exports.DashboardPlus=co;exports.ScheduleDashboard=cs;exports.SelectComponent=ke;exports.cleanCard=os;exports.downloadPdf=ls;exports.getDashbaordStateWithoutData=Dt;
|
|
405
|
+
ON ${T}`}),x};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[r.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>i(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":r.joins.length>0,"text-gray-500":r.joins.length===0})}),"Join",r.joins.length>1?"s":""," (",r.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(yr,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:l,generateSQLPreview:d})})]})}),e.jsx(Kt,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:m,onRemove:c,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Kt,{open:o,onOpenChange:i,joinPlan:r,availableDataSources:l,onSave:u,onCancel:m,onRemove:c,children:e.jsxs(t.Button,{onClick:()=>i(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function vr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(c=>c.card.dataSource),{updateDataSource:i}=t.useEditorActions(),l={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},u={...l,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"text-brand h-5 w-5"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[u.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[u.selectedEntities.slice(0,3).map((c,m)=>e.jsxs(t.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[t.getDisplayName(c),e.jsx("button",{onClick:d=>{d.stopPropagation();const h=u.selectedEntities.filter(S=>!(S.name===c.name&&S.type===c.type));i({...l,...o,selectedEntities:h})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 text-red-500"})})]},`${c.type}-${c.name}-${m}`)),u.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",u.selectedEntities.length-3," more"]})]}),e.jsx(br,{})]})]}),e.jsx(fr,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:u,fallbackDataSource:l})]})}const Nr=[{id:"table",icon:Qe,label:"Table"},{id:"bar",icon:Ye,label:"Bar Chart"},{id:"line",icon:Ke,label:"Line Chart"},{id:"stackedBar",icon:gt,label:"Stacked Bar Chart"},{id:"stackedLine",icon:Ft,label:"Stacked Line Chart"},{id:"scatter",icon:vt,label:"Scatter Chart"},{id:"bubble",icon:Lt,label:"Bubble Chart"},{id:"pie",icon:bt,label:"Pie Chart"},{id:"doughnut",icon:Nt,label:"Doughnut Chart"},{id:"funnel",icon:Ot,label:"Funnel Chart"},{id:"radar",icon:kt,label:"Radar Chart"},{id:"polarArea",icon:At,label:"Polar Area Chart"},{id:"tornado",icon:It,label:"Tornado Chart"},{id:"range",icon:yt,label:"Range Chart"},{id:"kpi",icon:Bt,label:"KPI"},{id:"text",icon:Wt,label:"Text"},{id:"map",icon:wt,label:"Map"},{id:"custom",icon:Et,label:"Custom"}];function Cr({selectedChart:s,onChartChange:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(m=>m.actions),{setCardCustomCfg:i,setCustomCardPreferences:l,setQueryConfig:u}=t.useEditorActions();function c(m){i(null),r({}),n(m),["kpi","custom","text","map"].includes(m)&&(o(!0),u(void 0)),a(m)}return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Select,{value:s,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"w-full",children:e.jsx(t.SelectValue,{placeholder:"Select chart type"})}),e.jsx(t.SelectContent,{children:Nr.map(m=>{const d=m.icon;return e.jsx(t.SelectItem,{value:m.id,className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{children:m.label})]})},m.id)})})]})})}const Ms=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function Sr({label:s,onLabelChange:a}){const[n,r]=L.useState(s??""),[o,i]=L.useState(!1);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Display Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:"Display label...",value:o?n:s??"",onChange:l=>{r(l.target.value),i(!0)},onFocus:()=>i(!0),onClick:l=>l.stopPropagation(),className:"h-8 text-xs",onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&o&&n!==(s??"")?(a(n),i(!1)):l.key==="Escape"&&(r(s??""),i(!1))},"aria-label":"Edit display label"}),o&&n!==(s??"")&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm label",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel label edit",onClick:()=>{r(s??""),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})]})}function wr({aliasTemplate:s,onAliasTemplateChange:a}){var c;const[n,r]=L.useState(s),[o,i]=L.useState(!1),l=(c=t.useEditorStore(m=>{var d;return(d=m.card.config)==null?void 0:d.pivotByColumns}))==null?void 0:c[0],u=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:u,value:o?n:s,onChange:m=>{r(m.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&o&&n!==s?(a(n),i(!1)):m.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function kr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[l,u]=L.useState(""),c=()=>{a({...s,"":""})},m=h=>{const S={...s};delete S[h],a(S)},d=h=>{const S={...s};delete S[h],S[o]=l,a(S),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([h,S],f)=>e.jsx("div",{className:"flex items-center gap-2",children:n===h?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:y=>i(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?d(h):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:l,onChange:y=>u(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?d(h):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>d(h),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),u(S)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:S,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),i(h),u(S)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(h),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},h+f)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:c,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Er({field:s,zone:a,onRemove:n,onLabelChange:r,sortDirection:o,onSortDirectionChange:i,onAliasTemplateChange:l,onValueAliasesChange:u,onAggregationChange:c,onDateFormatChange:m,onGranularityChange:d,hasPivotColumns:h=!1}){const{attributes:S,listeners:f,setNodeRef:y,transform:x,transition:g,isDragging:p}=t.useSortable({id:s.id}),[C,T]=L.useState(!1),[E,j]=L.useState(s.dateFormat||"YYYY-MM-DD"),[b,v]=L.useState(s.customFormat||""),[w,I]=L.useState(!!s.customFormat),[D,N]=L.useState(s.granularity||"day"),[F,O]=L.useState(s.aliasTemplate||""),[A,k]=L.useState(s.valueAliases||{}),M=q=>{q==="custom"?I(!0):(I(!1),j(q),a==="groupBy"&&m&&m(q,""))},B=q=>{v(q),a==="groupBy"&&m&&m("custom",q)},z=q=>{N(q),a==="groupBy"&&d&&d(q)},V=q=>{O(q),l&&l(q)},R=q=>{k(q),u&&u(q)},K={transform:t.CSS.Transform.toString(x),transition:g},J=t.getDataType(s.dataType),_=J==="date",U=[{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}];return e.jsxs("div",{ref:y,style:K,...S,...f,className:`group flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${p?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(Ms,{dataType:J}),e.jsx("span",{className:"max-w-[180px] flex-1 overflow-hidden truncate text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:q=>{q.stopPropagation(),T(!C)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${C?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:q=>{q.stopPropagation(),console.log("DraggableField - Current sortDirection:",o);const P=o==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",P),i(P)},children:o==="asc"?e.jsx(Ue,{className:"h-3 w-3"}):e.jsx(Je,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:q=>{q.stopPropagation(),n()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),C&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("span",{className:"flex-1 overflow-hidden truncate px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),a!=="pivotBy"&&e.jsx(Sr,{label:s.label??"",onLabelChange:r}),_&&a!=="groupBy"&&e.jsx("div",{className:"space-y-1",children:e.jsxs(t.Select,{defaultValue:"day",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})}),_&&a==="groupBy"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:D,onValueChange:z,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:w?"custom":E,onValueChange:M,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:U.map(q=>e.jsx(t.SelectItem,{value:q.value,children:q.label},q.value))})]}),w&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:b,onChange:q=>{q.stopPropagation(),B(q.target.value)},onClick:q=>q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}),a==="metrics"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:q=>{c&&c(q)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(Ds,{column:s}),h&&e.jsxs(e.Fragment,{children:[e.jsx(wr,{aliasTemplate:F,onAliasTemplateChange:V}),e.jsx(kr,{valueAliases:A,onValueAliasesChange:R})]})]})]})]})}function Ir({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-amber-50 text-xs font-medium dark:bg-amber-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-amber-100 text-xs font-medium dark:bg-amber-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metrics = Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});default:return null}};return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function qe({zone:s,fields:a,label:n,placeholder:r,onRemove:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:m,onValueAliasesChange:d,shouldShow:h,hasPivotColumns:S=!1}){const{isOver:f,setNodeRef:y}=t.useDroppable({id:s}),{updateSortByColumn:x}=t.useEditorActions(),g=t.useEditorStore(T=>T.card),p=a.length>0,C=(T,E)=>{var b;!((b=g.config)!=null&&b.sortByColumns)||g.config.sortByColumns.findIndex(v=>v.id===T)===-1||x(g.id,T,{direction:E})};return s==="sortBy"&&h===!1?null:e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:"block text-sm font-medium",children:n}),e.jsx(Ir,{concept:s})]}),e.jsx("div",{ref:y,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${f?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((T,E)=>{const b=T.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Er,{field:T,zone:s,onRemove:()=>o(E),onLabelChange:v=>i(E,v),sortDirection:b,onSortDirectionChange:v=>C(T.id,v),onAggregationChange:l?v=>l(E,v):void 0,onAliasTemplateChange:m?v=>m(E,v):void 0,onValueAliasesChange:d?v=>d(E,v):void 0,onDateFormatChange:u?(v,w)=>u(E,v,w):void 0,onGranularityChange:c?v=>c(E,v):void 0,hasPivotColumns:S})})},T.id)})})})})]})}function Dr({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,onRemoveField:o,onLabelChange:i,onAggregationChange:l,onDateFormatChange:u,onGranularityChange:c,onAliasTemplateChange:m,onValueAliasesChange:d}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(qe,{zone:"groupBy",fields:s,label:"Rows",placeholder:"Drop fields to group data",onRemove:h=>o("groupBy",h),onLabelChange:(h,S)=>i("groupBy",h,S),onDateFormatChange:(h,S,f)=>u&&u(h,S,f),onGranularityChange:(h,S)=>c&&c(h,S)}),e.jsx(qe,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",onRemove:h=>o("pivotBy",h),onLabelChange:(h,S)=>i("pivotBy",h,S)}),e.jsx(qe,{zone:"metrics",fields:n,label:"Metrics",placeholder:"Drop fields to measure",onRemove:h=>o("metrics",h),onLabelChange:(h,S)=>i("metrics",h,S),onAggregationChange:l,onAliasTemplateChange:m,onValueAliasesChange:d,hasPivotColumns:a.length>0}),r&&r.length>0&&e.jsx(qe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields to sort data",onRemove:h=>o("sortBy",h),onLabelChange:(h,S)=>i("sortBy",h,S),shouldShow:s.length>0||a.length>0||n.length>0})]})}function Tr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:m,onGranularityChange:d,onAliasTemplateChange:h,onValueAliasesChange:S}){t.useEditorStore(y=>y.showAIDialog);const{setShowAIDialog:f}=t.useEditorActions();return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"mt-1 space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"text-brand h-5 w-5"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(Cr,{selectedChart:s,onChartChange:a})]}),e.jsxs(t.ScrollArea,{className:"flex-1 p-6",children:[e.jsx(Dr,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i,onRemoveField:l,onLabelChange:u,onAggregationChange:c,onDateFormatChange:m,onGranularityChange:d,onAliasTemplateChange:h,onValueAliasesChange:S}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Mr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(j=>j.card.dataSource);const{columns:o,isLoading:i}=ze(),u=a||o||[],c={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},m=j=>{const b=v=>{if(v.id===j){const w=u[0]||c;return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...v,groups:v.groups.map(b)}};r(b(n))},d=j=>{const b=v=>{if(v.id===j){const w=u[0]||c;return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...v,groups:v.groups.map(b)}};r(b(n))},h=(j,b)=>{const v=w=>w.id===j?{...w,conditions:w.conditions.filter(I=>I.id!==b)}:{...w,groups:w.groups.map(v)};r(v(n))},S=(j,b)=>{const v=w=>w.id===j?{...w,groups:w.groups.filter(I=>I.id!==b)}:{...w,groups:w.groups.map(v)};r(v(n))},f=(j,b,v,w)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=D=>D.id===j?{...D,conditions:D.conditions.map(N=>N.id===b?{...N,[v]:w}:N)}:{...D,groups:D.groups.map(I)};r(I(n))},y=(j,b,v)=>{const w=I=>I.id===j?{...I,conditions:I.conditions.map(D=>D.id===b?{...D,...v}:D)}:{...I,groups:I.groups.map(w)};r(w(n))},x=(j,b)=>{const v=w=>w.id===j?{...w,logicalOperator:b}:{...w,groups:w.groups.map(v)};r(v(n))},g=(j,b)=>{const v=w=>w.id===j?{...w,negate:b}:{...w,groups:w.groups.map(v)};r(v(n))},p=(j,b,v)=>{const w=I=>I.id===j?{...I,conditions:t.arrayMove(I.conditions,b,v)}:{...I,groups:I.groups.map(w)};r(w(n))},C=(j,b,v)=>{const w=I=>I.id===j?{...I,groups:t.arrayMove(I.groups,b,v)}:{...I,groups:I.groups.map(w)};r(w(n))},T=j=>{if(!j||j.conditions.length===0&&j.groups.length===0)return"-- No filters defined";const b=w=>{let I="";typeof w.field=="object"?I=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:I=String(w.field);const D=w.operator;let N=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof N=="string"?N=`'${N}'`:Array.isArray(N)&&(N=`'${N.join(", ")}'`);else if(w.field.dataType==="date")(typeof N=="string"||N instanceof Date)&&(N=`DATE('${N}')`);else if(["in","not in"].includes(w.operator)){let F=[];Array.isArray(N)?F=N.map(O=>typeof O=="string"?`'${O}'`:String(O)):typeof N=="string"?F=N.split(",").map(O=>{const A=O.trim();return w.field.dataType==="string"?`'${A}'`:A}):typeof N=="number"&&(F=[String(N)]),N=`(${F.join(", ")})`}switch(D){case"contains":return typeof N=="string"?`${I} LIKE '%${N.replace(/'/g,"")}'`:`${I} LIKE '%${String(N)}'`;case"startsWith":return typeof N=="string"?`${I} LIKE '${N.replace(/'/g,"")}%'`:`${I} LIKE '${String(N)}%'`;case"endsWith":return typeof N=="string"?`${I} LIKE '%${N.replace(/'/g,"")}'`:`${I} LIKE '%${String(N)}'`;default:return`${I} ${D} ${N}`}},v=w=>{const I=w.conditions.map(b),D=w.groups.map(A=>v(A)),N=[...I,...D].filter(Boolean);if(N.length===0)return"";const F=N.join(` ${w.logicalOperator} `),O=N.length>1?`(${F})`:F;return w.negate?`NOT ${O}`:O};return v(j)},E=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:u,isLoading:i,addCondition:m,addGroup:d,removeCondition:h,removeGroup:S,updateCondition:f,updateConditionFields:y,updateGroupOperator:x,updateGroupNegate:g,reorderConditions:p,reorderGroups:C,generateSQLPreview:T,hasAnyFilters:E}}const Ar=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(jt,{className:"h-3 w-3"});case"file":return e.jsx(xn,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},Lr=s=>{switch(s){case"table":return"Table";case"view":return"View";case"dataset":return"Dataset";case"file":return"File";default:return"Table"}},Or=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Fr({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,l]=L.useState(!1),u=L.useMemo(()=>{const c={};return n.forEach(m=>{const d=Or(m);c[d]||(c[d]={}),c[d][m.entityId]||(c[d][m.entityId]=[]),c[d][m.entityId].push(m)}),c},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"truncate text-sm",children:[s.entityName,".",s.name]})}):r,e.jsx(sn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(u).map(([c,m])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),c]}),children:Object.entries(m).map(([d,h])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[Ar(h[0].entityType),e.jsx("span",{children:h[0].entityName}),e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:Lr(h[0].entityType)})]}),h.map(S=>e.jsxs(t.CommandItem,{value:S.id,onSelect:()=>{a(S),l(!1)},className:"pl-6",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===S.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:S.label}),S.role&&e.jsx(t.Badge,{variant:"outline",className:"text-xs capitalize",children:S.role})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:S.dataType}),S.description&&e.jsxs("span",{children:["• ",S.description]}),S.customFormat&&e.jsxs("span",{children:["• ",S.customFormat]})]})]})]},S.id))]},`${c}-${d}`))},c))})]})})]})}function Rt(s){var f;const a=t.useEditorStore(y=>y.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(y=>y.card.config),o=r==null?void 0:r.joinPlan,i={...s,label:"value",role:"groupby"},l={...s,role:"metric",label:"count",aggregate:"COUNT"},u={joinPlan:o,groupByColumns:[i],metricColumns:[l]},c=((f=a.dataSource)==null?void 0:f.connectionId)||a.connectionId,{data:m,isPending:d,error:h}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:c,cardConfig:u,cardDataSource:a.dataSource})}catch(y){console.log(s),console.error("error",y)}},enabled:!!c,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(y=>({label:y.value||"BLANK",value:y.value||"BLANK",count:y.count})),isPending:d,error:h}}function Br({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,l]=ie.useState(!1),{filterValues:u}=Rt(s),c=d=>{n(a.filter(h=>h!==d))},m=d=>{a.includes(d)?n(a.filter(h=>h!==d)):n([...a,d])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(d=>{const h=u.find(S=>S.value===d);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[h==null?void 0:h.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:S=>{S.key==="Enter"&&c(d)},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},onClick:S=>{S.stopPropagation(),c(d)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},d)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:u.map(d=>e.jsxs(t.CommandItem,{onSelect:()=>m(d.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(d.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:d.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:d.count})]})]},d.value))})]})]})})]})})}const As=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=As(n)}),a};function zr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:l,error:u}=Rt(s);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ue,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):u?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map(c=>e.jsx(t.SelectItem,{value:c.value,children:c.label},c.value))})]})}const Rr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Vr=["=","!=","contains","startsWith","endsWith","in","not in"],Pr=["=","!=",">",">=","<","<=","in","not in"],qr=["=","!="],_r=["=","!=",">",">=","<","<=","in","not in"];function Gr(s){switch(s){case"string":return Vr;case"number":return Pr;case"boolean":return qr;case"date":return _r;default:return Rr}}function Ls({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:u,updateConditionFields:c}){const{attributes:m,listeners:d,setNodeRef:h,transform:S,transition:f,isDragging:y}=t.useSortable({id:s.id}),{isPending:x,error:g}=Rt(s.field),p={transform:t.CSS.Transform.toString(S),transition:f};return e.jsxs("div",{ref:h,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${y?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...d,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:C=>l(n,C),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Fr,{value:s.field,onValueChange:C=>{c(n,s.id,{field:C,value:""})},availableFields:u,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:C=>{C==="in"||C==="not in"?c(n,s.id,{operator:C,value:[]}):c(n,s.id,{operator:C,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gr(t.getDataType(s.field.dataType)).map(C=>e.jsx(t.SelectItem,{value:C,children:C},C))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(ue,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):g?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Br,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(C=>typeof C=="string")?s.value:[],onChange:C=>c(n,s.id,{value:C}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:C=>c(n,s.id,{value:C.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(zr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:C=>c(n,s.id,{value:C}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:C=>c(n,s.id,{value:C==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:C=>o(n,s.id,"value",C.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function $r({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onReorderConditions:m,onReorderGroups:d,onAddCondition:h,onAddGroup:S,availableFields:f,renderFilterGroup:y,updateConditionFields:x}){const{attributes:g,listeners:p,setNodeRef:C,transform:T,transition:E,isDragging:j}=t.useSortable({id:s.id}),b={transform:t.CSS.Transform.toString(T),transition:E},v=I=>{const{active:D,over:N}=I;if(N&&D.id!==N.id){const F=s.conditions.findIndex(A=>A.id===D.id),O=s.conditions.findIndex(A=>A.id===N.id);F!==-1&&O!==-1&&m(s.id,F,O)}},w=I=>{const{active:D,over:N}=I;if(N&&D.id!==N.id&&n){const F=s.groups.findIndex(A=>A.id===D.id),O=s.groups.findIndex(A=>A.id===N.id);F!==-1&&O!==-1&&d(n,F,O)}};return e.jsxs("div",{ref:C,style:b,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${j?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...g,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:I=>r(s.id,I),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:v,children:e.jsx(t.SortableContext,{items:s.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((I,D)=>e.jsx(Ls,{condition:I,index:D,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:u,onRemoveCondition:c,onUpdateGroupOperator:r,availableFields:f,updateConditionFields:x},I.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(I=>y(I,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>S(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Hr({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:l,isLoading:u,addCondition:c,addGroup:m,removeCondition:d,removeGroup:h,updateCondition:S,updateConditionFields:f,updateGroupOperator:y,updateGroupNegate:x,reorderConditions:g,reorderGroups:p,generateSQLPreview:C,hasAnyFilters:T,setCurrentFilters:E}=Mr({initialFilters:s,availableFields:a}),j=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[b,v]=L.useState(!1),w=(N,F,O)=>{const A=k=>k.id===N?{...k,conditions:k.conditions.map(M=>M.id===F?{...M,field:O,dataType:O.dataType}:M)}:{...k,groups:k.groups.map(A)};E(A(i))},I=(N,F=0,O)=>F===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:k,over:M}=A;if(M&&k.id!==M.id){const B=N.conditions.findIndex(V=>V.id===k.id),z=N.conditions.findIndex(V=>V.id===M.id);B!==-1&&z!==-1&&g(N.id,B,z)}},children:e.jsx(t.SortableContext,{items:N.conditions.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:N.conditions.map((A,k)=>e.jsx(Ls,{condition:A,index:k,groupId:N.id,groupLogicalOperator:N.logicalOperator,onUpdateCondition:S,onUpdateField:w,onRemoveCondition:d,onUpdateGroupOperator:y,availableFields:l,updateConditionFields:f},A.id))})}),e.jsx(t.DndContext,{sensors:j,collisionDetection:t.closestCenter,onDragEnd:A=>{const{active:k,over:M}=A;if(M&&k.id!==M.id){const B=N.groups.findIndex(V=>V.id===k.id),z=N.groups.findIndex(V=>V.id===M.id);B!==-1&&z!==-1&&p(N.id,B,z)}},children:e.jsx(t.SortableContext,{items:N.groups.map(A=>A.id),strategy:t.verticalListSortingStrategy,children:N.groups.map(A=>I(A,F+1,N.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>c(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),b&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(N.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},N.id):e.jsx($r,{group:N,depth:F,parentGroupId:O,onUpdateGroupOperator:y,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:S,onUpdateField:w,onRemoveCondition:d,onReorderConditions:g,onReorderGroups:p,onAddCondition:c,onAddGroup:m,availableFields:l,renderFilterGroup:I,updateConditionFields:f},N.id),D=As(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[u?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):I(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:b,onCheckedChange:N=>v(!!N)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),T&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),D>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(T?i:null),children:"Apply Filters"})]})]})}function Jr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:l}){const u=m=>{n(s,m),l(!1)},c=()=>{r(s),l(!1)};return e.jsx(t.Dialog,{open:i,onOpenChange:l,children:e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Hr,{filters:a,availableFields:o,onSave:u,onCancel:()=>l(!1),onClearAll:c})]})})}function Os(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}function Fs(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Ur({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var g;const[o,i]=L.useState(null),l=t.useEditorStore(p=>p.card),u=(g=l==null?void 0:l.config)==null?void 0:g.joinPlan,c=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],m=L.useCallback(p=>p.startsWith("card-")?null:p.startsWith("source-")||a.find(C=>C.id===p)?"source":n("groupBy").find(C=>C.id===p)?"groupBy":n("metrics").find(C=>C.id===p)?"metrics":n("pivotBy").find(C=>C.id===p)?"pivotBy":n("sortBy").find(C=>C.id===p)?"sortBy":null,[a,n]),d=L.useCallback((p,C)=>{var T;return!u||!((T=u.baseEntity)!=null&&T.name)||!u.joins?!1:p===C||p===u.baseEntity.name||C===u.baseEntity.name?!0:u.joins.some(E=>{const j=ft(E.source),b=ft(E.target);return console.log(j,b),console.log(j===p&&b===C||j===C&&b===p),j===p&&b===C||j===C&&b===p})},[u]),h=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),S=(p,C)=>{const T=Fs(C,p),E=t.getDataType(p.dataType),j=E==="date",b={id:T,name:p.name,dataType:p.dataType,label:t.toLabel(p.name),qualifiedEntityName:p.qualifiedEntityName,entityId:p.entityId,entityName:p.entityName,entityType:p.entityType};if(C==="metrics"){const v=E==="number"?"SUM":"COUNT",w=Os(p.label,v);return{...b,role:"metric",label:w,aggregate:v}}return C==="groupBy"?{...b,role:"groupby",...j&&{granularity:"month"}}:C==="pivotBy"?{...b,role:"pivotby"}:C==="sortBy"?{...b,role:"sortby",direction:"asc"}:null},f=L.useCallback(p=>{i(p.active.id)},[]),y=L.useCallback(p=>{const{active:C,over:T}=p;if(!T||!s){i(null);return}const E=C.id,j=T.id,b=m(E),v=m(j)||j;if(b==="source"&&v!=="source"){const w=[...a].find(O=>O.id===E);if(!w){i(null);return}const I=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(I.length>0){const O=I[0].qualifiedEntityName;if(!O){i(null);return}if(O!==w.qualifiedEntityName&&w.qualifiedEntityName)if(u){if(!d(O,w.qualifiedEntityName)){h(),i(null);return}}else{h(),i(null);return}}const D=n(v);if(D.some(O=>O.name===w.name&&O.qualifiedEntityName===w.qualifiedEntityName)){i(null);return}const F=S(w,v);i(null),r(v,[...D,F]);return}if(b&&v&&b!=="source"&&v!=="source"&&b!==v){const w=n(b),I=n(v),D=w.find(O=>O.id===E);if(!D){i(null);return}const N=S(D,v);i(null);const F=w.filter(O=>O.id!==E);r(b,F),r(v,[...I,N]);return}if(b&&v&&b===v&&b!=="source"){const w=n(b),I=w.findIndex(N=>N.id===E),D=w.findIndex(N=>N.id===j);if(I!==D){const N=t.arrayMove(w,I,D);r(b,N)}}i(null)},[s,a,n,r,m,u,h,d]),x=o?c.find(p=>p.id===o):null;return{activeId:o,activeField:x,handleDragStart:f,handleDragEnd:y}}const Yr=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:c,removeSortByColumn:m}=t.useEditorActions(),d=s==null?void 0:s.id,h=L.useCallback(E=>{if(!(s!=null&&s.config))return[];switch(E){case"groupBy":return(s.config.groupByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,dateFormat:j.dateFormat,customFormat:j.customFormat,granularity:j.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(j=>({id:j.id,name:j.name,dataType:j.dataType,label:j.label!==void 0?j.label:j.name,qualifiedEntityName:j.qualifiedEntityName,entityId:j.entityId,entityName:j.entityName,entityType:j.entityType,direction:j.direction}));case"source":return[];default:return[]}},[s]),S=L.useCallback((E,j)=>{if(d)switch(E){case"groupBy":{a(d,{groupByColumns:j});break}case"metrics":{a(d,{metricColumns:j});break}case"pivotBy":{a(d,{pivotByColumns:j});break}case"sortBy":{a(d,{sortByColumns:j});break}}},[d,a]),f=L.useCallback((E,j,b)=>{if(!d)return;const w=h(E)[j];if(w)switch(E){case"groupBy":n(d,w.id,{label:b});break;case"metrics":r(d,w.id,{label:b});break;case"pivotBy":o(d,w.id,{label:b});break;case"sortBy":i(d,w.id,{label:b});break}},[d,h,n,r,o,i]),y=L.useCallback((E,j)=>{if(!d)return;const v=h("metrics")[E];v&&r(d,v.id,{aggregate:j,label:Os(v.name,j)})},[d,h,r]),x=L.useCallback((E,j,b)=>{if(!d)return;const w=h("groupBy")[E];if(!w)return;const I={dateFormat:j};j==="custom"&&b?I.customFormat=b:I.customFormat=void 0,n(d,w.id,I)},[d,h,n]),g=L.useCallback((E,j)=>{if(!d)return;const v=h("groupBy")[E];v&&n(d,v.id,{granularity:j})},[d,h,n]),p=L.useCallback((E,j)=>{if(!d)return;const v=h("metrics")[E];v&&r(d,v.id,{aliasTemplate:j})},[d,h,r]),C=L.useCallback((E,j)=>{if(console.log("handleValueAliasesChange",E,j),!d)return;console.log("handleValueAliasesChange",E,j);const v=h("metrics")[E];v&&(console.log("handleValueAliasesChange",j),r(d,v.id,{valueAliases:j}))},[d,h,r]),T=L.useCallback((E,j)=>{if(!d)return;const v=h(E)[j];if(v)switch(E){case"groupBy":l(d,v.id);break;case"metrics":u(d,v.id);break;case"pivotBy":c(d,v.id);break;case"sortBy":m(d,v.id);break}},[d,h,l,u,c,m]);return{getFieldsForContainer:h,setFieldsForContainer:S,updateLabel:f,handleAggregationChange:y,handleDateFormatChange:x,handleGranularityChange:g,handleAliasTemplateChange:p,handleValueAliasesChange:C,removeField:T}};function Kr({activeView:s,onViewChange:a}){return e.jsx(t.Tabs,{value:s,onValueChange:n=>a(n),children:e.jsxs(t.TabsList,{className:"h-9 w-fit bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"Results"}),e.jsx(t.TabsTrigger,{value:"sql",className:"rounded-none transition data-[state=active]:border-b-2 data-[state=active]:border-foreground data-[state=active]:bg-muted",children:"SQL"})]})})}const Qr=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Wr(){var c,m;const s=t.useEditorStore(d=>d.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),l=d=>{if(d==="custom"){r(!0);return}r(!1),a(s.id,parseInt(d))},u=d=>{const h=d.target.value;i(h),h&&!isNaN(parseInt(h))&&a(s.id,parseInt(h))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:u,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((m=(c=s.config)==null?void 0:c.rowLimit)==null?void 0:m.toString())||"100",onValueChange:l,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Qr.map(d=>e.jsx(t.SelectItem,{value:d.value,children:d.label},d.value))})]})})}function Xr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c,activeCard:m,columns:d,columnsLoading:h,columnsError:S}){var w;const f=t.useEditorStore(I=>I.card),{updateCardConfig:y}=t.useEditorActions(),x=t.useEditorStore(I=>I.showAIDialog),{data:g,errorMessage:p,isPending:C,isLoading:T,isFetching:E}=t.useDashboardCardQuery(m);function j(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(f.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(m.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",d.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:h?"Loading...":S?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})})}const b=I=>{if(!f.config)return;if(!I.length){y(f.id,{...f.config,sortByColumns:[]});return}const D=f.config,N=I.map(({id:F,desc:O})=>{var B,z;const A=(B=D.metricColumns)==null?void 0:B.find(V=>V.label===F),k=(z=D.groupByColumns)==null?void 0:z.find(V=>V.label===F),M=A||k;return M?{id:Fs("sortBy",M),name:M.name,dataType:M.dataType,label:M.label,qualifiedEntityName:M.qualifiedEntityName,entityId:M.entityId,entityName:M.entityName,entityType:M.entityType,role:"sortby",direction:O?"desc":"asc"}:null}).filter(F=>F!==null);y(f.id,{...D,sortByColumns:N})},v=L.useMemo(()=>{var I,D;return(D=(I=f.config)==null?void 0:I.sortByColumns)==null?void 0:D.map(N=>({id:N.label,desc:N.direction==="desc"}))},[(w=f.config)==null?void 0:w.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:l,onFiltersClick:u,filterCount:c}),n&&j(),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Kr,{activeView:s,onViewChange:a}),u&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"gap-1",onClick:u,children:[e.jsx(Ct,{className:"h-3.5 w-3.5"}),c>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:c})]}),e.jsx(Wr,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end",{"justify-between":x}),children:[s==="chart"&&x&&e.jsx(bs,{}),e.jsx("div",{className:"opacity-0 transition-opacity group-hover/visualization:opacity-100",children:s==="chart"&&e.jsx(vs,{})})]})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:T||E?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(ue,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(Ns,{})}),s==="table"&&(g==null?void 0:g.records)&&e.jsx("div",{className:"flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(t.TableVisual,{card:m,data:g==null?void 0:g.records,onSortChange:b,sortState:v})}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(us,{sql:g==null?void 0:g.sql,error:p})]})})]})]})]})}function Zr({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?e.jsxs("div",{className:`flex items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 text-muted-foreground"}),e.jsx(Ms,{dataType:s.dataType}),e.jsx("span",{className:"text-sm dark:text-muted-foreground",children:s.name})]}):null}const eo=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function to(){var $,H;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),l=t.useEditorStore(Y=>Y.showAIDialog),{setCardType:u}=t.useEditorActions(),c=t.useEditorStore(Y=>Y.card.type);L.useEffect(()=>eo(),[]);const m=()=>{console.log("Accept clicked - would save/apply current configuration")},d=()=>{console.log("Clear clicked - would reset all configurations")},h=()=>{console.log("Advanced mode toggled")},S=()=>{i(!0)},f=Y=>{u(Y)},y=t.useEditorStore(Y=>Y.frame),x=t.useEditorStore(Y=>Y.card);t.useEditorStore(Y=>Y.activeTabCardId),t.useEditorStore(Y=>Y.actions.getAvailableFields);const{addCard:g,removeCard:p,updateCard:C,setActiveCard:T,updateFilters:E}=t.useEditorActions(),{columns:j=[],isLoading:b,error:v}=ze(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),I=x,{getFieldsForContainer:D,setFieldsForContainer:N,updateLabel:F,handleAggregationChange:O,handleDateFormatChange:A,handleGranularityChange:k,handleAliasTemplateChange:M,handleValueAliasesChange:B,removeField:z}=Yr(I),{activeField:V,handleDragStart:R,handleDragEnd:K}=Ur({activeCardId:y.activeCardId,sourceFields:j,getFieldsForContainer:D,setFieldsForContainer:N}),J=(Y,Z)=>{Z&&E(Y,Z)},_=Y=>{var Z;C(Y,{config:{...(Z=y.cards.find(ae=>ae.id===Y))==null?void 0:Z.config,filters:void 0}})},U=j,q=Y=>{if(!Y)return 0;let Z=Y.conditions.length;return Y.groups.forEach(ae=>{Z+=q(ae)}),Z},P=q((($=I==null?void 0:I.config)==null?void 0:$.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:R,onDragEnd:K,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(vr,{}),!l&&e.jsx(Tr,{selectedChart:c,onChartChange:f,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),onRemoveField:z,onLabelChange:F,onAggregationChange:O,onDateFormatChange:A,onGranularityChange:k,onAliasTemplateChange:M,onValueAliasesChange:B}),e.jsx(Xr,{selectedChart:c,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:m,onClear:d,onAdvancedToggle:h,onFiltersClick:S,filterCount:P,activeCard:I,dataSourceState:x.dataSource||t.EMPTY_DATA_SOURCE,columns:j,columnsLoading:b,columnsError:v,getFieldsForContainer:D,cards:y.cards,activeCardId:y.activeCardId,addCard:g,setActiveCard:T})]}),I&&e.jsx(Jr,{cardId:I.id,filters:((H=I.config)==null?void 0:H.filters)||null,onFiltersChange:J,onClearFilters:_,availableFields:U,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Zr,{activeField:V||null})})]})}function so({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(C=>C.showAIDialog),i=t.useEditorStore(C=>C.isDevMode),{setAuthToken:l}=t.useDashboardActions(),{setShowAIDialog:u,setOnSave:c,setOnClose:m}=t.useEditorActions(),{handleDragOver:d,handleDragEnd:h,handleDragStart:S,handleDragCancel:f,sensors:y}=Yn();L.useEffect(()=>{a&&c(a),n&&m(n)},[a,c,n,m]),L.useEffect(()=>{s&&s.accessToken&&l(s)},[s,l]),L.useEffect(()=>{var C,T;o?((C=r.current)==null||C.resize(40),u(!0)):(u(!1),(T=r.current)==null||T.resize(0))},[o,u]);function x(C){C<1?u(!1):o||u(!0)}function g(){return e.jsxs(e.Fragment,{children:[e.jsx(ds,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(cr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Yt,{})})]})]})}function p(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(to,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Yt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:y,onDragStart:S,onDragEnd:h,onDragOver:d,onDragCancel:f,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:g()})}):p()})}function no(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(l=>l.actions),n=t.useDashboardStore(l=>l.isVisualEditing),r=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){s&&(r(s,l),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(so,{onSave:o,onClose:i})})}function ao(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=Es();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const l=n==null?void 0:n.find(u=>u.column===t.fmt(i.column_name)&&u.table===a&&u.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":l}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function ro(){t.useDashboardStore(a=>a.showFilters);const s=t.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(ds,{type:"filter",ColumnsComponent:()=>e.jsx(ao,{})})})]})}function oo(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function io(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(oo,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(ro,{})})]})}function lo(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function co({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(lo,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(Gn,{}),e.jsx(no,{}),e.jsx(io,{})]})]})]})})}exports.DashboardPlus=co;exports.ScheduleDashboard=ls;exports.SelectComponent=ke;exports.cleanCard=rs;exports.downloadPdf=is;exports.getDashbaordStateWithoutData=Dt;
|